@useanvil/claude-code 0.8.1 → 0.9.1
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/CHANGELOG.md +241 -1
- package/dist/claude-conditions.js +6 -6
- package/dist/claude-hook-core.js +84 -82
- package/dist/claude-hook.js +37 -35
- package/dist/claude-meter.js +55 -35
- package/dist/claude-sync.js +26 -24
- package/dist/cli/claude-main.js +7890 -1382
- package/docs/coding-agents/YOUR-RULES.md +293 -49
- package/package.json +1 -1
package/dist/claude-hook-core.js
CHANGED
|
@@ -1,87 +1,89 @@
|
|
|
1
|
-
import{posix as
|
|
2
|
-
`||l==="\r"){o=!0;break}s+=l,
|
|
3
|
-
`&&e[o]!=="\r";){let
|
|
4
|
-
`;)s++;let r=s>=
|
|
5
|
-
`||
|
|
6
|
-
`?p+2:p+1,A=
|
|
7
|
-
`){p+=2;continue}if(
|
|
8
|
-
`&&e[p]!=="\r";)p++;continue}let h=c.start===-1
|
|
9
|
-
`){
|
|
10
|
-
`){
|
|
11
|
-
`){
|
|
12
|
-
`||l==="\r")&&
|
|
13
|
-
`?
|
|
14
|
-
`&&e[
|
|
15
|
-
`,
|
|
16
|
-
`,
|
|
17
|
-
`,
|
|
18
|
-
`],["r","\r"],["t"," "],["v","\v"],["\\","\\"],["'","'"],['"','"']]);return r.has(s)?{text:r.get(s)??s,next:n+1}:s==="x"?ss(e,n+1,t,16,2,n+1):s==="u"?ss(e,n+1,t,16,4,n+1):s==="U"?ss(e,n+1,t,16,8,n+1):/[0-7]/.test(s)?ss(e,n,t,8,3,n+1):{text:s,next:n+1}}function ss(e,n,t,s,r,o){let i=s===16?/[0-9a-fA-F]/:/[0-7]/,a="",l=n;for(;l<t&&a.length<r&&i.test(e[l]??"");)a+=e[l],l++;if(!a)return{text:e[o-1]??"",next:o};let c=Number.parseInt(a,s);return c>1114111||c>=55296&&c<=57343?{text:"\uFFFD",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function as(e,n=!1){return n?"limited":e.some(t=>t.code==="invalid-ansi-c-code-point"||t.code==="missing-heredoc-delimiter"||t.code==="ambiguous-heredoc-delimiter"||t.code==="unterminated-heredoc"||t.code==="unsupported-heredoc-context"||t.code==="unsupported-function-substitution"||t.code==="unsupported-backtick-escape"||t.code==="unclosed-parameter-expansion"||t.code==="unsupported-parameter-expansion"||t.code==="unsupported-blank")?"invalid":e.length>0?"partial":"complete"}function vi(e,n,t,s,r){let o=ki(e,n,t);return{text:s+e.slice(n,o),provenance:vn(r,"variable"),next:o}}function id(e,n,t){let s=ri(e),r=n,o=!1,i=!1,a=n;for(;a<t;){let l=e[a];if(l==="\\"&&!o){a+=2;continue}if(!i&&l==="'"){o=!o,a++;continue}if(!o&&l==='"'){i=!i,a++;continue}if(o){a++;continue}let c=e.startsWith("$((",a),u=e.startsWith("$(",a)&&!c,d=!i&&(e.startsWith("<(",a)||e.startsWith(">(",a)),p=l==="`";if(c||u||d||p){let f=c?3:p?1:2,h=c?"))":p?"`":")",g=vr(e,a+f,t,h),y=g===-1?t:g+h.length;s.push(r,a,"literal"),s.push(a,y,c?"arithmetic":"command-substitution"),a=y,r=y;continue}if(l==="$"){let f=ki(e,a,t);if(f>a+1){s.push(r,a,"literal"),s.push(a,f,"variable"),a=f,r=f;continue}}if(!i&&(l==="*"||l==="?"||l==="[")){s.push(r,a,"literal"),s.push(a,a+1,"glob"),a++,r=a;continue}a++}return s.push(r,t,"literal"),s.parts}function vn(e,n){return n==="command-substitution"||e==="command-substitution"?"command-substitution":n==="arithmetic"||e==="arithmetic"?"arithmetic":n==="variable"||e==="variable"?"variable":n==="glob"||e==="glob"?"glob":e}function ad(e,n,t){return n+1>=t||$n(e[n+1]??"")||is(e,n+1)!==null}var ld=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),cd=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]),ci=new WeakSet,ui=256;function ud(e){if(ci.has(e))return!1;let n=0;for(;n<=e.length;){for(;/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[n]?.text??"");)n++;if(n===e.length)return!0;let t=dd(e,n);if((t===void 0||t===null&&e[n]?.text.toLowerCase()==="command")&&ci.add(e),t==null)return!1;n=t}return!1}function dd(e,n){let t=e[n]?.text.toLowerCase();if(t==="command")return fd(e,n);if(t==="env")return pd(e,n);if(t==="sudo")return hd(e,n)}function fd(e,n){if(e[n+1]?.text==="-v")return null;for(let t=n+1;t<e.length;t++){let s=e[t]?.text??"";if(s==="--")return t+1;if(!(s==="-p"||s==="-v"||s==="-V"||/^-[pvV]+$/.test(s)))return t}return e.length}function pd(e,n){for(let t=n+1;t<e.length;t++){let s=e[t]?.text??"";if(s==="--")return t+1;if(ld.has(s)){if(e[t+1]===void 0)return null;t++;continue}if(!(s.startsWith("-u=")||s.startsWith("--unset=")||s.startsWith("-C")&&s.length>2||s.startsWith("--chdir=")||s.startsWith("-S")&&s.length>2||s.startsWith("--split-string=")||s.startsWith("-P"))&&!(s.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(s)))return t}return e.length}function hd(e,n){for(let t=n+1;t<e.length;t++){let s=e[t]?.text??"";if(s==="--")return t+1;if(cd.has(s)){if(e[t+1]===void 0)return null;t++;continue}if(!s.startsWith("-"))return t}return e.length}function gd(e,n,t,s,r){if(n.provenance!=="literal"||!n.raw.includes("{"))return;let o=md(n.raw,t,s,r,!1);if(!o)return;if("limited"in o)return o.limited==="expansions"?{limitCode:"depth-limit"}:{limitCode:o.limited==="length"?"brace-expansion-limit":"word-limit"};let i=o.values.map(a=>kd(a,s));if(!i.some(a=>a===null))return{words:i.filter(a=>a!==null&&a!=="").map(a=>ns(e,n.span.start,n.span.end,a,"literal",!1))}}function md(e,n,t,s,r){let o=[e],i=e.length,a=0;for(;;){let l=o.findIndex(f=>di(f,r));if(l===-1)break;if(++a>t)return{limited:"expansions"};let c=o[l]??"",u=di(c,r);if(!u||u.kind==="range")return{limited:"expansions"};let d=u.start+c.length-u.end,p=u.alternatives.reduce((f,h)=>f+d+h.length,0);if(i-c.length+p>s)return{limited:"length"};if(o.length-1+u.alternatives.length>n)return{limited:"words"};o.splice(l,1,...yd(c,u)),i+=p-c.length}return a===0?void 0:{values:o}}function di(e,n){let t=[],s,r=null,o=!1;for(let i=0;i<e.length;i++){let a=e[i];if(o){o=!1;continue}if(a==="\\"&&r!=="'"){o=!0;continue}if(a===r){r=null;continue}if(r===null&&(a==="'"||a==='"')){r=a;continue}if(r!==null)continue;if(a==="{"){t.push({start:i,commas:[]});continue}if(a===","&&t.length>0){t.at(-1)?.commas.push(i);continue}if(a!=="}"||t.length===0)continue;let l=t.pop();if(!l)continue;let c=l.commas.length>0?{kind:"alternatives",start:l.start,end:i+1,commas:l.commas}:n&&wd(e.slice(l.start+1,i))?{kind:"range",start:l.start,end:i+1}:void 0;c&&(!s||c.start<s.start)&&(s=c)}return!s||s.kind==="range"?s:{kind:s.kind,start:s.start,end:s.end,alternatives:bd(e,s)}}function yd(e,n){return n.alternatives.map(t=>`${e.slice(0,n.start)}${t}${e.slice(n.end)}`)}function bd(e,n){let t=[n.start,...n.commas,n.end-1];return t.slice(0,-1).map((s,r)=>e.slice(s+1,t[r+1]))}function wd(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function kd(e,n){let t=`x${e}`,s=yr(t,0,t.length,{maxInputLength:t.length,maxWords:1,maxDepth:n},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);return s.limited||s.issues.length>0||s.next!==t.length||s.word.provenance!=="literal"?null:s.word.text.slice(1)}function vd(e,n,t,s){return{kind:"program",dialect:"posix",source:e.slice(n,t),span:{start:n,end:t},status:"limited",issues:[{code:s,message:"command structure exceeds parser limit"}],nodes:[]}}function Et(e,n,t,s,r){return{nodes:e,issues:[...n,{code:s,message:`command structure exceeds parser limit ${r}`}],next:t,closed:!1,limited:!0,pendingHeredocs:[]}}function rs(e,n,t){return{nodes:e,issues:n,next:t,closed:!1,limited:!0,pendingHeredocs:[]}}function gr(e){return e.wordsUsed++,e.wordsUsed<=e.maxWords}function $d(e,n,t){let s=e.slice(n,t),r=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(s)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(s),o=r?.[1];if(!(!r||!o))return{name:o,braceIndex:n+r[0].lastIndexOf("{")}}function _n(e){return e.some(n=>n.kind==="command"?n.redirections.some(t=>t.heredoc)||n.nested.some(t=>_n(t.nodes)):(n.kind==="group"||n.kind==="function")&&_n(n.body.nodes))}function _d(e){return e.map(n=>({code:"unterminated-heredoc",message:`heredoc delimiter ${n.delimiter} was not found`}))}function $i(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function fi(e,n){let t=e.at(-1);t?.kind!=="connector"||!pi.has(t.operator)||n.push({code:"missing-command-after-connector",message:`connector ${t.operator} requires a following command`})}function _i(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&Vu.has(e.text)}function mr(e,n){let t=e.at(-1);$i(t)&&(t?.kind==="command"&&_i(t.words[0])||n.push({code:"missing-command-connector",message:"adjacent commands require a connector"}))}function xd(e,n,t){return n===t||/[\s;&|()]/u.test(e[n-1]??"")}import{createRequire as Sd}from"module";var Sn,Cd="Anvil's PowerShell reader (claude-powershell.cjs) is missing or won't load";function xi(){if(Sn===void 0){Sn=null;let e=Sd(import.meta.url);for(let n of["./claude-powershell.cjs","../claude-powershell.cjs"])try{let t=e(n);if(typeof t.readPowerShell=="function"&&typeof t.readCmd=="function"){Sn=t;break}}catch{}}if(Sn===null)throw new Error(Cd);return Sn}function Bt(e,n){return xi().readPowerShell(e,n)}function Si(e,n){return xi().readCmd(e,n)}import{posix as Ai}from"path";var Ad=null;function H(){return Ad??process.platform==="win32"}var Ci=/^([A-Za-z]):(.*)$/s,Ed=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function $r(e,n){let t=Ai.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function Vt(e,n){return e.split("/").map(t=>{if(t===""||t==="."||t===".."||/[\u0000\u0001]/.test(t))return t;let s=t.indexOf(":"),r=s>=0?t.slice(0,s):t,o=n?r:r.replace(/[. ]+$/,"");return o===""?".":o}).join("/")}function We(e){if(!H())return e;let n=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),t=!1,s=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(n);if(s){let l=s[2];if(s[1]===".")return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(l))n=`\\\\${l.slice(4)}`;else if(Ci.test(l))n=l;else return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;t=!0}n=n.replace(/\\/g,"/");let r=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(n);if(r){let l=`/unc/${Vt(r[1],t).toLowerCase()}${r[2]?`/${Vt(r[2],t).toLowerCase()}`:""}`;return $r(l,Vt(r[3]??"",t).toLowerCase())}let o=Ci.exec(n);if(o){let l=o[2];return l===""?`/${o[1].toLowerCase()}`:l.startsWith("/")?$r(`/${o[1].toLowerCase()}`,Vt(l,t).toLowerCase()):null}let i=Ed.exec(n);if(i)return $r(`/${i[1].toLowerCase()}`,Vt(i[2]??"",t).toLowerCase());let a=Vt(n,t).toLowerCase();if(a.startsWith("/")){let l=Ai.normalize(a);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return a}function Ne(e){return We(e)??e}function ls(e){return H()&&/^\/dev\/(?:nul|con|conin\$|conout\$|(?:pipe|mailslot)\/.+)$/.test(e)}function Ei(e){return/^\/[a-z]$/.test(e)||/^\/unc\/[^/]+(?:\/[^/]+)?$/.test(e)}function Ye(e){if(!H())return e;let n=/^\/([a-z])(\/.*)?$/s.exec(e);if(n)return`${n[1].toUpperCase()}:${(n[2]??"/").replace(/\//g,"\\")}`;let t=/^\/unc\/(.+)$/s.exec(e);return t?`\\\\${t[1].replace(/\//g,"\\")}`:null}function Zt(e){return H()?Ye(e)??e:e}function cs(e){return H()?Ye(e)??e:e}var _r=["windows","windows/system32","windows/syswow64","program files","program files (x86)","programdata","users","recovery","boot","perflogs","system volume information","$recycle.bin","documents and settings"],xr=new Set(["desktop","documents","downloads","pictures","music","videos","favorites","contacts","links","saved games","searches","onedrive","appdata","3d objects","source",".ssh",".gnupg",".aws",".azure",".config",".claude",".local",".kube",".docker"]);function ie(e){return Object.assign(Object.create(null),e)}var ae="\0",le="",Rd=/\brailway\s+(variables|variable|vars)\b|\bheroku\s+config\b|\bdoppler\s+secrets\b|\bop\s+read\b|\baws\s+secretsmanager\b|\bgcloud\s+secrets\b|\bvault\s+(kv\s+get|read)\b/,je="\0$OLDPWD",Er=8,Od=32,Pd=8,jd=16,Wd=64,Kt=new Set(["bash","sh","zsh","dash","ksh","fish","ash","csh","tcsh","mksh","yash"]);function gs(e,n,t){for(let s=0;e.deferred.length>0;s++){if(s>=Od){e.bodyRead||(e.depthLimit.hit=!0),e.deferred.length=0;break}let r=e.deferred.shift();fe(r.code,{...e,vars:new Map(e.vars),cwd:je,depth:e.depth+1,via:"shell-string",captured:!1,frames:[],outerGuards:r.parent.guards,andGuards:[],parent:r.parent,errexit:r.errexit},n,t)}}var Nd=new Set([":",".","eval","exec","exit","export","readonly","return","set","shift","trap","unset","break","continue","times"]),Ri=new Set(["sh","dash","ksh","ash","mksh","yash"]),Mi=new Set(["do","then","else","elif","if","while","until","!","{","(","time"]),Td=new Set(["done","fi","esac","}",")","in","case",";;"]),Ld=new Set(["sudo","doas","pkexec","run0","env","nohup","time","nice","ionice","timeout","gtimeout","command","builtin","exec","caffeinate","stdbuf","unbuffer","chronic","script","npx","pnpx","bunx","uv","uvx","pipx","busybox","bundle","poetry","pdm","rye","op","doppler","infisical","dotenvx","dotenv","sshpass","aws-vault","cross-env"]),Id=new Set(["npx","pnpx","bunx","uv","uvx","pipx"]),Dd=ie({"eas-cli":"eas","expo-cli":"expo","@expo/cli":"expo","netlify-cli":"netlify","firebase-tools":"firebase","@railway/cli":"railway",localtunnel:"lt","@anthropic-ai/claude-code":"claude","@useanvil/sdk":"anvil","@useanvil/claude-code":"anvil-claude","@openai/codex":"codex","@google/gemini-cli":"gemini","appcenter-cli":"appcenter","snowflake-cli":"snow","snowflake-cli-labs":"snow","databricks-cli":"databricks","@ngrok/ngrok":"ngrok","@capgo/cli":"capgo","@smithery/cli":"smithery","@github/copilot":"copilot","@qwen-code/qwen-code":"qwen","chrome-webstore-upload-cli":"chrome-webstore-upload"});function ms(e){let n=new Set(["-w","--workspace","--filter","-F","-C","--dir","--prefix","--cwd","--recursive-filter"]),t=1;for(;t<e.length&&e[t].startsWith("-");)t+=n.has(e[t])?2:1;return e[0]!==void 0&&/(^|\/)yarn$/.test(e[0])&&e[t]==="workspace"&&(t+=2),{sub:e[t]??"",at:t}}function Oi(e){let n=/^((?:@[^/@\s]+\/)?[^@\s=/]+)(?:@[^\s/]*|==[^\s]*)$/.exec(e),t=n?n[1]:e;return Dd[t]??t}var Fd=new Set(["python","python3","node","ruby","perl","php","bun","deno","tsx","ts-node"]);function fe(e,n,t,s){let r=wr(e,fr);r.status==="limited"&&!n.bodyRead&&(n.depthLimit.hit=!0),Pt(r,n,t,s)}function ut(e,n){let t=[],s=wr(e,fr),r={vars:new Map,functions:new Map,called:new Set,cwd:n.cwd,depth:0,via:"top",remote:null,productionEnv:!1,captured:!1,frames:[],outerGuards:[],andGuards:[],cds:[],cdpath:!1,errexit:!1,ifs:null,posixOnly:!1,maybeRuns:!1,partial:s.status!=="complete",subshell:!1,inFunction:!1,newProcess:!1,deferred:[],locals:new Set,files:new Map(Object.entries(n.knownFiles??{})),loopBudget:{left:Wd},depthLimit:{hit:!1},parent:null,oldCwd:je,dirStack:[]};Pt(s,r,n,t);for(let[o,i]of r.functions)r.called.has(o)||Pt(i,{...r,vars:new Map(r.vars),depth:1,via:"shell-string",captured:!1,frames:[],andGuards:[]},n,t);return gs(r,n,t),{commands:t,status:r.depthLimit.hit?"limited":s.status}}function Qe(e){let n=[...e.outerGuards];for(let t of e.frames)t.phase!=="body"||t.negate||(t.kind==="case"?n.push(`case ${t.word??""} in ${t.pattern??""}`):n.push(...t.cond));return[...n,...e.andGuards]}var Rr=class{passed=[];joiner=null;open=!1;text=null;exits=!1;beforeOr=[];orExits=!1;runPassed=[];get afterOr(){return this.joiner==="||"}get joined(){return this.joiner!==null}start(){this.close(),this.runPassed=this.joiner==="&&"?this.passed:[],this.open=!0,this.text=null,this.exits=!1}set(n,t=!1){this.text=n,this.exits=t}extend(n){this.text=this.text!==null&&n!==null?`${this.text} | ${n}`:null,this.exits=!1}join(n){this.close(),n==="||"&&(this.beforeOr=this.passed),this.joiner=n}end(){this.close();let n={passed:this.passed,past:this.orExits?this.beforeOr:[],lone:this.elements===1&&this.lastText!==null&&!this.lastText.startsWith("! ")?this.lastText:null};return this.passed=[],this.beforeOr=[],this.orExits=!1,this.elements=0,this.joiner=null,n}elements=0;lastText=null;close(){if(!this.open)return;let n=this.text;this.elements++,this.lastText=n,this.joiner==="&&"?(n!==null&&(this.passed=[...this.passed,n]),this.orExits=!1):this.joiner==="||"?(this.passed=[],this.orExits=this.exits):(this.passed=n===null?[]:[n],this.orExits=!1),this.open=!1,this.joiner=null}};function zd(e){return e!==null&&(e.name==="exit"||e.name==="return")&&e.wrappers.length===0&&e.argv.length<=2&&e.via!=="xargs"}function Md(e){for(let n of e.words){if(n.provenance!=="literal"||n.quoted||!Mi.has(n.text))return!1;if(n.text==="!")return!0}return!1}function ct(e,n){for(let t=e.frames.length-1;t>=0;t--)if(e.frames[t].kind===n)return e.frames[t]}function fs(e,n){for(let t=e.frames.length-1;t>=0;t--)if(e.frames[t].kind===n){e.closed=e.frames[t],e.frames.splice(t,1);return}}function Ui(e){let n=[];for(let t=e;t&&n.length<8;t=t.pipeFrom)n.push(t.text);return n.reverse().join(" | ")}function Ud(e,n,t,s){let r=e[n];if(r.kind!=="command")return null;let o=r.words;if(!o[0]||o[0].text!=="for"||o[0].provenance!=="literal"||o[0].quoted)return null;let i=o[1]?.text,a=o.findIndex(_=>_.text==="in"&&_.provenance==="literal"),l=a>0?o.slice(a+1):[],c=l.length===1&&l[0].provenance==="command-substitution"?/^\$\(\s*(?:echo|printf)\s+([\w./ -]+?)\s*\)$/.exec(l[0].raw)?.[1]:void 0,u=_=>_.provenance==="literal"||_.provenance==="glob",d=_=>u(_)||/^"[^"`]*"$/.test(_.raw)&&!/\$\{?[@*]|\[[@*]\]/.test(_.raw)&&!C(Ee(_,t,s).text);if(!i||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)||l.length===0||!c&&!l.every(d))return null;let p=-1,f=0,h=-1;for(let _=n+1;_<e.length;_++){let k=e[_];if(k.kind!=="command")continue;let P=k.words[0];if(!(!P||P.provenance!=="literal"||P.quoted)){if(p<0){if(P.text==="do"&&k.words.length===1)p=_;else if(P.text!=="do")return null;continue}if(["for","while","until","select"].includes(P.text)&&f++,P.text==="done"){if(f===0){h=_;break}f--}}}if(p<0||h<0)return null;let g=c?c.split(/\s+/).filter(Boolean):l.map(_=>u(_)?_.text:Ee(_,t,s).text),y=Gi(t,Ki(l.map(_=>_.raw).join(" "))),$=g.map((_,k)=>{let P=l[k];return y.length===0||c||!P||u(P)?[]:[...new Set(y.map(S=>Ee(P,{...t,vars:S},s).text))].filter(S=>S!==_)}),E=Math.min(g.length,jd,t.loopBudget.left);return E<=0?null:(t.loopBudget.left-=E,{name:i,values:g.slice(0,E),alts:$.slice(0,E),truncated:E<g.length,body:e.slice(p+1,h),end:h})}function qd(e,n){let t=0;for(let s=n;s<e.length;s++){let r=e[s];if(r.kind!=="command")continue;let o=r.words[0];if(!(!o||o.provenance!=="literal"||o.quoted)&&(["while","until","for","select"].includes(o.text)&&t++,o.text==="done")){if(t>0){t--;continue}let i=r.redirections.find(c=>(c.operator==="<"||c.operator==="<<<")&&c.target);if(!i||!i.target)return null;let a=i.target.raw.replace(/^"|"$/g,""),l=/^(?:<\(|\$\()([\s\S]*)\)$/.exec(a);return l?l[1]:i.operator==="<"?`cat ${a}`:a}}return null}function Pi(e,n,t,s,r){let o=e.words,i=0;for(;i<o.length&&o[i].provenance==="literal"&&!o[i].quoted;){let a=o[i].text;if(a==="if")n.frames.push({kind:"if",phase:"cond",cond:[],negate:!1});else if(a==="while"||a==="until")n.frames.push({kind:"loop",phase:"cond",cond:[],negate:a==="until",input:r?Ui(r):qd(t,s+1)});else if(a==="then"){let l=ct(n,"if");l&&(l.phase="body")}else if(a==="elif"){let l=ct(n,"if");l&&Object.assign(l,{phase:"cond",cond:[],negate:!1})}else if(a==="else"){let l=ct(n,"if");l&&(l.phase="else")}else if(a==="fi")fs(n,"if");else if(a==="do"){let l=ct(n,"loop");l&&(l.phase="body")}else if(a==="done")fs(n,"loop");else if(a==="esac")fs(n,"case");else if(a==="!"&&n.frames.length&&n.frames[n.frames.length-1].phase==="cond")n.frames[n.frames.length-1].negate=!0;else if(!["{","}","(",")","time"].includes(a))break;i++}return i>0&&i===o.length}var us=new WeakMap;function Pt(e,n,t,s){if(n.depth>Er){n.bodyRead||(n.depthLimit.hit=!0);return}let r=null,o=[],i=!1,a=n.andGuards,l=n.maybeRuns,c=n.subshell,u=new Rr,d=[],p=S=>S.length<=n.frames.length&&S.every(([A,M],I)=>n.frames[I]===A&&A.phase===M),f=new Set,h=S=>{for(let A=S;A<n.frames.length;A++)f.add(n.frames[A])},g=()=>{u.start();let S=n.frames[n.frames.length-1];S&&S.phase==="cond"&&f.has(S)&&(S.cond=[])},y=()=>{n.andGuards=[...a,...d.filter(S=>p(S.at)).map(S=>S.text),...u.runPassed]},$=()=>{n.andGuards=a},E=0,_=!1,k=null,P=n.posixOnly?e.nodes:Hd(e.nodes);for(let S=0;S<P.length;S++){let A=P[S],M=_;_=!1;let I=k;k=null;for(let q of n.frames)us.has(q)||us.set(q,s.length);if(A.kind==="command"&&A.words.length===1&&A.words[0].text==="!"&&A.words[0].provenance==="literal"&&!A.words[0].quoted){let q=n.frames.length;Pi(A,n,P,S,null),h(q),_=!0;continue}if(A.kind==="connector"){if(i=A.operator==="|"||A.operator==="|&",A.operator==="&")for(let q of o)q.background=!0;if(!i)if(r=null,A.operator==="&&"||A.operator==="||")u.join(A.operator);else{let q=u.end(),B=n.frames[n.frames.length-1];B&&B.phase==="cond"&&f.has(B)&&(B.cond=[...q.passed]);let ge=n.frames.map(N=>[N,N.phase]),ne=n.frames.some(N=>N.phase==="cond"),Q=n.errexit&&!ne&&q.lone!==null?[q.lone]:[];A.operator!=="&"&&(d=[...d,...[...q.past,...Q].map(N=>({text:N,at:ge}))])}if(E=A.operator===";"?E+1:0,E>=2){let q=ct(n,"case");q&&Object.assign(q,{phase:"pattern",pattern:""})}continue}E=0;let D=ct(n,"case");if(A.kind!=="command"&&D&&D.phase==="pattern"){D.phase="body";continue}if(A.kind==="group"){let q=e.source.slice(A.span.start-e.span.start,A.span.end-e.span.start);if(q.startsWith("(("))for(let F of q.matchAll(/(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:[-+*\/%&|^]|<<|>>)?=(?!=)|(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:\+\+|--)|(?:\+\+|--)\s*([A-Za-z_][A-Za-z0-9_]*)/g))Je(n,F[1]??F[2]??F[3],{kind:"unknown"});i||g(),y();let B=A.style==="subshell"?{...n,vars:new Map(n.vars),functions:new Map(n.functions),outerGuards:Qe(n),frames:[],andGuards:[],deferred:[]}:n,ge=s.length,ne=P[S+1];B.maybeRuns=l||u.afterOr||i||ne?.kind==="connector"&&["|","|&","&"].includes(ne.operator),Pt(A.body,B,t,s),B!==n&&gs(B,t,s),B.maybeRuns=l,o=s.slice(ge);let Q=P[S+1];if(Q?.kind==="command"&&Q.words.length===0&&Q.redirections.some(Bd)){let F=new Set(o),ur=new Set(o.map(we=>we.parent)),dr=we=>{for(let Pe=we;Pe&&F.has(Pe);Pe=Pe.parent)if(Pe.captured||Pe.pipeTo!==null||Pe.redirects.some(K=>ds(K))||Ar.has(Pe))return!0;return!1};k=o.some(we=>we.name==="exec"&&we.redirects.some(Pe=>ds(Pe)))||Hi(A.body)?[]:o.filter(we=>!ur.has(we)&&!dr(we));for(let we of k)Ar.add(we)}else if(Q?.kind==="command"&&Q.words.length===0&&Q.redirections.some(ps)||Q?.kind==="connector"&&(Q.operator==="|"||Q.operator==="|&"))for(let F of o)Ar.add(F);let N=Q?.kind==="command"&&Q.words.length===0?Q.redirections.find(F=>(F.operator==="<"||F.operator==="<>")&&(F.fd===void 0||F.fd===0)&&F.target):void 0;N?.target&&Bi(o,Ee(N.target,n,t).text),$(),i?u.extend(null):u.set(null),r=null,i=!1;continue}if(A.kind==="function"){n.functions.set(A.name,A.body);let q=ys.get(n.functions)??new Set;ys.set(n.functions,q);let B=P[S+1],ge=i||B?.kind==="connector"&&["&","|","|&"].includes(B.operator);n.depth===0&&!n.subshell&&!n.maybeRuns&&!u.joined&&!ge&&n.frames.length===0&&Qe(n).length===0?q.add(A.name):q.delete(A.name),i||g(),u.set(null),r=null,i=!1;continue}if(A.kind!=="command")continue;let z=Ud(P,S,n,t);if(z){i||g(),y();let q=[...z.values.map(ne=>({kind:"value",value:ne})),...z.truncated?[{kind:"unknown"}]:[]],B=s.length;for(let[ne,Q]of q.entries())n.vars.set(z.name,Q),jr(Q,z.alts[ne]??[]),n.frames.push({kind:"loop",phase:"body",cond:[],negate:!1}),Pt({...e,nodes:z.body},{...n},t,s),fs(n,"loop");!z.truncated&&z.values.length>1&&n.vars.set(z.name,jr({kind:"value",value:z.values.at(-1)},[...z.values.slice(0,-1),...z.alts.flat()]));let ge=P[z.end];if(ge?.kind==="command"&&ge.words[0]?.text==="done"&&ge.redirections.some(ps)){let ne=s.slice(B).filter(Q=>!Q.captured&&Q.pipeTo===null&&!Q.redirects.some(N=>ds(N)));hs({...ge,words:[]},n,t,s,null,ne)}$(),u.set(null),S=z.end,r=null,i=!1;continue}let Z=A.words[0];if(Z&&Z.text==="case"&&Z.provenance==="literal"&&!Z.quoted){let q=A.words[1]?Ee(A.words[1],n,t).text:"",B=A.words.slice(3).map(Q=>Ee(Q,n,t).text).join(" "),ge=P[S+1],ne=ge?.kind==="connector"&&ge.operator==="|";n.frames.push({kind:"case",phase:B&&!ne?"body":"pattern",cond:[],negate:!1,word:q,pattern:B}),h(n.frames.length-1),B&&!ne&&ge&&ge.kind!=="command"&&S++,i||g(),u.set(null),r=null,i=!1;continue}if(D&&D.phase==="pattern"&&!(Z&&Z.text==="esac")){let q=A.words.map(B=>Ee(B,n,t).text).join(" ");D.pattern=D.pattern?`${D.pattern}|${q}`:q,i=!1,r=null;continue}let J=n.frames.length;n.closed=null;let ue=Pi(A,n,P,S,i?r:null);if(h(J),ue){let q=n.closed,B=q?s.slice(us.get(q)??s.length):null;if(q&&A.redirections.some(ps)){let ge=s.slice(us.get(q)??s.length).filter(ne=>!ne.captured&&ne.pipeTo===null&&!ne.redirects.some(Q=>ds(Q)));hs({...A,words:[]},n,t,s,null,ge)}i||g(),u.set(null),i=!1,r=null,B&&(o=B);continue}i||g(),y();let X=n.frames.length,ze=P[S+1],Oe=i||ze?.kind==="connector"&&["|","|&","&"].includes(ze.operator);n.maybeRuns=l||u.afterOr||Oe,n.subshell=c||Oe;let G=hs(A,n,t,s,i?r:null,I);n.maybeRuns=l,n.subshell=c,h(X),$();let Ke=M||Md(A),Me=G?`${Ke?"! ":""}${En(G)}`:null;i?u.extend(Me):u.set(Me,!Ke&&zd(G)),r=G??r,o=G?[G]:[],i=!1}}function qi(e,n,t){let s=new Set;for(let r of e.cds){let o=r.to===null?s.size>0?[je]:[]:"abs"in r.to?[]:[...s].map(i=>U(r.to.rel,i,t));s=new Set(n.includes(r.text)?o:[r.before,...s,...o]);for(let i of r.extra??[])s.add(i);s.size>8&&(s=new Set([je]))}return s.delete(e.cwd),[...s]}function Sr(e,n,t){if(!n.subshell)for(let[s,r]of e.vars){if(/^([0-9]+|[@*#])$/.test(s)||e.locals.has(s)||t.get(s)===r)continue;let o={...r},i=n.vars.get(s)??null;n.vars.set(s,o),Xe.set(o,{at:n.frames.map(a=>[a,a.phase]),guards:Qe(n),maybe:!0,prev:i})}}function Cr(e,n){n.cwd=e.cwd,n.oldCwd=e.oldCwd,n.dirStack=e.dirStack,n.cds=e.cds,n.cdpath=e.cdpath}function Hd(e){let n=[];for(let t=0;t<e.length;t++){let s=e[t],r=e[t+1],o=e[t+2],i=s.kind==="command"&&["done","fi","esac"].includes(s.words[0]?.text??"");if((s.kind==="command"||s.kind==="group")&&!i&&r?.kind==="connector"&&r.operator==="&"&&o?.kind==="command"&&o.words.length===0&&r.span.end===o.span.start&&o.source.startsWith(">")){s.kind==="command"?n.push({...s,source:`${s.source} &${o.source}`,redirections:[...s.redirections,...o.redirections]}):n.push(s,o),t+=2;continue}n.push(s)}return n}function ps(e){return e.fd===1||e.fd===void 0&&[">",">>",">|",">&"].includes(e.operator)}function Hi(e){return e.nodes.some(n=>n.kind==="command"&&["done","fi","esac"].includes(n.words[0]?.text??"")&&n.redirections.some(ps)||n.kind==="group"&&Hi(n.body))}function Bi(e,n){for(let t of e)t.stdinFile===null&&t.stdin===null&&t.pipeFrom===null&&!t.captured&&(t.stdinFile=n)}function Bd(e){return(e.operator===">"||e.operator===">>"||e.operator===">|")&&(e.fd===void 0||e.fd===1)}function ds(e){return e.fd===1||e.fd===null&&(e.op===">"||e.op===">>"||e.op===">|"||e.op===">&")}var Ar=new WeakSet;function En(e){return e.argv.map(v).join(" ")}function hs(e,n,t,s,r,o=null){for(let b of e.nested){let x={...n,vars:new Map(n.vars),depth:n.depth+1,via:"substitution",captured:!0,frames:[],outerGuards:Qe(n),andGuards:[],errexit:!1,deferred:[]};Pt(b,x,t,s),gs(x,t,s)}let i=[...e.words];for(;i.length&&Mi.has(i[0].text)&&i[0].provenance==="literal"&&!i[0].quoted;)i.shift();if(i.length&&Td.has(i[0].text)&&i.length===1)return null;if(i[0]?.text==="for"||i[0]?.text==="select"){n.frames.push({kind:"loop",phase:"header",cond:[],negate:!1});let b=i[1]?.text,x=i.slice(i.findIndex(W=>W.text==="in")+1);b&&n.vars.set(b,x.length>0&&i.some(W=>W.text==="in")&&x.some(W=>W.provenance==="command-substitution")?{kind:"value",value:`${ae}${x.map(W=>Nr(W.raw,n,t)).join(" ")}${le}`}:x.length>0&&x.every(W=>W.provenance==="literal"||W.provenance==="glob")?{kind:"list",values:x.map(W=>W.text)}:{kind:"unknown"});let O=i.findIndex((W,T)=>T>1&&W.text==="do"&&W.provenance==="literal"&&!W.quoted);if(O>0&&O<i.length-1){let W=ct(n,"loop");return W&&(W.phase="body"),hs({...e,words:i.slice(O+1)},n,t,s,null)}return null}let a=i.findIndex(b=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(b.raw)&&b.text!=="command"&&b.text!=="builtin");if(a>0&&["read","mapfile","readarray"].includes(i[a].text)&&(i=[...i.slice(a)]),(i[0]?.text==="mapfile"||i[0]?.text==="readarray")&&i[0].provenance==="literal"){let b=i.slice(1).filter((x,O,W)=>!x.text.startsWith("-")&&!["-d","-n","-O","-s","-u","-C","-c"].includes(W[O-1]?.text??"")).pop()?.text??"MAPFILE";/^[A-Za-z_][A-Za-z0-9_]*$/.test(b)&&Je(n,b,{kind:"unknown"})}if(i[0]?.text==="read"&&i[0].provenance==="literal"){let b=ct(n,"loop"),x=b&&b.phase==="cond"?b.input??null:null,O=e.redirections.find(ee=>ee.operator==="<"&&ee.target),W=e.redirections.find(ee=>ee.operator==="<<<"&&ee.target),T=r?Ui(r):O?.target?`cat ${Ee(O.target,n,t).text}`:W?.target?v(Ee(W.target,n,t).text):x,V=new Set(["-p","-d","-n","-N","-t","-u","-i"]);for(let ee=1;ee<i.length;ee++){let se=i[ee].text;if(V.has(se)){ee++;continue}se==="-a"||se.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*$/.test(se)&&n.vars.set(se,T?{kind:"value",value:`${ae}$(${T})${le}`}:{kind:"unknown"})}}let l=0,c=[],u=new Set;for(;l<i.length&&/^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(i[l].raw);){let b=i[l],x=b.raw.indexOf("=");b.raw[x-1]==="+"&&u.add(b),c.push([b.raw.slice(0,b.raw[x-1]==="+"?x-1:x),b]),l++}let d=i[l];if(d?.text==="getopts"&&i[l+2]&&Je(n,i[l+2].text,{kind:"unknown"}),d?.text==="let"||d?.raw.startsWith("(("))for(let b of i.slice(l))for(let x of b.raw.matchAll(/(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:[-+*\/%&|^]|<<|>>)?=(?!=)|(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:\+\+|--)|(?:\+\+|--)\s*([A-Za-z_][A-Za-z0-9_]*)/g))Je(n,x[1]??x[2]??x[3],{kind:"unknown"});let p=i.slice(l);if(p.length&&["export","local","declare","readonly","typeset"].includes(p[0].text)){let b=p[0].text,x=p.slice(1).filter(T=>T.text.startsWith("-")).map(T=>T.text),O=n.inFunction&&(b==="local"||(b==="declare"||b==="typeset")&&!x.some(T=>T.includes("g"))),W=x.some(T=>/^-[a-zA-Z]*n/.test(T));for(let T of p.slice(1)){let V=/^([A-Za-z_][A-Za-z0-9_]*)(=|$)/.exec(T.text);V&&(O&&n.locals.add(V[1]),W?Je(n,V[1],{kind:"unknown"}):V[2]==="="&&c.push([V[1],T]))}p=[]}let f=n.productionEnv,h=[];for(let[b,x]of c){let O=uf(x,b,n,t),W=n.vars.get(b),T=u.has(x)?W?.kind==="value"&&O.kind==="value"?{kind:"value",value:W.value+O.value}:{kind:"unknown"}:O;if(p.length>0){T.production&&(f=!0),h.push([b,T]);continue}Je(n,b,T),b==="OLDPWD"&&p.length===0&&(n.oldCwd=T.kind==="value"&&!C(T.value)?T.value:je),b==="CDPATH"&&p.length===0&&(n.cdpath=!(T.kind==="value"&&T.value==="")),b==="IFS"&&p.length===0&&(n.ifs=T.kind==="value"&&T.value!==""&&!C(T.value)?T.value:null)}if(p.length===0&&c.length===0&&e.redirections.length>0&&(p=[{kind:"word",text:":",raw:":",span:e.span,provenance:"literal",quoted:!1,parts:[]}]),p.length===0)return null;let g=p.map(b=>Ee(b,n,t)),y=n.ifs??`
|
|
19
|
-
`,$=new RegExp(`[${y.replace(/[\]\\^-]/g,"\\$&")}]+`),E=(
|
|
20
|
-
`);for(let
|
|
21
|
-
`)):
|
|
22
|
-
`):
|
|
23
|
-
`)}if(e.name==="base64"&&e.argv.some(
|
|
24
|
-
`):null}function
|
|
25
|
-
`||o==="\r"){r++;continue}o==="|"&&
|
|
1
|
+
import{posix as Et}from"path";import Wk from"vm";import{isMainThread as ed,parentPort as pr,workerData as kn}from"worker_threads";import{createHash as Yl}from"crypto";import{posix as R}from"path";function rd(e){return(typeof e=="string"?e:"").trim().replace(/\/+$/,"")}function fi(e){try{let t=new URL(rd(e)).hostname.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}import{posix as xe}from"path";import{posix as En}from"path";var yr=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});function pi(){return{words:[],redirections:[],nested:[],start:-1,end:-1,reset(){this.words=[],this.redirections=[],this.nested=[],this.start=-1,this.end=-1}}}function hi(e,t,n){e.push(n),t.reset()}function gi(e){let t=[];return{parts:t,push:(n,s,r)=>{s<=n||t.push({raw:e.slice(n,s),span:{start:n,end:s},provenance:r})}}}function od(e){let t=e.parts??[{raw:e.raw,span:e.span,provenance:e.provenance}];return{kind:"word",...e,parts:t}}function ss(e,t,n,s,r,o,a){return od({text:s,raw:e.slice(t,n),span:{start:t,end:n},provenance:r,quoted:o,...a?{parts:a}:{}})}function br(e,t,n){if(t>=n||yi(e[t]??""))return null;let s="",r=!1,o=!1,a=t;for(;a<n&&!yi(e[a]??"");){let i=e[a]??"";if(i==="'"){r=!0;let l=mi(e,a+1,n,"'");s+=l.text,o||=!l.closed,a=l.next;continue}if(i==='"'){r=!0;let l=mi(e,a+1,n,'"');s+=l.text,o||=!l.closed,a=l.next;continue}if(i==="\\"){r=!0;let l=e[a+1];if(!l||l===`
|
|
2
|
+
`||l==="\r"){o=!0;break}s+=l,a+=2;continue}(i==="`"||e.startsWith("$(",a)||e.startsWith("${",a)||e.startsWith("<(",a)||e.startsWith(">(",a))&&(o=!0),s+=i,a++}return{delimiter:s,quoted:r,next:a,ambiguous:o}}function wr(e,t,n,s){let r=[],o=t;for(let a of s){let i=o,l=!1;for(;o<n;){let c=id(e,o,n);if((a.stripTabs?c.text.replace(/^\t+/,""):c.text)===a.delimiter){a.attach({body:a.stripTabs?ad(e.slice(i,o)):e.slice(i,o),delimiter:a.delimiter,quotedDelimiter:a.quotedDelimiter,bodySpan:{start:i,end:o},terminatorSpan:{start:o,end:c.contentEnd}}),o=c.next,l=!0;break}if(c.next<=o)break;o=c.next}if(!l)return r.push({code:"unterminated-heredoc",message:`heredoc delimiter ${a.delimiter} was not found`}),{next:n,issues:r,terminated:!1}}return{next:o,issues:r,terminated:!0}}function mi(e,t,n,s){let r="",o=t;for(;o<n&&e[o]!==`
|
|
3
|
+
`&&e[o]!=="\r";){let a=e[o]??"";if(a===s)return{text:r,next:o+1,closed:!0};if(s==='"'&&a==="\\"&&e[o+1]){let i=e[o+1]??"";r+=["$","`",'"',"\\"].includes(i)?i:`\\${i}`,o+=2;continue}r+=a,o++}return{text:r,next:o,closed:!1}}function yi(e){return e!=="\r"&&(/[\s;&|<>)]/u.test(e)||e==="`")}function id(e,t,n){let s=t;for(;s<n&&e[s]!==`
|
|
4
|
+
`;)s++;let r=s>=n?n:s+1;return{text:e.slice(t,s),contentEnd:s,next:r}}function ad(e){return e.replace(/(^|\r\n?|\n)\t+/g,"$1")}var _i=new Set(["&&","||","|","|&"]),ld=new Set(["!","do","elif","else","if","then","until","while"]);function _r(e,t){let n={start:0,end:e.length};if(e.length>t.maxInputLength)return{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 s={wordsUsed:0,maxWords:t.maxWords,quotedExpansionEnd:1/0},r=is(e,0,e.length,t,s,0),o=[...r.issues,...bd(e,s.quotedExpansionEnd,r.nodes)?[Ei]:[],...md.test(e)?[Ai]:[]];return{kind:"program",dialect:"posix",source:e,span:n,status:ls(o,r.limited),issues:o,nodes:r.nodes}}function is(e,t,n,s,r,o,a){let i=[],l=[],c=pi(),u=[],f=()=>{if(c.words.length===0&&c.redirections.length===0)return;let d={start:c.start,end:c.end},h=c.words.map(g=>g.text);hi(i,c,{kind:"command",dialect:"posix",source:e.slice(d.start,d.end),span:d,words:c.words,redirections:c.redirections,nested:c.nested,displayText:l.length>0&&i.length===0?e.slice(t,n):h.join(" ")})},p=t;for(;p<n;){let d=e[p];if(!d)break;if(a&&d===a)return f(),xi(i,l),{nodes:i,issues:l,next:p+1,closed:!0,limited:!1,pendingHeredocs:u};if(xn(d)){if(d.charCodeAt(0)>127&&l.push(Ai),d===`
|
|
5
|
+
`||d==="\r"){f();let C=d==="\r"&&e[p+1]===`
|
|
6
|
+
`?p+2:p+1,A=i.at(-1);if((A?.kind!=="connector"||!_i.has(A.operator))&&i.push({kind:"connector",operator:e.slice(p,C),span:{start:p,end:C}}),u.length>0){let U=wr(e,C,n,u.splice(0));l.push(...U.issues),p=U.next;continue}p=C;continue}p++;continue}if(d==="\\"&&e[p+1]===`
|
|
7
|
+
`){p+=2;continue}if(d==="#"){for(;p<n&&e[p]!==`
|
|
8
|
+
`&&e[p]!=="\r";)p++;continue}let h=c.start===-1?Dd(e,p,n):void 0;if(h){if(vr(i,l),o>=s.maxDepth)return Rt(i,l,p,"depth-limit",s.maxDepth);if(!kr(r))return Rt(i,l,p,"word-limit",s.maxWords);let C=is(e,h.braceIndex+1,n,s,r,o+1,"}"),A=C.next,U={start:h.braceIndex+1,end:C.closed?A-1:A},I=bi(e,U,C);if(i.push({kind:"function",name:h.name,span:{start:p,end:A},body:I}),l.push(...C.issues),(C.pendingHeredocs.length>0||_n(C.nodes))&&l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside function bodies are not supported safely"}),u.push(...C.pendingHeredocs),C.limited)return os(i,l,C.next);C.closed||l.push({code:"unclosed-function-body",message:"function body is not closed"}),p=A;continue}let g=as(e,p);if(g){f(),Wi(i.at(-1))||l.push({code:"unexpected-connector",message:`connector ${g} has no preceding command`}),i.push({kind:"connector",operator:g,span:{start:p,end:p+g.length}}),p+=g.length;continue}if(d===")"){f(),l.push({code:"unexpected-closing-delimiter",message:"closing parenthesis has no matching opening parenthesis"}),i.push({kind:"unknown",source:d,span:{start:p,end:p+1}}),p++;continue}if((d==="("||d==="{"&&xd(e,p,n))&&c.start===-1){if(vr(i,l),o>=s.maxDepth)return Rt(i,l,p,"depth-limit",s.maxDepth);let C=d==="("?")":"}",A=is(e,p+1,n,s,r,o+1,C),U=A.next,I={start:p+1,end:A.closed?U-1:U},D=bi(e,I,A);if(i.push({kind:"group",style:d==="("?"subshell":"brace",span:{start:p,end:U},body:D}),l.push(...A.issues),(A.pendingHeredocs.length>0||_n(A.nodes))&&l.push({code:"unsupported-heredoc-context",message:"heredocs attached inside command groups are not supported safely"}),u.push(...A.pendingHeredocs),A.limited)return os(i,l,A.next);A.closed||l.push({code:d==="("?"unclosed-subshell":"unclosed-brace-group",message:`${d} group is not closed`}),p=U;continue}let y=(d==="<"||d===">")&&e[p+1]!=="("?fd(e,p):null;if(y){let C=c.words.at(-1),A=C&&C.span.end===p&&/^[0-9]+$/.test(C.raw)?Number(C.raw):void 0;A!==void 0&&c.words.pop();let U=A===void 0?p:C?.span.start??p;c.start=c.start===-1?p:c.start;let I=p+y.length;for(;I<n&&/[ \t]/.test(e[I]??"");)I++;let D=e[I],z=I>p+y.length&&D==="#",B=!D||xn(D)||!!as(e,I)||D===a||D===")"||z||(D==="<"||D===">")&&e[I+1]!=="(",Q=y==="<<"||y==="<<-",ce=Q?br(e,I,n):void 0,te=ce?{word:ss(e,I,ce.next,ce.delimiter,"literal",ce.quoted),nested:[],issues:[],next:ce.next,limited:!1}:B?void 0:$r(e,I,n,s,r,o);if(te){if(l.push(...te.issues),te.limited)return os(i,l,te.next);if(!kr(r))return Rt(i,l,te.next,"word-limit",s.maxWords)}let ze=te?.next??p+y.length,Oe={kind:"redirection",operator:y,span:{start:U,end:ze},...A===void 0?{}:{fd:A},...te?{target:te.word}:{}};if(c.redirections.push(Oe),Q&&!ce&&l.push({code:"missing-heredoc-delimiter",message:"heredoc redirection requires a delimiter word"}),ce){(ce.ambiguous||ce.delimiter.length===0)&&l.push({code:"ambiguous-heredoc-delimiter",message:"heredoc delimiter cannot be determined safely"});let K=c.nested;u.push({delimiter:ce.delimiter,quotedDelimiter:ce.quoted,stripTabs:y==="<<-",attach:Ye=>{if(Oe.heredoc=Ye,Ye.quotedDelimiter)return;let Me=ud(e,Ye.bodySpan.start,Ye.bodySpan.end,s,r,o+1);K.push(...Me.programs),l.push(...Me.issues)}})}!Q&&!te&&l.push({code:"missing-redirection-target",message:`redirection ${y} requires a target word`}),te&&c.nested.push(...te.nested),c.end=ze,p=ze;continue}let $=c.start===-1;$&&vr(i,l);let E=$r(e,p,n,s,r,o);if(l.push(...E.issues),E.limited)return os(i,l,E.next);let x=Cd(c.words);if(x&&c.words.length>=vi)return Rt(i,l,E.next,"word-limit",vi);let b=x?jd(e,E.word,r.maxWords-r.wordsUsed,s.maxDepth,s.maxInputLength):void 0;if(b?.limitCode)return Rt(i,l,E.next,b.limitCode,b.limitCode==="word-limit"?s.maxWords:b.limitCode==="depth-limit"?s.maxDepth:s.maxInputLength);let j=b?.words??[E.word];for(let C of j){if(!kr(r))return Rt(i,l,E.next,"word-limit",s.maxWords);c.words.push(C)}c.start=c.start===-1?p:c.start,c.end=E.next,c.nested.push(...E.nested),$&&Ni(E.word)&&f(),p=E.next>p?E.next:p+1}return f(),xi(i,l),l.push(...Fd(u)),{nodes:i,issues:l,next:p,closed:a===void 0,limited:!1,pendingHeredocs:[]}}function bi(e,t,n){return{kind:"program",dialect:"posix",source:e.slice(t.start,t.end),span:t,status:ls(n.issues,n.limited),issues:n.issues,nodes:n.nodes}}function $r(e,t,n,s,r,o){let a="",i=t,l=!1,c="literal",u=[],f=[],p=!1;for(;i<n;){let d=e[i],h=(d==="<"||d===">")&&e[i+1]==="(";if(!d||xn(d)||(d===";"||d==="|"||d==="&")&&as(e,i)||(d==="<"||d===">")&&!h||d===")")break;if(d==="'"){l=!0;let $=e.indexOf("'",i+1);if($===-1||$>=n){a+=e.slice(i+1,n),f.push({code:"unclosed-single-quote",message:"single-quoted word is not closed"}),i=n;break}a+=e.slice(i+1,$),i=$+1;continue}if(d==='"'){l=!0;let $=cd(e,i,n,s,r,o);if(a+=$.text,u.push(...$.nested),f.push(...$.issues),p||=$.limited,c=$n(c,$.provenance),i=$.next,p)break;continue}if(e.startsWith("$'",i)){l=!0;let $=kd(e,i+2,n);a+=$.text,f.push(...$.issues),$.closed||f.push({code:"unclosed-ansi-c-quote",message:"ANSI-C quoted word is not closed"}),i=$.next;continue}if(d==="\\"){let $=e[i+1];if(!$){f.push({code:"trailing-escape",message:"escape has no following character"}),i++;break}if($===`
|
|
9
|
+
`){i+=2;continue}a+=$,i+=2;continue}jt(e,i)&&f.push(Ot);let g=d==="$"||d==="<"||d===">"||d==="`"?Sn(e,i,n,s,r,o):null,y=g?Sr(g,u,f):Ri(e,i,n,s,r,o,u,f);if(y){if(y.provenance==="variable"&&(a+=e.slice(i,y.next)),p||=y.limited,c=$n(c,y.provenance),i=y.next,p)break;continue}if(d==="$"){let $=Pi(e,i,n,a,c);a=$.text,c=$.provenance,i=$.next;continue}(d==="*"||d==="?"||d==="[")&&(c=$n(c,"glob")),a+=d,i++}return{word:ss(e,t,i,a,c,l,c==="literal"?void 0:$d(e,t,i)),nested:u,issues:f,next:i,limited:p}}function cd(e,t,n,s,r,o){let a="",i="literal",l=[],c=[],u=!1,f=t+1;for(;f<n;){let p=e[f];if(p==='"')return{text:a,provenance:i,nested:l,issues:c,next:f+1,limited:u};if(p==="\\"&&e[f+1]){let g=e[f+1]??"";if(g===`
|
|
10
|
+
`){f+=2;continue}if(g==="\r"&&e[f+2]===`
|
|
11
|
+
`){f+=3;continue}a+=["$","`",'"',"\\"].includes(g)?g:`\\${g}`,f+=2;continue}jt(e,f)&&c.push(Ot);let d=Sn(e,f,n,s,r,o),h=d?Sr(d,l,c):Ri(e,f,n,s,r,o,l,c);if(h){if(h.provenance!=="command-substitution"&&(a+=e.slice(f,h.next)),f=h.next,u||=h.limited,i=$n(i,h.provenance),u)return{text:a,provenance:i,nested:l,issues:c,next:f,limited:u};continue}if(p==="$"){let g=Pi(e,f,n,a,i);a=g.text,i=g.provenance,f=g.next;continue}a+=p??"",f++}return c.push({code:"unclosed-double-quote",message:"double-quoted word is not closed"}),{text:a,provenance:i,nested:l,issues:c,next:n,limited:u}}function Sn(e,t,n,s,r,o){let a=Ci(e,t);if(!a)return null;let i=a.length,l=a.closing,c=l==="))",u=l==="`",f=e[t]==="<"||e[t]===">",p=Cr(e,t+i,n,l),d=p===-1?n:p,h=p===-1?n:p+l.length;if(o>=s.maxDepth)return{program:Id(e,t+i,d,"depth-limit"),next:h,provenance:c?"arithmetic":"command-substitution"};if(c){let b=[],j=[],C=!1,A=t+i;for(;A<d;){let U=Sn(e,A,d,s,r,o+1);if(!U){jt(e,A)&&j.push(Ot),A++;continue}if(b.push(...U.program.nodes),j.push(...U.program.issues),C||=U.program.status==="limited",A=U.next,C)break}return p===-1&&j.push({code:"unclosed-arithmetic",message:"$(( substitution is not closed"}),{program:{kind:"program",dialect:"posix",source:e.slice(t+i,d),span:{start:t+i,end:d},status:ls(j,C),issues:j,nodes:b},next:h,provenance:"arithmetic"}}let g=is(e,t+i,d,s,r,o+1),y=p===-1?[{code:"unclosed-command-substitution",message:`${e.slice(t,t+i)} substitution is not closed`}]:[],$=(u||f)&&_n(g.nodes)?[{code:"unsupported-heredoc-context",message:"heredocs are supported only in ordinary commands and $(...) substitutions"}]:[],E=u&&/\\[\\$`\n]/.test(e.slice(t+i,d))?[wd]:[],x=[...g.issues,...y,...$,...E];return{program:{kind:"program",dialect:"posix",source:e.slice(t+i,d),span:{start:t+i,end:d},status:ls(x,g.limited),issues:x,nodes:g.nodes},next:h,provenance:"command-substitution"}}function ud(e,t,n,s,r,o){let a=[],i=[],l=t;for(;l<n;){let c=e[l];if(c==="\\"){l+=2;continue}let u=c==="$"||c==="`"?Sn(e,l,n,s,r,o):null;if(!u){jt(e,l)&&i.push(Ot),l++;continue}a.push(u.program),pd(e,l,u.next)&&hd(u.program)&&i.push(Ot),l=u.next}return{programs:a,issues:i}}function Sr(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 Cr(e,t,n,s){if(s==="`"){for(let i=t;i<n;i++){if(e[i]==="\\"){i++;continue}if(e[i]==="`")return i}return-1}let r={single:!1,double:!1},o=[],a=[];for(let i=t;i<n;i++){let l=e[i];if((l===`
|
|
12
|
+
`||l==="\r")&&a.length>0){let f=l==="\r"&&e[i+1]===`
|
|
13
|
+
`?i+2:i+1,p=wr(e,f,n,a.splice(0));if(!p.terminated)return-1;i=p.next-1;continue}let c=Si(e,i,t,n,r);if(c!==null){i=c;continue}if(!r.double&&e.startsWith("$((",i)){let f=dd(e,i+3,n);if(f===-1)return-1;i=f+1;continue}if(s===")"&&!r.double&&l==="<"&&e[i+1]==="<"&&e[i+2]!=="<"){let f=e[i+2]==="-",p=i+(f?3:2);for(;p<n&&/[ \t]/.test(e[p]??"");)p++;let d=br(e,p,n);if(d){a.push({delimiter:d.delimiter,quotedDelimiter:d.quoted,stripTabs:f,attach:()=>{}}),i=d.next-1;continue}}if(e.startsWith("$(",i)&&!e.startsWith("$((",i)){o.push(r),r={single:!1,double:!1},i++;continue}if(l==="("&&!r.double){o.push(r),r={single:!1,double:!1};continue}if(l!==")"||r.double)continue;let u=o.pop();if(u){r=u;continue}return s==="))"&&e[i+1]!==")"?-1:i}return-1}function dd(e,t,n){let s=1,r={single:!1,double:!1};for(let o=t;o<n;o++){let a=e[o],i=Si(e,o,t,n,r);if(i!==null){o=i;continue}if(e.startsWith("$(",o)&&!e.startsWith("$((",o)){s++,o++;continue}if(a==="("&&!r.double&&s++,!(a!==")"||r.double)&&(s--,s===0))return e[o+1]===")"?o:-1}return-1}function Si(e,t,n,s,r){let o=e[t];if(o==="\\"&&!r.single)return t+1;if(!r.double&&o==="'"&&(r.single=!r.single),!r.single&&o==='"'&&(r.double=!r.double),r.single)return t;if(r.double||o!=="#"||!zd(e,t,n))return null;let a=t;for(;a+1<s&&e[a+1]!==`
|
|
14
|
+
`&&e[a+1]!=="\r";)a++;return a}function as(e,t){let n=e[t];return n===";"?";":n==="&"?e[t+1]==="&"?"&&":"&":n==="|"?e[t+1]==="|"?"||":e[t+1]==="&"?"|&":"|":null}function fd(e,t){let n=e[t];return n===">"?e[t+1]===">"?">>":e[t+1]==="&"?">&":e[t+1]==="|"?">|":">":n!=="<"?null:e.startsWith("<<<",t)?"<<<":e.startsWith("<<-",t)?"<<-":e[t+1]==="<"?"<<":e[t+1]==="&"?"<&":e[t+1]===">"?"<>":"<"}function xn(e){let t=e.charCodeAt(0);return t===32||t>=9&&t<=13?!0:t<128?!1:/\s/u.test(e)}var Ot=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});function jt(e,t){if(e[t]!=="$")return!1;let n=wi(e,t+1);if(e[n]!=="{")return!1;let s=e[wi(e,n+1)]??"";return s==="|"||xn(s)}function pd(e,t,n){for(let s=e.indexOf("$",t);s!==-1&&s<n;s=e.indexOf("$",s+1))if(jt(e,s))return!0;return!1}function hd(e){return e?.status==="limited"||(e?.issues??[]).some(t=>t.code===Ot.code)}function wi(e,t){let n=t;for(;e.startsWith(`\\
|
|
15
|
+
`,n)||e.startsWith(`\\\r
|
|
16
|
+
`,n);)n+=e[n+1]==="\r"?3:2;return n}function Ci(e,t){return e.startsWith("$((",t)?{length:3,closing:"))"}:e.startsWith("$(",t)||e.startsWith("<(",t)||e.startsWith(">(",t)?{length:2,closing:")"}:e[t]==="`"?{length:1,closing:"`"}:null}var gd=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"}),md=/[\v\f\r]/,Ai=Object.freeze({code:"unsupported-blank",message:"a vertical tab, form feed, carriage return or Unicode space is part of a word in bash and zsh, not a separator"}),Ei=Object.freeze({code:"unsupported-parameter-expansion",message:"a line continuation inside ${ }, or a quote or backslash inside ${ } with a substitution in or after it, cannot be analyzed"}),yd=/\$\(|`|[<>]\(/g;function bd(e,t,n){let s=xr(n);return[...e.slice(t).matchAll(yd)].some(r=>{let o=t+r.index;return!s.some(a=>o>=a.start&&o<a.end)})}function xr(e){return e.flatMap(t=>t.kind==="command"?[...t.redirections.flatMap(n=>n.heredoc?[n.heredoc.bodySpan]:[]),...t.nested.flatMap(n=>xr(n.nodes))]:t.kind==="group"||t.kind==="function"?xr(t.body.nodes):[])}var wd=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});function Ri(e,t,n,s,r,o,a,i){if(e[t]!=="$"||e[t+1]!=="{")return null;let l=Oi(e,t+2,n),c=l.close===-1?n:l.close+1;l.close===-1&&i.push(gd),(l.quoted&&l.substitutions.length>0||l.continued)&&i.push(Ei),l.quoted&&(r.quotedExpansionEnd=Math.min(r.quotedExpansionEnd,c));let u=l.substitutions.some(f=>{if(jt(e,f))return i.push(Ot),!1;let p=Sn(e,f,c,s,r,o);return p!==null&&Sr(p,a,i).limited});return{provenance:"variable",next:c,limited:u}}function Oi(e,t,n){let s=[],r=!1,o=!1,a=1,i=t;for(;i<n;){let l=e[i];if(l==="$"&&jt(e,i)&&s.push(i),l==="\\"||l==="'"||l==='"'){r=!0,o||=l==="\\"&&e[i+1]===`
|
|
17
|
+
`,i+=l==="\\"?2:1;continue}let c=Ci(e,i);if(c){s.push(i);let u=Cr(e,i+c.length,n,c.closing);if(u===-1)break;i=u+c.closing.length;continue}if(l==="$"&&e[i+1]==="{"){a++,i+=2;continue}if(l==="}"&&--a===0)return{close:i,substitutions:s,quoted:r,continued:o};i++}return{close:-1,substitutions:s,quoted:r,continued:o}}function ji(e,t,n){if(e[t+1]==="{"){let r=Oi(e,t+2,n).close;return r===-1?n:r+1}if(e[t+1]==="$")return t+2;let s=t+1;for(;s<n&&/[A-Za-z0-9_?@#!*-]/.test(e[s]??"");)s++;return s===t+1?t+1:s}function kd(e,t,n){let s="",r=[],o=t;for(;o<n;){let a=e[o];if(a==="'")return{text:s,next:o+1,closed:!0,issues:r};if(a!=="\\"){s+=a??"",o++;continue}let i=vd(e,o+1,n);s+=i.text,i.invalidCodePoint!==void 0&&r.push({code:"invalid-ansi-c-code-point",message:`ANSI-C escape is not a valid Unicode scalar value: ${i.invalidCodePoint}`}),o=i.next}return{text:s,next:n,closed:!1,issues:r}}function vd(e,t,n){let s=e[t];if(!s||t>=n)return{text:"\\",next:t};let r=new Map([["a","\x07"],["b","\b"],["e","\x1B"],["E","\x1B"],["f","\f"],["n",`
|
|
18
|
+
`],["r","\r"],["t"," "],["v","\v"],["\\","\\"],["'","'"],['"','"']]);return r.has(s)?{text:r.get(s)??s,next:t+1}:s==="x"?rs(e,t+1,n,16,2,t+1):s==="u"?rs(e,t+1,n,16,4,t+1):s==="U"?rs(e,t+1,n,16,8,t+1):/[0-7]/.test(s)?rs(e,t,n,8,3,t+1):{text:s,next:t+1}}function rs(e,t,n,s,r,o){let a=s===16?/[0-9a-fA-F]/:/[0-7]/,i="",l=t;for(;l<n&&i.length<r&&a.test(e[l]??"");)i+=e[l],l++;if(!i)return{text:e[o-1]??"",next:o};let c=Number.parseInt(i,s);return c>1114111||c>=55296&&c<=57343?{text:"\uFFFD",next:l,invalidCodePoint:c}:{text:String.fromCodePoint(c),next:l}}function ls(e,t=!1){return t?"limited":e.some(n=>n.code==="invalid-ansi-c-code-point"||n.code==="missing-heredoc-delimiter"||n.code==="ambiguous-heredoc-delimiter"||n.code==="unterminated-heredoc"||n.code==="unsupported-heredoc-context"||n.code==="unsupported-function-substitution"||n.code==="unsupported-backtick-escape"||n.code==="unclosed-parameter-expansion"||n.code==="unsupported-parameter-expansion"||n.code==="unsupported-blank")?"invalid":e.length>0?"partial":"complete"}function Pi(e,t,n,s,r){let o=ji(e,t,n);return{text:s+e.slice(t,o),provenance:$n(r,"variable"),next:o}}function $d(e,t,n){let s=gi(e),r=t,o=!1,a=!1,i=t;for(;i<n;){let l=e[i];if(l==="\\"&&!o){i+=2;continue}if(!a&&l==="'"){o=!o,i++;continue}if(!o&&l==='"'){a=!a,i++;continue}if(o){i++;continue}let c=e.startsWith("$((",i),u=e.startsWith("$(",i)&&!c,f=!a&&(e.startsWith("<(",i)||e.startsWith(">(",i)),p=l==="`";if(c||u||f||p){let d=c?3:p?1:2,h=c?"))":p?"`":")",g=Cr(e,i+d,n,h),y=g===-1?n:g+h.length;s.push(r,i,"literal"),s.push(i,y,c?"arithmetic":"command-substitution"),i=y,r=y;continue}if(l==="$"){let d=ji(e,i,n);if(d>i+1){s.push(r,i,"literal"),s.push(i,d,"variable"),i=d,r=d;continue}}if(!a&&(l==="*"||l==="?"||l==="[")){s.push(r,i,"literal"),s.push(i,i+1,"glob"),i++,r=i;continue}i++}return s.push(r,n,"literal"),s.parts}function $n(e,t){return t==="command-substitution"||e==="command-substitution"?"command-substitution":t==="arithmetic"||e==="arithmetic"?"arithmetic":t==="variable"||e==="variable"?"variable":t==="glob"||e==="glob"?"glob":e}function xd(e,t,n){return t+1>=n||xn(e[t+1]??"")||as(e,t+1)!==null}var _d=new Set(["-u","--unset","-C","--chdir","-S","--split-string","-P"]),Sd=new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-T","-U"]),ki=new WeakSet,vi=256;function Cd(e){if(ki.has(e))return!1;let t=0;for(;t<=e.length;){for(;/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[t]?.text??"");)t++;if(t===e.length)return!0;let n=Ad(e,t);if((n===void 0||n===null&&e[t]?.text.toLowerCase()==="command")&&ki.add(e),n==null)return!1;t=n}return!1}function Ad(e,t){let n=e[t]?.text.toLowerCase();if(n==="command")return Ed(e,t);if(n==="env")return Rd(e,t);if(n==="sudo")return Od(e,t)}function Ed(e,t){if(e[t+1]?.text==="-v")return null;for(let n=t+1;n<e.length;n++){let s=e[n]?.text??"";if(s==="--")return n+1;if(!(s==="-p"||s==="-v"||s==="-V"||/^-[pvV]+$/.test(s)))return n}return e.length}function Rd(e,t){for(let n=t+1;n<e.length;n++){let s=e[n]?.text??"";if(s==="--")return n+1;if(_d.has(s)){if(e[n+1]===void 0)return null;n++;continue}if(!(s.startsWith("-u=")||s.startsWith("--unset=")||s.startsWith("-C")&&s.length>2||s.startsWith("--chdir=")||s.startsWith("-S")&&s.length>2||s.startsWith("--split-string=")||s.startsWith("-P"))&&!(s.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(s)))return n}return e.length}function Od(e,t){for(let n=t+1;n<e.length;n++){let s=e[n]?.text??"";if(s==="--")return n+1;if(Sd.has(s)){if(e[n+1]===void 0)return null;n++;continue}if(!s.startsWith("-"))return n}return e.length}function jd(e,t,n,s,r){if(t.provenance!=="literal"||!t.raw.includes("{"))return;let o=Pd(t.raw,n,s,r,!1);if(!o)return;if("limited"in o)return o.limited==="expansions"?{limitCode:"depth-limit"}:{limitCode:o.limited==="length"?"brace-expansion-limit":"word-limit"};let a=o.values.map(i=>Td(i,s));if(!a.some(i=>i===null))return{words:a.filter(i=>i!==null&&i!=="").map(i=>ss(e,t.span.start,t.span.end,i,"literal",!1))}}function Pd(e,t,n,s,r){let o=[e],a=e.length,i=0;for(;;){let l=o.findIndex(d=>$i(d,r));if(l===-1)break;if(++i>n)return{limited:"expansions"};let c=o[l]??"",u=$i(c,r);if(!u||u.kind==="range")return{limited:"expansions"};let f=u.start+c.length-u.end,p=u.alternatives.reduce((d,h)=>d+f+h.length,0);if(a-c.length+p>s)return{limited:"length"};if(o.length-1+u.alternatives.length>t)return{limited:"words"};o.splice(l,1,...Wd(c,u)),a+=p-c.length}return i===0?void 0:{values:o}}function $i(e,t){let n=[],s,r=null,o=!1;for(let a=0;a<e.length;a++){let i=e[a];if(o){o=!1;continue}if(i==="\\"&&r!=="'"){o=!0;continue}if(i===r){r=null;continue}if(r===null&&(i==="'"||i==='"')){r=i;continue}if(r!==null)continue;if(i==="{"){n.push({start:a,commas:[]});continue}if(i===","&&n.length>0){n.at(-1)?.commas.push(a);continue}if(i!=="}"||n.length===0)continue;let l=n.pop();if(!l)continue;let c=l.commas.length>0?{kind:"alternatives",start:l.start,end:a+1,commas:l.commas}:t&&Ld(e.slice(l.start+1,a))?{kind:"range",start:l.start,end:a+1}:void 0;c&&(!s||c.start<s.start)&&(s=c)}return!s||s.kind==="range"?s:{kind:s.kind,start:s.start,end:s.end,alternatives:Nd(e,s)}}function Wd(e,t){return t.alternatives.map(n=>`${e.slice(0,t.start)}${n}${e.slice(t.end)}`)}function Nd(e,t){let n=[t.start,...t.commas,t.end-1];return n.slice(0,-1).map((s,r)=>e.slice(s+1,n[r+1]))}function Ld(e){return/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(e)||/^[A-Za-z]\.\.[A-Za-z](?:\.\.-?\d+)?$/.test(e)}function Td(e,t){let n=`x${e}`,s=$r(n,0,n.length,{maxInputLength:n.length,maxWords:1,maxDepth:t},{wordsUsed:0,maxWords:1,quotedExpansionEnd:1/0},0);return s.limited||s.issues.length>0||s.next!==n.length||s.word.provenance!=="literal"?null:s.word.text.slice(1)}function Id(e,t,n,s){return{kind:"program",dialect:"posix",source:e.slice(t,n),span:{start:t,end:n},status:"limited",issues:[{code:s,message:"command structure exceeds parser limit"}],nodes:[]}}function Rt(e,t,n,s,r){return{nodes:e,issues:[...t,{code:s,message:`command structure exceeds parser limit ${r}`}],next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function os(e,t,n){return{nodes:e,issues:t,next:n,closed:!1,limited:!0,pendingHeredocs:[]}}function kr(e){return e.wordsUsed++,e.wordsUsed<=e.maxWords}function Dd(e,t,n){let s=e.slice(t,n),r=/^(?:function[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*\([ \t]*\)[ \t]*\{/.exec(s)??/^function[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+\{/.exec(s),o=r?.[1];if(!(!r||!o))return{name:o,braceIndex:t+r[0].lastIndexOf("{")}}function _n(e){return e.some(t=>t.kind==="command"?t.redirections.some(n=>n.heredoc)||t.nested.some(n=>_n(n.nodes)):(t.kind==="group"||t.kind==="function")&&_n(t.body.nodes))}function Fd(e){return e.map(t=>({code:"unterminated-heredoc",message:`heredoc delimiter ${t.delimiter} was not found`}))}function Wi(e){return e?.kind==="command"||e?.kind==="group"||e?.kind==="function"}function xi(e,t){let n=e.at(-1);n?.kind!=="connector"||!_i.has(n.operator)||t.push({code:"missing-command-after-connector",message:`connector ${n.operator} requires a following command`})}function Ni(e){return e?.provenance==="literal"&&!e.quoted&&e.raw===e.text&&ld.has(e.text)}function vr(e,t){let n=e.at(-1);Wi(n)&&(n?.kind==="command"&&Ni(n.words[0])||t.push({code:"missing-command-connector",message:"adjacent commands require a connector"}))}function zd(e,t,n){return t===n||/[\s;&|()]/u.test(e[t-1]??"")}import{createRequire as Md}from"module";var Cn,Ud="Anvil's PowerShell reader (claude-powershell.cjs) is missing or won't load";function Li(){if(Cn===void 0){Cn=null;let e=Md(import.meta.url);for(let t of["./claude-powershell.cjs","../claude-powershell.cjs"])try{let n=e(t);if(typeof n.readPowerShell=="function"&&typeof n.readCmd=="function"){Cn=n;break}}catch{}}if(Cn===null)throw new Error(Ud);return Cn}function Vt(e,t){return Li().readPowerShell(e,t)}function Ti(e,t){return Li().readCmd(e,t)}import{posix as Di}from"path";var qd=null;function V(){return qd??process.platform==="win32"}var Ii=/^([A-Za-z]):(.*)$/s,Hd=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function Ar(e,t){let n=Di.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function Zt(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let s=n.indexOf(":"),r=s>=0?n.slice(0,s):n,o=t?r:r.replace(/[. ]+$/,"");return o===""?".":o}).join("/")}function We(e){if(!V())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,s=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(s){let l=s[2];if(s[1]===".")return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(l))t=`\\\\${l.slice(4)}`;else if(Ii.test(l))t=l;else return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let r=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(r){let l=`/unc/${Zt(r[1],n).toLowerCase()}${r[2]?`/${Zt(r[2],n).toLowerCase()}`:""}`;return Ar(l,Zt(r[3]??"",n).toLowerCase())}let o=Ii.exec(t);if(o){let l=o[2];return l===""?`/${o[1].toLowerCase()}`:l.startsWith("/")?Ar(`/${o[1].toLowerCase()}`,Zt(l,n).toLowerCase()):null}let a=Hd.exec(t);if(a)return Ar(`/${a[1].toLowerCase()}`,Zt(a[2]??"",n).toLowerCase());let i=Zt(t,n).toLowerCase();if(i.startsWith("/")){let l=Di.normalize(i);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return i}function Ne(e){return We(e)??e}function cs(e){return V()&&/^\/dev\/(?:nul|con|conin\$|conout\$|(?:pipe|mailslot)\/.+)$/.test(e)}function Fi(e){return/^\/[a-z]$/.test(e)||/^\/unc\/[^/]+(?:\/[^/]+)?$/.test(e)}function Je(e){if(!V())return e;let t=/^\/([a-z])(\/.*)?$/s.exec(e);if(t)return`${t[1].toUpperCase()}:${(t[2]??"/").replace(/\//g,"\\")}`;let n=/^\/unc\/(.+)$/s.exec(e);return n?`\\\\${n[1].replace(/\//g,"\\")}`:null}function Gt(e){return V()?Je(e)??e:e}function us(e){return V()?Je(e)??e:e}var Er=["windows","windows/system32","windows/syswow64","program files","program files (x86)","programdata","users","recovery","boot","perflogs","system volume information","$recycle.bin","documents and settings"],Rr=new Set(["desktop","documents","downloads","pictures","music","videos","favorites","contacts","links","saved games","searches","onedrive","appdata","3d objects","source",".ssh",".gnupg",".aws",".azure",".config",".claude",".local",".kube",".docker"]);function oe(e){return Object.assign(Object.create(null),e)}var ie="\0",le="",Bd=/\brailway\s+(variables|variable|vars)\b|\bheroku\s+config\b|\bdoppler\s+secrets\b|\bop\s+read\b|\baws\s+secretsmanager\b|\bgcloud\s+secrets\b|\bvault\s+(kv\s+get|read)\b/,Pe="\0$OLDPWD",Wr=8,Vd=32,Zd=8,Gd=16,Kd=64,Yt=new Set(["bash","sh","zsh","dash","ksh","fish","ash","csh","tcsh","mksh","yash"]);function ys(e,t,n){for(let s=0;e.deferred.length>0;s++){if(s>=Vd){e.bodyRead||(e.depthLimit.hit=!0),e.deferred.length=0;break}let r=e.deferred.shift();fe(r.code,{...e,vars:new Map(e.vars),cwd:Pe,depth:e.depth+1,via:"shell-string",captured:!1,frames:[],outerGuards:r.parent.guards,andGuards:[],parent:r.parent,errexit:r.errexit},t,n)}}var Yd=new Set([":",".","eval","exec","exit","export","readonly","return","set","shift","trap","unset","break","continue","times"]),zi=new Set(["sh","dash","ksh","ash","mksh","yash"]),zr=/^([0-9]+|[@*#])$/,Xi=new Set(["do","then","else","elif","if","while","until","!","{","(","time"]),Jd=new Set(["done","fi","esac","}",")","in","case",";;"]),Xd=new Set(["sudo","doas","pkexec","run0","env","nohup","time","nice","ionice","timeout","gtimeout","command","builtin","exec","caffeinate","stdbuf","unbuffer","chronic","script","npx","pnpx","bunx","uv","uvx","pipx","busybox","bundle","poetry","pdm","rye","op","doppler","infisical","dotenvx","dotenv","sshpass","aws-vault","cross-env","setsid","sandbox-exec","flock","taskset","chrt","prlimit","unshare","systemd-inhibit","launchctl"]),Qi=new Set(["-w","--timeout","-E","--conflict-exit-code"]),Qd=new Set(["npx","pnpx","bunx","uv","uvx","pipx"]),ef=oe({"eas-cli":"eas","expo-cli":"expo","@expo/cli":"expo","netlify-cli":"netlify","firebase-tools":"firebase","@railway/cli":"railway",localtunnel:"lt","@anthropic-ai/claude-code":"claude","@useanvil/sdk":"anvil","@useanvil/claude-code":"anvil-claude","@openai/codex":"codex","@google/gemini-cli":"gemini","appcenter-cli":"appcenter","snowflake-cli":"snow","snowflake-cli-labs":"snow","databricks-cli":"databricks","@ngrok/ngrok":"ngrok","@capgo/cli":"capgo","@smithery/cli":"smithery","@github/copilot":"copilot","@qwen-code/qwen-code":"qwen","chrome-webstore-upload-cli":"chrome-webstore-upload"});function bs(e){let t=new Set(["-w","--workspace","--filter","-F","-C","--dir","--prefix","--cwd","--recursive-filter"]),n=1;for(;n<e.length&&e[n].startsWith("-");)n+=t.has(e[n])?2:1;return e[0]!==void 0&&/(^|\/)yarn$/.test(e[0])&&e[n]==="workspace"&&(n+=2),{sub:e[n]??"",at:n}}function Mi(e){let t=/^((?:@[^/@\s]+\/)?[^@\s=/]+)(?:@[^\s/]*|==[^\s]*)$/.exec(e),n=t?t[1]:e;return ef[n]??n}var tf=new Set(["python","python3","node","ruby","perl","php","bun","deno","tsx","ts-node"]);function fe(e,t,n,s){let r=_r(e,yr);r.status==="limited"&&!t.bodyRead&&(t.depthLimit.hit=!0),Pt(r,t,n,s)}function dt(e,t){let n=[],s=_r(e,yr),r={vars:new Map,functions:new Map,called:new Set,cwd:t.cwd,depth:0,via:"top",remote:null,productionEnv:!1,captured:!1,frames:[],outerGuards:[],andGuards:[],cds:[],cdpath:!1,errexit:!1,ifs:null,posixOnly:!1,maybeRuns:!1,partial:s.status!=="complete",subshell:!1,inFunction:!1,newProcess:!1,deferred:[],locals:new Set,files:new Map(Object.entries(t.knownFiles??{})),loopBudget:{left:Kd},depthLimit:{hit:!1},parent:null,oldCwd:Pe,dirStack:[]};Pt(s,r,t,n);for(let[o,a]of r.functions)r.called.has(o)||Pt(a,{...r,vars:new Map(r.vars),depth:1,via:"shell-string",captured:!1,frames:[],andGuards:[]},t,n);return ys(r,t,n),{commands:n,status:r.depthLimit.hit?"limited":s.status}}function et(e){let t=[...e.outerGuards];for(let n of e.frames)n.phase!=="body"||n.negate||(n.kind==="case"?t.push(`case ${n.word??""} in ${n.pattern??""}`):t.push(...n.cond));return[...t,...e.andGuards]}var Nr=class{passed=[];joiner=null;open=!1;text=null;exits=!1;beforeOr=[];orExits=!1;runPassed=[];get afterOr(){return this.joiner==="||"}get joined(){return this.joiner!==null}start(){this.close(),this.runPassed=this.joiner==="&&"?this.passed:[],this.open=!0,this.text=null,this.exits=!1}set(t,n=!1){this.text=t,this.exits=n}extend(t){this.text=this.text!==null&&t!==null?`${this.text} | ${t}`:null,this.exits=!1}join(t){this.close(),t==="||"&&(this.beforeOr=this.passed),this.joiner=t}end(){this.close();let t={passed:this.passed,past:this.orExits?this.beforeOr:[],lone:this.elements===1&&this.lastText!==null&&!this.lastText.startsWith("! ")?this.lastText:null};return this.passed=[],this.beforeOr=[],this.orExits=!1,this.elements=0,this.joiner=null,t}elements=0;lastText=null;close(){if(!this.open)return;let t=this.text;this.elements++,this.lastText=t,this.joiner==="&&"?(t!==null&&(this.passed=[...this.passed,t]),this.orExits=!1):this.joiner==="||"?(this.passed=[],this.orExits=this.exits):(this.passed=t===null?[]:[t],this.orExits=!1),this.open=!1,this.joiner=null}};function nf(e){return e!==null&&(e.name==="exit"||e.name==="return")&&e.wrappers.length===0&&e.argv.length<=2&&e.via!=="xargs"}function sf(e){for(let t of e.words){if(t.provenance!=="literal"||t.quoted||!Xi.has(t.text))return!1;if(t.text==="!")return!0}return!1}function ut(e,t){for(let n=e.frames.length-1;n>=0;n--)if(e.frames[n].kind===t)return e.frames[n]}function ps(e,t){for(let n=e.frames.length-1;n>=0;n--)if(e.frames[n].kind===t){e.closed=e.frames[n],e.frames.splice(n,1);return}}function ea(e){let t=[];for(let n=e;n&&t.length<8;n=n.pipeFrom)t.push(n.text);return t.reverse().join(" | ")}function rf(e,t,n,s){let r=e[t];if(r.kind!=="command")return null;let o=r.words;if(!o[0]||o[0].text!=="for"||o[0].provenance!=="literal"||o[0].quoted)return null;let a=o[1]?.text,i=o.findIndex(x=>x.text==="in"&&x.provenance==="literal"),l=i>0?o.slice(i+1):[],c=l.length===1&&l[0].provenance==="command-substitution"?/^\$\(\s*(?:echo|printf)\s+([\w./ -]+?)\s*\)$/.exec(l[0].raw)?.[1]:void 0,u=x=>x.provenance==="literal"||x.provenance==="glob",f=x=>u(x)||/^"[^"`]*"$/.test(x.raw)&&!/\$\{?[@*]|\[[@*]\]/.test(x.raw)&&!S(Ee(x,n,s).text);if(!a||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a)||l.length===0||!c&&!l.every(f))return null;let p=-1,d=0,h=-1;for(let x=t+1;x<e.length;x++){let b=e[x];if(b.kind!=="command")continue;let j=b.words[0];if(!(!j||j.provenance!=="literal"||j.quoted)){if(p<0){if(j.text==="do"&&b.words.length===1)p=x;else if(j.text!=="do")return null;continue}if(["for","while","until","select"].includes(j.text)&&d++,j.text==="done"){if(d===0){h=x;break}d--}}}if(p<0||h<0)return null;let g=c?c.split(/\s+/).filter(Boolean):l.map(x=>u(x)?x.text:Ee(x,n,s).text),y=ia(n,aa(l.map(x=>x.raw).join(" "))),$=g.map((x,b)=>{let j=l[b];return y.length===0||c||!j||u(j)?[]:[...new Set(y.map(C=>Ee(j,{...n,vars:C},s).text))].filter(C=>C!==x)}),E=Math.min(g.length,Gd,n.loopBudget.left);return E<=0?null:(n.loopBudget.left-=E,{name:a,values:g.slice(0,E),alts:$.slice(0,E),truncated:E<g.length,body:e.slice(p+1,h),end:h})}function of(e,t){let n=0;for(let s=t;s<e.length;s++){let r=e[s];if(r.kind!=="command")continue;let o=r.words[0];if(!(!o||o.provenance!=="literal"||o.quoted)&&(["while","until","for","select"].includes(o.text)&&n++,o.text==="done")){if(n>0){n--;continue}let a=r.redirections.find(c=>(c.operator==="<"||c.operator==="<<<")&&c.target);if(!a||!a.target)return null;let i=a.target.raw.replace(/^"|"$/g,""),l=/^(?:<\(|\$\()([\s\S]*)\)$/.exec(i);return l?l[1]:a.operator==="<"?`cat ${i}`:i}}return null}function Ui(e,t,n,s,r){let o=e.words,a=0;for(;a<o.length&&o[a].provenance==="literal"&&!o[a].quoted;){let i=o[a].text;if(i==="if")t.frames.push({kind:"if",phase:"cond",cond:[],negate:!1});else if(i==="while"||i==="until")t.frames.push({kind:"loop",phase:"cond",cond:[],negate:i==="until",input:r?ea(r):of(n,s+1)});else if(i==="then"){let l=ut(t,"if");l&&(l.phase="body")}else if(i==="elif"){let l=ut(t,"if");l&&Object.assign(l,{phase:"cond",cond:[],negate:!1})}else if(i==="else"){let l=ut(t,"if");l&&(l.phase="else")}else if(i==="fi")ps(t,"if");else if(i==="do"){let l=ut(t,"loop");l&&(l.phase="body")}else if(i==="done")ps(t,"loop");else if(i==="esac")ps(t,"case");else if(i==="!"&&t.frames.length&&t.frames[t.frames.length-1].phase==="cond")t.frames[t.frames.length-1].negate=!0;else if(!["{","}","(",")","time"].includes(i))break;a++}return a>0&&a===o.length}var ds=new WeakMap;function Pt(e,t,n,s){if(t.depth>Wr){t.bodyRead||(t.depthLimit.hit=!0);return}let r=null,o=[],a=!1,i=t.andGuards,l=t.maybeRuns,c=t.subshell,u=new Nr,f=[],p=C=>C.length<=t.frames.length&&C.every(([A,U],I)=>t.frames[I]===A&&A.phase===U),d=new Set,h=C=>{for(let A=C;A<t.frames.length;A++)d.add(t.frames[A])},g=()=>{u.start();let C=t.frames[t.frames.length-1];C&&C.phase==="cond"&&d.has(C)&&(C.cond=[])},y=()=>{t.andGuards=[...i,...f.filter(C=>p(C.at)).map(C=>C.text),...u.runPassed]},$=()=>{t.andGuards=i},E=0,x=!1,b=null,j=t.posixOnly?e.nodes:af(e.nodes);for(let C=0;C<j.length;C++){let A=j[C],U=x;x=!1;let I=b;b=null;for(let H of t.frames)ds.has(H)||ds.set(H,s.length);if(A.kind==="command"&&A.words.length===1&&A.words[0].text==="!"&&A.words[0].provenance==="literal"&&!A.words[0].quoted){let H=t.frames.length;Ui(A,t,j,C,null),h(H),x=!0;continue}if(A.kind==="connector"){if(a=A.operator==="|"||A.operator==="|&",A.operator==="&")for(let H of o)H.background=!0;if(!a)if(r=null,A.operator==="&&"||A.operator==="||")u.join(A.operator);else{let H=u.end(),Z=t.frames[t.frames.length-1];Z&&Z.phase==="cond"&&d.has(Z)&&(Z.cond=[...H.passed]);let ge=t.frames.map(L=>[L,L.phase]),ne=t.frames.some(L=>L.phase==="cond"),ee=t.errexit&&!ne&&H.lone!==null?[H.lone]:[];A.operator!=="&"&&(f=[...f,...[...H.past,...ee].map(L=>({text:L,at:ge}))])}if(E=A.operator===";"?E+1:0,E>=2){let H=ut(t,"case");H&&Object.assign(H,{phase:"pattern",pattern:""})}continue}E=0;let D=ut(t,"case");if(A.kind!=="command"&&D&&D.phase==="pattern"){D.phase="body";continue}if(A.kind==="group"){let H=e.source.slice(A.span.start-e.span.start,A.span.end-e.span.start);if(H.startsWith("(("))for(let F of H.matchAll(/(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:[-+*\/%&|^]|<<|>>)?=(?!=)|(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:\+\+|--)|(?:\+\+|--)\s*([A-Za-z_][A-Za-z0-9_]*)/g))Xe(t,F[1]??F[2]??F[3],{kind:"unknown"});a||g(),y();let Z=A.style==="subshell"?{...t,vars:new Map(t.vars),functions:new Map(t.functions),outerGuards:et(t),frames:[],andGuards:[],deferred:[]}:t,ge=s.length,ne=j[C+1];Z.maybeRuns=l||u.afterOr||a||ne?.kind==="connector"&&["|","|&","&"].includes(ne.operator),Pt(A.body,Z,n,s),Z!==t&&ys(Z,n,s),Z.maybeRuns=l,o=s.slice(ge);let ee=j[C+1];if(ee?.kind==="command"&&ee.words.length===0&&ee.redirections.some(lf)){let F=new Set(o),gr=new Set(o.map(we=>we.parent)),mr=we=>{for(let je=we;je&&F.has(je);je=je.parent)if(je.captured||je.pipeTo!==null||je.redirects.some(Y=>fs(Y))||Pr.has(je))return!0;return!1};b=o.some(we=>we.name==="exec"&&we.redirects.some(je=>fs(je)))||na(A.body)?[]:o.filter(we=>!gr.has(we)&&!mr(we));for(let we of b)Pr.add(we)}else if(ee?.kind==="command"&&ee.words.length===0&&ee.redirections.some(hs)||ee?.kind==="connector"&&(ee.operator==="|"||ee.operator==="|&"))for(let F of o)Pr.add(F);let L=ee?.kind==="command"&&ee.words.length===0?ee.redirections.find(F=>(F.operator==="<"||F.operator==="<>")&&(F.fd===void 0||F.fd===0)&&F.target):void 0;L?.target&&sa(o,Ee(L.target,t,n).text),$(),a?u.extend(null):u.set(null),r=null,a=!1;continue}if(A.kind==="function"){t.functions.set(A.name,A.body);let H=ws.get(t.functions)??new Set;ws.set(t.functions,H);let Z=j[C+1],ge=a||Z?.kind==="connector"&&["&","|","|&"].includes(Z.operator);t.depth===0&&!t.subshell&&!t.maybeRuns&&!u.joined&&!ge&&t.frames.length===0&&et(t).length===0?H.add(A.name):H.delete(A.name),a||g(),u.set(null),r=null,a=!1;continue}if(A.kind!=="command")continue;let z=rf(j,C,t,n);if(z){a||g(),y();let H=[...z.values.map(ne=>({kind:"value",value:ne})),...z.truncated?[{kind:"unknown"}]:[]],Z=s.length;for(let[ne,ee]of H.entries())t.vars.set(z.name,ee),Ir(ee,z.alts[ne]??[]),t.frames.push({kind:"loop",phase:"body",cond:[],negate:!1}),Pt({...e,nodes:z.body},{...t},n,s),ps(t,"loop");!z.truncated&&z.values.length>1&&t.vars.set(z.name,Ir({kind:"value",value:z.values.at(-1)},[...z.values.slice(0,-1),...z.alts.flat()]));let ge=j[z.end];if(ge?.kind==="command"&&ge.words[0]?.text==="done"&&ge.redirections.some(hs)){let ne=s.slice(Z).filter(ee=>!ee.captured&&ee.pipeTo===null&&!ee.redirects.some(L=>fs(L)));gs({...ge,words:[]},t,n,s,null,ne)}$(),u.set(null),C=z.end,r=null,a=!1;continue}let B=A.words[0];if(B&&B.text==="case"&&B.provenance==="literal"&&!B.quoted){let H=A.words[1]?Ee(A.words[1],t,n).text:"",Z=A.words.slice(3).map(ee=>Ee(ee,t,n).text).join(" "),ge=j[C+1],ne=ge?.kind==="connector"&&ge.operator==="|";t.frames.push({kind:"case",phase:Z&&!ne?"body":"pattern",cond:[],negate:!1,word:H,pattern:Z}),h(t.frames.length-1),Z&&!ne&&ge&&ge.kind!=="command"&&C++,a||g(),u.set(null),r=null,a=!1;continue}if(D&&D.phase==="pattern"&&!(B&&B.text==="esac")){let H=A.words.map(Z=>Ee(Z,t,n).text).join(" ");D.pattern=D.pattern?`${D.pattern}|${H}`:H,a=!1,r=null;continue}let Q=t.frames.length;t.closed=null;let ce=Ui(A,t,j,C,a?r:null);if(h(Q),ce){let H=t.closed,Z=H?s.slice(ds.get(H)??s.length):null;if(H&&A.redirections.some(hs)){let ge=s.slice(ds.get(H)??s.length).filter(ne=>!ne.captured&&ne.pipeTo===null&&!ne.redirects.some(ee=>fs(ee)));gs({...A,words:[]},t,n,s,null,ge)}a||g(),u.set(null),a=!1,r=null,Z&&(o=Z);continue}a||g(),y();let te=t.frames.length,ze=j[C+1],Oe=a||ze?.kind==="connector"&&["|","|&","&"].includes(ze.operator);t.maybeRuns=l||u.afterOr||Oe,t.subshell=c||Oe;let K=gs(A,t,n,s,a?r:null,I);t.maybeRuns=l,t.subshell=c,h(te),$();let Ye=U||sf(A),Me=K?`${Ye?"! ":""}${Rn(K)}`:null;a?u.extend(Me):u.set(Me,!Ye&&nf(K)),r=K??r,o=K?[K]:[],a=!1}}function ta(e,t,n){let s=new Set;for(let r of e.cds){let o=r.to===null?s.size>0?[Pe]:[]:"abs"in r.to?[]:[...s].map(a=>M(r.to.rel,a,n));s=new Set(t.includes(r.text)?o:[r.before,...s,...o]);for(let a of r.extra??[])s.add(a);s.size>8&&(s=new Set([Pe]))}return s.delete(e.cwd),[...s]}function Or(e,t,n){if(!t.subshell)for(let[s,r]of e.vars){if(zr.test(s)||e.locals.has(s)||n.get(s)===r)continue;let o={...r},a=t.vars.get(s)??null;t.vars.set(s,o),Qe.set(o,{at:t.frames.map(i=>[i,i.phase]),guards:et(t),maybe:!0,prev:a})}}function jr(e,t){t.cwd=e.cwd,t.oldCwd=e.oldCwd,t.dirStack=e.dirStack,t.cds=e.cds,t.cdpath=e.cdpath}function af(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n],r=e[n+1],o=e[n+2],a=s.kind==="command"&&["done","fi","esac"].includes(s.words[0]?.text??"");if((s.kind==="command"||s.kind==="group")&&!a&&r?.kind==="connector"&&r.operator==="&"&&o?.kind==="command"&&o.words.length===0&&r.span.end===o.span.start&&o.source.startsWith(">")){s.kind==="command"?t.push({...s,source:`${s.source} &${o.source}`,redirections:[...s.redirections,...o.redirections]}):t.push(s,o),n+=2;continue}t.push(s)}return t}function hs(e){return e.fd===1||e.fd===void 0&&[">",">>",">|",">&"].includes(e.operator)}function na(e){return e.nodes.some(t=>t.kind==="command"&&["done","fi","esac"].includes(t.words[0]?.text??"")&&t.redirections.some(hs)||t.kind==="group"&&na(t.body))}function sa(e,t){for(let n of e)n.stdinFile===null&&n.stdin===null&&n.pipeFrom===null&&!n.captured&&(n.stdinFile=t)}function lf(e){return(e.operator===">"||e.operator===">>"||e.operator===">|")&&(e.fd===void 0||e.fd===1)}function fs(e){return e.fd===1||e.fd===null&&(e.op===">"||e.op===">>"||e.op===">|"||e.op===">&")}var Pr=new WeakSet;function Rn(e){return e.argv.map(k).join(" ")}function gs(e,t,n,s,r,o=null){for(let w of e.nested){let _={...t,vars:new Map(t.vars),depth:t.depth+1,via:"substitution",captured:!0,frames:[],outerGuards:et(t),andGuards:[],errexit:!1,deferred:[]};Pt(w,_,n,s),ys(_,n,s)}let a=[...e.words];for(;a.length&&Xi.has(a[0].text)&&a[0].provenance==="literal"&&!a[0].quoted;)a.shift();if(a.length&&Jd.has(a[0].text)&&a.length===1)return null;if(a[0]?.text==="for"||a[0]?.text==="select"){t.frames.push({kind:"loop",phase:"header",cond:[],negate:!1});let w=a[1]?.text,_=a.slice(a.findIndex(N=>N.text==="in")+1);w&&t.vars.set(w,_.length>0&&a.some(N=>N.text==="in")&&_.some(N=>N.provenance==="command-substitution")?{kind:"value",value:`${ie}${_.map(N=>Fr(N.raw,t,n)).join(" ")}${le}`}:_.length>0&&_.every(N=>N.provenance==="literal"||N.provenance==="glob")?{kind:"list",values:_.map(N=>N.text)}:{kind:"unknown"});let O=a.findIndex((N,W)=>W>1&&N.text==="do"&&N.provenance==="literal"&&!N.quoted);if(O>0&&O<a.length-1){let N=ut(t,"loop");return N&&(N.phase="body"),gs({...e,words:a.slice(O+1)},t,n,s,null)}return null}let i=a.findIndex(w=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(w.raw)&&w.text!=="command"&&w.text!=="builtin");if(i>0&&["read","mapfile","readarray"].includes(a[i].text)&&(a=[...a.slice(i)]),(a[0]?.text==="mapfile"||a[0]?.text==="readarray")&&a[0].provenance==="literal"){let w=a.slice(1).filter((_,O,N)=>!_.text.startsWith("-")&&!["-d","-n","-O","-s","-u","-C","-c"].includes(N[O-1]?.text??"")).pop()?.text??"MAPFILE";/^[A-Za-z_][A-Za-z0-9_]*$/.test(w)&&Xe(t,w,{kind:"unknown"})}if(a[0]?.text==="read"&&a[0].provenance==="literal"){let w=ut(t,"loop"),_=w&&w.phase==="cond"?w.input??null:null,O=e.redirections.find(G=>G.operator==="<"&&G.target),N=e.redirections.find(G=>G.operator==="<<<"&&G.target),W=r?ea(r):O?.target?`cat ${Ee(O.target,t,n).text}`:N?.target?k(Ee(N.target,t,n).text):_,q=new Set(["-p","-d","-n","-N","-t","-u","-i"]);for(let G=1;G<a.length;G++){let J=a[G].text;if(q.has(J)){G++;continue}J==="-a"||J.startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*$/.test(J)&&t.vars.set(J,W?{kind:"value",value:`${ie}$(${W})${le}`}:{kind:"unknown"})}}let l=0,c=[],u=new Set;for(;l<a.length&&/^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(a[l].raw);){let w=a[l],_=w.raw.indexOf("=");w.raw[_-1]==="+"&&u.add(w),c.push([w.raw.slice(0,w.raw[_-1]==="+"?_-1:_),w]),l++}let f=a[l];if(f?.text==="getopts"&&a[l+2]&&Xe(t,a[l+2].text,{kind:"unknown"}),f?.text==="let"||f?.raw.startsWith("(("))for(let w of a.slice(l))for(let _ of w.raw.matchAll(/(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:[-+*\/%&|^]|<<|>>)?=(?!=)|(?<![A-Za-z0-9_])([A-Za-z_][A-Za-z0-9_]*)\s*(?:\+\+|--)|(?:\+\+|--)\s*([A-Za-z_][A-Za-z0-9_]*)/g))Xe(t,_[1]??_[2]??_[3],{kind:"unknown"});let p=a.slice(l);if(p.length&&["export","local","declare","readonly","typeset"].includes(p[0].text)){let w=p[0].text,_=p.slice(1).filter(W=>W.text.startsWith("-")).map(W=>W.text),O=t.inFunction&&(w==="local"||(w==="declare"||w==="typeset")&&!_.some(W=>W.includes("g"))),N=_.some(W=>/^-[a-zA-Z]*n/.test(W));for(let W of p.slice(1)){let q=/^([A-Za-z_][A-Za-z0-9_]*)(=|$)/.exec(W.text);q&&(O&&t.locals.add(q[1]),N?Xe(t,q[1],{kind:"unknown"}):q[2]==="="&&c.push([q[1],W]))}p=[]}let d=t.productionEnv,h=[];for(let[w,_]of c){let O=Cf(_,w,t,n),N=t.vars.get(w),W=u.has(_)?N?.kind==="value"&&O.kind==="value"?{kind:"value",value:N.value+O.value}:{kind:"unknown"}:O;if(p.length>0){W.production&&(d=!0),h.push([w,W]);continue}Xe(t,w,W),w==="OLDPWD"&&p.length===0&&(t.oldCwd=W.kind==="value"&&!S(W.value)?W.value:Pe),w==="CDPATH"&&p.length===0&&(t.cdpath=!(W.kind==="value"&&W.value==="")),w==="IFS"&&p.length===0&&(t.ifs=W.kind==="value"&&W.value!==""&&!S(W.value)?W.value:null)}if(p.length===0&&c.length===0&&e.redirections.length>0&&(p=[{kind:"word",text:":",raw:":",span:e.span,provenance:"literal",quoted:!1,parts:[]}]),p.length===0)return null;let g=p.map(w=>Ee(w,t,n)),y=t.ifs??`
|
|
19
|
+
`,$=new RegExp(`[${y.replace(/[\]\\^-]/g,"\\$&")}]+`),E=(w,_)=>w.flatMap((O,N)=>/^"?\$(@|\{@\})"?$/.test(p[N].raw)&&Dr.has(_.get("@"))?[...Dr.get(_.get("@"))]:/\$(@|\{@\})/.test(p[N].raw)&&!S(O.text)?O.text.split(/\s+/).filter(Boolean):!p[N].quoted&&(p[N].provenance==="variable"||p[N].provenance==="command-substitution")&&!S(O.text)&&$.test(O.text.trim())?O.text.trim().split($).filter(Boolean):[O.text]),x=(w,_)=>V()?E(w,_).map(Gi):E(w,_),b=x(g,t.vars),j=et(t),C=aa(p.map(w=>w.raw).join(" ")),A=t.frames.map(w=>[w,w.phase]),U=ta(t,j,n),I=C.has("PWD")&&!t.vars.has("PWD")?U.filter(w=>w!==null&&!S(w)):[],z=I.length>0||[...C].some(w=>{let _=t.vars.get(w);return _!==void 0&&!Tr(_,t,j,A)})?{...t,vars:new Map(t.vars)}:null,B=b,Q=null,ce=()=>Q??=z?[...ia(z,C,A,j),...I.map(w=>new Map(z.vars).set("PWD",{kind:"value",value:w}))].map(w=>x(p.map(_=>Ee(_,{...z,vars:w},n)),w)).filter(w=>w.join("\0")!==B.join("\0")):[],te=b.length;if(t.partial||t.posixOnly&&Yd.has(p[0]?.text??""))for(let[w,_]of h)Xe(t,w,_);let ze=[...new Set(g.flatMap(w=>w.unresolved))],Oe=e.redirections.map(w=>({op:w.operator,target:w.target?Gi(Ee(w.target,t,n).text):null,fd:w.fd??null})),K=Oe.find(w=>w.op==="<&"&&(w.fd===null||w.fd===0)&&/^\d+$/.test(w.target??"")),Ye=(K?Oe.find(w=>(w.op==="<"||w.op==="<>")&&w.fd===Number(K.target))?.target:Oe.find(w=>(w.op==="<"||w.op==="<>")&&(w.fd===null||w.fd===0)&&w.target)?.target)??null,Me=e.redirections.find(w=>w.heredoc)?.heredoc??null,H=e.redirections.find(w=>w.operator==="<<<"&&w.target),Z=Me?Me.body:H?.target?Ee(H.target,t,n).text:null,ge=Me?"heredoc":H?"here-string":null,ne=[],ee=[];for(let w=0;b.length;w++){let _=ue(b[0]);if(!Xd.has(_))break;if(w>=Zd){t.bodyRead||(t.depthLimit.hit=!0);break}let O=_==="env"?b.findIndex(W=>W==="-S"||W==="--split-string"||W.startsWith("--split-string=")):-1;if(O>0){let W=b[O].startsWith("--split-string=")?b[O].slice(15):b[O+1]??"",q=b.slice(O+(b[O].includes("=")?1:2));ne.push(_),b=[...W.trim().split(/\s+/).filter(Boolean),...q];continue}if(_==="flock"){let W=1;for(;W<b.length&&b[W].startsWith("-")&&b[W]!=="--";)W+=Qi.has(b[W])?2:1;if((b[W+1]==="-c"||b[W+1]==="--command")&&b[W+2]!==void 0){ne.push(_),ee.push(...b.slice(1,W+2)),b=["sh","-c",b[W+2]];continue}}let N=df(_,b);if(N===null)break;ne.push(_),ee.push(...b.slice(1,N)),b=b.slice(N),Qd.has(_)&&b[0]!==void 0&&(b=[Mi(b[0]),...b.slice(1)])}b.length===0&&(b=[ne.pop()??""]);let L=kf(ue(b[0]??"")),F={argv:b,name:L,wrappers:ne,wrapperArgs:ee,cwd:t.cwd,redirects:Oe,groupWriters:o,stdin:Z,stdinKind:ge,stdinExpands:Me?!Me.quotedDelimiter:H!==void 0,via:t.via,remote:t.remote,productionEnv:d,pipeFrom:r,pipeTo:null,captured:t.captured,background:!1,unresolved:ze,unreadableCode:null,text:e.source,guards:j,cwdFallbacks:U,altArgvs:[],stdinFile:Ye,functionCall:!1,scriptText:null,scriptPath:null,parent:t.parent},gr=b.length,mr=null;z&&Object.defineProperty(F,"altArgvs",{enumerable:!0,get:()=>mr??=ce().map(w=>w.length===te?w.slice(te-gr):w)}),r&&(r.pipeTo=F),s.push(F),jf(F,t,n);let $e=Pf(F,t,n);$e!==null&&(F.scriptText=$e.text,F.scriptPath=$e.path);let we=t.functions.get(b[0]??"");if(we&&ne.length===0&&!t.newProcess&&ws.get(t.functions)?.has(b[0])&&(F.functionCall=!0),we&&t.depth>=Wr&&!t.called.has(b[0])&&!t.bodyRead&&(t.depthLimit.hit=!0),we&&t.depth<Wr){let w=t.called.has(b[0]);t.called.add(b[0]);let _=new Map([...t.vars,...h]);b.slice(1).forEach((W,q)=>_.set(String(q+1),Ir({kind:"value",value:W},[...new Set(F.altArgvs.filter(G=>G.length===b.length).map(G=>G[q+1]).filter(G=>G!==W))]))),_.set("@",Ji(b.slice(1)));let O={...t,vars:_,depth:t.depth+1,via:"shell-string",captured:!1,frames:[],outerGuards:F.guards,andGuards:[],parent:F,locals:new Set,inFunction:!0,bodyRead:t.bodyRead||w},N=new Map(_);Pt(we,O,n,s),jr(O,t),Or(O,t,N)}if((L==="cd"||L==="pushd"||L==="popd")&&ne.every(w=>w==="command"||w==="builtin")){let w=b.slice(1),_=w.find(J=>!J.startsWith("-")&&!J.startsWith("+")),O=w.some(J=>/^[+-]\d+$/.test(J)),N=t.cwd,W=null;L==="popd"?O?(t.cwd=Pe,t.dirStack=t.dirStack.map(()=>Pe)):t.dirStack.length>0&&(w.includes("-n")||(t.cwd=t.dirStack[t.dirStack.length-1]),t.dirStack=t.dirStack.slice(0,-1)):L==="pushd"&&w.includes("-n")?_!==void 0&&(t.dirStack=[...t.dirStack,M(_,t.cwd,n)]):L==="pushd"&&(O||_===void 0)?!O&&t.dirStack.length>0?(t.cwd=t.dirStack[t.dirStack.length-1],t.dirStack=[...t.dirStack.slice(0,-1),N]):O&&(t.cwd=Pe,t.dirStack=[...t.dirStack.map(()=>Pe),Pe]):(w.includes("-")?t.cwd=t.oldCwd:_!==void 0&&/^~[-+](\/|$)/.test(_)?t.cwd=M(`.${_.slice(2)}`,_[1]==="-"?t.oldCwd:t.cwd,n):_!==void 0&&t.cdpath&&!_.startsWith("/")&&!_.startsWith("~")?t.cwd=Pe:t.cwd=_===void 0?n.home:M(_,t.cwd,n),L==="pushd"&&(t.dirStack=[...t.dirStack,N]),!w.includes("-")&&!t.cdpath&&(W=_===void 0||_.startsWith("/")||/^~(\/|$)/.test(_)?{abs:t.cwd??""}:/^~[-+]/.test(_)?null:{rel:_}));let q=_===void 0?-1:b.indexOf(_),G=q<0?[]:[...new Set(F.altArgvs.filter(J=>J.length===b.length).map(J=>J[q]).filter(J=>J!==_))].map(J=>J===""?N:M(J,N,n));(t.cwd!==N||G.length>0)&&(t.cwd!==N&&(t.oldCwd=N),t.cds=[...t.cds,{text:Rn(F),before:N,to:W,extra:G}])}if(L==="dirs"&&ne.length===0&&b.slice(1).some(w=>/^-[a-z]*c/.test(w))&&(t.dirStack=[]),L==="unset"&&!b.slice(1).some(w=>/^-[a-z]*f/.test(w)))for(let w of b.slice(1))/^[A-Za-z_][A-Za-z0-9_]*$/.test(w)&&Xe(t,w,{kind:"value",value:""});if(L==="unset"||L==="unfunction")for(let w of b.slice(1))ws.get(t.functions)?.delete(w);if((L==="shift"||L==="set"&&b.slice(1).some(w=>w==="--"||!/^[-+]./.test(w)))&&ms(t.vars),L==="printf"){let w=b.findIndex(O=>O==="-v"),_=w>0?b[w+1]:b.find(O=>/^-v[A-Za-z_]/.test(O))?.slice(2);_&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(_)&&Xe(t,_,{kind:"unknown"})}if(L==="set"&&ne.length===0){let w=b.slice(1);w.some((_,O)=>/^-[a-zA-Z]*e[a-zA-Z]*$/.test(_)||_==="-o"&&w[O+1]==="errexit")&&(t.errexit=!0),w.some((_,O)=>/^\+[a-zA-Z]*e[a-zA-Z]*$/.test(_)||_==="+o"&&w[O+1]==="errexit")&&(t.errexit=!1)}let je=[],Y=(w,_={})=>{let O={...t,vars:new Map([...t.vars,...h]),locals:new Set,maybeRuns:!1,subshell:!1,inFunction:!1,newProcess:!0,depth:t.depth+1,via:w,captured:!1,frames:[],outerGuards:F.guards,andGuards:[],parent:F,errexit:!1,deferred:[],..._};return O.deferred!==t.deferred&&je.push(O),O};if($e!==null&&$e.shell&&V()&&/\.(?:ps1|psm1|bat|cmd)$/i.test($e.path))An(/\.(?:bat|cmd)$/i.test($e.path)?"cmd":"powershell",$e.text,F,t,n,w=>fe(w,Y("shell-string"),n,s));else if($e!==null&&$e.shell){let w=$e.direct?0:b.findIndex((G,J)=>J>0&&!G.startsWith("-")),_=new Map([...t.vars,...h]),O=w>=0?b.slice(w+1):[];O.forEach((G,J)=>_.set(String(J+1),{kind:"value",value:G})),_.set("@",Ji(O));let N=$e.direct&&/^#!\s*\S*\/(?:env\s+)?(sh|dash|ksh|ash|mksh)\b/.test($e.text),W=Y("shell-string",{vars:_,posixOnly:zi.has(L)||N||(L==="source"||L===".")&&t.posixOnly,...L==="source"||L==="."?{errexit:t.errexit,deferred:t.deferred,newProcess:t.newProcess}:{}}),q=new Map(_);fe($e.text,W,n,s),(L==="source"||L===".")&&(jr(W,t),Or(W,t,q))}else if((L==="source"||L===".")&&ne.length===0){t.cwd=Pe;for(let w of[...t.vars.keys()])t.vars.set(w,{kind:"unknown"})}if(L==="osascript"){let w=b.slice(1).filter((_,O,N)=>N[O-1]==="-e").join(`
|
|
20
|
+
`);for(let _ of w.matchAll(/do\s+shell\s+script\s+"((?:\\.|[^"\\])*)"/gi))fe(_[1].replace(/\\(.)/g,"$1"),Y("shell-string"),n,s)}if(vf.has(L)){let w=Mr(b);if(w!==null)for(let _ of $f(w))fe(_,Y("shell-string"),n,s)}if(Yt.has(L)||L==="at"||L==="batch"){let w=Yt.has(L)?Jt(b):null,_=w?.command??null,O=L==="at"||L==="batch"||(w?.stdin??!1),N=zi.has(L);if(_!==null){Hi(_)&&!qi(_)&&(F.unreadableCode=`${L} -c ${k(_).slice(0,80)}`);let W=b.slice(b.indexOf(_)+1),q=new Map([...t.vars,...h]);W.length>0&&(ms(q),/\bshift\b/.test(_)||W.forEach((G,J)=>q.set(String(J),G.includes("{}")?{kind:"unknown"}:{kind:"value",value:G}))),fe(_,Y("shell-string",{posixOnly:N,vars:q}),n,s)}else if(Z!==null&&O)fe(Z,Y("stdin-script",{posixOnly:N}),n,s);else if(r&&O){let W=Lr(r);W!==null?fe(W,Y("stdin-script",{posixOnly:N}),n,s):["curl","wget","fetch","http","https","xh","aria2c"].includes(r.name)||(F.unreadableCode=`${L} reading a script from ${r.name}`)}}else if(L==="trap"&&b.length>=3&&!b[1].startsWith("-"))t.deferred.push({code:b[1],parent:F,errexit:t.errexit});else if(L==="eval"){let w=/^"?\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?"?$/.exec(p[1]?.raw??"")?.[1],_=w?t.vars.get(w):void 0,O=_?.kind==="list"&&p.length===2?[..._.values]:[b.slice(1).join(" ")];for(let N of O){Hi(N)&&!qi(N)&&(F.unreadableCode=`eval ${k(N).slice(0,80)}`);let W=Y("shell-string",{errexit:t.errexit,locals:t.locals,inFunction:t.inFunction,newProcess:t.newProcess,deferred:t.deferred}),q=new Map(W.vars);if(fe(N,W,n,s),S(N)){t.cwd=Pe;for(let G of[...t.vars.keys()])t.vars.set(G,{kind:"unknown"})}else jr(W,t),Or(W,t,q),[...W.vars].some(([G,J])=>zr.test(G)&&q.get(G)!==J)&&ms(t.vars)}}else if(L==="flock"||L==="script"){let w=b.findIndex(_=>_==="-c"||_==="--command");if(w>0&&b[w+1]!==void 0)fe(b[w+1],Y("shell-string"),n,s);else if(L==="flock"){let _=1;for(;_<b.length&&b[_].startsWith("-");)_+=["-w","--timeout","-E","--conflict-exit-code"].includes(b[_])?2:1;_+1<b.length&&Be(b.slice(_+1),Y("shell-string"),n,s,null)}}else if(V()&&(L==="cmd"||L==="powershell"||L==="pwsh")){let w=_f(L,b),_=O=>An(L==="cmd"?"cmd":"powershell",O,F,t,n,N=>fe(N,Y("shell-string"),n,s));if(w?.kind==="line")_(w.text);else if(w?.kind==="file"){let O=Ki(w.path,F,t,n);O!==null&&_(O)}else if(w?.kind==="unreadable")F.unreadableCode=`${L}: ${w.why}`;else if(Z!==null)_(Z);else if(r){let O=Lr(r);O!==null?_(O):F.unreadableCode=`${L} reading its commands from ${r.name}`}else if(F.stdinFile!==null){let O=Ki(F.stdinFile,F,t,n);O!==null&&_(O)}}else if(V()&&L==="wmic"&&b.some(w=>/^process$/i.test(w))&&b.some(w=>/^create$/i.test(w))){let w=b.findIndex(_=>/^create$/i.test(_));b[w+1]!==void 0&&An("cmd",b.slice(w+1).join(" "),F,t,n,_=>fe(_,Y("shell-string"),n,s))}else if(V()&&L==="robocopy"&&b.some(w=>/^\/{1,2}mov(?:e)?$/i.test(w))){let[w,_]=b.slice(1).filter(N=>!/^\/{1,2}[A-Za-z]+(?::.*)?$/.test(N)),O=N=>`'${N.replace(/'/g,"'\\''")}'`;w!==void 0&&_!==void 0&&fe(`mv ${O(w)} ${O(_)}`,Y("shell-string"),n,s)}else if(V()&&L==="forfiles"){let w=q=>{let G=b.findIndex(J=>new RegExp(`^/{1,2}${q}$`,"i").test(J));return G>0?b[G+1]:b.find(J=>new RegExp(`^/{1,2}${q}\\S`,"i").test(J))?.replace(new RegExp(`^/{1,2}${q}`,"i"),"")},_=(w("p")??".").replace(/(?<![\\/])[\\/]+$/,""),O=w("m")??"*",W=(w("c")??"cmd /c echo @file").replace(/@path/gi,`"${_}\\${O}"`).replace(/@relpath/gi,`".\\${O}"`).replace(/@(?:file|fname)/gi,`"${O}"`).replace(/@ext/gi,'"*"');An("cmd",W,F,t,n,q=>fe(q,Y("shell-string"),n,s))}else if(V()&&L==="schtasks"&&b.some(w=>/^\/{1,2}(?:create|change)$/i.test(w))){let w=b.findIndex(_=>/^\/{1,2}tr$/i.test(_));w>0&&b[w+1]!==void 0&&An("cmd",b[w+1],F,t,n,_=>fe(_,Y("shell-string"),n,s))}else if(L==="watch"){let w=new Set(["-n","--interval","-d","--differences","-q","--equexit","-g","-c","-x","-t","-b","-e","-p"]),_=1;for(;_<b.length&&b[_].startsWith("-");)_+=["-n","--interval","-q","--equexit"].includes(b[_])?2:1;_<b.length&&fe(b.slice(_).join(" "),Y("shell-string"),n,s)}else if(L==="git"&&b.some((w,_)=>b[_-1]==="-c"&&w.startsWith("alias."))){let w=cf(b);w&&fe(w,Y("shell-string"),n,s)}else if(L==="xargs"){let w=hf(b),_=b.find((W,q)=>b[q-1]==="-d"||b[q-1]==="--delimiter")??b.find(W=>/^-d./.test(W))?.slice(2)??b.find(W=>W.startsWith("--delimiter="))?.slice(12),O=Z!==null&&!S(Z)?(b.includes("-0")?Z.split("\0"):_?Z.split(_.replace(/^\\n$/,`
|
|
21
|
+
`)):Z.split(/\s+/)).map(W=>W.trim()).filter(Boolean):null,N=b.find((W,q)=>b[q-1]==="-I")??b.find(W=>/^-I./.test(W))?.slice(2)??b.find(W=>W.startsWith("--replace="))?.slice(10)??(b.includes("-i")||b.includes("--replace")?"{}":null);if(w.length&&O&&N)for(let W of O)Be(w.map(q=>q.split(N).join(W)),Y("xargs"),n,s,F);else w.length&&Be(O?[...w,...O]:w,Y("xargs"),n,s,F)}else if(L==="find")for(let w of gf(b))Be(w,Y("find-exec"),n,s,null);else if(L==="fd"||L==="fdfind")for(let w of mf(b))Be(w,Y("find-exec"),n,s,null);else if(L==="ssh"){let w=yf(b);w&&w.command&&fe(w.command,Y("remote",{remote:w.host,cwd:null}),n,s)}else if((L==="docker"||L==="podman")&&b[1]==="run"&&Zi(b).length>0){let w=bf(b);if(w){let _=Zi(b),O=w.map(N=>_.reduce((W,q)=>W.replace(new RegExp(`(^|[\\s'"=])${q.target.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?=/|$|[\\s'"])`,"g"),`$1${q.source}`),N));Be(O,Y("remote",{remote:null,cwd:null}),n,s,null)}}else if((L==="docker"||L==="podman")&&Vi(b).sub==="exec"){let{at:w,remoteHost:_}=Vi(b),O=wf([b[0],...b.slice(w)]);O&&Be(O.argv,Y("remote",{remote:_!==null?`docker:${_}`:`container:${O.container}`,cwd:null}),n,s,null)}else if((L==="kubectl"||L==="oc")&&Bi(b,ff)==="exec"){let w=b.indexOf("--");w>0&&Be(b.slice(w+1),Y("remote",{remote:"kubernetes",cwd:null}),n,s,null)}else if((L==="fly"||L==="flyctl")&&Bi(b,pf)==="ssh"){let w=b.findIndex(N=>N==="-C"||N==="--command"),_=w>0?b[w+1]:b.find(N=>N.startsWith("--command="))?.slice(10),O=b.find((N,W)=>b[W-1]==="-a"||b[W-1]==="--app")??b.find(N=>N.startsWith("--app="))?.slice(6);_&&fe(_,Y("remote",{remote:O&&/^[\w.-]+$/.test(O)?`the Fly app ${O}`:"a Fly machine",cwd:null}),n,s)}else if(L==="railway"&&b[1]==="run"){let w=b.slice(2).filter((O,N,W)=>!(O.startsWith("-")&&N===0)||W.length===1),_=b.slice(2).findIndex(O=>!O.startsWith("-"));_>=0&&Be(b.slice(2+_),Y("shell-string",{productionEnv:!0}),n,s,null)}else if(["doppler","infisical"].includes(L)&&b[1]==="run"){let w=b.findIndex(O=>O==="--command"||O.startsWith("--command=")),_=w<0?null:b[w].startsWith("--command=")?b[w].slice(10):b[w+1]??null;_&&fe(_,Y("shell-string"),n,s)}else if(["npm","pnpm","yarn","bun"].includes(L)&&["exec","dlx","x"].includes(bs(b).sub)){let w=bs(b).at,_=b.slice(w+1).findIndex(O=>!O.startsWith("-"));_>=0&&Be([Mi(b[w+1+_]),...b.slice(w+2+_)],Y("shell-string"),n,s,null)}for(let w of je)ys(w,n,s);return F.stdinFile!==null&&sa(s.filter(w=>{for(let _=w.parent;_;_=_.parent)if(_===F)return!0;return!1}),F.stdinFile),F}function qi(e){let t=k(e.trim()),n=/^\$\(\s*([^\s)]+)([^)]*)\)?/.exec(t)??/^`\s*([^\s`]+)([^`]*)`?/.exec(t);if(!n)return!1;let s=ue(n[1]),r=n[2].split(/\s+/);return["ssh-agent","direnv","starship","fnm","mise","rtx","pyenv","rbenv","nodenv","goenv","jenv","opam","zoxide","atuin","thefuck","keychain","gpg-agent"].includes(s)||r.some(o=>["shellenv","activate","hook"].includes(o))||r[0]==="init"&&r.length<=3}function Hi(e){return e.trimStart().startsWith(ie)}function Lr(e){if(e.name==="echo"||e.name==="printf"){let t=e.argv.slice(1).filter(n=>!/^-[neE]+$/.test(n));return t.some(S)?null:e.name==="printf"&&t[0]?.includes("%")?t.slice(1).join(`
|
|
22
|
+
`):t.join(" ").replace(/\\n/g,`
|
|
23
|
+
`)}if(e.name==="base64"&&e.argv.some(t=>t==="-d"||t==="-D"||t==="--decode")&&e.pipeFrom){let t=Lr(e.pipeFrom);if(t===null)return null;try{return Buffer.from(t.trim(),"base64").toString("utf8")}catch{return null}}if(e.stdin!==null&&e.name==="base64"&&e.argv.some(t=>t==="-d"||t==="-D"||t==="--decode"))try{return Buffer.from(e.stdin.trim(),"base64").toString("utf8")}catch{return null}return null}function cf(e){let t=new Map,n=1;for(;n<e.length&&e[n].startsWith("-");)if(e[n]==="-c"&&e[n+1]){let a=/^alias\.([^=]+)=(.*)$/s.exec(e[n+1]);a&&t.set(a[1],a[2]),n+=2}else n+=e[n]==="-C"?2:1;let s=e[n],r=s?t.get(s):void 0;if(r===void 0)return null;let o=e.slice(n+1).join(" ");return r.startsWith("!")?`${r.slice(1)} ${o}`:`git ${r} ${o}`}function Be(e,t,n,s,r){if(!e.length)return;let o=e.map(uf).join(" "),a=s.length;fe(o,t,n,s);let i=s[a];i&&r?.pipeFrom?i.pipeFrom=r.pipeFrom:i&&r?.stdinFile&&(i.stdinFile=r.stdinFile)}function uf(e){return/^[A-Za-z0-9_\-./=:@%+,~]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Jt(e){let t=!1,n=!1;for(let s=1;s<e.length;s++){let r=e[s];if(r==="--"||r==="-"){let o=e[s+1];return t?{command:o??null,script:null,stdin:!1}:{command:null,script:n?null:o??null,stdin:n||o===void 0}}if(r==="--rcfile"||r==="--init-file"){s++;continue}if(!r.startsWith("--")){if(/^[-+][a-zA-Z]+$/.test(r)){r.startsWith("-")&&r.includes("c")&&(t=!0),r.startsWith("-")&&r.includes("s")&&(n=!0),/[oO]/.test(r.slice(1))&&s++;continue}return t?{command:r,script:null,stdin:!1}:{command:null,script:n?null:r,stdin:n}}}return{command:null,script:null,stdin:!t}}function df(e,t){let n=1,r={sudo:new Set(["-u","-g","-C","-D","-h","-p","-r","-t","-U","--user","--group","--host","--prompt"]),doas:new Set(["-u","-C"]),pkexec:new Set(["--user","-u"]),run0:new Set(["-u","--user","-g","--group","-D","--chdir","--unit","--property","--description","--slice","--nice","--setenv"]),env:new Set(["-u","-C","-S","--unset","--chdir","--split-string"]),nice:new Set(["-n","--adjustment"]),ionice:new Set(["-c","-n","-p"]),timeout:new Set(["-s","-k","--signal","--kill-after"]),gtimeout:new Set(["-s","-k","--signal","--kill-after"]),stdbuf:new Set(["-i","-o","-e"]),exec:new Set(["-a"]),script:new Set(["-c","-t"]),npx:new Set(["-p","--package","-c","--call","--registry","--cache","--prefix","--userconfig","--workspace","-w","--node-options"]),pnpx:new Set(["--package","--registry","--cache","--prefix","--userconfig","--workspace","-w"]),bunx:new Set(["-p","--package","--cwd","--registry","--cache-dir"]),uv:new Set(["--from","--with","--python","-p","--directory","--project","--index","--index-url","--env-file"]),uvx:new Set(["--from","--with","--python","-p","--directory","--index","--index-url"]),pipx:new Set(["--spec","--python","--index-url","--pip-args"]),poetry:new Set(["-C","--directory","-P","--project"]),pdm:new Set(["-p","--project"]),op:new Set(["--env-file","--account","--cache","--config","--encoding","--session"]),doppler:new Set(["-c","--config","-p","--project","--command","--mount","--mount-format","--mount-template","--mount-max-reads","--fallback","--token","--scope","--name-transformer"]),infisical:new Set(["--env","--projectId","--path","--token","--domain","--command","--tags"]),dotenvx:new Set(["-f","--env-file","-e","--env","--convention"]),dotenv:new Set(["-e","-c","-v","-p","-f","--file"]),sshpass:new Set(["-p","-f","-d","-P"]),"aws-vault":new Set(["-d","--duration","--region","-t","--mfa-token","--backend","--prompt"]),"sandbox-exec":new Set(["-f","-n","-p","-D"]),flock:Qi,chrt:new Set(["-T","--sched-runtime","-P","--sched-period","-D","--sched-deadline"]),unshare:new Set(["-S","--setuid","-G","--setgid","-R","--root","-w","--wd"]),"systemd-inhibit":new Set(["--what","--who","--why","--mode"])}[e]??new Set;if(e==="launchctl")return(t[1]==="asuser"||t[1]==="bsexec")&&t.length>3?3:null;if((e==="taskset"||e==="chrt"||e==="prlimit")&&t.slice(1).some(a=>a==="-p"||a==="--pid"||a.startsWith("--pid="))||e==="systemd-inhibit"&&t.includes("--list"))return null;if(e==="uv")if(t[1]==="run")n=2;else if(t[1]==="tool"&&t[2]==="run")n=3;else return null;let o={bundle:"exec",poetry:"run",pdm:"run",rye:"run",pipx:"run",op:"run",doppler:"run",infisical:"run",dotenvx:"run"};if(o[e]!==void 0){let a=1;for(;a<t.length&&t[a].startsWith("-");)a+=r.has(t[a])?2:1;if(t[a]!==o[e])return null;n=a+1}if(e==="aws-vault"){if(t[1]!=="exec")return null;for(n=2;n<t.length&&t[n].startsWith("-")&&t[n]!=="--";)n+=r.has(t[n])?2:1;return n++,t[n]==="--"&&n++,n<t.length?n:null}if(e==="cross-env"){for(;n<t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[n]);)n++;return n<t.length?n:null}for(;n<t.length;){let a=t[n];if(a==="--")return n+1<t.length?n+1:null;if(e==="env"&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){n++;continue}if((e==="timeout"||e==="gtimeout")&&/^\d+(\.\d+)?[smhd]?$/.test(a)&&!t.slice(1,n).some(i=>/^\d/.test(i))){n++;continue}if(e==="nice"&&/^-\d+$/.test(a)){n++;continue}if(a.startsWith("-")&&a.length>1){n+=r.has(a)?2:1;continue}break}if(e==="dotenv"){if(["list","get","set","unset"].includes(t[n]??""))return null;if(t[n]==="run"){for(n++;n<t.length&&t[n].startsWith("-")&&t[n]!=="--";)n++;t[n]==="--"&&n++}return n<t.length?n:null}return e==="npx"||e==="pnpx"||e==="bunx"?n<t.length?n:null:e==="script"?t.slice(1,n).some(a=>a==="-c"||a==="--command")?null:n+1<t.length?n+1:null:e==="taskset"||e==="chrt"||e==="flock"?n+1<t.length?n+1:null:n<t.length?n:null}var ff=new Set(["-n","--namespace","--context","--cluster","--kubeconfig","--user","-s","--server","--as","--request-timeout"]),pf=new Set(["-a","--app","-c","--config","-t","--access-token","-r","--region","--org"]);function Bi(e,t){for(let n=1;n<e.length;n++){let s=e[n];if(s==="--")return;if(!s.startsWith("-"))return s;!s.includes("=")&&t.has(s)&&n++}}function Vi(e){let t=new Set(["-H","--host","--context","-c","--config","-l","--log-level","--tlscacert","--tlscert","--tlskey"]),n=1,s=null;for(;n<e.length&&e[n].startsWith("-");){let r=e[n],o=r.indexOf("="),a=o>0?r.slice(0,o):r,i=o>0?r.slice(o+1):e[n+1];["-H","--host","--context","-c"].includes(a)&&i&&!/^(default|desktop-linux|colima|orbstack|unix:\/\/.*)$/.test(i)&&(s=i),n+=o<0&&t.has(r)?2:1}return{sub:e[n]??"",at:n,remoteHost:s}}function hf(e){let t=new Set(["-n","-P","-L","-s","-I","-E","-d","-a","--max-args","--max-procs","--delimiter","--arg-file","--replace"]),n=1;for(;n<e.length&&e[n].startsWith("-");)n+=t.has(e[n])?2:1;return e.slice(n)}function gf(e){let t=[];for(let n=1;n<e.length;n++)if(["-exec","-execdir","-ok","-okdir"].includes(e[n])){let s=e.findIndex((r,o)=>o>n&&(r===";"||r==="+"||r==="\\;"));t.push(e.slice(n+1,s===-1?e.length:s)),s!==-1&&(n=s)}return t}function mf(e){let t=e.findIndex((s,r)=>r>0&&["-x","--exec","-X","--exec-batch"].includes(s));if(t<0)return[];let n=e.findIndex((s,r)=>r>t&&(s===";"||s==="\\;"));return[e.slice(t+1,n===-1?e.length:n)]}function yf(e){let t=new Set(["-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w","-B"]),n=1;for(;n<e.length&&e[n].startsWith("-");)n+=t.has(e[n])?2:1;let s=e[n];if(!s)return null;let r=e.slice(n+1);return{host:s,command:r.length?r.join(" "):null}}function Zi(e){let t=[];for(let n=2;n<e.length;n++){let s=e[n],r=s==="-v"||s==="--volume"?e[n+1]:s.startsWith("--volume=")?s.slice(9):/^-v./.test(s)?s.slice(2):null;if(r){let[a,i]=r.split(":");a&&i&&(a.startsWith("/")||a.startsWith("~")||S(a))&&t.push({source:a,target:i.replace(/\/$/,"")||"/"})}let o=s==="--mount"?e[n+1]:s.startsWith("--mount=")?s.slice(8):null;if(o&&/type=bind/.test(o)){let a=/(?:source|src)=([^,]+)/.exec(o)?.[1],i=/(?:target|dst|destination)=([^,]+)/.exec(o)?.[1];a&&i&&t.push({source:a,target:i.replace(/\/$/,"")||"/"})}}return t}function bf(e){let t=new Set(["-v","--volume","--mount","-e","--env","-w","--workdir","--name","-p","--publish","--network","--net","-u","--user","--entrypoint","--env-file","-l","--label","--platform","--memory","-m","--cpus","--add-host","--hostname","-h","--device","--restart","--pid","--ipc","--cap-add","--cap-drop","--security-opt","--tmpfs","--log-driver","--ulimit"]),n=2;for(;n<e.length&&e[n].startsWith("-");)n+=t.has(e[n])?2:1;return n+1<e.length?e.slice(n+1):null}function wf(e){let t=new Set(["-e","--env","-u","--user","-w","--workdir","--env-file"]),n=2;for(;n<e.length&&e[n].startsWith("-");)n+=t.has(e[n])?2:1;let s=e[n];return!s||n+1>=e.length?null:{container:s,argv:e.slice(n+1)}}function ue(e){let t=e.lastIndexOf("/"),n=t>=0?e.slice(t+1):e;return V()?n.slice(n.lastIndexOf("\\")+1).toLowerCase().replace(/\.(?:exe|cmd|bat|com)$/,""):n}function Gi(e){if(!V()||!e.includes("\\")||/^(?:HK(?:LM|CU|CR|U|CC)|HKEY_|Registry::)/i.test(e))return e;let t=/^(-[\w-]*=)?(.*)$/s.exec(e),n=t[2];return/^(?:[A-Za-z]:\\|\\\\|\.{1,2}\\|~\\)/.test(n)||/^[\w .()$@{}~-]+(?:\\[\w .()$@{}~-]+)+\\?$/.test(n)?`${t[1]??""}${n.replace(/\\/g,"/")}`:e}function kf(e){if(e==="python"||e==="python3")return e;if(/^python\d+(?:\.\d+)*[tdmu]?$/.test(e)||/^pypy\d*(?:\.\d+)*$/.test(e))return"python3";if(/^node(?:js|\d+(?:\.\d+)*)$/.test(e))return"node";let t=/^(ruby|perl|php|bash|zsh|ksh|gawk)\d+(?:\.\d+)*$/.exec(e);return t?t[1]:e}var vf=new Set(["awk","gawk","mawk","nawk","busybox-awk"]);function Mr(e){let t=[];for(let n=1;n<e.length;n++){let s=e[n];if(s==="-f"||s==="--file"||s.startsWith("--file="))return null;if(s==="-e"||s==="--source")t.push(e[++n]??"");else if(s.startsWith("--source="))t.push(s.slice(9));else if(["-F","-v","-i","--include","-l","--load","--assign","--field-separator"].includes(s))n++;else if(s==="--"){t.length===0&&e[n+1]!==void 0&&t.push(e[n+1]);break}else if(!s.startsWith("-")){t.length===0&&t.push(s);break}}return t.length>0?t.join(`
|
|
24
|
+
`):null}function $f(e){let t=s=>{let r="";for(let o of s.matchAll(/"((?:\\.|[^"\\])*)"|([^\s"]+)/g))r+=o[1]!==void 0?o[1].replace(/\\(.)/g,"$1"):'"$(unknown)"';return r},n=[];for(let s of e.matchAll(/\bsystem\s*\(([^()]*)\)/g))n.push(t(s[1]));for(let s of e.matchAll(/\|&?\s*((?:"(?:\\.|[^"\\])*"\s*)+)/g))n.push(t(s[1]));for(let s of xf(e))n.push(t(s));for(let s of e.matchAll(/\bprintf?\s*\(?\s*((?:"(?:\\.|[^"\\])*"|[^;}|"()])+?)\)?\s*\|&?\s*"\s*(?:\/\S*\/)?(?:ba|z|da|k|mk|a)?sh\b[^"]*"/g))n.push(t(s[1]));return[...new Set(n.map(s=>s.trim()).filter(Boolean))]}function S(e){return e.includes(ie)}function k(e){return e.replace(new RegExp(`${ie}([^${le}]*)${le}`,"g"),"$1")}function xf(e){let t=[],n=-1,s=-1,r=0;for(;r<e.length;){let o=e[r];if(o==='"'){let a=r+1;for(;a<e.length&&e[a]!=='"';)a+=e[a]==="\\"?2:1;if(a>=e.length)break;n<0&&(n=r),s=a+1,r=a+1;continue}if(o===" "||o===" "||o===`
|
|
25
|
+
`||o==="\r"){r++;continue}o==="|"&&n>=0&&/^\|&?\s*getline\b/.test(e.slice(r,r+64))&&t.push(e.slice(n,s)),n=-1,r++}return t}function M(e,t,n){if(V())return Sf(e,t,n);let s=e;if(s==="~"||s.startsWith("~/"))s=n.home+s.slice(1);else if(s.startsWith("~")){let o=s.indexOf("/");return`${ie}${o<0?s:s.slice(0,o)}${le}${o<0?"":s.slice(o)}`}if(S(s)&&!s.startsWith("/"))return s;s.startsWith("/")||(s=En.join(t??".",s));let r=En.normalize(s);return r.length>1&&r.endsWith("/")?r.slice(0,-1):r}function _f(e,t){let n=t.map((a,i)=>i===0?a:/^\/\/[^/]+$/s.test(a)?a.slice(1):a.replace(/^\/([A-Za-z])(?=\/)/,(l,c)=>`${c.toUpperCase()}:`));if(e==="cmd"){for(let a=1;a<n.length;a++){let i=/^\/([ck])(.*)$/is.exec(n[a]);if(i)return{kind:"line",text:[i[2],...n.slice(a+1)].filter(l=>l!=="").join(" ")};if(!n[a].startsWith("/"))break}return null}let s=a=>/^(?:--|[-\u2013\u2014\u2015/])[A-Za-z]/.test(a)?a.replace(/^(?:--|[-\u2013\u2014\u2015/])/,"").toLowerCase():null,r=(a,i,l)=>{let c=s(a);return c!==null&&c.length>=l&&i.startsWith(c)},o=[["executionpolicy",2],["ep",2],["windowstyle",1],["version",1],["inputformat",2],["outputformat",1],["psconsolefile",2],["configurationname",4],["workingdirectory",2],["wd",2],["settingsfile",2],["custompipename",2]];for(let a=1;a<n.length;a++){let i=n[a];if(r(i,"encodedcommand",1)||/^(?:--|[-\u2013\u2014\u2015/])(?:ec|enc)$/i.test(i)){let l=n[a+1]??"";return!/^[A-Za-z0-9+/]+={0,2}$/.test(l)||l.length%4!==0?{kind:"unreadable",why:"an encoded command that is not base64"}:{kind:"line",text:Buffer.from(l,"base64").toString("utf16le")}}if(r(i,"command",1)){let l=n.slice(a+1);return l.length===1&&l[0]==="-"?null:{kind:"line",text:l.join(" ")}}if(r(i,"file",1))return n[a+1]===void 0||n[a+1]==="-"?null:{kind:"file",path:n[a+1]};if(s(i)!==null){o.some(([l,c])=>r(i,l,c))&&a++;continue}return e==="pwsh"?{kind:"file",path:i}:{kind:"line",text:n.slice(a).join(" ")}}return null}function An(e,t,n,s,r,o){let a=s.cwd!==null&&!S(s.cwd)?Je(s.cwd):null,i=e==="cmd"?Ti(t,{cwd:a}):Vt(t,{cwd:a});i.kind==="shell"?o(i.text):n.unreadableCode=`${e==="cmd"?"cmd":"PowerShell"}: ${i.why}`}function Ki(e,t,n,s){if(S(e))return t.unreadableCode=`a script whose name the line does not show (${k(e).slice(0,80)})`,null;let r=M(e,t.cwd,s),o=n.files.get(r);return o!==void 0?o:(S(r)||s.wantFiles?.add(r),s.unreadableFiles?.includes(r)&&(t.unreadableCode=`${ue(r)}, a script this session wrote that could not be read`),null)}function Sf(e,t,n){if(/^nul(?:\.[^\\/]*)?$/i.test(e))return"/dev/null";let s=We(e);if(s===null)return`${ie}${e.slice(0,2)}${le}/${e.slice(2).replace(/\\/g,"/")}`;let r=s;if(r==="~"||r.startsWith("~/"))r=n.home+r.slice(1);else if(r.startsWith("~")){let o=r.indexOf("/");return`${ie}${o<0?r:r.slice(0,o)}${le}${o<0?"":r.slice(o)}`}if(S(r)&&!r.startsWith("/"))return r;if(!r.startsWith("/")){let o=t!==null?/^(\/[a-z]|\/unc\/[^/]+\/[^/]+)(\/.*)?$/s.exec(t):null;r=o?`${o[1]}${En.normalize(`/${o[2]??""}/${r}`)}`:En.join(t??".",r)}return We(r)??r}function Cf(e,t,n,s){let r=e.raw.slice(e.raw.indexOf("=")+1);if(Bd.test(r))return{kind:"unknown",production:!0};if([...r.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)].some(l=>n.vars.get(l[1])?.production))return{kind:"unknown",production:!0};if(/^["']?\$\(\s*mktemp\b/.test(r)||/^["']?`\s*mktemp\b/.test(r))return{kind:"value",value:En.join(s.tmpdir,`${t}.mktemp`)};if(/^["']?(\$\(\s*pwd\s*\)|`\s*pwd\s*`)["']?$/.test(r)||/^["']?\$(PWD|\{PWD\})["']?$/.test(r)&&!n.vars.has("PWD")){if(!n.cwd)return{kind:"unknown"};let l={kind:"value",value:n.cwd},c=Rf(n,et(n),s);return c.length>0&&oa.set(l,c),l}if(/^["']?\$\(\s*git rev-parse --show-toplevel\s*\)["']?$/.test(r)){let l=ra(n.cwd,s);return l?{kind:"value",value:l}:{kind:"unknown"}}if(/^["']?\$!["']?$/.test(r))return{kind:"value",value:"$!"};let a=Ee(e,n,s),i=a.text.slice(a.text.indexOf("=")+1);return S(i)?{kind:"value",value:i}:{kind:"value",value:i==="~"||i.startsWith("~/")?s.home+i.slice(1):i}}function ra(e,t){let n=t.projectDir?t.projectDir.replace(/(?<!\/)\/+$/,""):null;return e&&n&&!S(n)&&(e===n||e.startsWith(`${n}/`))?n:e}var Yi=/^(?:\$\(\s*pwd(?:\s+-[LP])?\s*\)|`\s*pwd(?:\s+-[LP])?\s*`)$/,Af=/^(?:\$\(\s*git rev-parse --show-toplevel\s*\)|`\s*git rev-parse --show-toplevel\s*`)$/;function Ee(e,t,n){if(e.provenance==="literal"||e.parts.length===0)return{text:e.text,unresolved:[]};let s="",r=!1,o=[],a=null;for(let i of e.parts){if(i.provenance==="command-substitution"&&s===""&&a===null&&(Yi.test(i.raw)||Af.test(i.raw))){let u=Yi.test(i.raw)?null:ra(t.cwd,n);a={raw:i.raw,path:u!==null&&u!==t.cwd?u:"."};continue}if(i.provenance==="variable"){let u=Ef(i.raw,t,n);u===null?(o.push(i.raw),s+=`${ie}${i.raw}${le}`):s+=u;continue}let l=i.provenance==="command-substitution"?/^(?:\$\(|`)\s*(?:echo|printf)\s+([A-Za-z0-9_./~ -]+?)\s*(?:\)|`)$/.exec(i.raw):null;if(l){s+=l[1].trim();continue}if(i.provenance==="command-substitution"||i.provenance==="arithmetic"||i.provenance==="unknown"){o.push(i.raw),s+=`${ie}${i.provenance==="command-substitution"?Fr(i.raw,t,n):i.raw}${le}`;continue}let c=Wf(i.raw,r);s+=c.text,r=c.inDouble}return a?s===""||s.startsWith("/")?{text:a.path+s,unresolved:o}:{text:`${ie}${Fr(a.raw,t,n)}${le}${s}`,unresolved:[a.raw,...o]}:{text:s,unresolved:o}}function Ef(e,t,n){let s=/^\$([A-Za-z_][A-Za-z0-9_]*|[0-9!$?#@*-])(.*)$/s.exec(e);if(s&&!e.startsWith("${")){let u=s[1]==="IFS"?" ":Kt(s[1],t,n);return u===null?null:u+s[2]}if(e==="${IFS}")return" ";let r=/^\$\{([A-Za-z_][A-Za-z0-9_]*)(%%?|##?)([^}*?[]*)\}$/.exec(e);if(r){let u=Kt(r[1],t,n);if(u===null)return null;let f=r[3];return r[2].startsWith("%")?f&&u.endsWith(f)?u.slice(0,-f.length):u:f&&u.startsWith(f)?u.slice(f.length):u}let o=/^\$\{([A-Za-z_][A-Za-z0-9_]*)(%%?|##?|\/\/?|:[\s\d-])/.exec(e);if(o){let u=Kt(o[1],t,n);if(u!==null&&S(u))return u}let a=/^\$\{([A-Za-z_][A-Za-z0-9_]*):?\?[^}]*\}$/.exec(e);if(a)return Kt(a[1],t,n);let i=/^\$\{([A-Za-z_][A-Za-z0-9_]*|[0-9!$?#@*-])(?:(:?[-=])([^}]*))?\}$/.exec(e);if(!i)return null;let l=i[1],c=Kt(l,t,n);if(c!==null&&!(c===""&&i[2]?.startsWith(":")))return c;if(i[2]&&i[3]!==void 0&&(c===""||!t.vars.has(l))){let u=i[3];if(!u.includes("$")&&!u.includes("`"))return u==="~"||u.startsWith("~/")?n.home+u.slice(1):u}return null}var Qe=new WeakMap,ws=new WeakMap,oa=new WeakMap;function Rf(e,t,n){return ta(e,t,n).filter(s=>s!==null&&!S(s))}function ms(e){for(let t of[...e.keys()])zr.test(t)&&e.set(t,{kind:"unknown"})}function Xe(e,t,n){/^argv\b/.test(t)&&ms(e.vars);let s=e.vars.get(t)??null;e.vars.set(t,n);let r={at:e.frames.map(a=>[a,a.phase]),guards:et(e),maybe:e.maybeRuns,prev:s},o=null;for(let a of[...oa.get(n)??[]].reverse()){let i={kind:"value",value:a};Qe.set(i,o?{...r,maybe:!0,prev:o}:r),o=i}Qe.set(n,o?{...r,maybe:!0,prev:o}:r)}function Tr(e,t,n,s){let r=Qe.get(e);if(!r)return!0;if(r.maybe)return!1;let o=s??t.frames.map(l=>[l,l.phase]);if(!(r.at.length<=o.length&&r.at.every(([l,c],u)=>o[u][0]===l&&o[u][1]===c)))return!1;if(r.guards.length===0)return!0;let i=n??et(t);return r.guards.every(l=>i.includes(l))}function ia(e,t,n,s){let r=[],o=new Map,a;for(let[i,l]of e.vars){if(t&&!t.has(i)||!Qe.has(l)||(a??=s??et(e),Tr(l,e,a,n)))continue;let c=new Set;for(let u=Qe.get(l)?.prev??null;r.length<16;u=u?Qe.get(u)?.prev??null:null){let f=u??{kind:"value",value:""};o.has(i)||o.set(i,f);let p=f.kind==="value"?f.value:`\0${f.kind}`;if(c.has(p)||(c.add(p),r.push(new Map(e.vars).set(i,f))),!u||Tr(u,e,a,n))break}if(r.length>=16)break}return o.size>1&&r.unshift(new Map([...e.vars,...o])),r}function aa(e){return new Set([...e.matchAll(/\$\{?#?([A-Za-z_][A-Za-z0-9_]*|[0-9@*#])/g)].map(t=>t[1]))}function Ir(e,t){let n=null;for(let s of[...t].reverse()){let r={kind:"value",value:s};n&&Qe.set(r,{at:[],guards:[],maybe:!0,prev:n}),n=r}return n&&Qe.set(e,{at:[],guards:[],maybe:!0,prev:n}),e}var Dr=new WeakMap;function Ji(e){let t={kind:"value",value:e.join(" ")};return Dr.set(t,e),t}function Kt(e,t,n){let s=t.vars.get(e);return s?s.kind==="value"?s.value:null:e==="HOME"?n.home:e==="TMPDIR"?n.tmpdir:e==="PWD"?t.cwd:e==="OLDPWD"?t.oldCwd:e==="CLAUDE_PROJECT_DIR"?n.projectDir??null:e==="CLAUDE_CONFIG_DIR"?n.claudeConfigDir??null:e==="!"?"$!":V()?Of(e,n):null}function Of(e,t){switch(e.toUpperCase()){case"USERPROFILE":return t.home;case"TEMP":case"TMP":return t.tmpdir;case"SYSTEMROOT":case"WINDIR":return"/c/windows";case"SYSTEMDRIVE":return"/c";case"PROGRAMFILES":return"/c/program files";case"PROGRAMFILES(X86)":return"/c/program files (x86)";case"PROGRAMDATA":case"ALLUSERSPROFILE":return"/c/programdata";case"APPDATA":return`${t.home}/appdata/roaming`;case"LOCALAPPDATA":return`${t.home}/appdata/local`;default:return null}}function Fr(e,t,n){let s="",r=0,o=!1;for(;r<e.length;){let a=e[r];if(a==="'"&&!o){(s.split('"').length-1)%2===0&&(o=!0),s+=a,r++;continue}if(a==="'"&&o){o=!1,s+=a,r++;continue}if(!o&&a==="\\"&&r+1<e.length){s+=e.slice(r,r+2),r+=2;continue}if(!o&&a==="$"){let i=/^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/.exec(e.slice(r));if(i){let l=Kt(i[1]??i[2],t,n);if(l!==null&&l!=="$!"&&!S(l)){s+=l,r+=i[0].length;continue}}}s+=a,r++}return s}function jf(e,t,n){let s=e.redirects.find(l=>(l.op===">"||l.op===">>"||l.op===">|")&&l.target&&!S(l.target)),r=e.name==="tee"?e.argv.slice(1).find(l=>!l.startsWith("-")&&!S(l)):void 0,o=s?.target??r;if(!o||o.startsWith("/dev/"))return;let a=null;if((e.name==="cat"||e.name==="tee")&&e.stdin!==null&&e.argv.length<=2)a=e.stdin;else if(e.name==="echo"||e.name==="printf"){let l=e.argv.slice(1).filter(c=>!/^-[neE]+$/.test(c));l.some(S)||(a=e.name==="printf"&&l[0]?.includes("%")?l.slice(1).join(`
|
|
26
26
|
`):l.join(" ").replace(/\\n/g,`
|
|
27
|
-
`))}if(
|
|
28
|
-
`&&(
|
|
29
|
-
`&&(
|
|
30
|
-
`,t:" ",r:"\r","\\":"\\","'":"'",'"':'"',a:"\x07",b:"\b",e:"\x1B",E:"\x1B",f:"\f",v:"\v",0:"\0"},s="",r=n;for(;r<e.length&&e[r]!=="'";){if(e[r]==="\\"&&r+1<e.length){let o=e[r+1];if(o==="x"){let i=/^[0-9a-fA-F]{1,2}/.exec(e.slice(r+2))?.[0]??"";s+=i?String.fromCharCode(parseInt(i,16)):"x",r+=2+i.length;continue}s+=t[o]??o,r+=2;continue}s+=e[r],r++}return{text:s,next:r+1}}var Rn="what this session made earlier";function bs(e,n,t){if(!n||C(e)||!e.startsWith("/"))return null;let s=t?"full":"parent";n.touched?.[s].add(e);let r=n.real?.[s][e];return r!==void 0&&r!==e?r:null}var Yi={catastrophic:3,normal:2,disposable:1},Xi=new Set(["node_modules","dist","build","out",".next",".nuxt",".output",".svelte-kit",".turbo",".parcel-cache",".vite",".cache","coverage",".nyc_output","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".venv","venv","target",".gradle","tmp",".tmp","temp",".vscode-test",".vscode-test-web","test-results","playwright-report","storybook-static",".docusaurus",".angular",".expo",".astro",".wrangler",".serverless",".terraform",".dart_tool",".stack-work","htmlcov",".hypothesis",".benchmarks",".pnpm-store",".webpack",".esbuild",".vinxi",".contentlayer",".velite",".nx",".yarn-cache",".eslintcache",".vitest-reports"]),wf=/^\.?(tmp|temp)([-_.].*)?$|[-_.](tmp|temp)$/i,Qi=new Set(["Desktop","Documents","Downloads","Library","Pictures","Movies","Music","Applications","Public",".ssh",".gnupg",".aws",".config",".claude",".local",".kube",".docker"]),ea=new Set(["/bin","/sbin","/usr","/etc","/var","/opt","/System","/Library","/Applications","/Users","/private","/Volumes","/home","/root","/lib","/boot","/srv","/cores","/dev"]);function ta(e){let n=["/tmp","/private/tmp","/var/tmp","/private/var/tmp","/var/folders","/private/var/folders"],t=e.tmpdir.replace(/(?<!\/)\/+$/,"");return t&&n.push(t,t.startsWith("/private/")?t.slice(8):`/private${t}`),H()&&n.push("/c/windows/temp"),n}function kf(e,n){if(Ei(e))return{kind:"catastrophic",path:e,token:"fs.root",why:e.startsWith("/unc/")?`a network share (${cs(e)})`:`the drive ${cs(e)}`};let t=/^\/[a-z]\/(.+)$/s.exec(e);return t&&_r.includes(t[1])?{kind:"catastrophic",path:e,token:"fs.system",why:`the system folder ${cs(e)}`}:_e.dirname(e)===n&&xr.has(_e.basename(e))?{kind:"catastrophic",path:e,token:"fs.home",why:`the ${_e.basename(e)} folder in home`}:null}var vf=[..."abcdefghijklmnopqrstuvwxyz"].map(e=>`/${e}`).concat(_r.map(e=>`/c/${e}`)),na=(e,n)=>e===n||e.startsWith(n.endsWith("/")?n:`${n}/`);function Y(e,n,t){let s=Ji(e,n,t);if(!t.onDisk)return s;let r=U(e,n??t.base??t.projectRoot,t),o=_e.basename(e.replace(/(?<!\/)\/+$/,"")),i=bs(r,t.onDisk,e.endsWith("/")||/[*?[]/.test(o));if(i===null)return s;let a=Ji(i,null,t);return Yi[a.kind]>Yi[s.kind]?{...a,why:`${a.why}, through a link`}:s}function Ji(e,n,t){let s=U(e,n??t.base??t.projectRoot,t),r=s.replace(new RegExp(`[${ae}${le}]`,"g"),"");return s.startsWith("/dev/")&&!["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"].includes(s)&&!ls(s)?{kind:"catastrophic",path:r,token:"fs.device",why:`a raw device (${r})`}:C(s)?xf(s,r,t,n??t.base??null):sa(s,t)}function $f(e){let n="",t=!1;for(let r=0;r<e.length;r++){let o=e[r];if(o==="*"||o==="?"){n+=o==="*"?"[^/]*":"[^/]",t=!0;continue}if(o==="["){let i=e.indexOf("]",r+(e[r+1]==="!"||e[r+1]==="^"?3:2));if(i>r){let a=e.slice(r+1,i),l=a.startsWith("!")||a.startsWith("^"),c=(l?a.slice(1):a).replace(/[\\\]^]/g,"\\$&");n+=`[${l?"^/":""}${c}]`,t=!0,r=i;continue}}n+=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(!t)return null;let s;try{s=new RegExp(`^${n}$`,"s")}catch{return()=>!1}return r=>(!r.startsWith(".")||e.startsWith("."))&&s.test(r)}function _f(e,n){let t=e.split("/").filter(Boolean),s=t.map($f);if(s.every(a=>a===null))return null;let r=n.home.replace(/(?<!\/)\/+$/,""),o=n.projectRoot&&!C(n.projectRoot)?n.projectRoot.replace(/(?<!\/)\/+$/,""):null,i=[];if(o){i.push(`${o}/.git`);for(let a=o;a.length>1;a=_e.dirname(a))i.push(a)}r&&i.push(r,...[...H()?xr:Qi].map(a=>`${r}/${a}`)),i.push(...ea),H()&&i.push(...vf);for(let a of i){let l=a.split("/").filter(Boolean);if(l.length!==t.length||!l.every((p,f)=>s[f]?s[f](p):p===t[f]))continue;let c=sa(a,n),u=e.split("/"),d=u.slice(Math.max(0,u.findIndex(p=>/[*?[]/.test(p)))).join("/");if(c.kind==="catastrophic")return{...c,path:e,why:`${c.why} (${d} matches it)`}}return null}function sa(e,n){if(/[*?[]/.test(e)){let o=_f(e,n);if(o)return o}let t=n.home.replace(/(?<!\/)\/+$/,"");if(e==="/"||e==="")return{kind:"catastrophic",path:"/",token:"fs.root",why:"the filesystem root"};if(H()){let o=kf(e,t);if(o)return o}if(e===t)return{kind:"catastrophic",path:e,token:"fs.home",why:"the home folder"};if(_e.dirname(e)===t&&Qi.has(_e.basename(e)))return{kind:"catastrophic",path:e,token:"fs.home",why:`the ${_e.basename(e)} folder in home`};for(let o of ta(n)){if(na(e,o)&&e!==o)return{kind:"disposable",path:e,token:null,why:"a temp folder"};if(e===o)return{kind:"catastrophic",path:e,token:"fs.system",why:`the system temp root ${o}`}}if(/\/scratchpad(\/|$)/.test(e))return{kind:"disposable",path:e,token:null,why:"a session scratchpad"};if(e.startsWith(`${t}/Library/Caches/`))return{kind:"disposable",path:e,token:null,why:"an app cache folder"};if(_e.basename(e)===".git")return{kind:"catastrophic",path:e,token:"fs.git_dir",why:"a .git folder (the repository history)"};if(n.projectRoot&&e===n.projectRoot.replace(/(?<!\/)\/+$/,"")&&e!==t)return{kind:"catastrophic",path:e,token:"fs.project_root",why:"the project root"};if(n.projectRoot&&n.projectRoot.replace(/(?<!\/)\/+$/,"").startsWith(`${e}/`)&&e!==t)return{kind:"catastrophic",path:e,token:"fs.project_root",why:`a folder holding the project (${e})`};let s=e.split("/").filter(Boolean);if(s.some(o=>Xi.has(o)))return{kind:"disposable",path:e,token:null,why:"build or cache output"};if(/\.tsbuildinfo$/.test(_e.basename(e)))return{kind:"disposable",path:e,token:null,why:"build output"};if(_e.basename(e)===".auth"&&/(^|\/)(e2e|playwright|tests?|cypress)(\/|$)/.test(_e.dirname(e)))return{kind:"disposable",path:e,token:null,why:"a browser test's saved sign-in state"};if(s.some(o=>wf.test(o)))return{kind:"disposable",path:e,token:null,why:"a folder named as temporary"};if(/\.lock$/.test(_e.basename(e))&&!/(^|\/)(Cargo|Gemfile|poetry|uv|yarn|pnpm-lock|package-lock|composer|Pipfile|flake|mix|pubspec)\.lock$/.test(e))return{kind:"disposable",path:e,token:null,why:"a lock folder (a convention, not data)"};if(ea.has(e))return{kind:"catastrophic",path:e,token:"fs.system",why:`the system folder ${e}`};if(n.made&&n.made.some(o=>e===o||e.startsWith(`${o}/`)))return{kind:"disposable",path:e,token:null,why:Rn};let r=_e.basename(e);return(r==="bin"||r==="obj")&&n.projectRoot&&n.projectRoot.replace(/(?<!\/)\/+$/,"")!==t&&e.startsWith(`${n.projectRoot.replace(/(?<!\/)\/+$/,"")}/`)&&n.ignored?.(e)?{kind:"disposable",path:e,token:null,why:"build output git ignores"}:{kind:"normal",path:e,token:null,why:/\.[A-Za-z0-9]{1,8}$/.test(_e.basename(e))&&!/\/$/.test(e)?"a real file":"a real folder"}}function xf(e,n,t,s){let r=new RegExp(`^${ae}([^${le}]*)${le}(/.+)$`).exec(e);if(r&&/tmpdir\(\)|gettempdir\(\)|\bmktemp\b|\$TMPDIR\b|\$\{TMPDIR\}/.test(r[1])&&!r[2].split("/").includes(".."))return{kind:"disposable",path:n,token:null,why:"a temp folder (computed)"};let o=e.replace(new RegExp(`^${ae}[^${le}]*${le}`),"");if(e.startsWith(ae)&&(o==="/"||o==="/*"||o==="/.*"))return{kind:"catastrophic",path:n,token:"fs.root",why:`${n}: if the variable is empty, this is the filesystem root`};let i=e.replace(new RegExp(`${ae}[^${le}]*${le}`,"g"),"");if(i.split("/").filter(c=>c&&!c.includes("")).some(c=>Xi.has(c))||/\/scratchpad(\/|$)/.test(i))return{kind:"disposable",path:n,token:null,why:"build, cache or scratch output under a variable"};let l=e.slice(0,e.indexOf(ae));return l&&ta(t).some(c=>na(l.replace(/\/$/,""),c))?{kind:"disposable",path:n,token:null,why:"a temp folder"}:{kind:"normal",path:n,token:null,why:`a path that could not be resolved (${n})`}}function xe(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}var Sf=/^--(?:count|instance-count|num-nodes|nodes|num-workers|replicas|max-count|node-count)$/,Cf=/^--(?:max-run-duration|max-duration|duration|time-limit|hours)$/,Af=/^--(?:gpus?|accelerators?|accelerator-type|gpu-type|gpu-count)$/,Ef=/gpu|a100|h100|h200|v100|l40|a10g|b200|tpu/i,Rf=/(?:^|[^a-z0-9])(?:t4|l4)(?:$|[^a-z0-9])/i,ra=e=>Ef.test(e)||Rf.test(e),Of=/^--(?:machine-type|instance-type|vm-size|size)$/;function Pf(e,n){let t=/^(\d{1,3}):(\d{2})(?::(\d{2}))?$/.exec(e);if(t)return Number(t[1])+Number(t[2])/60+Number(t[3]??0)/3600;let s=/^(\d+(?:\.\d+)?)(h|m|s|d)?$/i.exec(e);if(!s)return null;let r=Number(s[1]),o=(s[2]??(n==="hours"?"h":"s")).toLowerCase(),i=o==="h"?r:o==="m"?r/60:o==="d"?r*24:r/3600;return Number.isFinite(i)&&i>0?i:null}function oa(e){let n=(e??"").split(/\s+/).filter(Boolean).slice(0,400),t=null,s=null,r=null,o=a=>{let l=n[a],c=l.indexOf("=");return c>0?[l.slice(0,c),l.slice(c+1)]:[l,n[a+1]]};for(let a=0;a<n.length;a++){let[l,c]=o(a);if(c===void 0)continue;let u=c.replace(/^["']|["']$/g,"");Sf.test(l)&&/^\d{1,5}$/.test(u)&&Number(u)>0?t=Math.max(t??0,Number(u)):Cf.test(l)?s=Pf(u,l==="--hours"?"hours":"seconds")??s:(Af.test(l)||Of.test(l)&&ra(u))&&(r=!0)}let i=n.indexOf("create");if(t===null&&i>0&&n.slice(0,i).includes("instances")){let a=[];for(let l=i+1;l<n.length&&!n[l].startsWith("-");l++)a.push(n[l]);a.length>0&&(t=a.length)}return r===null&&n.some(ra)&&(r=!0),{machines:t??1,hours:s??1,gpu:r,estimated:t===null||s===null}}import{posix as et}from"path";var ws={paths:[],launched:[]},On=600;function ia(e,n,t){if(!e||C(e)||e.startsWith("-")||/[*?[\]{}]/.test(e))return null;let s=U(e,n.cwd,t).replace(/(?<!\/)\/+$/,"");return!s.startsWith("/")||s==="/"||s===t.home||s.startsWith("/dev/")?null:et.normalize(s)}function Jt(e,n=new Set){let t=[],s=!1;for(let r=1;r<e.length;r++){let o=e[r];if(!s&&o==="--"){s=!0;continue}if(!s&&o.startsWith("-")){n.has(o)&&r++;continue}t.push(o)}return t}var jf=new Set(["--out","--output","--out-dir","--outdir","--output-dir","--dest","--destination","--target-dir","--results-dir","--report-dir","--save-dir","--log-dir","--out-file","--output-file","--pack-destination"]),Wf=new Set(["gcc","clang","cc","go","rustc","esbuild","tsc","curl","wget","pandoc","ffmpeg"]);function Nf(e,n){let t=[],s=r=>{let o=r?ia(r,e,n):null;o&&t.push(o)};for(let r of e.redirects)r.target&&/^(>|>>|>\||&>|&>>)$/.test(r.op)&&(r.fd===null||r.fd===1||r.fd===2)&&s(r.target);for(let r=1;r<e.argv.length;r++){let o=e.argv[r],i=o.indexOf("="),a=i>0?o.slice(0,i):o;!jf.has(a)&&!(a==="-o"&&(Ir.has(et.basename(e.name))||Wf.has(e.name)))||s(i>0?o.slice(i+1):e.argv[r+1])}switch(e.name){case"mkdir":for(let r of Jt(e.argv,new Set(["-m","--mode"])))s(r);break;case"touch":for(let r of Jt(e.argv,new Set(["-r","-t","-d","--reference","--date"])))s(r);break;case"tee":for(let r of Jt(e.argv))s(r);break;case"cp":case"rsync":case"ditto":case"install":{let r=Jt(e.argv,new Set(["-t","--target-directory","-e","--exclude","--include","-m","--mode","-o","-g","--chmod","--rsh"]));r.length>=2&&s(r[r.length-1]);break}case"git":{let r=e.argv.slice(1),o=0,i=null;for(;o<r.length&&r[o].startsWith("-");)r[o]==="-C"&&(i=r[o+1]??null),o+=r[o]==="-C"||r[o]==="-c"?2:1;let a=i===null?e:{...e,cwd:C(i)?null:U(i,e.cwd,n)},l=c=>{let u=c?ia(c,a,n):null;u&&t.push(u)};if(r[o]==="worktree"&&r[o+1]==="add"&&l(Jt(["git",...r.slice(o+2)],new Set(["-b","-B","--reason"]))[0]),r[o]==="clone"){let c=Jt(["git",...r.slice(o+1)],new Set(["-b","--branch","--depth","-o","--origin","--reference","-c","--config","--filter","--separate-git-dir"]));c.length>=2?l(c[1]):c[0]&&l(et.basename(c[0]).replace(/\.git$/,""))}break}case"npm":case"pnpm":case"yarn":{let r=e.argv.indexOf("--pack-destination");r>0&&s(e.argv[r+1]);break}case"tar":{let r=e.argv.findIndex(i=>i==="-C"||i==="--directory");r>0&&e.argv.slice(1).some(i=>/^-?[a-zA-Z]*x/.test(i)||i==="--extract")&&s(e.argv[r+1]);let o=e.argv.findIndex(i=>i==="-f"||i==="--file"||/^-[a-zA-Z]*c[a-zA-Z]*f$/.test(i));o>0&&e.argv.slice(1).some(i=>/^-?[a-zA-Z]*c/.test(i)||i==="--create")&&s(e.argv[o+1]);break}default:break}return t}function la(e,n,t,s){let r=n&&typeof n=="object"?n:{};if(e==="Write"||e==="NotebookEdit"){let c=typeof r.file_path=="string"?r.file_path:typeof r.notebook_path=="string"?r.notebook_path:null;return c&&c.startsWith("/")&&c!==s.home?{paths:[et.normalize(c)],launched:[]}:ws}if(e!=="Bash"||typeof r.command!="string")return ws;let o=r.command;if(o.length>64*1024)return ws;let i;try{i=ut(o,{home:s.home,tmpdir:s.tmpdir,cwd:t,projectDir:s.projectDir??null})}catch{return ws}let a=new Set,l=[];for(let c of i.commands){let u=Dr(c,s);for(let d of u.paths)a.add(d);l.push(...u.launched)}if(r.run_in_background===!0){l.push(o.slice(0,On));for(let c of i.commands)!C(c.argv.join(" "))&&c.argv.length>1&&l.push(c.argv.map(u=>v(u)).join(" ").slice(0,On))}return{paths:[...a].slice(0,64),launched:[...new Set(l)].slice(0,16)}}var ks=new Set(["serve","server","start","preview","develop","watch","install","update","build","test","tests","runner","worker","workers","python3","python","module","script","scripts","index.js","main.py","app.py","server.js","index.ts","main.ts","railway","vercel","heroku","kubectl","supabase","wrangler","netlify","firebase","stripe","ngrok","monitor","stream","follow","logs","runserver","uvicorn","gunicorn","hypercorn","daphne","nodemon","webpack","webpack-dev-server","http-server","live-server","browser-sync","celery","sidekiq","puma","unicorn","rackup","flask","rails","manage.py","artisan","storybook","jupyter","notebook","streamlit","gradio"]),Ir=new Set(["node","nodejs","npx","tsx","ts-node","python","python3","uv","bun","deno","ruby","perl","bash","sh","zsh","pnpm","yarn","npm"]);function Dr(e,n){let t=[];if(e.background||e.wrappers.includes("nohup")||e.wrappers.includes("setsid")){t.push(e.text.slice(0,On));let s=e.argv.map(r=>v(r)).join(" ");s!==e.text&&!C(e.argv.join(" "))&&t.push(s.slice(0,On))}else!C(e.argv.join(" "))&&(Ir.has(et.basename(e.name))?e.argv.slice(1).some(s=>!s.startsWith("-")&&Pn(s)):Pn(e.argv[0]??"")&&(e.argv[0]??"").includes("/"))&&t.push(e.argv.join(" ").slice(0,On));return{paths:Nf(e,n),launched:t}}var vs=new Set(["node","nodejs","python","python3","python2","ruby","perl","php","java","go","deno","bun","uv","npm","npx","pnpm","yarn","sh","bash","zsh","fish","dash","claude","code","docker","postgres","redis-server","mysqld","vite","next","tsx","ts-node","vitest","jest","make","cargo","git","ssh","tail","sleep","cat","less","watch","top","login","launchd","kernel_task","Finder","Dock"]);function ca(e,n,t,s){if((!n||n.length===0)&&(!s||s.length===0))return!1;let r=e.replace(/^["']|["']$/g,"").trim();if(r.length<4||vs.has(r)||/[|()?*+[\]{}\\^$]/.test(r.replace(/\\\./g,"."))||/^\.?\w{1,6}$/.test(r)&&r.startsWith("."))return!1;let o=r.split(/\s+/).some(a=>a.length>=6&&!a.startsWith("-")&&!vs.has(et.basename(a))&&!Ir.has(a)&&!ks.has(a)&&!ks.has(et.basename(a))&&!$s.test(et.basename(a))&&!/^[\d.:]+$|^(localhost|0\.0\.0\.0|127\.0\.0\.1)(:\d+)?$|^[\w.]+:(app|application|server|api|asgi|wsgi|main)$/i.test(a));if((t?o&&(/[/.]/.test(r)&&/\w{3}[/.]|[/.]\w{3}/.test(r)||r.length>=8&&/\s/.test(r)||r.length>=10):!vs.has(r)&&!ks.has(r)&&!$s.test(r)&&r.length>=4)&&n&&Lr(r.replace(/\\\./g,"."),n))return!0;if(!t)return!1;for(let a of r.split(/\s+/)){let l=a.replace(/\\\./g,".").replace(/^\.\//,"");if(!(l.startsWith("-")||l.includes("="))){if(l.includes("/")&&s&&aa(l,s))return!0;if(Pn(l)&&(n&&Lr(l,n)||s&&aa(l,s)))return!0}}return!1}function Pn(e){let n=et.basename(e);return e.length>=6&&/\.[A-Za-z0-9]{1,5}$/.test(n)&&!vs.has(n)&&!ks.has(n)&&!$s.test(n)&&!/^\.[A-Za-z0-9]+$/.test(n)&&!e.includes("node_modules/.bin/")}var $s=/^(server|app|main|index|worker|run|start|dev|cli|manage|setup|test|tests|build|serve|api|bot|job|task|script|wsgi|asgi|entry|entrypoint|bootstrap)\.[A-Za-z0-9]{1,5}$/i;function Lr(e,n){let t=new RegExp(`(^|[\\s/'"=])${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}($|[\\s'";&|)@])`);return n.some(s=>t.test(s))}function aa(e,n){for(let t of n){if(e.startsWith("/")&&(e===t||e.startsWith(`${t}/`)))return!0;let s=t.split("/").filter(r=>r!=="");for(let r=1;r<=s.length;r++){let o=s.slice(-r).join("/");if(!(o.length<6||r===1&&!Pn(o))&&(e===o||e.startsWith(`${o}/`)||e.endsWith(`/${o}`)))return!0}}return!1}function ua(e,n){let t=i=>i.replace(/\s+/g," ").trim(),s=t(e);if(n.some(i=>t(i).length>=24&&s.includes(t(i))))return!0;let r=i=>{let a=t(i),l=a.indexOf(" ");if(l<0)return null;let c=(a.slice(0,l).split("/").pop()??"").toLowerCase(),u=c.length;for(;u>0&&"0123456789.".includes(c[u-1]);)u--;return{prog:c.slice(0,u),args:a.slice(l+1)}},o=r(e);if(o&&n.some(i=>{let a=r(i);return a!==null&&a.args.length>=24&&a.prog===o.prog&&a.args===o.args}))return!0;for(let i of n)if(i.split(/\s+/).map(l=>l.replace(/^["']+|["';&|)]+$/g,"").replace(/^(\.\.?\/)+/,"")).flatMap(l=>{let c=l.split("/").filter(u=>u!=="");return c.length>2?[l,c.slice(-2).join("/")]:[l]}).filter(l=>!l.startsWith("-")&&!l.includes("=")&&Pn(l)&&!/^\/(dev|tmp|var|usr|bin|opt)\b/.test(l)).some(l=>new RegExp(`(^|\\s${l.includes("/")?"|/":""})${l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`).test(e)))return!0;return!1}function Tf(e,n){return[...new Set(n.flatMap(s=>s.split(/\s+/).map(r=>r.replace(/^["']+|["';&|)]+$/g,"").split("/").pop()??"")).filter(s=>$s.test(s)))].some(s=>Lr(s,[e]))}var Fr=e=>e.trim().split(/\s+/).filter(n=>n!=="");function dt(e){let n=(e.split("/").pop()??"").toLowerCase(),t=n.length;for(;t>0&&"0123456789.".includes(n[t-1]);)t--;return n.slice(0,t)}function da(e){let n=[],t=Fr(e.replace(/["']/g,""));for(let s=0;s<t.length;s++){let r=t[s].endsWith("&")&&!/[<>]&$/.test(t[s])?t[s].slice(0,-1):t[s];/^\d*(>>?|<)&?$/.test(r)?s++:r!==""&&!/^\d*(>>?|<)/.test(r)&&!(n.length===0&&(/^\w+=/.test(r)||r==="nohup"))&&n.push(r)}return n}function zr(e,n){let t=Fr(e);if(t.length===0)return!1;let s=dt(t[0]),r=t[1]?dt(t[1]):"";return n.some(o=>{let i=da(o);return i.length>0&&(dt(i[0])===s||dt(i[0])===r)})}function fa(e,n){let t=r=>r.replace(/\s+/g," ").trim(),s=t(e);return n.some(r=>t(r).length>=24&&s.includes(t(r)))}function pa(e,n){if(Tf(e,n)&&zr(e,n))return!0;let t=Fr(e);return n.some(s=>{let r=da(s);if(r.length===0||r.length===1&&!r[0].includes("/"))return!1;let o=t.length>r.length&&dt(t[1])===dt(r[0])?t.slice(1):t;if(o.length!==r.length||dt(o[0])!==dt(r[0]))return!1;let i=r.length===1;for(let a=1;a<r.length;a++)if(r[a].includes("$")){if(!Lf(r[a],o[a]))return!1}else{if(r[a]!==o[a])return!1;i=!0}return i})}function Lf(e,n){let t=[],s=0,r="";for(;s<e.length;){if(e[s]!=="$"){r+=e[s++];continue}if(t.push(r),r="",s++,e[s]==="{"){let i=e.indexOf("}",s);if(i<0)return!1;s=i+1}else if(e[s]==="("){let i=e.indexOf(")",s);if(i<0)return!1;s=i+1}else for(;s<e.length&&/\w/.test(e[s]);)s++}if(t.push(r),!n.startsWith(t[0])||!n.endsWith(t[t.length-1])||n.length<t[0].length+t[t.length-1].length)return!1;let o=t[0].length;for(let i of t.slice(1,-1)){let a=n.indexOf(i,o);if(a<0)return!1;o=a+i.length}return o<=n.length-t[t.length-1].length}var rv=10080*60*1e3;var ov=3600*1e3;var jn=e=>`${e.kind}\0${e.cwd??""}\0${e.arg??""}`;import{realpathSync as $v}from"fs";import{readdir as xv,stat as Sv}from"fs/promises";import{homedir as Av}from"os";import{join as Rv,relative as Ov,resolve as Pv,sep as jv}from"path";import{closeSync as cv,openSync as uv,readSync as dv}from"fs";var ha=64*1024*1024;var fv=Buffer.from('"tool_use"'),pv=Buffer.from('"tool_result"'),hv=Buffer.from('"permissionMode"'),gv=1024*1024;var mv=256*1024;var Nv=3600*1e3;function ga(e){return e.replace(/[^A-Za-z0-9]/g,"-")}var Wn="anvil-claude",If=new Set(["login","logout","open"]);function ma(e){let n=e[0];return n==="claude"||n!==void 0&&If.has(n)?[...e]:["claude",...e]}function Se(e){let n=e.trim();return n===Wn||n.endsWith(` ${Wn}`)||n.endsWith(`/${Wn}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}function Nn(e){return e[0]==="logout"?"anvil logout signs this machine out, so its rules stop following your workspace":e[0]==="remove"?"anvil remove puts an action in ghost in your workspace and hides it":e[0]==="login"?"anvil login changes the workspace whose rules this machine follows":e[0]==="control"&&e[1]==="kill-switch"&&!["off","status","show"].includes(e[2]??"")?"anvil control kill-switch puts every action in ghost, this agent's included":e[0]==="control"&&["set-action-mode","set-service-mode","set-mode"].includes(e[1]??"")&&e.includes("ghost")?`anvil control ${e[1]} ghost switches off a rule your workspace enforces`:e[0]!=="claude"?null:e[1]==="allow"?"anvil claude allow approves a call Anvil held":e[1]==="off"||e[1]==="ghost"?`anvil claude ${e[1]} switches off Anvil's checks on this agent`:e[1]==="rules"&&e[2]==="remove"?"anvil claude rules remove deletes one of the developer's rules":e[1]==="sync"?"anvil claude sync applies changes to your rules.md":e[1]==="rules"&&(e[2]==="add"||e[2]==="import")?`anvil claude rules ${e[2]} changes your rules`:e[1]===void 0||e[1].startsWith("-")?"anvil claude opens the screen that changes your rules":e[1]==="rules"&&e[2]==="edit"?"anvil claude rules edit opens the screen that changes your rules":e[1]==="on"?"anvil claude on reinstalls Anvil and recompiles your rules":e[1]==="statusline"?"anvil claude statusline feeds the meter your budgets count":null}function _s(e,n=e){if(e.length===0&&n.some(s=>s==="--version"||s==="-v"||s==="--help"||s==="-h"))return null;let t=Nn(ma(e));return t===null?null:t.replace(/^anvil( claude)?\b/,Wn)}var Df=["prod","production","prd","live","main","master"],Ff=["staging","stage","dev","development","preview","test","qa","sandbox"],Ce=e=>new Set(e.split(" ")),zf=new Set(Df),ya=new Set(Ff),Wt={environment:null,said:null};function Ca(e,n){try{return pp(e,n)}catch{return Wt}}function Aa(e,n,t){try{return $p(e,n,t)}catch{return Wt}}function Cs(e){return e.normalize("NFKC").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var ba="\u0430a\u0435e\u043Eo\u0440p\u0441c\u0456i\u0455s\u0501d\u04CFl\u043Cm\u0442t\u043Fn\u0443u\u03BDv\u03BFo\u03C1p\u03B9i\u03B1a\u03B5e\u03C4t\u03C5u\u03BCm",Mf=e=>e.normalize("NFKC").replace(new RegExp("\\p{Cf}","gu"),"").replace(/[^\u0000-\u007f]/g,n=>{let t=ba.indexOf(n.toLowerCase());return t>=0&&t%2===0?ba[t+1]:n}),Uf=/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=\d)|(?<=\d)(?=[A-Za-z])/;function Tt(e){for(let n of Mf(e).split(/[^A-Za-z0-9]+/))for(let t of[n,...n.split(Uf)])if(zf.has(t.toLowerCase()))return t.toLowerCase();return null}function Qt(e){let n=e.normalize("NFKC").replace(/^([a-z][\w+.-]*:\/\/)?[^@/\s:]*@/i,"$1");if(/[^\u0000-\u007f]/.test(n))return!1;if(n.includes("/")&&(/^(\/|~|\$\{?HOME\b)/.test(n)||n.split("/").includes(".."))){let t=n.replace(/\/+$/,"").split("/"),s=t.pop()??"";return Cs(s).some(r=>ya.has(r)&&(!/^(dev|test)$/.test(r)||/^(envs?|environments?|stages?|deploy(ments?)?|overlays?)$/.test(t.pop()??"")))}return Cs(n).some(t=>ya.has(t))}var Lt=e=>/[$`*]|\{[^}]*(,|\.\.)|[<>]\(/.test(e),qf=Ce("env environment stage target tier profile context namespace ns cluster app application project stack site service alias workspace destination dest channel track deployment inventory limit host hosts server to config configuration"),Ea=e=>e.replace(/^-+/,"").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().split(/[-_.]/).filter(n=>!["name","id","file"].includes(n)).pop()??"",As=e=>!/^(NODE|BABEL|RAILS|RACK|FLASK|MIX|SENTRY|APP|ASPNETCORE|DOTNET|SPRING|DJANGO)_/i.test(e)&&qf.has(Ea(e)),Hf=Ce("app application project stack site cluster host hosts server destination dest deployment to target"),Bf=e=>/^-[ap]$/.test(e)||Hf.has(Ea(e)),Vf=/^-[esadncpPESADilHCfF]$/,wa=e=>/^-[A-Za-z]$/.test(e)?Vf.test(e):As(e),Zf=/^--?(staging|preview|qa|sandbox|dev|development)$/i,Gf={frame:[],guards:[],first:!0,cond:!1,fresh:!1},Kf=/(?:^|[\s;&|(){}])(?:function\s+[^\s(){};&|]+|[^\s(){};&|]+\s*\(\s*\))\s*[{(]/,Yf=e=>({pipes:0,ids:0,frames:0,compound:0,functions:Kf.test(e)}),Jf=Ce("if while until case select for"),Xf=Ce("fi done esac");function Ur(e,n,t,s){let r=s.length,o=[],i=[],a="",l=!1,c="word",u=[],d=[{frame:t.frame,base:t.guards,first:t.first}],p={guards:t.guards,first:t.first,joined:""},f=()=>{l&&(c==="heredoc"?u.push({end:a,fed:i}):c==="fed"?i.push(a):c==="word"&&o.push(a),a="",l=!1,c="word")},h=y=>{f();let $=d[d.length-1];if(o.length>0||i.length>0){let E=n.compound,_=!1;for(let P of o)if(Jf.has(P))E++,_=!0;else if(Xf.has(P))E=Math.max(0,E-1);else if(!Oa.has(P))break;let k={words:o,fed:i,pipe:n.pipes,id:n.ids++,frame:y==="&"?[...$.frame,n.frames++]:[...$.frame],guards:p.guards,first:p.first,cond:t.cond||n.functions||_||n.compound>0,fresh:t.fresh};n.compound=E,s.push(k),y==="&&"?p={guards:p.joined==="||"?$.base:[...k.guards,k.id],first:!1,joined:"&&"}:y==="||"?p={guards:$.base,first:!1,joined:"||"}:y==="|"?p={guards:k.guards,first:!1,joined:p.joined}:p={guards:$.base,first:$.first,joined:""}}else y==="list"||y==="&"?p={guards:$.base,first:$.first,joined:""}:(y==="&&"||y==="||")&&(p={guards:y==="||"?$.base:p.guards,first:!1,joined:y});o=[],i=[],y!=="|"&&n.pipes++};for(let y=0;y<e.length;y++){let $=e[y],E=e[y+1]??"";if($==="\\")E!==`
|
|
31
|
-
`&&(
|
|
32
|
-
`,y++;else if($==="'"){let
|
|
33
|
-
`,y);y=(
|
|
34
|
-
`)h("list"),y=
|
|
35
|
-
`,s+1),
|
|
36
|
-
`))}return s}var Nt=/^[A-Za-z_][A-Za-z0-9_]*=/,Oa=Ce("if then else elif fi do done while until esac ! { } time"),ka=Ce("sh bash zsh dash ksh ash"),va=ie({sudo:"-u -g -C -D -h -p -r -t -U --user --group --chdir",doas:"-u -C",env:"-u -C -S --unset --chdir",nohup:"",nice:"-n",timeout:"-s -k --signal --kill-after",command:"",builtin:"",exec:"-a",xargs:"-I -n -P -L -d -E -s -a",watch:"-n -d",flock:"-w -E",npx:"-p --package -c --call",bunx:"-p --package",op:"--env-file --account",doppler:"-c --config -p --project --token",infisical:"--env --projectId --path --token",dotenv:"-e -c -v",dotenvx:"-f --env-file","aws-vault":"--duration -d","cross-env":""}),ep=ie({timeout:1,flock:1,"aws-vault":2,op:1,doppler:1,infisical:1,dotenvx:1}),qr=Ce("op doppler infisical dotenv dotenvx aws-vault mise asdf"),tp=ie({npm:"exec",pnpm:"dlx exec",yarn:"dlx exec",bun:"x",uv:"run",poetry:"run",pipenv:"run",bundle:"exec",mise:"exec x",asdf:"exec",railway:"run"}),np=ie({flyctl:"fly","netlify-cli":"netlify","firebase-tools":"firebase","@railway/cli":"railway",tofu:"terraform",terragrunt:"terraform","docker-compose":"docker",oc:"kubectl",kubecolor:"kubectl"});function Ve(e){let n=/^((?:@[^/@\s]+\/)?[^@\s=/]+)(?:@[^\s/]*|==\S*)$/.exec(e),t=n?n[1]:e.startsWith("@")?e:e.slice(e.lastIndexOf("/")+1);return np[t]??t}function $a(e,n,t){let s=t.split(" "),r=n;for(;r<e.length&&e[r].startsWith("-")&&e[r]!=="--";)r+=!e[r].includes("=")&&s.includes(e[r])?2:1;return e[r]==="--"?r+1:r}function Pa(e){let n=0;for(let t=0;t<12&&n<e.length;t++){let s=e[n];if(Nt.test(s)){n++;continue}let r=Ve(s),o=e.indexOf("--",n);if(tp[r]?.split(" ").includes(e[n+1]??""))n=qr.has(r)&&o>n?o+1:$a(e,n+2,"");else if(va[r]!==void 0)qr.has(r)&&o>n?n=o+1:(n=$a(e,n+1,va[r])+(ep[r]??0),e[n]==="--"&&n++);else return(r==="yarn"||r==="pnpm")&&en[Ve(e[n+1]??"")]&&n++,n}return n<e.length?n:-1}function Hr(e,n,t){return e.flatMap(s=>{let r=0;for(;r<s.words.length&&Oa.has(s.words[r]);)r++;let o=s.words.slice(r);if(t>=3)return[{...s,words:o}];let i=(h,g)=>({frame:g?[...s.frame,n.frames++]:s.frame,guards:s.guards,first:s.first&&!s.cond,cond:s.cond,fresh:s.fresh||h}),a=o.flatMap(sp).flatMap(h=>Hr(Ur(h,n,i(!1,!0),[]),n,t+1)),l=Pa(o),c=l<0?"":Ve(o[l]),u=null;if(ka.has(c)){let h=o.findIndex((g,y)=>y>l&&/^-[a-zA-Z]*c[a-zA-Z]*$/.test(g));u=h>0?o[h+1]??null:null}else c==="eval"&&(u=o.slice(l+1).join(" "));if(u===null)return[...a,{...s,words:o}];let d=o.slice(0,l).filter(h=>Nt.test(h)),p=ka.has(c)?i(!0,!0):i(!1,!1),f=c==="eval"&&Lt(u)?[{...s,words:[],wild:!0}]:[];return[...a,...f,...Hr(Ur(u,n,p,[]),n,t+1).map(h=>({...h,words:[...d,...h.words]}))]})}function sp(e){let n=[];for(let t=0;t<e.length;t++)if("$<>".includes(e[t])&&e[t+1]==="("&&e[t+2]!=="("){let s=Ra(e,t+1);n.push(e.slice(t+2,s)),t=s}else if(e[t]==="`"){let s=Es(e,t+1,"`");n.push(e.slice(t+1,s)),t=s}return n}var Rs=(e,n)=>e.frame.length<=n.frame.length&&e.frame.every((t,s)=>n.frame[s]===t),ja=(e,n)=>Rs(e,n)&&!e.cond&&(n.guards.includes(e.id)||e.first),nt="${?}";function Wa(e,n,t){let s=t.filter(l=>(l.name===e||l.name==="*")&&Rs(l.part,n)&&(!n.fresh||l.part.fresh||l.exported||l.name==="*"));if(!s.some(l=>l.name===e))return null;let r=-1;for(let l=s.length-1;l>=0;l--){let c=s[l];if(c.name===e&&!c.unknown&&(c.loop||ja(c.part,n))){r=l;break}}let o=r>=0?[...s[r].values]:[],i=r>=0;for(let l of s.slice(r+1))l.unknown?i=!1:o.push(...l.values);let a=s.filter(l=>l.name===e).pop().said;return{values:[...new Set(o)].slice(0,16),certain:i,said:a}}var rp=(e,n,t)=>e.replace(/\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g,(s,r,o)=>{let i=Wa(r??o,n,t);return!i||i.values.length===0?s:i.certain&&i.values.length===1&&!/\s/.test(i.values[0])?i.values[0]:`${i.values.join(nt)}${nt}`}),Tn=e=>e.slice(0,e.indexOf("=")),Ln=e=>e.slice(e.indexOf("=")+1),op=Ce("export declare typeset local readonly");function ip(e){let n=[];return e.map(t=>{let s=t.words.map(u=>rp(u,t,n)),r=Pa(s),o=r<0?"":Ve(s[r]),i=new Map,a=s.slice(0,Math.max(r,0)).some(u=>/^(-[a-zA-Z]*[iu]|--unset.*|--ignore-environment|-)$/.test(u)||["sudo","doas"].includes(Ve(u)));for(let u of a?[]:new Set(n.filter(d=>d.exported&&d.name!=="*").map(d=>d.name))){let d=Wa(u,t,n);d&&d.values.length>0&&i.set(u,{said:d.said,value:d.certain&&d.values.length===1?d.values[0]:`${d.values.join(" ")}${nt}`})}for(let u of r<0?[]:s.slice(0,r))Nt.test(u)&&i.set(Tn(u),{said:u,value:Ln(u)});let l=u=>n.some(d=>d.name===u&&d.exported&&Rs(d.part,t)),c=(u,d,p,f={})=>{n.push({name:u,values:d,unknown:f.unknown??!1,exported:(f.exported??!1)||l(u),loop:f.loop??!1,part:t,said:p})};if(t.wild)c("*",[],"eval",{unknown:!0});else if(r<0)for(let u of s.filter(d=>Nt.test(d)))c(Tn(u),[Ln(u)],u);else if(op.has(o)){let u=s.slice(r+1).filter(f=>/^[-+]/.test(f)),d=o==="export"||u.some(f=>/^-[a-zA-Z]*x/.test(f)),p=u.some(f=>/^(-[a-zA-Z]*n|\+[a-zA-Z]*x)/.test(f));for(let f of s.slice(r+1))p&&/^[A-Za-z_]\w*(=|$)/.test(f)?c(f.replace(/=.*/s,""),[],o,{unknown:!0}):Nt.test(f)?c(Tn(f),[Ln(f)],`${o} ${f}`,{exported:d}):d&&/^[A-Za-z_]\w*$/.test(f)&&n.push(...n.filter(h=>h.name===f).slice(-1).map(h=>({...h,exported:!0,part:t})))}else if(o==="for"&&s[r+2]==="in")c(s[r+1],s.slice(r+3),s.slice(r).join(" "),{loop:!0});else if(o==="source"||o==="."||o==="eval"&&s.slice(r+1).some(Lt)||o==="set"&&s.slice(r+1).some(u=>/^-[a-zA-Z]*a/.test(u)))c("*",[],o,{unknown:!0});else for(let u of s.slice(r+1))/^[A-Za-z_]\w*$/.test(u)&&n.some(d=>d.name===u)&&c(u,[],o,{unknown:!0});return{part:t,words:s,fed:t.fed,pipe:t.pipe,at:r,tool:o,env:i}})}var ap=(e,n)=>ja(e.part,n.part)&&n.part.guards.includes(e.part.id),lp=Ce("version help status logs log list ls info show get describe whoami auth login logout doctor history inspect open ps top explain plan validate fmt init output graph providers preview diff synth config context use link pull build template lint package search repo dependency dep workspace stack"),cp=Ce("cd pushd popd export declare typeset local readonly unset source . echo printf sleep true false set test [ [[ for case git cat ls grep tee read wait exit return mkdir cp mv rm touch chmod which pwd date kubectx kubens alias unalias"),up=[Ce("deploy deploys deploying deployment deployments redeploy"),Ce("release releases ship publish rollout promote apply provision rollback destroy")],dp=e=>jt(e.words.slice(e.at+1),Be[e.tool]??"")[0]??"";function fp(e,n){let t=e.map((a,l)=>l),s=a=>!lp.has(dp(e[a]))||e[a].words.some(l=>/^(delete|rm|remove|destroy|drop|purge|prune|uninstall|reset)$/.test(l)),r=n?Ve(n.toLowerCase()):null;if(r){let a=t.filter(l=>e[l].at>=0&&e[l].tool===r);if(a.length>0)return a.some(s)?a.filter(s):a;for(let l of e){let c=l.words.findIndex((u,d)=>d>l.at&&Ve(u)===r);if(l.at>=0&&c>0)return l.at=c,l.tool=r,[e.indexOf(l)]}}let o=t.filter(a=>e[a].at>=0&&!cp.has(e[a].tool)),i=o.filter(a=>e[a].words.some(l=>Cs(l).some(Vr))||en[e[a].tool]!==void 0&&s(a));return i.length>0?i:o}function Na(e){let n=Yf(e);return ip(Hr(Ur(e,n,Gf,[]),n,0))}function pp(e,n){let t=Na(e),s=fp(t,n);if(s.length===0){for(let l of t)for(let c of[...l.words,...l.fed])if(Tt(c))return{environment:"production",said:ft(c)};return Wt}let r=s.map(l=>yp(t,l,n)),o=r.find(l=>l.environment==="production")??(r.some(l=>l.environment===null)?Wt:r[0]);if(o.environment!=="non-production")return o;let i=e.replace(/["']/g,"").split(/[\s`;&|()<>{}$\\]+/),a=[n?Ve(n.toLowerCase()):"",...s.map(l=>t[l].tool)].some(l=>l&&i.filter(c=>Ve(c)===l).length>t.filter(c=>c.tool===l).length);return Tt(e)||a||t.some(l=>l.tool==="alias")?Wt:o}var ft=e=>{let n=e.split(nt).join("");return n.length>80?`${n.slice(0,79)}\u2026`:n};function _a(e,n){for(let t=0;t<e.length;t++){let s=e[t];if(!Tt(s))continue;let r=e[t-1]??"",o=r.startsWith("-")&&!r.includes("=")&&!s.startsWith("-")&&(n===void 0||n.split(" ").includes(r));return ft(o?`${r} ${s}`:s)}return null}var Ta="terraform workspace select|terraform workspace new|terraform init:-backend-config|kubectl config use-context|kubectx|pulumi stack select|firebase use|gcloud config set project|gcloud config configurations activate|docker context use|railway environment|railway link:-e --environment".split("|").map(e=>{let[n,t]=e.split(":"),s=n.split(" ")[0];return[s==="kubectx"?"kubectl":s,n,t]}),hp=Ce("terraform pulumi fly vercel netlify wrangler firebase railway docker");function gp(e,n){let t=e.tool,s=t==="helm"?"kubectl":t,r=[],o=[],i=a=>[{said:a,value:nt}];for(let a of n){if(a.at<0||!Rs(a.part,e.part))continue;let l=ap(a,e),c=a.words.slice(a.at),u=ft(c.join(" "));if(["cd","pushd","popd"].includes(a.tool)||(a.tool==="source"||a.tool===".")&&!en[t]){let p=jt(c.slice(1),"")[0];r=l&&p&&p!=="-"&&a.tool!=="popd"?[{said:u,value:p}]:i(u)}let d=Ta.filter(([p,f])=>p===s&&f.split(" ").every((h,g)=>(g>0?c[g]:a.tool)===h)).flatMap(([,p,f])=>{let h=c.slice(p.split(" ").length);return f?he(h,f):jt(h,"").slice(0,1).map(g=>({said:u,value:g}))});d.length>0&&(o=l?d:i(u))}return r.length>0&&e.words.some((a,l)=>a==="-C"||l<e.at&&a==="-D"||a==="-d"&&/^(task|just)$/.test(e.tool)||/^--(chdir|cwd|prefix|dir|directory|working-dir)(=|$)/.test(a))&&(r=i("")),{folders:hp.has(t)||!en[t]?r:[],picks:o}}var mp=Ce("cd pushd export declare typeset local readonly source . test [ [[ kubectx kubens case alias");function yp(e,n,t){let s=e[n],r=e.slice(0,n),o=s.tool==="helm"?"kubectl":s.tool,i=r.filter(f=>f.at<0||mp.has(f.tool)||f.tool===s.tool&&en[s.tool]||Ta.some(([h,g])=>h===o&&`${g} `.startsWith(`${f.tool} `))),a=_a(s.words,Be[s.tool]);if(a)return{environment:"production",said:a};for(let f of[...s.fed,...r.filter(h=>h.pipe===s.pipe).flatMap(h=>[...h.words,...h.fed])]){let h=Tt(f);if(h)return{environment:"production",said:h}}for(let f of i)if(_a(f.words))return{environment:"production",said:ft(f.words.slice(Math.max(f.at,0)).join(" "))};if(t&&Tt(t))return{environment:"production",said:t};let l=gp(s,r),c={args:s.words.slice(s.at+1),env:s.env,chosen:[...l.folders,...l.picks],folders:l.folders,picks:l.picks},u=en[s.tool]?.(c)??kp(c,s.words.slice(Math.max(0,s.words.findIndex((f,h)=>h===s.at||qr.has(Ve(f))))),s.tool);if(u.production)return{environment:"production",said:u.production};let d=u.first?u.sels.filter(f=>f.rank===u.sels[0].rank):u.sels,p=d.length>0&&d.every(f=>!Lt(f.value)&&Qt(f.value))?d[0]:void 0;return p?{environment:"non-production",said:ft(p.said)}:u.preview?{environment:"non-production",said:u.preview}:Wt}function he(e,n){let t=n.split(" "),s=[];return e.forEach((r,o)=>{let i=r.indexOf("=");i>0&&t.includes(r.slice(0,i))?s.push({said:r,value:r.slice(i+1)}):t.includes(r)&&o+1<e.length?s.push({said:`${r} ${e[o+1]}`,value:e[o+1]}):/^-[A-Za-z]$/.test(r.slice(0,2))&&r.length>2&&!r.startsWith("--")&&t.includes(r.slice(0,2))&&s.push({said:r,value:r.slice(2)})}),s}function jt(e,n){let t=n.split(" "),s=[];for(let r=0;r<e.length;r++){let o=e[r];if(o==="--")return[...s,...e.slice(r+1)];!o.startsWith("-")||o==="-"?s.push(o):!o.includes("=")&&t.includes(o)&&r++}return s}function bp(e,n){let t=n.split(" "),s=[];for(let r=0;r<e.length;r++){let o=e[r];if(o==="--")return[...s,...e.slice(r+1)];!o.startsWith("-")||o==="-"?/^-./.test(e[r-1]??"")&&!e[r-1].includes("=")||s.push(o):!o.includes("=")&&t.includes(o)&&r++}return s}var xs=e=>e.map(n=>({said:n,value:n})),Xt=(e,n)=>n.split(" ").flatMap(t=>e.env.get(t)??[]),xa=(e,n)=>he(e.args,n).map(t=>({...t,value:nt})),Sa=e=>e.env.has("KUBECONFIG")||e.args.some(n=>n.startsWith("--kubeconfig"))?[]:e.picks,tt=(...e)=>{let n=e.findIndex(t=>t.length>0);return{sels:n<0?[]:e[n].map(t=>({...t,rank:n})),first:!0}},Br=e=>e.flatMap(n=>{let t=n.value.split(/[\s,]+/).filter(s=>Nt.test(s));return t.length===0?[n]:t.filter(s=>As(Tn(s))).map(s=>({said:n.said,value:Ln(s)}))}),Mr=(e,n)=>{let t=n.split(" ");return e.every((s,r)=>!Lt(s)||s.startsWith("-")||t.includes(e[r-1]??""))},Be=ie({vercel:"--token -t --scope -S --cwd --local-config -A --global-config -Q --team -T --build-env -b --env -e --meta -m --regions --archive --target --name -n",netlify:"--dir -d --functions -f --site -s --auth --alias --branch -b --context --message -m --filter --timeout",fly:"-a --app -c --config -i --image -e --env --build-arg --build-secret --dockerfile --strategy -r --region --vm-size --wait-timeout --image-label -t --access-token -o --org",terraform:"-var -var-file -target -replace -state -state-out -backup -lock-timeout -parallelism",firebase:"-P --project --only --except -m --message --token --account --expires -e"}),en=ie({vercel:e=>{let n=jt(e.args,Be.vercel),t=/^(deploy)?$|[/.]/.test(n[0]??"")?"deploy":n[0];if(t==="rollback"||t==="promote")return{sels:[],production:t};let s=[...he(e.args,"--target"),...Mr(e.args,Be.vercel)?[]:[{said:"",value:nt}]];return t!=="deploy"?{sels:[...s,...xs(t==="env"?n.slice(3,4):n.slice(1)),...e.chosen]}:{sels:s,...s.length===0?{preview:"no --prod"}:{}}},netlify:e=>e.args.some(t=>/^-[a-z]*p[a-z]*$/.test(t))?{sels:[],production:"-p"}:{sels:[...he(e.args,"--context --alias --branch -b --site -s"),...e.chosen],...jt(e.args,Be.netlify)[0]==="deploy"&&Mr(e.args,Be.netlify)?{preview:"no --prod"}:{}},fly:e=>{let n=jt(e.args,Be.fly),t=n[0]==="apps"||n[0]==="app"?n.slice(2,3):[];return tt([...he(e.args,"-a --app"),...xs(t)],Xt(e,"FLY_APP"),he(e.args,"-c --config"),n[0]==="deploy"&&n[1]?[{said:"",value:nt}]:[],e.folders)},railway:e=>tt(he(e.args,"-e --environment"),e.picks),kubectl:e=>tt(he(e.args,"--context --cluster --server -s"),Sa(e)),helm:e=>tt([...he(e.args,"--kube-context --kube-apiserver"),...Xt(e,"HELM_KUBEAPISERVER")],Xt(e,"HELM_KUBECONTEXT"),Sa(e)),terraform:e=>{let n=bp(e.args,Be.terraform),t=["apply","destroy"].includes(n[0]??"")?n.slice(1):[],s=[...he(e.args,"-chdir --chdir --terragrunt-working-dir --working-dir"),...Xt(e,"TF_WORKSPACE"),...xs(t),...e.chosen];return{sels:s.length>0?[...s,...he(e.args,"-var-file --var-file"),...Br(he(e.args,"-var --var"))]:[]}},pulumi:e=>tt(he(e.args,"-s --stack"),e.picks,[...he(e.args,"-C --cwd"),...e.folders]),firebase:e=>{let n=jt(e.args,Be.firebase),t=/^hosting:channel:deploy/.test(n[0]??"");return{sels:[...tt(he(e.args,"-P --project"),e.picks,xa(e,"--config"),e.folders).sels,...t?xs(n.slice(1,2)).map(r=>({...r,rank:9})):[]],first:!0,...t&&Mr(e.args,Be.firebase)?{preview:n[0]}:{}}},wrangler:e=>tt(he(e.args,"--name --route --routes"),he(e.args,"-e --env --branch --project-name"),xa(e,"-c --config"),e.chosen),docker:e=>{let n=e.args.findIndex((t,s)=>!t.startsWith("-")&&!["-c","--context","-H","--host","--config"].includes(e.args[s-1]??""));return tt([...he(n<0?e.args:e.args.slice(0,n),"-c"),...he(e.args,"--context -H --host")],Xt(e,"DOCKER_HOST DOCKER_CONTEXT"),e.picks)},modal:e=>tt(he(e.args,"-e --env"),Xt(e,"MODAL_ENVIRONMENT"))}),wp=Ce("make gmake rake just task cap"),Vr=e=>up.some(n=>n.has(e.toLowerCase()));function kp(e,n,t){let s=[],r=[],o=(f,h)=>{s.push(...h),Bf(f)&&r.push(...h)},i=[],a=!1;for(let f=0;f<n.length;f++){let h=n[f];if(h==="--")a=!0;else if(h.startsWith("-")&&h.length>1){let g=h.indexOf("="),y=t==="npm"&&!a;h==="--all"&&r.push({said:h,value:h}),g>0?o(h.slice(0,g),wa(h.slice(0,g))&&!y?Br([{said:h,value:h.slice(g+1)}]):[]):Zf.test(h)?s.push(...y?[]:[{said:h,value:h}]):n[f+1]!==void 0&&!n[f+1].startsWith("-")&&(f++,wa(h)&&!y&&o(h,Br([{said:`${h} ${n[f]}`,value:n[f]}])))}else Nt.test(h)?wp.has(t)&&As(Tn(h))&&s.push({said:h,value:Ln(h)}):(Lt(h)||!/\s/.test(h)&&!/^v?\d+(\.\d+)+/.test(h))&&(s.push({said:h,value:f>0?h:h.slice(h.lastIndexOf("/")+1)}),f>0&&i.push(h))}for(let[f,h]of e.env)As(f)&&o(f,[h]);let l=[...s,...e.chosen],c=i.filter(f=>Cs(f).some(Vr)),u=i.findIndex(Vr),d=i.slice(u<0?i.length:u+1).filter(f=>!/[/.]/.test(f));return{sels:l.some(f=>Lt(f.value))||[c,d].some(f=>f.length>1&&!f.every(Qt))||!r.every(f=>Qt(f.value))?[{said:"",value:nt}]:l.filter(f=>Qt(f.value))}}function Zr(e){let n=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/\s]*@)?([^/?#\s]*)(\/[^?#\s]*)?/i.exec(e.trim());return n?`${n[1]??""} ${(n[2]??"").replace(/^\//,"")}`:e}var Ss=null;function vp(e){if(Ss?.command===e)return Ss;let n=Na(e).flatMap(s=>[...s.words,...s.fed]),t=n.flatMap((s,r)=>[.../^(-h|--host)$/.test(n[r-1]??"")?[s]:[],...[...s.matchAll(/(?:^--host=|^-h(?=.)|(?:^|[\s;='"])host(?:addr)?=|^\w*HOST(?:ADDR)?=)([^\s;]*)|[a-z][\w+.-]*:\/\/\S*/gi)].map(o=>o[1]??o[0])]);return Ss={command:e,prod:n.find(s=>Tt(s))??null,servers:t.every(s=>!Lt(s)&&s.split(",").every(r=>Qt(Zr(r))))},Ss}function $p(e,n,t){let s=[t,n].filter(i=>typeof i=="string"&&i.length>0);for(let i of s)if(Tt(Zr(i)))return{environment:"production",said:ft(i)};let r=vp(e);if(r.prod!==null)return{environment:"production",said:ft(r.prod)};let o=s.find(i=>Qt(Zr(i)));return o&&r.servers?{environment:"non-production",said:ft(o)}:Wt}var _p=["fs.root","fs.home","fs.system","fs.project_root","fs.git_dir","fs.device","git.main","proc.all"],xp=new Set(_p),ro={"claude.bash.fs.delete_recursive":10,"claude.bash.db.destructive":9,"claude.bash.git.force_push":9,"claude.bash.git.discard":8,"claude.bash.git.push_main":8,"claude.bash.deploy":8,"claude.bash.publish":7,"claude.bash.secrets.print":7,"claude.bash.privilege":7,"claude.file.write_secret":6,"claude.file.read_secret":6,"claude.bash.process.kill_by_name":6,"claude.bash.external_write":6,"claude.bash.spend":6,"claude.bash.crypto.transaction":8,"claude.bash.secrets.expose":9,"claude.agent.controls":7,"claude.bash.net.expose":6,"claude.bash.data.export":6,"claude.bash.persistence":6,"claude.mcp.side_effect":6,"claude.bash.fs.delete_disposable":1,"claude.agent.helper":1,"claude.mcp.call":0,"claude.tool.other":0,"claude.bash.unclassified":0};var mt=new Set(["Write","Edit","MultiEdit","NotebookEdit"]),Fl=new Set(["Read","Grep","NotebookRead"]),Sp=new Set(["Agent","Task","Workflow"]),Cp=new Set(["Agent","Task"]),Ap="claude.agent.helper";function zl(e,n){return gn({tool:e.tool,command:e.command_local,target:e.target,cwd:e.cwd,git_branch:e.git_branch,project_dir:Ep(e),session_id:e.session_id??null},n)}function Ep(e){let n=e.source_file.split("/")[0];if(!n||!e.cwd)return null;for(let t=e.cwd;;t=R.dirname(t)){if(ga(t)===n)return t;if(t==="/"||t==="."||t===R.dirname(t))return null}}function Rp(e,n){let t=r=>typeof r=="string"&&r!==""?Ne(r):r??null,s=typeof e.target=="string"&&(mt.has(e.tool)||Fl.has(e.tool))?We(e.target)??e.target:e.target;return{input:{...e,cwd:t(e.cwd),...e.project_dir===void 0?{}:{project_dir:t(e.project_dir)},target:s},ctx:{...n,home:Ne(n.home),tmpdir:Ne(n.tmpdir),claudeConfigDir:t(n.claudeConfigDir)}}}function gn(e,n){let{input:t,ctx:s}=H()?Rp(e,n):{input:e,ctx:n},r=typeof s.claudeConfigDir=="string"&&s.claudeConfigDir.startsWith("/")?xe(s.claudeConfigDir):s.claudeConfigDir??null,o=s.home!==xe(s.home)||s.tmpdir!==xe(s.tmpdir)||(s.claudeConfigDir??null)!==r?{...s,home:xe(s.home),tmpdir:xe(s.tmpdir),claudeConfigDir:r}:s,i=I=>typeof I=="string"&&I.startsWith("/")?xe(I):I??null,a=t.cwd!==i(t.cwd)||(t.project_dir??null)!==i(t.project_dir)?{...t,cwd:i(t.cwd),project_dir:i(t.project_dir)}:t,l=Gp(a),c=new Map,u=(I,D=!1)=>{let z=I.action==="claude.bash.db.destructive";if(a.tool!=="Bash"||!a.command||!z&&I.action!=="claude.bash.deploy")return{};if(D)return{environment:null,environment_said:null};let Z=z?Aa(a.command,I.target,I.host):c.get(I.host);return Z||c.set(I.host,Z=Ca(a.command,I.host)),{environment:Z.environment,environment_said:Z.said}},d=(I,D,z=[],Z=[])=>{let J=I??{action:"claude.bash.unclassified",service:null,target:null,branch:null,host:null,is_local:null,why:"no rule applies"},ue=Z.find(G=>G.catastrophic),X=ue&&Z.indexOf(ue)>15?[...Z.slice(0,15),ue]:Z.slice(0,16),ze=G=>u(G,Z.length>16),Oe=G=>G.push&&Z.length>16?{...G.push,repo_dir:null}:G.push;return{action:J.action,service:J.service,attributes:{target:J.target,branch:J.branch,host:J.host,is_local:J.is_local,args_hash:l,...ze(J),...Oe(J)},why:J.why,parse:D,also:z,...Z.length>1?{findings:X.map(G=>({action:G.action,service:G.service,target:G.target,why:G.why,...G.catastrophic?{catastrophic:!0}:{},...ze(G),...Oe(G),...G.host?{host:G.host}:{}}))}:{},...J.catastrophic?{catastrophic:!0}:{},...a.tool==="Bash"&&(J.action==="claude.bash.spend"||z.includes("claude.bash.spend"))?{units:oa(a.command)}:{},...(Z.length>1?Z.filter(G=>G.action===J.action).every(G=>G.housekeeping):J.housekeeping)?{housekeeping:!0}:{}}},p=a.tool;if(Cp.has(p))return d(Zp(a.args),"not-shell");if(Sp.has(p))return d(Gr(p,"a subagent or workflow launch (its text is never read)"),"not-shell");if(p.startsWith("mcp__")){let I={hit:!1},D=uh(a,o,I);return D.also&&D.also.length>0?d(D,I.hit?"limited":"not-shell",[...new Set(D.also.filter(z=>z!==D.action))]):d(D,I.hit?"limited":"not-shell")}if(mt.has(p)||Fl.has(p)){let I=a.target??Yp(a.args),D=I!==null&&H()?We(I)??I:I,z=[a.cwd,a.project_dir??null].find(X=>typeof X=="string"&&X.startsWith("/")&&!C(X))??null,Z=D?D.startsWith("/")||D.startsWith("~")?U(D,null,o):z!==null?U(D,z,o):null:null,J=X=>({...X,attributes:{...X.attributes,path:Z!==null&&Z.startsWith("/")&&!C(Z)?Z:null}});if(D&&mt.has(p)&&H()&&/^\/dev\/(?!(?:null|stdout|stderr|tty)$)/.test(D)&&!ls(D))return J(d({action:"claude.bash.fs.delete_recursive",service:"fs.device",target:D,branch:null,host:null,is_local:!0,why:`writes a raw disk or volume (${D})`},"not-shell"));let ue=D&&mt.has(p)?Bn(D,o,[a.project_dir??null,a.cwd]):null;if(ue)return J(d(ue,"not-shell"));if(D&&mt.has(p)&&Gc(D,o)&&Zc.test(yl(a.args)))return J(d({action:"claude.agent.controls",service:null,target:D,branch:null,host:null,is_local:!0,why:`gives a subagent, command or skill its own bypass or unrestricted shell (${R.basename(D)})`},"not-shell"));if(D&&mt.has(p)&&(rt.test(D)||rt.test(iy(D,o)))&&(fn(yl(a.args))||fn(JSON.stringify(a.args??""))))return J(d({action:"claude.agent.controls",service:null,target:D,branch:null,host:null,is_local:!0,why:`changes how every later Claude Code session starts (${R.basename(D)})`},"not-shell"));if(D&&(mt.has(p)?ye(D):po(D))){let X=mt.has(p);return J(d({action:X?"claude.file.write_secret":"claude.file.read_secret",service:null,target:D,branch:null,host:null,is_local:!0,why:`${X?"writes":"reads"} a secrets file (${R.basename(D)})`},"not-shell"))}return J(d(Gr(p,`${p} of a regular file`),"not-shell"))}if(p==="PowerShell"&&a.command){let I=Bt(a.command,{cwd:a.cwd!==null?Ye(a.cwd):null});return I.kind==="unreadable"?d(m("claude.bash.privilege",`runs PowerShell Anvil can't read (${I.why})`,{target:a.command.slice(0,200),is_local:null}),"partial"):gn({...a,tool:"Bash",command:I.text},o)}if(p!=="Bash"||!a.command)return d(Gr(p,`the ${p} tool`),"not-shell");let f=a.project_dir??null,h=ut(a.command,{home:o.home,tmpdir:o.tmpdir,cwd:a.cwd,projectDir:f,claudeConfigDir:o.claudeConfigDir??null,...wo(o)}),g={ctx:o,projectRoot:f,base:a.cwd,branch:a.git_branch,branchDir:a.cwd,createdBranches:new Map,stashApplied:new Set,stashCreated:!1,stashPushes:0,sessionId:a.session_id??null,lineText:a.command,lineMade:[],lineLaunched:[],secretCopies:new Set,links:new Map,downloads:new Set,cut:{hit:!1}},y=[];g.lineCommands=h.commands;for(let I of h.commands){bg(I,g);for(let D of Zn(I,g))y.push(Fm(D,I));Dt(g,()=>Vp(I,g)),Dp(I,g),Fp(I,g),zp(I,g)}Ip(a.command)&&y.push(m("claude.agent.controls","runs a command without Claude Code's session marker (CLAUDECODE), which Anvil uses to tell this session from the person's own terminal",{target:"CLAUDECODE",is_local:!0}));let $=g.cut.hit?"limited":h.status;if(y.length===0)return d(null,$);let E=[...y].sort((I,D)=>Ia(D)-Ia(I)),_=E[0],k=[...new Set(E.slice(1).map(I=>I.action).filter(I=>I!==_.action&&ro[I]>1))],P=d(_,$,k,E.filter(I=>ro[I.action]>1)),S=_.is_local===!0||_.host!==null&&vc.test(_.host),A=Op.has(_.action)&&_.catastrophic!==!0&&!_.housekeeping&&!S?Np(a.args,_.target==="no server shown"):null;if(A===null)return P;let M=`${P.why} (Claude's description says ${A})`;return{...P,why:M,catastrophic:!0,...P.findings?{findings:P.findings.map((I,D)=>D===0?{...I,why:M,catastrophic:!0}:I)}:{}}}var Op=new Set(["claude.bash.deploy","claude.bash.db.destructive","claude.bash.external_write","claude.bash.git.push_main","claude.bash.git.force_push","claude.bash.publish","claude.bash.secrets.print","claude.bash.secrets.expose","claude.bash.data.export","claude.bash.crypto.transaction","claude.bash.spend","claude.bash.net.expose"]),Pp=/(?<![A-Za-z0-9])(?<!(?:non|pre|not|no|un)[\s_-]?)(?:(?:prod|production)(?![A-Za-z0-9])(?![\s_-]+(?:build|bundle|ready|grade|quality|mode|deps|dependencies|code|like|image|assets|shape|parity|optimi[sz]\w*)\b)|go(?:es|ing)?[\s-]+live\b|went[\s-]+live\b|live[\s-]+(?:site|app|application|environment|env|database|db|cluster|servers?|system|stack|account|customers?|users?|traffic|instance|deployment|mode|store|services?|keys?)\b)/i,jp=/\b(?:drop|wipe|truncate|destroy|erase|purge|nuke|delete)\w*\s+(?:(?:the|all|every|entire|whole)\s+)*(?:(?:all|every|entire|whole)\s+(?:\w+\s+)?(?:tables|databases?|dbs?|schemas?|collections|keyspaces?|clusters?)|(?:database|db|cluster)\b(?![.-]\w)(?!\s+(?:file|connection|client|config|entry|row|record|column|migration|pod|node|member|replica|shard|user|role|secret|namespace|context)s?\b))/i,Wp=/\b(local|localhost|dev|development|test|testing|tests|sandbox|scratch|temp|tmp|throwaway)\b/i;function Np(e,n=!1){let t=e!==null&&typeof e=="object"?e.description:void 0;if(typeof t!="string")return null;let s=Math.min(t.length,500);if(t.length>500)for(;s>0&&/[A-Za-z0-9_]/.test(t[s-1]);)s--;let r=t.slice(0,s),o=r.toLowerCase();return(o.includes("prod")||o.includes("prd")||o.includes("live"))&&Pp.test(r)?"production":!n&&["drop","wipe","truncate","destroy","erase","purge","nuke","delete"].some(i=>o.includes(i))&&jp.test(r)&&!Wp.test(r)?"a whole database or cluster is wiped":null}var Tp=/(^|\/)\.git\/(worktrees\/[^/]+\/)?((logs|refs)(\/|$)|(packed-refs|HEAD|ORIG_HEAD|FETCH_HEAD)$)/,In="(?:CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)",Os=String.raw`(?:^|[;&|(\n{]\s*|\$\(\s*)(?:(?:nohup|sudo|exec|command|time|nice|builtin)\s+)*`,Lp=new RegExp([String.raw`${Os}(?:(?:export|declare\s+-x|typeset\s+-x|local|readonly)\s+)?(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:CLAUDECODE=(?!1(?:[\s;&|)]|$))|CLAUDE_CODE_ENTRYPOINT=)`,String.raw`${Os}setenv\s+${In}\b`,String.raw`${Os}unset\s+(?:-[vf]\s+)?(?:\w+\s+){0,8}${In}\b`,String.raw`${Os}env\s+(?:\S+\s+){0,8}?(?:-u\s*${In}\b|--unset[=\s]\s*${In}\b|CLAUDECODE=(?!1(?:\s|$))|CLAUDE_CODE_ENTRYPOINT=)`,String.raw`(?:del\s+os\.environ|delete\s+process\.env|environ\.pop|unsetenv|Remove-Item\s+Env:)[^;\n]{0,24}${In}`].join("|"));function Ip(e){return Lp.test(e.slice(0,65536))}function wo(e){return{knownFiles:e.session?.scripts??null,unreadableFiles:e.session?.unreadableScripts??null,wantFiles:e.wantScripts??null}}function Yn(e,n,t,s=t.projectRoot){let r=ut(e,{home:t.ctx.home,tmpdir:t.ctx.tmpdir,cwd:n,projectDir:s,claudeConfigDir:t.ctx.claudeConfigDir??null,...wo(t.ctx)});return r.status==="limited"&&(t.cut.hit=!0),r}function Ml(e,n){let t=n.lineMade.length+n.lineLaunched.length>0?{...n.ctx,session:{...n.ctx.session??{made:[],launched:[]},made:ql(n),launched:Ul(n)}}:n.ctx,s=gn(e,t);return s.parse==="limited"&&(n.cut.hit=!0),s}var La=200;function Ze(e,n){return e.length>La&&(n.hit=!0),e.slice(0,La)}function Dp(e,n){let t=e.argv;if(e.name!=="ln"||!t.slice(1).some(l=>/^-[a-zA-Z]*s/.test(l)||l==="--symbolic"))return;let s=t.findIndex(l=>l==="--target-directory"||/^-[a-zA-Z]*t$/.test(l)),r=s>0?t[s+1]:t.find(l=>l.startsWith("--target-directory="))?.slice(19),o=t.slice(1).filter((l,c)=>!l.startsWith("-")&&c+1!==s+1&&!["-S","--suffix"].includes(t[c]??""));if(o.some(C)||r!==void 0&&C(r))return;let i=(l,c)=>R.normalize(Y(l,c,te(n)).path??l),a=r!==void 0?o.map(l=>[l,R.join(r,R.basename(l))]):o.length===1?[[o[0],R.basename(o[0])]]:o.length===2?[[o[0],o[1]]]:[];for(let[l,c]of a){let u=i(c,e.cwd);n.links.set(u,i(l,R.dirname(u)))}}function Fp(e,n){if(!Qs.has(e.name))return;let t=e.argv,s=t.find(i=>cn(i));if(!s||Re(s))return;let r=e.name==="wget"?["-O","--output-document"]:["-o","--output"],o=t.find((i,a)=>r.includes(t[a-1]??""))??t.find(i=>i.startsWith(`${r[1]}=`))?.split("=")[1];o&&!C(o)&&o!=="-"&&n.downloads.add(Y(o,e.cwd,te(n)).path)}function zp(e,n){if(n.lineMade.length+n.lineLaunched.length>64)return;let t=Dr(e,{home:n.ctx.home,tmpdir:n.ctx.tmpdir,projectDir:n.projectRoot});n.lineMade.push(...t.paths),n.lineLaunched.push(...t.launched)}function Ul(e){let n=e.ctx.session?.launched??[];return e.lineLaunched.length>0?[...n,...e.lineLaunched]:n}function ql(e){let n=e.ctx.session?.made??[];return e.lineMade.length>0?[...n,...e.lineMade]:n}function ot(e,n){let t=e.ctx.session?.probed,s=jn(n);if(t&&s in t)return t[s]??null;e.ctx.wantProbes?.set(s,n)}function ko(e){let n=e.ctx.session?.startedAt;return typeof n=="number"&&n>0?n-1e3:null}function Hl(e){let n=r=>{if(!r||C(r)||xe(r)===xe(e.ctx.home))return null;let o=ot(e,{kind:"file",arg:r});return typeof o=="string"?o.split(" ")[0]:o},t=n(e.base),s=e.projectRoot?n(e.projectRoot):null;return t===void 0||s===void 0?null:{here:t,project:s}}function Mp(e,n,t){let s=o=>o.replace(/^\/private(?=\/(?:var|tmp)\/)/,""),r=s(e);return on(r,n.here&&s(n.here))||on(r,n.project&&s(n.project))||(t.ctx.session?.made??[]).some(o=>on(r,s(o)))}var $t=e=>e.wrappers.some(n=>["sudo","doas","pkexec","run0"].includes(n)),on=(e,n)=>!!n&&(e===n||e.startsWith(`${n}/`));function vo(e){let n=ot(e,{kind:"ps"});if(typeof n!="string")return null;let t=new Map;for(let s of n.split(`
|
|
37
|
-
`)){let r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(s);r&&
|
|
38
|
-
`).map(l=>l.trim()).filter(l=>/^\d+$/.test(l)))];if(
|
|
39
|
-
`).filter(
|
|
40
|
-
`).pop()??"":"",i=/@\{(\d+)\} branch: Created from /.exec(o);return i!==null&&Number(i[1])*1e3>=s}function Gl(e,n){return ot(n,{kind:"ignored",arg:e,cwd:R.dirname(e)})===""}function Bp(e,n){if(C(e))return null;let t=ko(n),s=ot(n,{kind:"file",arg:e}),r=Hl(n),o=Gl(e,n);if(typeof s!="string"||!r||!o)return null;let[i,a]=s.split(" ");return!on(i,r.here)&&!on(i,r.project)?null:t!==null&&Number(a)>=t?"own":"dev"}function Ie(e,n,t){if(t.links.size===0||C(e))return e;let s=e.startsWith("/")?e:e.startsWith("~/")?t.ctx.home+e.slice(1):n.cwd?`${n.cwd}/${e}`:e;if(!s.startsWith("/"))return e;let r=s.split("/").filter(a=>a!==""),o="/",i=!1;for(let[a,l]of r.entries()){if(l===".")continue;o=l===".."?R.dirname(o):R.join(o,l);let c=a===r.length-1&&!s.endsWith("/");for(let u=0;!c&&u<8&&t.links.has(o);u++)o=t.links.get(o),i=!0}return i?o+(s.endsWith("/")?"/":""):e}function Vp(e,n){let t=e.argv.slice(1).filter(i=>!i.startsWith("-")),s=i=>n.secretCopies.add(Y(i,e.cwd,te(n)).path);if(["cp","mv","install","ditto","rsync"].includes(e.name)&&t.length>=2&&t.slice(0,-1).some(i=>ye(i)||n.secretCopies.has(Y(i,e.cwd,te(n)).path))&&s(t[t.length-1]),e.name==="cat"&&t.some(i=>ye(i)))for(let i of e.redirects)(i.op===">"||i.op===">>")&&i.target&&s(i.target);let r=[];for(let i=1,a=!1;i<e.argv.length;i++){let l=e.argv[i];if(["--exclude","--exclude-from","-X"].includes(l))i++;else{if(l.startsWith("--exclude"))continue;e.name==="zip"&&(l==="-x"||l==="--exclude")?a=!0:l.startsWith("-")?a=!1:a||r.push(l)}}if(["tar","gtar","bsdtar","zip","7z"].includes(e.name)&&r.some(i=>ye(i)||/(^|\/)\.(ssh|aws|gnupg|kube)\/?$/.test(v(i)))){let i=/^[A-Za-z]+$/.test(e.argv[1]??"")&&(e.argv[1]??"").includes("f")?e.argv[2]:void 0,a=j(e.argv,"-f","--file")??Us(e.argv,"f")??i??(e.name==="zip"||e.name==="7z"?t.find(l=>/\.(zip|7z)$/.test(l)):t[0]);a&&s(a)}let o=e.stdinFile!==null&&ye(e.stdinFile)||e.pipeFrom!==null&&e.pipeFrom.name==="cat"&&e.pipeFrom.argv.slice(1).some(i=>ye(i));if(e.name==="tee"&&o)for(let i of t)s(i)}function Ia(e){return(e.service&&xp.has(e.service)?100:0)+ro[e.action]}function Zp(e){let n=e&&typeof e=="object"?e:{},t=typeof n.subagent_type=="string"&&n.subagent_type.trim()?n.subagent_type.trim():"general-purpose",s=/^[A-Za-z0-9_.:-]{1,64}$/.test(t)?t:`type-${Dl("sha256").update(t).digest("hex").slice(0,8)}`,r=typeof n.model=="string"&&/^[a-z0-9.\-[\]]{1,40}$/i.test(n.model)?n.model:null;return{action:Ap,service:null,target:s,branch:null,host:null,is_local:null,why:`launches a helper agent (${s}${r?`, ${r}`:""})`}}function Gr(e,n){return{action:"claude.tool.other",service:null,target:e,branch:null,host:null,is_local:null,why:n}}function Gp(e){if(e.args===void 0&&e.command===null&&e.tool.startsWith("mcp__"))return null;let n=e.args!==void 0?oo(e.args):e.command??e.target??"";return Dl("sha256").update(JSON.stringify([e.tool,n])).digest("hex").slice(0,16)}var Kp=64;function oo(e,n=0){return n>Kp?"[nested too deep]":Array.isArray(e)?e.map(t=>oo(t,n+1)):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,oo(e[t],n+1)])):e}function Yp(e){if(!e||typeof e!="object")return null;let n=e;for(let t of["file_path","notebook_path","path"])if(typeof n[t]=="string")return n[t];return null}var Fn=new Set(["ask","get","list","search","read","fetch","find","query","describe","view","show","lookup","check","count","browse","preview","inspect","status","info","details","stats","history","logs","index","guide","help","export","download","screenshot","validate","diff","compare","estimate","explain","summarize","extract","scrape","research","retrieve","whoami","analyze","analyse","aggregate","size","health","usage","schema","metadata","metrics","overview","summary","parse"]),wt=new Set(["send","reply","forward","post","publish","deploy","merge","delete","remove","destroy","purge","trash","wipe","drop","purchase","buy","pay","payout","refund","charge","transfer","withdraw","cancel","revoke","archive","unpublish","create","update","write","insert","append","upload","share","grant","execute","exec","upsert","submit","invite","modify","patch","put","replace","schedule","approve","provision","trigger","enable","disable","assign","import","add","set","close","stop","scale","rollout","transition","restore","invoke","fork","move","rename","clear","discard","clean","edit","run","change","save","store","commit","push","start","restart","pause","resume","reopen","resolve","mark","pin","unpin","react","star","follow","subscribe","unsubscribe","link","unlink","attach","detach","lock","unlock","block","ban","mute","duplicate","copy","sync","apply","rebase","draft","notify","reserve","register","claim","redeem","capture","void","mint","broadcast","swap","stake","activate","deactivate","suspend","reset","rotate","generate","train","launch","spawn","kill","terminate","reboot","shutdown","setup","manage","configure","initialize","init","install","uninstall","upgrade","migrate","seed","reindex"]),vt=new Set(["delete","remove","destroy","purge","trash","wipe","drop","terminate","reset","flush","rollback","revert","rotate","revoke","kill","truncate","erase","push","apply","merge","deploy","publish","refund","charge","pay","payout","transfer","clear","restore","discard"]),Jp=/^(ccd_(turn|view|window|sidebar|session|directory)|visualize|claude_browser|claude_in_chrome|computer_use)$/,Xp=/^ccd_pr__(set_monitor|bind_pr|unbind_pr|get_status)$/,Da=/^(playwright|puppeteer|browser|browsermcp|browser_use|chrome_devtools|chrome|everything|filesystem|fs|files|desktop_commander|desktopcommander|git|docker|sqlite)$/,Qp=/^(memory|sequential_thinking|sequentialthinking|time)$/,eh=new Set(["push","delete","clean","force","rebase","prune","gc","filter"]),th=new Set(["env","environment","secret","secrets","credential","credentials","password","passwords"]),nh=new Set(["backups","deployments","releases","migrations","payments","payouts","refunds","transfers","charges","subscriptions","jobs","runs","builds","workflows","stacks","instances","clusters","resources","records","messages","emails","invites","invitations","webhooks","keys","tokens","secrets","domains","dns","databases","tables","volumes","buckets","users","members","roles","permissions"]),sh=new Set(["hget","hgetall","hexists","hkeys","hvals","hlen","lrange","llen","lindex","smembers","sismember","scard","zrange","zscore","zcard","exists","ttl","pttl","type","dbsize","xrange","xlen","mget","scan","keys"]),rh=/^(context7|brave_search|brave|fetch|deepwiki|ref|microsoft_docs|aws_docs|mcp_registry)$/,oh=/^(filesystem|fs|files|desktop_commander|desktopcommander)$/;function Kl(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Is(e){let n=Kl(e);if(n.length===0)return"unknown";let t=n[0],s=n[n.length-1],r=n.find(i=>Fn.has(i)||wt.has(i)||vt.has(i))??t;return n.some(i=>vt.has(i))&&!Fn.has(r)||n.findIndex((i,a)=>a>0&&["or","and","then"].includes(i)&&n.slice(a+1).some(l=>wt.has(l)||vt.has(l)))>0?"write":Fn.has(r)||Fn.has(s)&&!n.slice(0,-2).some(i=>wt.has(i))&&!wt.has(t)?"read":n.some(i=>wt.has(i))?"write":n.length===1&&sh.has(t)||n.length>1&&/[a-z]{3}s$/.test(s)&&!/(ss|us|is)$/.test(s)&&!nh.has(s)?"read":"unknown"}function ih(e){return e.length===1?["bash","shell","terminal","sh","zsh"].includes(e[0]):(e.includes("write")||e.includes("send"))&&e.includes("terminal")||e.includes("bash")&&e.includes("command")?!0:e.some(n=>["run","exec","execute","start","interact"].includes(n))&&e.some(n=>["command","commands","terminal","shell","script","cmd","bash","process"].includes(n))}function ah(e){let n=e.args!==void 0?e.args:e.command?Yl(e.command):void 0;return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Yl(e){try{return JSON.parse(e)}catch{return}}function tn(e,n){for(let t of n)if(e&&typeof e[t]=="string")return e[t];return null}function Fa(e){if(!e)return[];let n=[];for(let t of["path","file_path","filePath","relative_path","relativePath","pathInProject","repo_path","repoPath","source","destination","target","targetPath","sourcePath","destinationPath","file","filename","dest","from","to","old_path","new_path","oldPath","newPath","paths","files"]){let s=e[t];if(typeof s=="string")n.push(s);else if(Array.isArray(s))for(let r of s.slice(0,64))typeof r=="string"&&n.push(r)}return H()?n.map(t=>We(t)??t):n}function Jl(e,n){if(e.action==="claude.bash.unclassified")return[];let t={action:e.action,service:e.service,target:e.attributes.target,branch:e.attributes.branch,host:e.attributes.host,is_local:e.attributes.is_local,why:`${e.why} ${n}`};return[t,...e.also.filter(s=>s!==e.action).map(s=>({...t,action:s,service:null}))]}var lh=new Set(["supabase","neon","planetscale","turso","bigquery","snowflake","databricks","motherduck","xata","cloudflare","d1","upstash","spanner","redshift","tinybird","firebase","railway","render","heroku","vercel","nile","tidb","aiven","aws","azure","gcp"]),ch=/^(database|db|database_?name|db_?name|branch|branch_?name|branch_?id|project|project_?id|project_?ref|env|environment|schema|catalog|dataset|instance)$/i;function uh(e,n,t){let[,s="",r=""]=e.tool.split("__"),o=Ma(s),i=`mcp.${o}.${Ma(r)}`,a=Kl(r),l=ah(e),c=p=>({action:"claude.mcp.call",service:null,target:i,branch:null,host:o,is_local:null,why:p}),u=p=>({action:"claude.mcp.side_effect",service:null,target:i,branch:null,host:o,is_local:null,why:p});if(ih(a)||tn(l,["cli_command"])!==null){let p=l?.action_json,f=typeof p=="string"?Yl(p):p,h=tn(l,["command","cmd","script","input","code","cli_command"])??tn(f&&typeof f=="object"&&!Array.isArray(f)?f:null,["command","cmd"]);if(h===null)return u(`an MCP tool that runs shell commands, with no command to read (${i})`);let g=tn(l,["cwd","workdir","directory"])??e.cwd,y=gn({tool:"Bash",command:h,target:null,cwd:g,git_branch:e.git_branch,project_dir:e.project_dir??null,session_id:e.session_id??null},n);return y.parse==="limited"&&(t.hit=!0),iu(h,g,n,e.project_dir??null,t,a.includes("terminal"))?y.action==="claude.bash.unclassified"?c(`an MCP tool running a command no rule flags (${i})`):{action:y.action,service:y.service,target:y.attributes.target,branch:y.attributes.branch,host:y.attributes.host,is_local:y.attributes.is_local,why:`${y.why} (run by ${i})`,also:y.also}:{action:"claude.agent.controls",service:null,target:i,branch:null,host:o,is_local:!0,why:`hands a command to ${i}, which may run it outside this session, and Anvil cannot read that command here`}}if(Is(r)!=="read"){let p=Fa(l).map(h=>Bn(h,n,[e.project_dir??null,e.cwd])).filter(h=>h!==null),f=p.find(h=>h.action==="claude.agent.controls")??p[0];if(f)return{...f,host:o,also:[...new Set(p.map(h=>h.action))]};for(let h of Fa(l))if(rt.test(h)&&fn(JSON.stringify(l)))return{action:"claude.agent.controls",service:null,target:h,branch:null,host:o,is_local:!0,why:`changes how every later Claude Code session starts (${R.basename(h)}, through ${i})`}}if(oh.test(o)){let p=tn(l,["path","file_path","filePath","destination","target"]),f=Is(r);if(p&&ye(p)){let h=f!=="read";return{action:h?"claude.file.write_secret":"claude.file.read_secret",service:null,target:p,branch:null,host:o,is_local:!0,why:`${h?"writes":"reads"} a secrets file (${R.basename(p)}) through ${i}`}}}if(a.some(p=>["sql","query"].includes(p))&&a.some(p=>["run","execute","exec","query"].includes(p))){let p=tn(l,["sql","query","statement"]);if(p!==null&&!(Wo.test(p)||be.test(p)))return c(`an MCP tool running a read-only query (${i})`);let f=rn(p),h=o.split("_").some(y=>lh.has(y))&&!o.split("_").includes("local"),g=f===null?void 0:[...Object.entries(l??{}).filter(([y,$])=>ch.test(y)&&typeof $=="string"&&$.length<200&&!/\s/.test($)).map(([,y])=>y)].find(nr);if(p!==null)return f!==null&&(h||g!==void 0)?{...u(`an MCP tool running destructive SQL (${f}) on ${g!==void 0?`${g}, named for production`:`${o}'s hosted database`} (${i})`),catastrophic:!0}:u(`an MCP tool running SQL that writes (${i})`)}if((a.includes("sql")||a.includes("query")&&a.some(p=>["database","db","d1","sql"].includes(p)))&&!Da.test(o))return u(`an MCP tool that runs SQL, with no statement to read (${i})`);if(Xp.test(`${o}__${r}`))return c(`a setting of this machine's own app (${i})`);if(Jp.test(o)){let p=a.find(f=>["upload","send","submit","purchase","buy","publish"].includes(f));return p?u(`a browser tool that ${p}s something to a website (${i})`):c(`a tool of this machine's own app (${i})`)}if(Qp.test(o))return c(`the agent's own notes or thinking (${i})`);let d=Is(r);if(a.some(p=>th.has(p))&&d!=="write")return u(`an MCP tool that reads secrets or the environment (${i})`);if(rh.test(o)){let p=a.find(f=>vt.has(f)||["upload","send","submit","publish","post","create","update","write"].includes(f));return p?u(`an MCP tool that ${p}s (${i})`):c(`a documentation tool (${i})`)}if(Da.test(o)){let p=o==="git"?a.find(h=>eh.has(h)):a.find(h=>vt.has(h));if(p&&!Fn.has(a[0]??""))return u(`a local MCP tool that ${p}s (${i})`);if(o==="docker"&&a.some(h=>["run","exec","execute"].includes(h)))return u(`a local MCP tool that runs a container or a command in one (${i})`);let f=a.find(h=>["upload","send","submit","purchase","buy","publish","post"].includes(h));return f?u(`a local MCP tool that ${f}s something to another service (${i})`):d==="write"&&a.some(h=>["config","configuration","settings","setting","permission","permissions","policy"].includes(h))?u(`a local MCP tool that changes its own configuration (${i})`):c(`a tool that acts on this machine (${i})`)}return d==="read"?c(`an MCP tool that reads (${i})`):mh(a,l)?c(`an MCP edit to a document's content (${i})`):d==="unknown"&&["profile","me","whoami"].includes(a[a.length-1]??"")&&!a.some(p=>wt.has(p)||vt.has(p))?c(`an MCP tool that returns the caller's profile (${i})`):u(d==="write"?`an MCP tool that ${a.find(p=>vt.has(p))??a.find(p=>wt.has(p))}s (${i})`:`an MCP tool whose name does not say it only reads (${i})`)}var dh=new Set(["update","edit","append","insert","write","replace","patch","save","create","batch","add","set","modify","change","draft","rename"]),fh=new Set(["doc","docs","document","documents","page","pages","block","blocks","note","notes","section","sections","tab","tabs","paragraph","paragraphs","wiki","article","articles","markdown","prose"]),ph=new Set(["delete","remove","destroy","purge","trash","archive","share","unshare","publish","unpublish","send","post","comment","invite","grant","permission","permissions","move","transfer","email","notify","export"]),hh=/^(share|shares|sharing|shared_with|permission|permissions|visibility|public|is_public|publish|published|invite|invites|invitees|recipient|recipients|to|cc|bcc|email|emails|role|roles|grant|grants|notify|send|send_notification|acl|access|access_level|link_sharing)$/i,za=/share|publish|permission|invite|send|notify|email|trash|archive|transfer|(delete|remove)[-_ ]?(doc|document|page|file|project)/i,gh=/^(page_?id|document_?id|doc_?id|block_?id|note_?id|documentId|pageId|docId|blockId|noteId)$/i;function mh(e,n){if(!n||e.length===0||!e.some(i=>dh.has(i))||e.some(i=>ph.has(i)))return!1;let t=!1,s=!1,r=!1,o=(i,a)=>{if(!(t||a>12||i===null||typeof i!="object")){if(Array.isArray(i)){for(let l of i.slice(0,500))o(l,a+1);return}for(let[l,c]of Object.entries(i))hh.test(l)&&(t=!0),gh.test(l)&&(s=!0),["op","type","action","operation"].includes(l)&&typeof c=="string"&&za.test(c)&&(t=!0),(l==="kind"&&typeof c=="string"&&/^(blocks?|text|tabs?|range|paragraphs?|sections?|heading|inline|markdown)$/.test(c)||l==="engine"&&typeof c=="string")&&(r=!0),a===0&&l==="container"&&c&&typeof c=="object"&&typeof c.kind=="string"&&(r=!0),a===0&&l==="ref"&&c&&typeof c=="object"&&/^(project|tab|node|doc|document|page|block)$/.test(String(c.object))&&(r=!0),l==="kind"&&typeof c=="string"&&za.test(c)&&(t=!0),o(c,a+1)}};return o(n,0),t?!1:e.some(i=>fh.has(i))||s||r}function Ma(e){return e.toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"")||"unknown"}var Xl=new Set(["main","master"]),yh=new Set(["production","prod","live"]);function m(e,n,t={}){let s=n.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g,""),r=s.length>300?`${s.slice(0,297)}\u2026`:s,o=typeof t.target=="string"&&t.target.length>200?{...t,target:`${t.target.slice(0,197)}\u2026`}:t;return{action:e,service:null,target:null,branch:null,host:null,is_local:null,why:r,...o}}function bh(e,n){if(!C(e.argv[0]??""))return[];let t=e.argv.slice(1),s=[];t.some(o=>/^-[rRfviIdP]*[rR][rRfviIdP]*$/.test(o)||o==="--recursive")&&t.some(o=>!o.startsWith("-"))&&s.push(...Ro({...e,name:"rm",argv:["rm",...t]},n)),(t.includes("manage.py")||t.some(o=>/^db:(drop|reset)/.test(o)))&&s.push(...Ms({...e,name:"python",argv:["python",...t]}));let r=o=>({...e,name:o,argv:[o,...t]});return["push","reset","clean","branch","stash","checkout","restore"].includes(t[0]??"")&&s.push(...mc(r("git"),n)),["destroy","apply"].includes(t[0]??"")&&t.some(o=>o.startsWith("-auto-approve")||o==="-auto-approve")&&s.push(...Ms(r("terraform"))),["delete","apply","replace","drain"].includes(t[0]??"")&&s.push(...Ms(r("kubectl"))),["publish","unpublish"].includes(t[0]??"")&&s.push(...jc(r("npm"))),t.includes("-c")&&be.test(ke(t.join(" ")))&&s.push(...Lo(r("psql"),n)),s.map(o=>o.why.includes("cannot name")?o:{...o,why:`${o.why} (by a program it cannot name: ${v(e.argv[0])})`})}function Zn(e,n){if(e.functionCall)return[...Il(e,n),...ml(e,n),...Xs(e,n)];let t=Rm(e.argv);if(t!==null)return Zn({...e,name:pe(t[0]),argv:t},n);if(["pnpm","yarn","bun"].includes(e.name)){let{sub:o,at:i}=ms(e.argv);if(i>0&&!To.has(o)&&fm.has(o))return Zn({...e,name:o,argv:[o,...e.argv.slice(i+1)]},n)}if(e.argv.slice(1).some((o,i)=>(o==="--help"||o==="--version"&&i===0)&&!/^-/.test(e.argv[i]??""))||["help","--help"].includes(e.argv[1]??""))return e.redirects.length>0?Xs({...e,name:"echo",argv:["echo"]},n):[];let s=[];s.push(...bb(e,n)),s.push(...Cb(e)),s.push(...Nb(e,n)),s.push(...bh(e,n)),s.push(...Il(e,n));let r=e.name;switch(r){case"rm":case"unlink":case"shred":case"srm":case"rimraf":s.push(...Ro(e,n));break;case"rsync":s.push(...dc(e,n));break;case"find":s.push(...pg(e,n));break;case"fd":case"fdfind":s.push(...gg(e,n));break;case"dd":case"mkfs":case"diskutil":case"wipefs":case"fdisk":case"newfs_apfs":case"newfs_hfs":s.push(...el(e,n));break;case"git":s.push(...mc(e,n));break;case"gh":s.push(...xg(e,n.lineText,n));break;case"curl":case"wget":case"http":case"https":case"xh":s.push(...Sg(e));break;case"pkill":case"killall":case"kill":case"fuser":case"colima":case"launchctl":case"tmux":case"systemctl":case"shutdown":case"reboot":case"halt":case"osascript":s.push(...Ng(e,n));break;default:break}if(r.startsWith("mkfs.")&&s.push(...el(e,n)),s.length===0&&s.push(...Sh(e,n)),s.push(...Ms(e)),(r==="docker"||r==="podman"||r==="docker-compose")&&!s.some(o=>o.action==="claude.bash.deploy")&&s.push(...sm(e,n.lineText)),s.length===0&&s.push(...Ch(e)),s.push(...Lo(e,n)),s.push(...Dt(n,()=>Km(e,n))),s.push(...ml(e,n)),s.push(...Dt(n,()=>Xm(e,n))),s.push(...mb(e,n)),s.push(...$b(e,n)),H()&&s.push(...My(e,n)),s.push(...Yh(e)),s.length===0&&s.push(...Om(e)),s.length===0&&s.push(...wh(e)),s.length===0&&s.push(...Rh(e)),s.length===0&&s.push(...Dt(n,()=>rg(e,n))),!s.some(o=>o.action==="claude.bash.db.destructive"&&!o.why.includes(" runs SQL that changes data ("))){let o=Em(e,n);if(o.length>0){for(let i=s.length-1;i>=0;i--)s[i].why.includes(" runs SQL that changes data (")&&s.splice(i,1);s.push(...o)}}return["aws","gcloud","az"].includes(e.name)&&e.argv.some(o=>o==="update-kubeconfig"||o==="get-credentials")&&j(e.argv,"--file","-f")!=="-"&&!L(e.argv,"--dry-run")?s.filter(o=>o.action!=="claude.bash.deploy"&&o.action!=="claude.bash.secrets.print"):s}var $o=new Set(["npm","pnpm","yarn","bun","npx","pnpx","bunx","deno","node","nodejs","pip","pip3","pipx","poetry","uv","pdm","hatch","rye","conda","mamba","micromamba","brew","apt","apt-get","yum","dnf","pacman","apk","port","nix","nix-env","flatpak","snap","cargo","rustup","gem","bundle","bundler","go","composer","pod","carthage","flutter","dart","dotnet","mvn","gradle","make","cmake","ninja","bazel","xcodebuild","xcrun","swift","nvm","fnm","volta","asdf","mise","rbenv","pyenv","sdk","direnv","pre-commit","husky","lefthook","git","hg","svn","docker","podman","colima","minikube","kind","k3d","vagrant","tmux","screen","code","cursor","vim","nvim","emacs","jest","vitest","pytest","mocha","eslint","prettier","tsc","python","python3","ruby","perl","php","java","echo","printf","ls","cat","grep","rg","sed","awk","jq","yq","sort","uniq","head","tail","wc","cut","tr","tee","touch","mkdir","cp","mv","ln","chmod","chown","tar","zip","unzip","gzip","gunzip","open","say","defaults","du","df","stat","file","which","type","command","test","true","false","sleep","wait","date","seq","basename","dirname","realpath","readlink","cd","export","unset","set","source","eval","exec","trap","read","history","sqlite3","redis-server","pg_ctl","initdb","ollama","anvil","anvil-claude","claude","pm2","nodemon","turbo","nx","lerna","changeset","rimraf","trash","kubectx","kubens","corepack","tsx","ts-node","esbuild","vite","next","webpack","rollup","parcel","storybook","playwright","cypress","lsof","ps","top","pgrep","pkill","kill"]),Ua=null;function Hs(e){return Ua??=new Set([...Object.keys(Sc),...Qs,"aws","az","gcloud","gsutil","bq","kubectl","helm","terraform","tofu","pulumi","psql","mysql","mariadb","mongosh","mongo","mongoimport","mongorestore","pg_restore","pg_dump","redis-cli","clickhouse","clickhouse-client","cqlsh","snowsql","snow","beeline","impala-shell","spark-sql","heroku","railway","vercel","wrangler","fly","flyctl","firebase","doppler","infisical","vault","op","security","gpg","gpg2","prisma","alembic","artisan","rails","rake","flask","rsync","find","fd","dd","gh","ssh","scp","sftp","crontab","systemctl","launchctl","ngrok","cloudflared","tailscale","stripe","cast","forge","solana","fastlane","eas","7z","7za","7zr","7zz","aider","amp","anchor","anvil","anvil-claude","ape","aptos","artisan","at","autossh","awk","aws","az","azcopy","base64","batch","bcp","beeline","bitcoin-cli","bore","bq","branch","brew","brownie","bsdtar","bun","cardano-cli","cast","checkout","chflags","chgrp","chmod","chown","claude","clean","clickhouse","clickhouse-client","cloudflared","cmp","cockroach","code","code-insiders","codex","colima","copilot","cp","cqlsh","croc","crontab","crush","curl","cursor-agent","cut","databricks","dbt","dd","ddev","deno","devtunnel","diff","diskutil","ditto","docker","droid","dropdb","dropuser","duckdb","ed","egrep","emacs","ex","expo","fastmcp","fd","fdfind","fdisk","ffsend","filter-branch","filter-repo","find","firebase","fish","fly","flyctl","flyway","forge","frpc","fuser","gawk","gc","gcloud","gcp","gemini","gh","git","glab","gmv","gpg","gpg2","grep","gsed","gsutil","gtar","halt","hardhat","head","herd","heroku","http","https","impala-shell","install","install-mcp","jq","kill","killall","knex","kubectl","launchctl","liquibase","ln","lncli","localxpose","loclx","lt","mariadb","mariadb-dump","mawk","mc","mcp-get","md5","md5sum","mix","mkfifo","mkfs","mknod","mongo","mongodump","mongoexport","mongosh","mv","mydumper","mysql","mysqladmin","mysqldump","mysqlpump","nawk","nc","ncat","near","neon","neonctl","netcat","newfs_apfs","newfs_hfs","ngrok","node","nvim","oc","openssl","osascript","patch","pbcopy","perl","pg_basebackup","pg_dump","pg_dumpall","pgcli","php","pkill","plutil","pm2","podman","powershell","powershell.exe","presto","prisma","pscale","psql","push","pwsh","pwsh.exe","python","python3","q","qwen","rclone","reboot","red","redis-cli","reflog","reset","restore","rg","rimraf","rm","rsync","ruby","s3cmd","schtasks","schtasks.exe","scp","security","sed","sequelize","sequelize-cli","set","sftp","sha256sum","shasum","shred","shutdown","smithery","snow","snowsql","socat","solana","soroban","sort","spark-sql","spl-token","sponge","sqlcmd","sqlite","sqlite3","srm","ssh","starkli","stash","stellar","stripe","sui","supabase","switch","symbolic-ref","systemctl","tailscale","tar","tee","telnet","tmole","tmux","touch","trash","trino","true","truffle","truncate","ts-node","tsx","tunnelmole","turso","typeorm","typeorm-ts-node-commonjs","typeorm-ts-node-esm","unlink","untun","unzip","update-ref","valet","vi","vim","wc","wget","wipefs","worktree","wormhole","wrangler","xclip","xh","yq","zrok","format","format-volume","clear-disk","initialize-disk","remove-partition","clear-recyclebin","diskpart","vssadmin","wmic","wbadmin","wsl","bcdedit","reg","set-itemproperty","new-itemproperty","remove-itemproperty","remove-item","sc","new-service","remove-service","set-service","stop-service","register-scheduledtask","set-scheduledtask","unregister-scheduledtask","new-scheduledtask","set-executionpolicy","set-mppreference","add-mppreference","netsh","set-netfirewallprofile","new-netfirewallrule","disable-netfirewallrule","remove-netfirewallrule","takeown","icacls","taskkill","runas","gsudo","mountvol","robocopy","setx","forfiles"]),zy.has(e)?H():Ua.has(e)}var sn=new Set(["delete","destroy","drop","purge","wipe","terminate","nuke","erase","truncate","flushall","flushdb","teardown","decommission","deprovision","deregister","tombstone"]),Kr=new Set(["rm","remove","reset","revoke"]),Ql=new Set(["app","apps","application","applications","project","projects","bucket","buckets","database","databases","db","dbs","cluster","clusters","service","services","instance","instances","volume","volumes","branch","branches","environment","environments","env","envs","secret","secrets","domain","domains","zone","zones","record","records","dns","repo","repos","repository","repositories","deployment","deployments","function","functions","table","tables","queue","queues","topic","topics","stream","streams","namespace","namespaces","org","orgs","organization","organizations","team","teams","user","users","member","members","workspace","workspaces","site","sites","server","servers","machine","machines","vm","vms","droplet","droplets","pool","pools","stack","stacks","schema","schemas","collection","collections","keyspace","keyspaces","storage","backup","backups","snapshot","snapshots","token","tokens","webhook","webhooks","subscription","subscriptions","account","accounts","pg","postgres","mysql","redis","kv","d1","r2","s3","index","indexes","indices","key","keys","certificate","certificates","cert","certs","distribution","distributions","role","roles","policy","policies","vpc","subnet","subnets","gateway","node","nodes","worker","workers","job","jobs","pipeline","pipelines","model","models","endpoint","endpoints","volume-snapshot","organization-member","tenant","tenants","serverless","store","stores","region","regions","replica","replicas","shard","shards","partition","partitions","tablet","tablets","broker","brokers","changefeed","changefeeds","network","networks","firewall","firewalls","disk","disks","peer","peers","keyring","keyrings","vault","vaults"]),_o=new Set(["database","databases","db","dbs","table","tables","schema","schemas","collection","collections","keyspace","keyspaces","pg","postgres","mysql","redis","kv","d1","index","indexes","indices","backup","backups","snapshot","snapshots","bucket","buckets","storage","r2","s3","volume","volumes","store","stores","region","regions","replica","replicas","shard","shards","partition","partitions","tablet","tablets","disk","disks","vault","vaults"]),xo=/^--?(dry-?run|plan|preview|what-?if|check|diff|validate|help|version|list|ls)$/i;function ec(e){let n=[];for(let t=1;t<e.length&&n.length<6;t++){let s=v(e[t]);if(!s.startsWith("-")&&/^[a-z][a-z0-9_-]*(:[a-z0-9_-]+)*$/.test(s))for(let r of s.split(":"))r&&n.push(r)}return n}function So(e){let n=R.basename(e.name);return["const","let","var"].includes(n)&&v(e.argv[2]??"")==="="?!0:/^[A-Z][a-z]+$/.test(n)&&e.argv.length>=4&&e.argv.slice(1).some(t=>/[a-z]\.$/.test(v(t)))}function wh(e){let n=R.basename(e.name);if(!n||$o.has(n)||Hs(n)||e.functionCall||e.via==="substitution"||C(e.argv[0]??"")||e.argv[0]?.includes("/"))return[];if(So(e))return[];let t=ec(e.argv);if(t.length===0||e.argv.some(u=>xo.test(u)))return[];let s=u=>sn.has(u)||Kr.has(u)?u:sn.has(u.split("-")[0]??"")||Kr.has(u.split("-")[0]??"")&&!Vs.has(u.split("-").slice(1).join("-"))?u.split("-")[0]:null,r=t.findIndex(u=>s(u)!==null);if(r>=0){let u=s(t[r]);t[r].includes("-")&&!sn.has(t[r])&&t.splice(r+1,0,t[r].slice(u.length+1));let d=t.flatMap(h=>[h,...h.split("-")]).find(h=>Ql.has(h)),p=t.filter((h,g)=>g!==r||h.includes("-")).flatMap(h=>h.split("-")).filter(h=>h!==u);if(d===void 0&&p.length>0&&p.every(h=>oc.has(h)))return[];let f=t.length>r+1||e.argv.some(h=>/^--?(app|project|name|id|db|database|bucket|cluster|service|instance|env|environment|org|zone|branch)(=|$)/.test(h)||Ao.test(v(h)));if(sn.has(u)&&(d!==void 0||f)||Kr.has(u)&&d!==void 0){let h=_o.has(d??"")||["drop","truncate","flushall","flushdb","purge","wipe"].includes(u);return[m(h?"claude.bash.db.destructive":"claude.bash.deploy",`${n} ${zs(u)} ${d?lo(d):"what it names"} (a command with no rule of its own, read by its words)`,{target:`${n} ${t.slice(0,3).join(" ")}`,is_local:!1})]}}let o="(a command with no rule of its own, read by its words)",i=e.argv.some(u=>/\b(localhost|127\.0\.0\.1|::1)\b|^--local$/.test(v(u))),a=e.argv.map(u=>v(u)),l=a.slice(1).find((u,d)=>/\s/.test(u)&&!/^(i?like|=|!=|<>)$/i.test(a[d]??"")&&be.test(ke(u)));if(l!==void 0&&!i)return[m("claude.bash.db.destructive",`${n} runs SQL that changes data (${(be.exec(ke(l))?.[1]??"").replace(/\s+/g," ").toUpperCase()}) ${o}`,{target:n,is_local:!1})];let c=t.findIndex(u=>Vs.has(u));return c>=0&&t.some(u=>cc.has(u))&&oe(e)?[m("claude.bash.secrets.print",`${n} prints ${lo(t[c])} ${o}`,{target:`${n} ${t.slice(0,3).join(" ")}`,is_local:!0})]:t.slice(0,3).some(u=>cu.test(u))?[m("claude.bash.deploy",`${n} ${t.slice(0,2).join(" ")} deploys or publishes ${o}`,{target:`${n} ${t.slice(0,2).join(" ")}`,is_local:!1})]:t.some(u=>["tunnel","expose","funnel"].includes(u))&&e.argv.some(u=>/^(\d{2,5}|localhost:\d{2,5}|127\.0\.0\.1:\d{2,5}|https?:\/\/(localhost|127\.0\.0\.1):\d{2,5})$/.test(v(u)))?[m("claude.bash.net.expose",`${n} opens a local port to the internet ${o}`,{target:n,is_local:!1})]:[]}var kh=new Set(["-c","-F","-i","-J","-l","-o","-P","-S","-D","-X"]),vh=new Set(["-e","-f","-T","-B","-M","--rsh","--exclude","--include","--filter","--exclude-from","--include-from","--files-from","--rsync-path","--password-file","--chmod","--chown","--log-file","--temp-dir","--partial-dir","--backup-dir","--suffix","--port","--bwlimit","--timeout","--max-size","--min-size","--compare-dest","--copy-dest","--link-dest"]),tc=new Set(["--config","--transfers","--checkers","--include","--exclude","--filter","--include-from","--exclude-from","--filter-from","--files-from","--max-age","--min-age","--max-size","--min-size","--log-file","--log-level","--bwlimit","--backup-dir","--suffix","--max-depth","--order-by","--tpslimit","--retries"]),$h=/^(localhost|127\.0\.0\.1|\[::1\]|::1)$/i,_h=new Set(["copy","copyto","move","moveto","sync","bisync","rcat","copyurl","delete","deletefile","purge","rmdir","rmdirs","cleanup","dedupe"]),xh=new Set(["rcat","delete","deletefile","purge","rmdir","rmdirs","cleanup","dedupe"]);function Sh(e,n){let t=R.basename(e.name);if(!["scp","rsync","rclone"].includes(t))return[];let s=e.argv.map(u=>v(u));if(s.some(u=>u==="-n"||u==="--dry-run"||t==="rsync"&&/^-[a-zA-Z]*n[a-zA-Z]*$/.test(u)))return[];let o=ce(s,1,t==="scp"?kh:t==="rsync"?vh:tc),i=u=>Le(u)&&!$h.test(Vn(u));if(t==="rclone"){let u=o.findIndex(g=>_h.has(g));if(u<0)return[];let d=o[u],p=o.slice(u+1,u+1+(xh.has(d)?1:2));if(p.length===0)return[];if(p.every(g=>!Le(g))){if(["delete","deletefile","purge","rmdir","rmdirs"].includes(d))return Ro({...e,name:"rm",argv:["rm","-rf",...p]},n).map(g=>({...g,why:`rclone ${d}: ${g.why}`}));if(d==="sync"&&p.length>=2){let g=Zs(p[p.length-1],e,n);return g.kind==="disposable"?[]:[{..._t([g],e),why:`rclone sync replaces what is in ${g.why}`}]}return[]}let f=p[p.length-1];if(d==="sync"&&p.length===2&&Le(p[0])&&!Le(f)){let g=Zs(f,e,n);return g.kind==="disposable"?[]:[{..._t([g],e),why:`rclone sync replaces what is in ${g.why}`}]}if(!["copy","copyto","move","moveto","sync","bisync","rcat","copyurl"].includes(d)||d!=="rcat"&&p.length<2||!i(f))return[];let h=f.split(":")[0];return d==="sync"||d==="bisync"?[m("claude.bash.db.destructive",`rclone ${d} makes ${h}: match the source, deleting what is not in it`,{target:f,host:h,is_local:!1})]:[m("claude.bash.external_write",`rclone ${d} copies files to ${h}:`,{target:f,host:h,is_local:!1})]}let a=o.filter(u=>Le(u)||/[/.~]/.test(u));if(a.length<2)return[];let l=a[a.length-1];if(!i(l))return[];let c=Vn(l);return[m("claude.bash.external_write",`${t} copies files to another machine (${c})`,{target:l,host:c,is_local:!1})]}function Ch(e){let n=Mn.has(R.basename(e.name))?e.argv.slice(1).map(i=>v(i)).find(i=>!i.startsWith("-"))??"":v(e.argv[0]??""),t=R.basename(n).replace(/\.sh$/,"");if(!/^kafka-[a-z-]+$/.test(t)||["kafka-server-start","kafka-server-stop","kafka-storage","kafka-run-class","kafka-console-consumer","kafka-dump-log"].includes(t))return[];let s=e.argv.map(i=>v(i));if(s.some(i=>/^--(help|version|dry-run)$/.test(i)))return[];let r=t==="kafka-delete-records"?"(its one action)":s.find(i=>/^--(delete|delete-[a-z-]+|purge)$/.test(i));if(r)return[m("claude.bash.db.destructive",`${t} ${r} deletes from a live Kafka cluster`,{target:t,is_local:!1})];if(t==="kafka-leader-election")return[m("claude.bash.deploy","kafka-leader-election moves partition leaders on a live Kafka cluster",{target:t,is_local:!1})];let o=s.find(i=>/^--(create|alter|add|remove|execute|reset-offsets|reassign|elect|grant|revoke|expire|renew|cancel)$/.test(i));return o&&!(o==="--reset-offsets"&&!s.includes("--execute"))?[m("claude.bash.deploy",`${t} ${o} changes a live Kafka cluster`,{target:t,is_local:!1})]:t==="kafka-console-producer"?[m("claude.bash.external_write","kafka-console-producer writes messages to a topic",{target:t,is_local:!1})]:[]}var Ah=/^--?(?!no-|skip-|keep-|without-|dry-|preview-|show-|list-|exclude-|disable-|dont-|don-t-|prevent-|protect-|avoid-|never-)([a-z0-9]+-)*(purge|destroy|wipe|drop|nuke|erase|truncate|delete)(-(all|data|tables?|database|databases|db|volumes?|everything|existing|objects?|records?|rows?|keys?|files?|snapshots?|backups?|indexes|indices|schemas?|clusters?|namespaces?|buckets?|branch(es)?|resources?|old))?(=.*)?$/,Eh=new Set(["magick","convert","mogrify","montage","composite","gm"]);function Rh(e){let n=R.basename(e.name);if(!n||$o.has(n)||Eh.has(n)||e.functionCall||e.via==="substitution"||C(e.argv[0]??"")||So(e))return[];let t=e.argv.map(u=>v(u));if(t.some(u=>xo.test(u)))return[];let s="(what its own words say it does)",r=ec(t),o=Hs(n)?-1:r.findIndex(u=>u.split("-").includes("unsafe"));if(o>=0&&(r[o].includes("-")||r.length>o+1)&&!r.slice(o+1).some(u=>an.has(u)))return[m("claude.bash.db.destructive",`${n} runs a subcommand it calls unsafe (${r.slice(0,3).join(" ")}) ${s}`,{target:`${n} ${r.slice(0,3).join(" ")}`,is_local:!1})];if(Hs(n))return[];let a=t.slice(1).find((u,d)=>Ah.test(u)&&!/=(false|0|no|none|off|never)$/i.test(u)&&!/^(false|0|no|none|off|never)$/i.test(t[d+2]??""));if(a===void 0)return[];let l=/(purge|destroy|wipe|drop|nuke|erase|truncate|delete)/.exec(a)[1],c=["drop","truncate","purge","wipe"].includes(l)||r.flatMap(u=>[u,...u.split("-")]).some(u=>_o.has(u));return[m(c?"claude.bash.db.destructive":"claude.bash.deploy",`${n} is told to ${l} (${a.split("=")[0]}) ${s}`,{target:`${n} ${r.slice(0,2).join(" ")}`.trim(),is_local:!1})]}var io=new Set([...sn,"rollback","unpublish"]),Ds=new Set(["rm","remove","reset","revoke","uninstall"]),Oh=new Set(["cluster","clusters","kube","k8s","kubernetes","infra","infrastructure","eks","gke","aks"]),Ph=new Set(["kind","minikube","k3d","microk8s","local","dev","docker","compose"]),Yr=new Set(["drop","truncate","flushall","flushdb","teardown","deprovision","decommission"]),ao=new Set(["deploy","release","publish","promote","rollout","ship"]),nc=new Set(["create","add","set","update","put","attach","scale","enable","disable","rotate"]),Ps=new Set(["bucket","buckets","cluster","clusters","database","databases","db","namespace","namespaces","instance","instances","volume","volumes","service","services","function","functions","fn","lambda","addon","addons","lifecycle","environment","environments","domain","domains","zone","zones","record","records","dns","app","apps","deployment","deployments","queue","queues","topic","topics","stack","stacks","vpc","subnet","subnets","gateway","pool","pools","certificate","certificates","distribution","distributions","worker","workers","machine","machines","droplet","droplets","server","servers","site","sites","project","projects","table","tables","schema","schemas","identity","identities","layer","layers","kv","d1","r2","s3","broker","brokers","partition","partitions","replica","replicas","shard","shards","region","regions","store","stores","serverless","tablet","tablets"]),an=new Set(["plan","verify","check","validate","list","ls","status","diff","extract","describe","view","lint","test","tests","dry","dryrun","notes","changelog","preview","smoke","inspect","show","get","help","download","fetch","pull","template","render","history","logs","log","info","url","urls","open","browse","wait","watch","tail","search","find","explain"]),Co=new Set([...an,"doctor","whoami","version","completion","login","logout","install","init"]),sc=new Set(["test","tests","e2e","spec","specs","check","checks","verify","validate","lint","dry","plan","diff","preview","smoke","generate","gen","codegen","mock","mocks","fake","stub","example","examples","sample","docs","notes","changelog","build","watch","dev","local","list","ls","status","show","get","inspect","count","find","search","report","help","storybook","bench","benchmark","prepare","eval","evals","evaluate","scan","audit","probe","probes"]),jh=new Set(["detect","find","get","next","determine","should","is","has","needs","parse","extract","wait","print","read","info"]),Wh=new Set([...sc,"start","serve","bundle","compile","analyze","typecheck","format","copy","env","logs","log"]),Nh=new Set(["prod","production"]),Th=new Set(["fn","func","lambda","lambdas","addon","addons","identity","identities","layer","layers","relationship","relationships","lifecycle","data","migrate","migration","migrations","seed","seeds"]),qa=new Set([..._o,"data","migrate","migration","migrations","seed","seeds"]),Fs=new Set(["config","configure","configuration","context","profile","alias","completion","completions","auth","login","local"]),Ao=/^--?(app|project|project-?id|db|database|bucket|cluster|service|instance|env|environment|org|zone|branch|deployment|deployment-?id|identity|stack|namespace|site|([a-z][a-z0-9]*[-.])+(id|ids|name|arn|uri))(=|$)/,Lh=new Set(["ssh","scp","sftp","mosh","autossh","rsync","curl","wget","http","https","xh","git","nc","ncat","netcat","telnet","socat","xargs","env","sudo","doas","time","timeout","nohup","watch","nice","caffeinate","stdbuf","command","builtin","exec"]),nn=/\.(sh|bash|zsh|py|rb|js|mjs|cjs|ts|mts|cts|pl|ps1)$/,Ih=new Set(["dotenv","dotenvx","env-cmd","cross-env","with-env","mise","asdf","op","doppler","infisical","railway","kubectl","oc","uv","poetry","pipenv","direnv","nix","nix-shell","devbox","flox","aws-vault","sops","chamber","teller","envchain"]),Bs=/\$\{?[A-Za-z_]*(TOKEN|API_?KEY|SECRET|PAT|PASSWORD|CREDENTIALS?)[A-Za-z_]*\}?/,rc=new Set(["skill","skills","plugin","plugins","completion","completions","toolchain","toolchains","font","fonts","venv","virtualenv","shim","shims"]),oc=new Set([...Fs,...rc,"cache","caches","history","log","logs","tmp","temp","session-cache","settings","setting","shell","workspace-cache","extension","extensions","download","downloads"]),Dh=new Set(["repo","repos","remote","remotes","source","sources","registry","registries","tap","taps","channel","channels","index","indexes"]);function Ha(e){return e.argv.some(n=>{let t=v(n);return Bs.test(n)||Bs.test(t)||Ao.test(t)||/^[a-z][a-z0-9+.-]*:\/\//.test(t)&&!Re(t)})}var Fh=/\b(claude|anvil|mcp|codex|cursor|copilot|gemini|aider|settings|permissions?)\b/i,Ba=/(^|[-_.:/])(prod|production|live|mainnet)([-_.:/]|$)/i,Va=/^(\w+:\/\/)?([^@/\s]*@)?(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/\S*)?$/i;function zh(e){let n=e.text,t=[],s=a=>a===" "||a===" ",r=a=>a!==void 0&&(a>="A"&&a<="Z"||a>="a"&&a<="z"||a==="_"),o=a=>r(a)||a!==void 0&&a>="0"&&a<="9",i=0;for(;t.length<32;){for(;s(n[i]);)i++;let a=i;if(!r(n[a]))break;for(;o(n[a]);)a++;if(n[a]!=="=")break;let l=n.slice(i,a);a++;let c;if(n[a]==='"'||n[a]==="'"){let u=n.indexOf(n[a],a+1);if(u<0)break;c=n.slice(a+1,u),a=u+1}else{let u=a;for(;u<n.length&&!s(n[u])&&n[u]!==`
|
|
41
|
-
`;)u++;c=n.slice(a,u),a=u}if(a<n.length&&!s(n[a]))break;t.push([l,c]),i=a}return t}function Mh(e,n){let t=e.argv.map(_=>v(_)),s=_=>/^--?[a-z][\w-]*=/i.test(_)?_.slice(_.indexOf("=")+1):_;if(t.some(_=>xo.test(_)||/^--dry-?run=(true|1|yes|client|server|all)$/i.test(_)))return{strict:!0,ship:!0};if(t.some(_=>/^--(snapshot|skip-publish|no-publish|skip-push)$|^--skip=([\w,]*,)?(publish|push)\b/.test(_)))return{strict:!1,ship:!0};if(["make","gmake"].includes(R.basename(e.name))&&t.some(_=>/^-[a-zA-Z]*n[a-zA-Z]*$|^--(just-print|recon)$/.test(_)))return{strict:!0,ship:!0};let r=zh(e);if(t.slice(1).some(_=>Ba.test(s(_)))||r.some(([,_])=>Ba.test(_)))return{strict:!1,ship:!1};let o=_=>t.flatMap((k,P)=>_.test(k)?[t[P+1]??""]:/^--?[a-z][\w-]*=/i.test(k)&&_.test(k.slice(0,k.indexOf("=")))?[s(k)]:[]),i=t.findIndex((_,k)=>k>0&&!_.startsWith("-")),a=o(/^--?(db-url|database-url|url|host|registry|endpoint|server|api-url|connection|connection-string|dsn)$/i),l=r.some(([_,k])=>/(DATABASE|DB|POSTGRES|PG|MYSQL|MONGO|REDIS)_?(URL|URI|HOST)$/i.test(_)&&!Va.test(k)),c=r.some(([_,k])=>/^(NODE_ENV|APP_ENV|RAILS_ENV|RACK_ENV|MIX_ENV|FLASK_ENV|DJANGO_ENV|ENVIRONMENT|STAGE)$/.test(_)&&/^(test|testing|dev|development|local)$/i.test(k))&&!l;if(t.slice(1,i<0?void 0:i).includes("--local")||a.length>0&&a.every(_=>Va.test(_))||c)return{strict:!0,ship:!0};let d=o(/^--?(channel|track|deployment|network|net|chain)$/i),p=o(/^--?([\w-]+\.)?cluster$/i),h=t.some(_=>/^code-?push(-standalone)?$/.test(_))||/code-?push/.test(R.basename(e.name))?o(/^-d$/):[],g=[...d.map(_=>Za.test(_)),...p.map(_=>qh.test(_)),...h.map(_=>Za.test(_))],y=g.length>0&&g.every(Boolean),$=n.lineText.indexOf(e.text),E=R.basename(e.name);if(!y&&g.length===0&&$>0&&/^[a-z][a-z0-9_-]*$/.test(E)){let _=[...n.lineText.slice(0,$).matchAll(new RegExp(`\\b${E}\\s[^;&|]*\\b(?:config\\s+set|switch|use)\\b[^;&|]*\\s--?(?:url|u|env|network|cluster)[= ]([\\w:/.-]+)`,"g"))],k=_[_.length-1]?.[1];y=k!==void 0&&/^(devnet|testnet|localnet|localhost|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)$/.test(k)}return{strict:!1,ship:y}}var Uh=new Set(["sequelize","sequelize-cli","knex","typeorm","typeorm-ts-node-commonjs","typeorm-ts-node-esm","mix","artisan","php","rails","rake","alembic","flask","flyway","liquibase"]),Za=/^([\w-]+:)?(staging|stage|stg|dev|develop|development|test|testing|qa|uat|preview|sandbox|devnet|testnet|localnet|local|ci|sepolia|goerli|holesky|hoodi|mumbai|amoy|fuji|chiado|alfajores|shasta|nile)$/i,qh=/^([\w-]+:)?(devnet|testnet|localnet|sepolia|goerli|holesky|hoodi|mumbai|amoy|fuji|chiado|alfajores|shasta)$/i,Ga=/^--(publish|deploy|promote)(=true)?$/,Hh=new Set(["npx","pnpx","bunx"]),Bh=new Set(["--import","--require","-r","--loader","--experimental-loader","--env-file","--project","-P","--tsconfig","--inspect-port"]);function lo(e){return/s$/.test(e)?e:`a ${e}`}function st(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().split(/[-:_./]+/).filter(n=>/^[a-z][a-z0-9]*$/.test(n))}function Ka(e,n,t=!1){let s=[],r=n;for(;t&&r<e.length&&v(e[r]).startsWith("-")&&v(e[r])!=="--";){let i=v(e[r]);r+=!i.includes("=")&&r+1<e.length&&/[/.$~=]|^\d/.test(v(e[r+1]))&&!v(e[r+1]).startsWith("-")?2:1}for(let i=0;i<2&&r<e.length&&/^\$/.test(v(e[r]));i++)r++;for(;r<e.length&&s.length<6;r++){let i=v(e[r]);if(i==="--"||i.startsWith("-")||i.includes("://")||i.includes("@")||!/^[a-z][a-z0-9_.:/-]*$/.test(i)||i.includes("/")||/\.[a-z0-9]{1,5}(:[\d,-]+)?$/.test(i))break;let a=st(i);a.length>0&&s.push(a)}let o=0;for(;r<e.length;r++){let i=v(e[r]);if(i==="--")break;i.startsWith("-")||o++}return{groups:s,values:o}}function Vh(e){let n=e.argv.map(d=>v(d)),t=R.basename(e.name),s=[],r=[],o=(d,p)=>({...e,name:d,argv:[d,...p]}),i=(d,p)=>{let f=Ka(n,p),h=n.flatMap((g,y)=>y>=p&&/^--?(command|cmd|action|task|step|op|operation|job)$/.test(g)?[st(n[y+1]??"")]:/^--?(command|cmd|action|task|step|op|operation|job)=/.test(g)?[st(g.slice(g.indexOf("=")+1))]:[]).filter(g=>g.length>0);return{name:R.basename(d),groups:[st(R.basename(d).replace(/\.[^.]+$/,"")),...f.groups.slice(0,1),...h],values:f.values+Math.max(0,f.groups.length-1),script:!0}},a=d=>({name:d,groups:[st(d)],values:0,script:!0});if(n[0]?.includes("/")&&nn.test(n[0]))return{readings:[i(n[0],1)],nested:r};if((t==="."||t==="source")&&nn.test(n[1]??""))return{readings:[i(n[1],2)],nested:r};let l=n.indexOf("--");if(Ih.has(t)&&l>0&&/^[a-z][a-z0-9._-]*$/.test(n[l+1]??"")){let d=o(n[l+1],n.slice(l+2));(t==="kubectl"||t==="oc"||t==="railway")&&/^(exec|run)$/.test(w(n)[0]??"")&&Ys.add(d),r.push(d)}if(Uo.has(t)||t==="zsh"){for(let d=1;d<n.length;d++){let p=n[d];if(["-c","-e","--eval","-p","--print","-m"].includes(p))return{readings:s,nested:r};if(Bh.has(p)){d++;continue}if(!p.startsWith("-")){if(nn.test(p))return uu(t,n.slice(1,d))?{readings:s,nested:r}:{readings:[i(p,d+1)],nested:r};break}}if(t!=="bun")return{readings:s,nested:r}}let c=Hh.has(t)?1:["npm","pnpm","yarn","bun"].includes(t)&&["exec","dlx","x"].includes(n[1]??"")?2:-1;if(c>0){let d=c;for(;d<n.length&&n[d].startsWith("-");)d+=["-p","--package"].includes(n[d])?2:1;let p=(n[d]??"").replace(/^@[^/]+\//,"").replace(/@[^/]*$/,"");return/^[a-z][a-z0-9._-]*$/i.test(p)&&r.push(o(p,n.slice(d+1))),{readings:s,nested:r}}if(["npm","pnpm","yarn","bun"].includes(t)){let d=Pc(n),p=d[0]??"";if((p==="run"||p==="run-script")&&d[1])s.push(t==="bun"&&nn.test(d[1])?i(d[1],n.indexOf(d[1])+1):a(d[1])),t!=="npm"&&/^[a-z][a-z0-9._-]*$/.test(d[1])&&!nn.test(d[1])&&r.push(o(d[1],n.slice(n.indexOf(d[1])+1)));else if(p==="npm"&&t==="yarn")r.push(o("npm",n.slice(n.indexOf("npm")+1)));else{if(t==="pnpm"&&p==="deploy")return{readings:s,nested:r};t!=="npm"&&p&&!To.has(p)&&(s.push(a(p)),/^[a-z][a-z0-9._-]*$/.test(p)&&r.push(o(p,n.slice(n.indexOf(p)+1))))}let f=n.indexOf("--");return f>0&&/^[a-z][a-z0-9._-]*$/.test(n[f+1]??"")&&r.push(o(n[f+1],n.slice(f+2))),{readings:s,nested:r}}if(["nx","turbo","mise","make","just","task","lerna","run-s","run-p","npm-run-all"].includes(t)){let p=t==="mise"&&!["run","r","watch","w"].includes(n[1]??"")&&!/^(\/\/|:)/.test(n[1]??"")?[]:n.slice(1).filter((h,g,y)=>!h.startsWith("-")&&!h.includes("=")&&!h.startsWith("$")&&!["-C","-f","--file","-j","--projects","-p"].includes(y[g-1]??"")),f=n.flatMap((h,g)=>["-t","--target","--targets"].includes(h)?(n[g+1]??"").split(","):/^--targets?=/.test(h)?h.slice(h.indexOf("=")+1).split(","):[]);for(let h of[...p,...f])h&&h!=="run"&&h!=="run-many"&&h!=="affected"&&!["-t","--target","--targets"].includes(h)&&s.push(a(h));return{readings:s,nested:r}}if($o.has(t)||Lh.has(t)||!/^[a-z][a-z0-9._-]*$/.test(t)||/^\/[a-z-]+$/.test(n[0]??""))return{readings:s,nested:r};if(st(t).some(d=>Co.has(d)||["print","echo"].includes(d)))return{readings:s,nested:r};let u=Ka(n,1,!0);return s.push({name:t,groups:u.groups.slice(0,4),values:u.values+Math.max(0,u.groups.length-4),script:!1}),{readings:s,nested:r}}var Zh=ie({mix:["release","assets.deploy"]});function Gh(e,n){let t=e.groups.flat();if(t.length===0||!e.script&&Zh[e.name]?.includes(e.groups[0].join(".")))return null;let s=e.script?`runs ${e.name}`:`${e.name} ${e.groups.map(S=>S.join("-")).slice(0,4).join(" ")}`,r=e.script?"(read by its name)":"(read by its words)",o=e.script?e.name:s,i=n.argv.some(S=>Bs.test(S)||Bs.test(v(S))),a=i||n.argv.some(S=>Ao.test(v(S)));if(e.script&&(t.some(S=>sc.has(S))||jh.has(t[0]??"")))return null;if(e.script&&n.argv.some(S=>Ga.test(v(S))))return m("claude.bash.deploy",`${s}, told to ${n.argv.map(S=>v(S)).find(S=>Ga.test(S)).slice(2).replace(/=true$/,"")} ${r}`,{target:o,is_local:!1});if(!e.script){if(e.groups[0].length===1&&Co.has(t[0])&&!Vs.has(t[1]??""))return null;let S=t.findIndex(A=>Vs.has(A));if(S>=0&&!t.slice(0,S).some(A=>Fs.has(A))){if(t.some(A=>cc.has(A))&&oe(n))return m("claude.bash.secrets.print",`${s} prints ${lo(t[S])} ${r}`,{target:o,is_local:!0});if(t.some(A=>["create","lease","issue","generate","mint"].includes(A))&&oe(n))return m("claude.bash.secrets.print",`${s} makes a credential and prints it ${r}`,{target:o,is_local:!1});if(t.some(A=>["set","update","put","add","rotate","delete","remove","rm","unset","revoke","reset","reencrypt","rekey"].includes(A)))return m("claude.bash.deploy",`${s} changes a secret a service keeps ${r}`,{target:o,is_local:!1})}if(["post","put","patch"].includes(t[0]??"")&&n.argv.slice(2).some(A=>v(A).includes("/")))return m("claude.bash.external_write",`${e.name} ${t[0]} sends a write to its service's API ${r}`,{target:o,is_local:!1})}if(e.script&&t.includes("down")&&t.some(S=>Oh.has(S))&&!t.some(S=>Ph.has(S)))return m("claude.bash.deploy",`${s}: named to take down ${t.some(S=>S.startsWith("infra"))?"its infrastructure":"a cluster"} ${r}`,{target:o,is_local:!1});let l=-1;for(let S=0;S<t.length;S++){let A=t[S];(io.has(A)||Ds.has(A)||ao.has(A)||!e.script&&(nc.has(A)||A==="apply"||A==="push"))&&(l=S)}let c=e.script&&t.some(S=>Nh.has(S))&&!t.some(S=>Wh.has(S)||an.has(S)),u=n.argv.some(S=>["--force","-f","--yes","-y","--overwrite"].includes(v(S))||v(S)==="--force=true"),d=n.argv.some(S=>/\.(tar|tgz|tar\.gz|sql|dump|bak|gz|zip|bson|archive)$/i.test(v(S)));if(!e.script&&l<0&&u&&t.some(S=>["import","restore","load"].includes(S))&&(d||t.some(S=>qa.has(S)))&&!t.some(S=>an.has(S)))return m("claude.bash.db.destructive",`${s}: forced, over the data it holds ${r}`,{target:o,is_local:!1});if(l<0)return c?m("claude.bash.deploy",`${s}, named for production ${r}`,{target:o,is_local:!1,host:"production"}):null;let p=t[l];if(t.slice(l+1).some(S=>an.has(S)))return null;let f=S=>Ql.has(S)||Th.has(S),h=[...t.slice(0,l)].reverse().find(f)??t.slice(l+1).find(f)??t.find(f),g=t.some(S=>qa.has(S)),y=S=>/s$/.test(S)?S:`a ${S}`,$=e.groups.flatMap((S,A)=>S.map(()=>A))[l]??0,E=e.groups.length-1-$,_=n.argv.some((S,A)=>/^--?[a-z][\w-]*=./.test(v(S))||/^--?[a-z][\w-]*$/.test(v(S))&&/^[^-]/.test(v(n.argv[A+1]??"-")));if(io.has(p)||Ds.has(p)){if(!e.script&&t.slice(0,l).some(M=>Fs.has(M))||!e.script&&h===void 0&&t.length>1&&t.every((M,I)=>I===l||oc.has(M))||!e.script&&["remove","rm"].includes(p)&&t.slice(0,l).some(M=>Dh.has(M))&&!Ha(n))return null;let S;if(Ds.has(p)?S=h!==void 0||(e.script?Yr.has(p):!1):e.script?$>0?S=["nuke","wipe","purge","destroy","erase",...Yr].includes(p)||h!==void 0||e.values>0||_||i:S=Yr.has(p)||h!==void 0||p==="destroy"||["purge","wipe","nuke","erase"].includes(p)&&e.groups[0].length>1:S=h!==void 0||e.values>0||a||E>0||l>0&&sn.has(p),!S||h===void 0&&t.some(M=>rc.has(M))&&!Ha(n)&&!Fh.test(n.text))return null;let A=g||["drop","truncate","flushall","flushdb","purge","wipe"].includes(p)?"claude.bash.db.destructive":"claude.bash.deploy";return m(A,`${s}: ${e.script?`named to ${p}`:zs(p)} ${h?y(h):"what it names"} ${r}`,{target:o,is_local:!1})}if(ao.has(p))return["build","gen","generate","new","scaffold","init","template"].includes(t[l-1]??"")?null:m(p==="publish"?"claude.bash.publish":"claude.bash.deploy",`${s}: ${e.script?`named to ${p}`:zs(p)} ${r}`,{target:o,is_local:!1});if(p==="push"){if(n.argv.some(A=>["--force","-f","--yes","-y"].includes(v(A))))return m("claude.bash.deploy",`${s}: a forced push to its service ${r}`,{target:o,is_local:!1});let S=n.argv.map(A=>v(A)).find(A=>/^[a-z][a-z0-9+.-]*:\/\//.test(A)&&!Re(A));return S?m("claude.bash.publish",`${s}: pushes to ${S.split("/").slice(0,3).join("/")} ${r}`,{target:o,is_local:!1}):null}if(p==="apply")return m("claude.bash.deploy",`${s}: applies a configuration to its service ${r}`,{target:o,is_local:!1});if(t.slice(0,l).some(S=>Fs.has(S)))return null;let k=[...t.slice(0,l)].reverse().find(S=>Ps.has(S))??t.slice(l+1).find(S=>Ps.has(S))??(i?"a service it signs in to":void 0);if(k===void 0)return null;let P=Ps.has(k)?/\d/.test(k)||k.length<=2?`changes ${k.toUpperCase()}, a live service`:`${zs(p)} ${y(k)} on a live service`:k;return m("claude.bash.deploy",`${s}: ${Ps.has(k)?P:`changes something on ${k}`} ${r}`,{target:o,is_local:!1})}function ic(e,n,t){return[e,...t!==void 0&&t!==e?[t]:[]].map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).some(r=>new RegExp(`(^|[^>\\w./-])(>|\\btee\\s+)\\s*["']?${r}["']?(\\s|;|&|\\||$)`).test(n.lineText))&&/<<-?\s*['"]?\w+|\bprintf\b|\becho\b|\btee\b/.test(n.lineText)}function ac(e,n){let t=R.basename(n);return e.text.split(/\s+/).map(s=>s.replace(/^["']|["']$/g,"")).find(s=>s===n||s.endsWith(`/${t}`)||s===t)}function Kh(e,n,t){let s=n.argv.map(i=>v(i)).find(i=>R.basename(i)===e.name);if(s===void 0)return!1;let r=Y(s,n.cwd,te(t)).path??"",o=t.sessionId;return o!==null&&/^[\w-]{8,}$/.test(o)&&new RegExp(`^/(private/)?tmp/claude-\\d+/[^/]+/${o}/scratchpad/`).test(r)}function zs(e){return{rollback:"rolls back",rollout:"rolls out",teardown:"tears down",rm:"removes",push:"pushes",flushall:"flushes all of",flushdb:"flushes",set:"sets",put:"puts"}[e]??(/(sh|ch|s|x)$/.test(e)?`${e}es`:`${e}s`)}function Yh(e){let n=R.basename(e.name),t=e.argv.map(r=>v(r)),s=r=>[m("claude.agent.controls",`sends keystrokes into a terminal or another app (${r}), which can answer prompts meant for the person`,{target:r,is_local:!0})];return n==="tmux"&&t.some(r=>/^(send-keys|send|send-prefix|paste-buffer|pasteb)$/.test(r))?s("tmux send-keys"):n==="screen"&&t.some((r,o)=>r==="-X"&&/^(stuff|paste|readbuf)$/.test(t[o+1]??""))?s("screen -X stuff"):n==="osascript"&&t.some(r=>/\b(keystroke|key code|key down)\b/i.test(r))?s("osascript keystrokes"):["xdotool","ydotool","wtype","dotool"].includes(n)&&t.slice(1).some(r=>/^(type|key|keydown|keyup)$/.test(r)||n==="wtype")?s(n):n==="kitty"&&t.includes("@")&&t.some(r=>/^send-(text|key)$/.test(r))?s("kitty @ send-text"):n==="wezterm"&&t.includes("cli")&&t.includes("send-text")?s("wezterm cli send-text"):[]}var lc=new Set(["dokku","kamal","fly","flyctl","netlify","serverless","sls","caprover","cap","flux","argocd","eb","doctl","hcloud","linode-cli","scw","vultr-cli","civo","koyeb","okteto","porter","northflank","render","sst","amplify"]),Ya=new Set([...Co,"get","describe","logs","log","top","explain","versions","info","port","forward","proxy","wait","diff","events","kustomize","completion","options","print","docs","open","whoami","status","ls","list","show","current","help","version","doctor","details","audit","lint","validate","template","render","search","history","watch","tail","metrics","inspect","check","report","dashboard","export","can","login","logout","auth","context","contexts","use","switch","link","unlink","plugin","console","ssh","exec","shell","debugger","dev","build","test","package"]),Jh=new Set(["local","offline","mock"]),Xh=new Set(["api","resources","cluster","config","apps","domains","certs","volumes","ps","releases","storage","secrets","env","i"]),Qh=new Set([...io,...Ds,...ao,...nc,"apply","prune","import","fork","mount","unmount","clear","set","unset","restart","reboot","boot","stop","start","scale","invoke","run","rolling","reconcile","cordon","drain","taint","label","annotate","patch","replace","expose","autoscale","launch","reset","uninstall","upgrade","sync","suspend","resume","enable","disable","detach","attach","join","leave","rotate","renew","issue","revoke","promote","release","redeploy","restore","backup","move","rename","transfer","swap","bootstrap","extend","resize","allocate","clone"]),eg=new Set(["apply","create","delete","edit","patch","replace","scale","autoscale","label","annotate","taint","drain","cordon","uncordon","expose","run","debug","set","rollout","certificate","new-app","new-project","new-build","start-build","cancel-build","rollback","tag","import-image","policy","adm","idle"]),tg=new Set(["-n","--namespace","--context","--cluster","--kubeconfig","--user","-o","--output","-l","--selector","-a","--app","-c","--config","-r","--region","--org","-s","--stage","--profile","--token","--project","--server","-e","--env","--environment","--team","--site","-f","--filename","--function","-d","--destination","--field-selector","--tail","--since","--container","--host","-H","--as","--request-timeout"]);function Ja(e,n){let t=[];for(let s=1;s<e.length&&t.length<n;s++){let r=e[s];if(r==="--")break;if(r.startsWith("-")){!r.includes("=")&&tg.has(r)&&s++;continue}if(r.includes("://")||r.includes("@")||r.includes("/")||!/^[a-z][a-z0-9_.:-]*$/.test(r))break;t.push(r)}return t}function ng(e){let n=R.basename(e.name);if(n!=="docker"&&n!=="docker-compose"&&n!=="podman")return[];let t=e.argv.map(l=>v(l)),s=t.slice(1).filter((l,c,u)=>!l.startsWith("-")&&!["-f","--file","-p","--project-name","--context","-c","-H","--host","--env-file"].includes(u[c-1]??"")),r=n==="docker-compose"||s[0]==="compose",o=r&&n==="docker"?s.slice(1):s,i=o[0]??"",a=(l,c)=>[m(l,`${n} ${o.slice(0,2).join(" ")} ${c}`,{target:`${n} ${o.slice(0,2).join(" ")}`,is_local:!1})];return r?i==="down"&&t.some(l=>l==="-v"||l==="--volumes"||/^-[a-z]*v[a-z]*$/.test(l)&&l!=="-v"&&!l.startsWith("--"))?a("claude.bash.fs.delete_recursive","deletes the project's data volumes"):i==="publish"?a("claude.bash.publish","publishes the project to a registry"):[]:["service","stack","node","secret","config"].includes(i)&&["create","rm","remove","update","scale","deploy","rollback","promote","demote"].includes(o[1]??"")?a("claude.bash.deploy","changes a live swarm"):i==="swarm"&&["join","leave","init","update","unlock-key","ca"].includes(o[1]??"")?a("claude.bash.deploy","changes swarm membership"):i==="buildx"&&o[1]==="imagetools"&&o[2]==="create"&&!t.includes("--dry-run")?a("claude.bash.publish","pushes a manifest to a registry"):i==="trust"&&(["sign","revoke"].includes(o[1]??"")||o[1]==="signer"&&["add","remove"].includes(o[2]??""))?a("claude.bash.publish","changes who can sign images in a registry"):i==="scout"&&o[1]==="repo"&&["enable","disable"].includes(o[2]??"")?a("claude.bash.external_write","changes a registry setting"):[]}function sg(e,n){let t=R.basename(e.name);if(n.ship)return[];let s=e.argv.map(u=>v(u));if(t==="kubectl"||t==="oc"){let[u="",d=""]=Ja(s,2);if(!eg.has(u))return[];if(u==="run"&&bc(s))return[];if((u==="rollout"||u==="adm")&&Ya.has(st(d)[0]??""))return[];if(u==="certificate"&&!["approve","deny"].includes(d))return[];let p=["rollout","set","certificate","adm","create"].includes(u)&&d?`${t} ${u} ${d}`:`${t} ${u}`;return[m("claude.bash.deploy",`${p} changes a live cluster`,{target:p,is_local:!1})]}if(!lc.has(t))return[];let r=Ja(s,3).filter(u=>!/^\d/.test(u)),o=r.flatMap(u=>st(u));if(o.length===0||o.some(u=>Jh.has(u)))return[];if(o.find(u=>["deploy","create","issue","mint","add","generate"].includes(u))!==void 0&&o.some(u=>/^(tokens?|keys?|credentials?)$/.test(u))){let u=`${t} ${r.slice(0,2).join(" ")}`;return[oe(e)?m("claude.bash.secrets.print",`${u} makes a credential and prints it`,{target:u,is_local:!1}):m("claude.bash.deploy",`${u} makes a credential for a live account`,{target:u,is_local:!1})]}if(o.includes("secrets")&&o.some(u=>["extract","print","fetch","get","show"].includes(u)))return oe(e)?[m("claude.bash.secrets.print",`${t} ${r.slice(0,2).join(" ")} prints a secret`,{target:`${t} ${r.slice(0,2).join(" ")}`,is_local:!0})]:[];if(t!=="dokku"&&o.some(u=>u==="plugin"||u==="plugins"))return[];let a=o.find(u=>Qh.has(u));if(a===void 0&&o.some(u=>Ya.has(u)))return[];if(a===void 0&&o.every(u=>Xh.has(u)))return[];if(a!==void 0&&an.has(o[o.indexOf(a)+1]??""))return[];let l=a!==void 0?r.findIndex(u=>st(u).includes(a)):0,c=`${t} ${r.slice(0,Math.max(l,0)+1).join(" ")}`;return[m("claude.bash.deploy",a!==void 0?`${c} changes a live deployment`:`${c} is not a read, and ${t} works on live deployments`,{target:c,is_local:!1})]}function rg(e,n){let t=e.argv.map(c=>v(c)).find((c,u)=>u<=3&&nn.test(c));if(t!==void 0){let c=Y(t,e.cwd,te(n)).path;if(c&&n.lineMade.includes(c)&&ic(t,n,ac(e,t)))return[]}if(e.functionCall||C(e.argv[0]??""))return[];if(So(e))return[];let s=e.argv.slice(1).map(c=>v(c)).find(c=>!c.startsWith("-")&&!/^[A-Za-z_]\w*=/.test(c))??"";if(Uh.has(R.basename(e.name))&&(/^(db|migrate|migration|migrations|seed|schema|ecto)([:.]|$)/i.test(s)||["manage.py","artisan"].includes(R.basename(s))))return[];let r=Mh(e,n);if(r.strict)return[];let o=ng(e);if(o.length>0)return o;let i=sg(e,r);if(i.length>0)return i;let{readings:a,nested:l}=Vh(e);for(let c of a){if(c.script&&Kh(c,e,n))continue;let u=Gh(c,e);if(!(u&&r.ship&&(u.action==="claude.bash.publish"||/: (named to )?(deploy|release|publish|promote|rollout|ship)/.test(u.why)))&&u)return[u]}for(let c of l){if(c.argv.length>=e.argv.length&&c.name===e.name)continue;let u=Zn(c,n);if(u.length>0)return u.map(d=>({...d,why:`${d.why} (run by ${R.basename(e.name)})`}))}return[]}var Vs=new Set(["secret","secrets","token","tokens","credential","credentials","password","passwords","apikey","api-key","api_key","apikeys","api-keys"]),cc=new Set(["get","show","reveal","print","read","view","cat","dump","export","decrypt","download","value","access"]),Eo=/(^|\/)\*\.(egg-info|pyc|pyo|log|tmp|o|class|orig|rej|bak|swp|tsbuildinfo)$|(^|\/)\*~$/,uc=/^(node_modules|dist|build|out|\.next|coverage|__pycache__|\.pytest_cache|\.mypy_cache|\.ruff_cache|\.cache|\.turbo|\.DS_Store|target|\.tox|\.venv|venv|[\w.-]*\.tsbuildinfo|\*\.(egg-info|pyc|pyo|log|tmp|o|class|orig|rej|bak|swp|tsbuildinfo))$/;function Ro(e,n){let t=e.argv.slice(1),s=e.name==="rimraf",r=!1,o=[],i=new Map;for(let[d,p]of t.entries()){if(!r&&p==="--"){r=!0;continue}if(!r&&p.startsWith("--")){p==="--recursive"&&(s=!0);continue}if(!r&&/^-[A-Za-z]+$/.test(p)){/[rR]/.test(p)&&(s=!0);continue}e.via==="find-exec"&&p==="{}"||(o.push(p),i.set(p,d+1))}e.via==="xargs"&&e.pipeFrom&&o.push(...ag(e.pipeFrom,n));let a=new Map;for(let d of o){let p=Un(d),f=fc(d,e,i.get(d)).flatMap(Un);for(let h of p)a.set(h,f)}if(o.splice(0,o.length,...o.flatMap(Un)),o.length===0)return[];let l=o.find(d=>ig(Ie(d,e,n),e,n));if(l!==void 0)return[m("claude.bash.fs.delete_recursive",`${e.name==="shred"?"shreds":"deletes"} a key or credentials file (${v(l)})`,{target:v(l),is_local:e.remote===null,host:e.remote})];let c=d=>d==="*"||d===".*"||d.endsWith("/*")||d.endsWith("/.*");if(!s&&!o.some(c))return[];let u=o.map(d=>{if(Eo.test(d))return{kind:"disposable",path:d,token:null,why:"build or cache artifacts"};let p=Ie(d,e,n),f=h=>c(h)?h==="*"||h===".*"?"./":`${h.replace(/\/\.?\*$/,"")}/`:h;return qe(f(p),e,n,(a.get(d)??[]).map(h=>f(Ie(h,e,n))))});return[_t(u,e)]}var og=/^\.(ssh\/(?!known_hosts(\.old)?$|config$)[^/]+|gnupg\/.+|aws\/(credentials|config)|kube\/config|docker\/config\.json|config\/gcloud\/.+|azure\/.+|netrc|git-credentials|npmrc|pypirc)$/;function ig(e,n,t){let s=U(e,n.cwd,t.ctx);if(C(s))return!1;let r=t.ctx.home.replace(/(?<!\/)\/+$/,""),o=s.startsWith(`${r}/`)?s.slice(r.length+1):null;if(o!==null&&og.test(o))return!0;if(!ye(s)||Y(s,null,te(t)).kind==="disposable")return!1;let i=t.projectRoot;return!(i&&!C(i)&&(s===i||s.startsWith(`${i}/`)))}var Xa=64;function Un(e){let n=[],t=!1,s=r=>{if(n.length>=Xa){t=!0;return}let o=/^(.*?)\{([^{}]*,[^{}]*)\}(.*)$/s.exec(r);if(!o){n.push(r);return}for(let i of o[2].split(","))s(`${o[1]}${i}${o[3]}`)};return s(e),t?[...n.slice(0,Xa-1),`${ae}(more words from a brace expansion)${le}`]:n}function dc(e,n){let t=e.argv.slice(1);if(!t.some(i=>i==="--del"||i.startsWith("--delete")||i==="--remove-source-files"))return[];if(t.some(i=>i==="-n"||i==="--dry-run"||/^-[a-zA-Z]*n[a-zA-Z]*$/.test(i)))return[];let s=t.filter(i=>!i.startsWith("-")),r=s[s.length-1];if(!r||s.length<2)return[];if(/^[^/]*:/.test(r)&&!r.startsWith("/")&&!(H()&&/^[A-Za-z]:(?:[\\/]|$)/.test(r)))return[m("claude.bash.fs.delete_recursive",`rsync --delete removes files on ${r.split(":")[0]}`,{target:r,host:r.split(":")[0]??null,is_local:!1})];let o=qe(r,e,n);return[{..._t([o],e),why:`rsync --delete into ${o.why}`}]}function ag(e,n){if(e.name==="echo"||e.name==="printf")return e.argv.slice(1).filter(t=>!t.startsWith("-")||t==="-");if(e.name==="find"){let t=pc(e);return t.disposableFilter?["/tmp/__find_matches_disposable__"]:t.roots}return[`${ae}(paths from ${e.name})${le}`]}function _t(e,n){let t={catastrophic:2,normal:1,disposable:0},s=[...e].sort((o,i)=>t[i.kind]-t[o.kind])[0],r=n.remote!==null;return s.kind==="disposable"&&!r?m("claude.bash.fs.delete_disposable",`deletes ${e.length>1?"temp, build or scratch paths":s.why}`,{target:s.path,is_local:!0}):m("claude.bash.fs.delete_recursive",`deletes ${s.why}${r?` on ${n.remote}`:""}`,{target:s.path,service:s.kind==="catastrophic"&&!r?s.token:null,is_local:!r,host:n.remote})}function qe(e,n,t,s=fc(e,n)){let r=Ie(e,n,t),o=Y(r,n.cwd,te(t));if(o.kind==="catastrophic")return o;for(let i of n.cwdFallbacks){let a=Y(r,i,te(t));if(a.kind==="catastrophic")return{...a,why:`${a.why} if the cd before it failed`}}for(let i of s){if(i===""||i===e)continue;let a=Y(Ie(i,n,t),n.cwd,te(t)),l=n.cwdFallbacks.some(c=>c!==null&&(i===c||i.startsWith(`${c}/`)));if(a.kind==="catastrophic")return{...a,why:`${a.why} ${l?"if the cd before it failed":"if an assignment before it did not run"}`}}return o}function fc(e,n,t){let s=t??n.argv.indexOf(e);return n.altArgvs.flatMap(r=>r.length===n.argv.length&&s>=0?[r[s]]:r.slice(1))}function te(e){return{home:e.ctx.home,tmpdir:e.ctx.tmpdir,projectRoot:e.projectRoot,base:e.base,onDisk:e.ctx.onDisk??null,made:e.ctx.session?.made??null,ignored:n=>Gl(n,e)}}function ln(e,n,t=e.base){let s=e.ctx.onDisk,r=C(n)&&!n.startsWith("/")&&!n.startsWith(ae)&&t!==null&&t.startsWith("/")&&!C(t)?R.join(t,n):n;C(r)?s?.unknown?.add(r):r.startsWith("/")&&s?.written?.add(r)}function Dt(e,n){let t=e.ctx.onDisk;if(!t?.touched||!t.read)return n();let s=new Set([...t.touched.full,...t.touched.parent]),r=n();for(let o of[...t.touched.full,...t.touched.parent])s.has(o)||t.read.add(o);return r}var lg=new Set(["go","cargo","docker","podman","gradle","gradlew","mvn","mvnw","deno","poetry","uv","pipenv","dotnet","swift","flutter","dart","mix","npx","bunx","pnpx"]),cg=new Set(["npm","pnpm","yarn","bun"]),ug=new Set(["make","gmake","just","task","rake","mage"]);function dg(e){let n=pe(e.name),t=e.argv.slice(1).filter(r=>!r.startsWith("-")),s=r=>/^[\w:@+-]+$/.test(r);return ug.has(n)?new Set(t.filter(s)):cg.has(n)?new Set((["run","run-script"].includes(t[0]??"")?t.slice(0,2):t.slice(0,1)).filter(s)):lg.has(n)?new Set(t.slice(0,1).filter(s)):new Set}function Zs(e,n,t){return ln(t,U(Ie(e,n,t),n.cwd??t.base??t.projectRoot,t.ctx)),qe(e,n,t)}var Qa=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-regex","-iregex","-empty","-mtime","-mmin","-atime","-amin","-ctime","-cmin","-newer","-anewer","-cnewer","-size","-user","-group","-perm","-links","-inum","-samefile","-nouser","-nogroup"]);function fg(e){let n=[[]];for(let i of e)i==="-o"||i==="-or"||i===","?n.push([]):n[n.length-1].push(i);let t=[],s=!1,r=!0,o=!0;for(let i of n){let a=!1,l=!1;for(let c=0;c<i.length;c++){let u=i[c];if(u==="!"||u==="-not"){(i[c+1]==="("||i[c+1]==="\\(")&&(s=!0),c+=Qa.has(i[c+1]??"")||["-type","-maxdepth","-mindepth"].includes(i[c+1]??"")?2:1;continue}Qa.has(u)&&(a=!0,["-name","-iname","-path","-ipath","-wholename"].includes(u)&&i[c+1]!==void 0&&(t.push(i[c+1]),l=!0))}a||(r=!1,i.some(c=>c==="!"||c==="-not")&&(s=!0)),l||(o=!1)}return n.length>1&&!r&&(s=!0),{names:t,narrows:r&&!s,everyBranchNamed:o,invertible:s}}function pc(e){let n=e.argv.slice(1),t=[],s=0;for(;s<n.length&&!/^[-(!]/.test(n[s]);)t.push(n[s++]);t.length===0&&t.push(".");let r=!1;for(let g=s;g<n.length;g++){let y=n[g];y==="-delete"&&(r=!0),["-exec","-execdir","-ok","-okdir"].includes(y)&&["rm","unlink","shred","rmdir"].includes(pe(n[g+1]??""))&&(r=!0)}let o=n.slice(s),i=fg(o),a=i.names,l=a.length>0&&a.every(g=>uc.test(R.basename(g.replace(/\/$/,"")))||Eo.test(g))&&!i.invertible&&i.everyBranchNamed,c=i.invertible,u=i.narrows,d=u&&o.includes("-empty"),p=o.some((g,y)=>g==="-type"&&o[y+1]==="d"),f=g=>/[*?[]/.test(g),h=u?d?p?"empty folders":"empty files and folders":a.length>0?`${a.every(g=>!f(g))?(a.length===1,"every file named"):"the files matching"} ${a.slice(0,3).join(", ")}${a.length>3?", \u2026":""}`:"the files its filters match":null;return{roots:t,deletes:r,disposableFilter:l,narrowed:h,emptyOnly:d,filesOnly:!u&&o.some((g,y)=>g==="-type"&&o[y+1]==="f"),invertible:c}}function pg(e,n){let t=pc(e);if(!t.deletes)return[];let s=t.roots.map(l=>Zs(l,e,n)),r=s.find(l=>l.token==="fs.root"||l.token==="fs.home"||l.token==="fs.system");if(t.disposableFilter&&r)return[m("claude.bash.fs.delete_recursive",`find deletes matching files under ${r.path}`,{target:t.roots.join(" "),is_local:!0})];if(t.disposableFilter)return[m("claude.bash.fs.delete_disposable","find deletes build or cache artifacts",{target:t.roots.join(" "),is_local:!0})];let o=r??s.find(l=>l.kind==="catastrophic")??s.find(l=>l.kind==="normal")??s[0],i=o.token==="fs.home"&&o.path===n.ctx.home.replace(/(?<!\/)\/+$/,"")?"your home folder":o.token==="fs.project_root"?"the project":o.token==="fs.root"?"the whole disk":v(o.path);if(t.narrowed!==null){let l=`find deletes ${t.narrowed} under ${i}`;return t.emptyOnly&&!r?[m("claude.bash.fs.delete_disposable",l,{target:t.roots.join(" "),is_local:!0})]:s.every(c=>c.kind==="disposable")?[m("claude.bash.fs.delete_disposable",l,{target:t.roots.join(" "),is_local:!0})]:[m("claude.bash.fs.delete_recursive",l,{target:t.roots.join(" "),is_local:!0})]}let a=_t(s,e);return a.action==="claude.bash.fs.delete_recursive"&&t.filesOnly?[{...a,why:`find deletes every file under ${i}`}]:a.action==="claude.bash.fs.delete_recursive"&&t.invertible?[{...a,why:`find deletes everything under ${i} except what its filter keeps`}]:[a]}var hg=new Set(["-t","--type","-e","--extension","-d","--max-depth","--min-depth","--exact-depth","-E","--exclude","-S","--size","--changed-within","--changed-before","-o","--owner","-j","--threads","--path-separator","-c","--color","--ignore-file","--max-results","--batch-size"]);function gg(e,n){let t=e.argv.slice(1),s=t.findIndex(g=>["-x","--exec","-X","--exec-batch"].includes(g));if(s<0||!["rm","unlink","shred","rmdir"].includes(pe(t[s+1]??"")))return[];if(pe(t[s+1]??"")==="rmdir")return[];let r=t.slice(0,s).flatMap((g,y)=>g==="-t"||g==="--type"?[t[y+1]??""]:/^-t./.test(g)?[g.slice(2)]:g.startsWith("--type=")?[g.slice(7)]:[]);if(r.some(g=>g==="e"||g==="empty"))return[m("claude.bash.fs.delete_disposable","fd deletes empty files or folders",{target:".",is_local:!0})];let o=[],i=[],a=[],l=!1;for(let g=0;g<s;g++){let y=t[g];y==="--search-path"||y==="--base-directory"?(t[g+1]!==void 0&&i.push(t[g+1]),g++):y==="-e"||y==="--extension"?(t[g+1]!==void 0&&a.push(`*.${t[g+1].replace(/^\./,"")}`),g++):y.startsWith("--extension=")?a.push(`*.${y.slice(12).replace(/^\./,"")}`):y==="-g"||y==="--glob"?l=!0:y.startsWith("-")?hg.has(y)&&g++:o.push(y)}let c=o[0]??"";if(c!==""&&c!=="."&&c!=="^"){let g=/^\\?\.([\w-]+)\$$/.exec(c);a.push(l?c:g?`*.${g[1]}`:c.replace(/^\^|\$$/g,"").replace(/\\(.)/g,"$1"))}let u=[...o.slice(1),...i];u.length===0&&u.push(".");let d=u.map(g=>Zs(g,e,n)),p=d.find(g=>g.token==="fs.root"||g.token==="fs.home"||g.token==="fs.system"),f=a.length>0&&a.every(g=>uc.test(R.basename(g))||Eo.test(g));return f&&p?[m("claude.bash.fs.delete_recursive",`fd deletes matching files under ${p.path}`,{target:u.join(" "),is_local:!0})]:f?[m("claude.bash.fs.delete_disposable","fd deletes build or cache artifacts",{target:u.join(" "),is_local:!0})]:a.length>0||r.length>0||t.slice(0,s).some(g=>/^(-S|--size|--changed-(within|before)|--newer|--older)(=|$)/.test(g))?[m("claude.bash.fs.delete_recursive",`fd deletes the files matching ${a.join(", ")||"its filters"} under ${u.join(" ")}`,{target:u.join(" "),is_local:!0})]:[_t(d,e)]}function el(e,n){let t=e.argv.slice(1);if(e.name==="dd"){let s=t.find(o=>o.startsWith("of="))?.slice(3);if(!s)return[];let r=qe(s,e,n);return r.token==="fs.device"?[m("claude.bash.fs.delete_recursive",`overwrites a raw disk (${s})`,{target:s,service:"fs.device",is_local:!0})]:du.test(s)&&r.kind!=="disposable"?[m("claude.bash.fs.delete_recursive",`dd overwrites a data file (${R.basename(s)})`,{target:r.path,is_local:!0})]:[]}return e.name==="diskutil"?t.some(s=>/^(erase|zeroDisk|randomDisk|secureErase|partitionDisk|reformat)/i.test(s))?[m("claude.bash.fs.delete_recursive","erases a disk",{target:t.join(" "),service:"fs.device",is_local:!0})]:[]:[m("claude.bash.fs.delete_recursive",`formats or repartitions a disk (${e.name})`,{target:t.join(" "),service:"fs.device",is_local:!0})]}function xt(e){let n=e.argv,t=1,s=null;for(;t<n.length;){let o=n[t];if(o==="-C"&&n[t+1])s=n[t+1],t+=2;else if(o==="-c"||o==="--git-dir"||o==="--work-tree"||o==="--namespace")o==="--work-tree"&&n[t+1]&&(s=n[t+1]),t+=2;else if(o.startsWith("--work-tree="))s=o.slice(12),t++;else if(o.startsWith("-"))t++;else break}let r=n[t];return r?{sub:r,args:n.slice(t+1),dir:s}:null}function hc(e,n){return e.cwdFallbacks.length>0||e.altArgvs.length>0||/\bgit\s+(?:-[cC]\s+\S+\s+|--?[\w-]+=\S+\s+|-(?![cC]\s)[\w-]+\s+)*(?:remote\s+(?:add|set-url|rename|remove|rm|set-head|set-branches)\b|config\s+(?!--get|--list|-l\b)|clone\b|init\b|submodule\b)|\bgh\s+repo\s+(?:clone|set-default|create|fork)\b|\b(?:HOME|XDG_CONFIG_HOME)=|\bGIT_(?:CONFIG|DIR|WORK_TREE|COMMON_DIR)|--git-dir|--work-tree/.test(n)}function Ft(e,n,t){if(/\bGIT_(DIR|WORK_TREE|COMMON_DIR)\b|--git-dir/.test(t.lineText)||e.wrappers.includes("env")&&e.wrapperArgs.some(r=>/^-C/.test(r)||r.startsWith("--chdir")))return null;let s=n.dir?yc(n.dir,e,t):e.cwd;return s===null||C(s)?null:s}function mg(e,n,t){let s=e[n];if(!/^-[a-zA-Z]/.test(s))return null;for(let r=1;r<s.length;r++)if(t.includes(s[r]))return{letter:s[r],value:s.slice(r+1)||e[n+1]};return null}function gc(e,n){let[t,s,r]=n==="switch"?["c","C","--create"]:["b","B",""],o=[];for(let i=0;i<e.length;i++){let a=e[i];if(a==="--")break;if(a==="--force-create"&&e[i+1])o.push({letter:s,branch:e[++i]});else if(a.startsWith("--force-create="))o.push({letter:s,branch:a.slice(15)});else if(r&&a===r&&e[i+1])o.push({letter:t,branch:e[++i]});else if(r&&a.startsWith(`${r}=`))o.push({letter:t,branch:a.slice(r.length+1)});else{let l=mg(e,i,t+s);l&&l.value!==void 0&&(o.push({letter:l.letter,branch:l.value}),l.value===e[i+1]&&i++)}}return o}function yg(e,n){return gc(e,n).at(-1)??null}function bg(e,n){if(e.name!=="git")return;let t=xt(e);if(!t)return;let s=t.dir??e.cwd;if(t.sub==="stash"){let r=t.args[0];(r===void 0||r==="push"||r==="save"||r.startsWith("-"))&&(n.stashCreated=!0,n.stashPushes++),r==="apply"&&n.stashApplied.add(co(t.args.slice(1)))}if(t.sub==="worktree"&&t.args[0]==="add"){let r=t.args.lastIndexOf("-b");r>=0&&t.args[r+1]&&n.createdBranches.set(t.args[r+1],{by:En(e),repo:Ft(e,t,n)})}if(t.sub==="checkout"||t.sub==="switch"){if(t.args.includes("--"))return;let r=yg(t.args,t.sub);if(r){n.branch=r.branch,n.branchDir=s,(r.letter==="b"||r.letter==="c")&&n.createdBranches.set(n.branch,{by:En(e),repo:Ft(e,t,n)});return}let o=t.args.find(i=>!i.startsWith("-"));o&&!o.includes("/")&&o!=="."&&!C(o)&&(n.branch=o,n.branchDir=s)}}function wg(e,n){return n===e.branchDir?e.branch:null}function Oo(e){return e!==null&&/\/scratchpad(\/|$)/.test(e)}function kt(e,n){return e===null?!1:Oo(e)?!0:Y(e,null,te(n)).kind==="disposable"}function tl(e,n,t,s){let r=n!==null&&!C(n)?n.replace(/(?<!\/)\/+$/,""):null,i=(t.ctx.projectControls??[]).filter(l=>typeof l=="object"&&l!==null&&typeof l.path=="string").filter(l=>(r===null||l.path.startsWith(`${r}/`))&&(l.staged===!0?s.staged:l.ignored===!0?s.ignored:s.untracked)).map(l=>l.path);if(i.length===0)return[];let a=v(i[0]);return[m("claude.agent.controls",`${e} takes this project's own ${R.basename(a)} away, so later sessions here run without it`,{target:a,is_local:!0})]}function mc(e,n){let t=xt(e);if(!t)return[];let s=t.dir?yc(t.dir,e,n):e.cwd,r=a=>t.args.some(l=>a.includes(l)),o=a=>t.args.some(l=>/^-[a-zA-Z]+$/.test(l)&&l.includes(a)),i=t.sub.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();if(/(^|-)(delete|del|remove|rm|prune|purge|drop|nuke|wipe|clean|cleanup)(-|$)/.test(i)&&/(^|-)(branch|branches|tag|tags|gone|merged|stale|worktree|worktrees)(-|$)/.test(i))return[m("claude.bash.git.discard",`git ${t.sub}: a command named for deleting branches or tags (an alias or extension)`,{target:[t.sub,...t.args.filter(a=>!a.startsWith("-"))].join(" "),is_local:!0})];switch(t.sub){case"push":{let a=hc(e,n.lineText)||e.argv.filter(l=>l==="-C").length>1||e.argv.some(l=>/^(-c|--config-env)/.test(l))?null:Ft(e,t,n);return kg(t.args,n,e,wg(n,t.dir??e.cwd),a)}case"reset":return r(["--hard"])&&!Oo(s)?[m("claude.bash.git.discard","git reset --hard discards uncommitted work",{target:t.args.find(a=>!a.startsWith("-"))??"HEAD",branch:n.branch,is_local:!0})]:[];case"checkout":{let a=t.args.indexOf("--"),l=a>=0?t.args.slice(a+1):t.args.filter(u=>!u.startsWith("-"));return(l.some(u=>u==="."||u==="./"||u===":/"||u==="*"||u===":(top)")||r(["-f","--force"]))&&!kt(s,n)?[m("claude.bash.git.discard","git checkout discards every uncommitted change",{target:l.join(" ")||".",branch:n.branch,is_local:!0})]:nl(t.args,"checkout",e,n)}case"rm":{let a=t.args.filter(c=>!c.startsWith("-"));return a.some(c=>c==="."||c==="./"||c==="./*"||c===":/"||c==="*"||c===":(top)")&&(r(["-f","--force"])||o("f"))&&!r(["--cached","-n","--dry-run"])&&!o("n")&&!kt(s,n)?[m("claude.bash.git.discard","git rm -f deletes every tracked file, uncommitted changes too",{target:a.join(" "),branch:n.branch,is_local:!0})]:[]}case"restore":{if((r(["--staged"])||o("S"))&&!r(["--worktree"])&&!o("W"))return[];let a=t.args.filter(l=>!l.startsWith("-"));return a.some(l=>l==="."||l==="./"||l===":/"||l==="*")&&!kt(s,n)?[m("claude.bash.git.discard","git restore discards every uncommitted change",{target:a.join(" "),branch:n.branch,is_local:!0})]:[]}case"branch":{let a=t.args.filter(f=>!f.startsWith("-")),l=r(["-f","--force"])||o("f"),c=r(["-d","--delete","-D"])||t.args.some(f=>/^-[a-zA-Z]*[dD]/.test(f)&&/^-[a-zA-Z]+$/.test(f)),u=c&&(r(["-D"])||t.args.some(f=>/^-[a-zA-Z]*D/.test(f))||l);if(u&&a.length>0&&a.every(f=>zn(f,e,n)||Hp(f,Ft(e,t,n),n)))return[];if(u)return[m("claude.bash.git.discard","git branch force-deletes a branch",{target:a.join(" "),is_local:!0})];let d=f=>t.args.some(h=>/^-[a-zA-Z]{2,}$/.test(h)&&f.test(h.slice(1))),p=r(["-m","--move","-c","--copy"])||d(/[mc]/);return r(["-M","-C"])||d(/[MC]/)||l&&p?[m("claude.bash.git.discard","git branch -M / -C overwrites a branch",{target:a.join(" "),is_local:!0})]:l&&!c&&a[0]!==void 0&&!zn(a[0],e,n)?[m("claude.bash.git.discard",`git branch -f moves ${a[0]}`,{target:a.join(" "),branch:a[0],is_local:!0})]:[]}case"stash":{if(t.args[0]==="drop"){let u=co(t.args.slice(1));if(n.stashApplied.has(u))return[];if(u.startsWith("computed:")&&n.stashCreated&&n.stashApplied.size>0)return[]}if((t.args[0]==="drop"||t.args[0]==="clear")&&qp(co(t.args.slice(1)),t.args[0]==="clear",Ft(e,t,n),n,e))return[];if(t.args[0]==="drop"||t.args[0]==="clear")return[m("claude.bash.git.discard",`git stash ${t.args[0]} deletes stashed work`,{target:t.args.slice(1).join(" ")||"stash",is_local:!0})];let a=t.args.length===0||["push","save"].includes(t.args[0])||t.args[0].startsWith("-"),l=r(["--all"])||o("a"),c=/\bgit\s+add\s+(?:[^;&|\n]*\s)?(-A|--all|\.)(\s|$)/.test(n.lineText.slice(0,65536));return a?tl("git stash",null,n,{untracked:l||c||r(["--include-untracked"])||o("u"),ignored:l,staged:!0}):[]}case"clean":{if(r(["--dry-run"])||o("n"))return[];if(!(r(["--force"])||o("f"))||kt(s,n))return[];let a={untracked:!o("X"),ignored:o("x")||o("X"),staged:!1},l=s??e.cwd;return[m("claude.bash.git.discard","git clean -f deletes untracked files",{target:s??".",is_local:!0,housekeeping:l!==null&&n.lineMade.some(c=>on(c,l))}),...tl("git clean -f",s,n,a)]}case"reflog":return t.args[0]==="delete"||t.args[0]==="expire"&&t.args.some(a=>/^--expire=(now|all|0)/.test(a)||a==="--all")?[m("claude.bash.git.discard",`git reflog ${t.args[0]} removes the record of lost commits`,{is_local:!0})]:[];case"gc":return t.args.some(a=>a==="--prune=now"||a==="--prune=all")?[m("claude.bash.git.discard","git gc --prune=now makes lost commits unrecoverable",{is_local:!0})]:[];case"filter-branch":case"filter-repo":return[m("claude.bash.git.discard",`git ${t.sub} rewrites history`,{is_local:!0})];case"symbolic-ref":{let a=t.args.filter(l=>!l.startsWith("-"));return!r(["-d","--delete"])&&a.length>=2&&a[0]!=="HEAD"?[m("claude.bash.git.discard",`git symbolic-ref points ${a[0]} at ${a[1]}`,{target:a[0],is_local:!0})]:[]}case"update-ref":{if(r(["-d"]))return[m("claude.bash.git.discard","git update-ref -d deletes a ref",{target:t.args.find(l=>!l.startsWith("-"))??null,is_local:!0})];let a=t.args.filter((l,c)=>!l.startsWith("-")&&t.args[c-1]!=="-m")[0]??"";return r(["--stdin"])||a.startsWith("refs/heads/")&&!zn(a.slice(11),e,n)?[m("claude.bash.git.discard",`git update-ref moves ${a||"refs from stdin"}`,{target:a||"stdin",is_local:!0})]:[]}case"worktree":if(t.args[0]==="add"){let a=t.args.findIndex(c=>c==="-B"),l=a>0?t.args[a+1]:void 0;if(l!==void 0&&!zn(l,e,n))return[m("claude.bash.git.discard",`git worktree add -B resets ${l}`,{target:l,branch:l,is_local:!0})]}if(t.args[0]==="remove"&&(r(["--force"])||o("f"))){let a=t.args.slice(1).find(u=>!u.startsWith("-"))??"",l=t.dir&&!C(t.dir)?Y(t.dir,e.cwd,te(n)).path??e.cwd:e.cwd,c=Y(a,l,te(n));return kt(c.path,n)||c.why===Rn?[]:e.guards.some(u=>/\bgit\b[^;&|]*\bworktree\s+add\b/.test(u)&&u.split(/\s+/).some(d=>d.replace(/^["']|["']$/g,"")===a))?[]:[m("claude.bash.git.discard","git worktree remove --force discards its changes",{target:a,is_local:!0})]}return[];case"switch":return r(["--discard-changes","-f","--force"])?[m("claude.bash.git.discard","git switch discards uncommitted changes",{branch:n.branch,is_local:!0})]:nl(t.args,"switch",e,n);default:return[]}}function nl(e,n,t,s){let r=gc(e,n).find(o=>(o.letter==="B"||o.letter==="C")&&!zn(o.branch,t,s));return r?[m("claude.bash.git.discard",`git ${n} -${r.letter} resets ${r.branch}`,{target:r.branch,branch:r.branch,is_local:!0})]:[]}function zn(e,n,t){let s=t.createdBranches.get(e),r=xt(n),o=r?Ft(n,r,t):null;return s!==void 0&&n.guards.includes(s.by)&&s.repo!==null&&s.repo===o}function co(e){let n=e.find(t=>!t.startsWith("-"));return n===void 0?"stash@{0}":/^\d+$/.test(n)?`stash@{${n}}`:C(n)?`computed:${v(n)}`:n}function yc(e,n,t){let s=`${e.replace(/\/$/,"")}/_`,r=Ie(s,n,t);return Y(r!==s&&r.endsWith("/_")?r.slice(0,-2):e,n.cwd,te(t)).path}function kg(e,n,t,s,r=null){let o=!1,i=!1,a=!1,l=[],c=null,u=new Set(["--repo","--receive-pack","--exec","-o","--push-option","--signed"]);for(let y=0;y<e.length;y++){let $=e[y];if($==="-n"||$==="--dry-run")return[];if($==="-f"||$==="--force"||$.startsWith("--force-with-lease")||$==="--force-if-includes"||$==="--mirror")o=!0;else if($==="-d"||$==="--delete")i=!0;else if($==="--all"||$==="--branches")a=!0;else if(/^-[a-zA-Z]+$/.test($)){if($.includes("f")&&(o=!0),$.includes("n"))return[];$.includes("d")&&(i=!0)}else $==="--repo"?c=e[++y]??null:$.startsWith("--repo=")?c=$.slice(7):u.has($)?y++:$.startsWith("-")||l.push($)}let d=l[0]??c,p={repo_dir:r===null||C(r)?null:r,repo_remote:d===null?null:C(d)?"$?":v(d),repo_via:"git"};if(e.includes("--mirror"))return[m("claude.bash.git.force_push","mirrors every branch and tag to the remote, overwriting or deleting what differs (main included)",{branch:null,target:"every branch and tag",service:null,is_local:!1})];let f=l.slice(1),h=[];f.length===0&&h.push({branch:a?"main":s,plus:!1,deleting:!1});for(let y of f){let $=y.startsWith("+"),E=$?y.slice(1):y,_=E.indexOf(":"),k=_>=0?E.slice(0,_):E,P=_>=0?E.slice(_+1):E,S=_===0,A=M=>C(M)&&/git\s+(branch\s+--show-current|rev-parse\s+--abbrev-ref\s+HEAD|symbolic-ref\s+--short\s+HEAD)/.test(v(M));(P==="HEAD"||_<0&&k==="HEAD"||A(P))&&(P=s??""),P=P.replace(/^refs\/heads\//,""),h.push({branch:P||null,plus:$,deleting:S||i})}let g=[];for(let y of h){let $=y.branch!==null&&Xl.has(y.branch),E=y.branch??"the current branch";y.deleting?g.push($?m("claude.bash.git.force_push",`deletes the remote ${E} branch`,{branch:y.branch,target:E,service:"git.main",is_local:!1}):m("claude.bash.git.discard",`deletes the remote branch ${E}`,{branch:y.branch,target:E,is_local:!1})):o||y.plus?g.push(m("claude.bash.git.force_push",`force-pushes ${E}`,{branch:y.branch,target:E,service:$?"git.main":null,is_local:!1})):$?g.push(m("claude.bash.git.push_main",`pushes to ${y.branch} (a deploy)`,{branch:y.branch,target:y.branch,is_local:!1,push:p})):y.branch!==null&&yh.has(y.branch)&&g.push(m("claude.bash.deploy",`pushes to ${y.branch} (a deploy branch)`,{branch:y.branch,target:y.branch,is_local:!1}))}return g}function bc(e){let n=e.indexOf("--"),s=(n<0?e:e.slice(0,n)).filter(r=>r==="--rm"||r.startsWith("--rm="));return s.length>0&&!/^--rm=(false|0)$/i.test(s[s.length-1])}function vg(e,n){let t=n.ctx.session?.repoRemotes;if(!t||!e.cwd||C(e.cwd))return null;let s=Object.keys(t).filter(r=>e.cwd===r||e.cwd.startsWith(`${r}/`)).sort((r,o)=>o.length-r.length)[0];return s===void 0?null:t[s]??null}function $g(e,n){let t=vg(e,n)?.filter(Boolean);if(!t||t.length===0)return!1;let s=[];return e.argv.forEach((r,o)=>{r==="-R"||r==="--repo"?s.push(e.argv[o+1]??null):r.startsWith("--repo=")?s.push(r.slice(7)):/^-R\S/.test(r)&&s.push(r.slice(2))}),s.length===0?!1:s.every(r=>!r||C(r)?!1:t.includes((_g(r)??r).toLowerCase().replace(/^github\.com\//,"")))}function _g(e){let n=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(e.trim());return n?`${n[1]}/${n[2]}`:null}function js(e,n){let t=[];e.argv.forEach((l,c)=>{l==="-R"||l==="--repo"?t.push(e.argv[c+1]??""):l.startsWith("--repo=")?t.push(l.slice(7)):/^-R\S/.test(l)?t.push(l.slice(2).replace(/^=/,"")):/^-[A-Za-z]+R/.test(l)&&t.push("$?")});let s=e.argv.slice(3).find(l=>/^https?:\/\/[^/]+\/[^/]+\/[^/]+\/(?:pulls?|issues)\/\d+/.test(v(l))),o=[...e.text.slice(0,Math.max(0,e.text.search(/(?:^|\s)(?:\S*\/)?gh\s/))).matchAll(/\bGH_REPO=("[^"]*"|'[^']*'|[^\s;&|)]+)/g)].pop()?.[1]?.replace(/^["']|["']$/g,""),i=s??t[t.length-1]??o??null;return{repo_dir:e.cwd!==null&&!C(e.cwd)&&(i!==null||!(hc(e,n)||/\bGH_REPO\b/.test(n)))?e.cwd:null,repo_remote:i===null?null:C(i)?"$?":v(i),repo_via:"gh"}}function xg(e,n,t){let[,s="",r=""]=e.argv,o=e.argv.slice(3),i=(...l)=>e.argv.some(c=>l.includes(c)||l.some(u=>c.startsWith(`${u}=`)));if(s==="pr"&&r==="merge")return[m("claude.bash.git.push_main","gh pr merge merges a pull request into its base branch (main, unless it says otherwise: a deploy)",{target:o.find(l=>!l.startsWith("-"))??"current PR",branch:"main",is_local:!1,host:"github.com",push:js(e,n)})];if(s==="pr"&&(r==="create"||r==="edit"))if(i("-R","--repo")||e.argv.some(c=>/^-R\S/.test(c))||/\bGH_REPO=/.test(n)){if(t&&!/\bGH_REPO=/.test(n)&&$g(e,t))return[]}else return[];let a={pr:new Set(["create","comment","review","close","reopen","edit","ready","lock","unlock"]),issue:new Set(["create","comment","close","reopen","edit","delete","transfer","lock","unlock","pin","unpin","develop"]),release:new Set(["delete","edit","upload","delete-asset"]),repo:new Set(["create","delete","edit","fork","rename","archive","unarchive"]),secret:new Set(["set","delete","remove"]),variable:new Set(["set","delete"]),workflow:new Set(["run","enable","disable"]),run:new Set(["cancel","delete"]),gist:new Set(["create","edit","delete"]),label:new Set(["create","edit","delete","clone"]),cache:new Set(["delete"])};if(s==="release"&&r==="create")return i("--draft","-d")?[m("claude.bash.external_write","gh release create makes a draft release on GitHub (nothing is published until someone publishes it)",{target:o.find(l=>!l.startsWith("-"))??null,is_local:!1,host:"github.com",push:js(e,n)})]:[m("claude.bash.publish","gh release create publishes a release",{target:o.find(l=>!l.startsWith("-"))??null,is_local:!1,host:"github.com",push:js(e,n)})];if(s==="workflow"&&r==="run"){let l=e.argv.findIndex(h=>h==="--ref"||h==="-r"),c=l>=0?e.argv[l+1]:e.argv.find(h=>h.startsWith("--ref="))?.slice(6),u=e.argv.slice(3).some(h=>!h.startsWith("-")&&/deploy|release|publish|prod/i.test(h)),d="";for(let h=3;h<e.argv.length&&!d;h++)/^(--ref|-r|-f|-F|--field|--raw-field|--repo|-R)$/.test(e.argv[h])?h++:e.argv[h].startsWith("-")||(d=e.argv[h]);let p=/deploy|release|publish|promot|rollout|(?:^|[^a-z])(?:prod(?:uction)?|ship)(?:[^a-z]|$)/i.test(d),f=e.argv.flatMap((h,g)=>/^(-f|-F|--field|--raw-field)$/.test(e.argv[g-1]??"")?[h]:/^(--field|--raw-field)=/.test(h)?[h.slice(h.indexOf("=")+1)]:[]);if(p||f.some(h=>/^(environment|env|stage|deploy_env|target)=/i.test(h)))return[m("claude.bash.deploy",p?"gh workflow run starts a deploy or release workflow":"gh workflow run starts a workflow for an environment",{target:o.find(h=>!h.startsWith("-"))??null,is_local:!1,host:"gh"})];if(c&&!C(c)&&!Xl.has(c.replace(/^refs\/heads\//,""))&&!u)return[]}if(s==="run"&&r==="rerun"&&/(?<![\w-])[\w-]*(deploy|release|publish|prod)[\w-]*\.ya?ml\b|--workflow[= ]+['"]?[\w -]*(deploy|release|publish|prod)/i.test(n))return[m("claude.bash.external_write","gh run rerun next to a deploy or release workflow can redo a release",{target:"run rerun",is_local:!1,host:"github.com"})];if(a[s]?.has(r))return[m("claude.bash.external_write",`gh ${s} ${r} changes GitHub`,{target:`${s} ${r}`,is_local:!1,host:"github.com",push:js(e,n),...s==="repo"&&r==="delete"?{catastrophic:!0}:{}})];if(s==="auth"&&r==="setup-git")return[m("claude.bash.persistence","gh auth setup-git makes gh the git credential helper for every repository",{target:"credential.helper",is_local:!0})];if(s==="auth"&&(r==="token"||r==="status"&&i("-t","--show-token")))return oe(e)?[m("claude.bash.secrets.print","prints the GitHub token",{target:"gh auth token",is_local:!0})]:[];if(s==="api"){let l=e.argv.findIndex(p=>p==="-X"||p==="--method"),c=(l>=0?e.argv[l+1]:e.argv.find(p=>p.startsWith("--method="))?.slice(9)??e.argv.find(p=>/^-X[A-Z]+$/.test(p))?.slice(2)??null)?.toUpperCase()??null,u=i("-f","-F","--field","--raw-field","--input"),d=e.argv.slice(2).find((p,f,h)=>!p.startsWith("-")&&!["-X","--method"].includes(h[f-1]??""))??"";if(c==="GET"||c==="HEAD")return[];if(d==="graphql"){let p=e.argv.join(" ");return/\bmutation\b/.test(p)?[m("claude.bash.external_write","gh api runs a GraphQL mutation",{target:"graphql",is_local:!1,host:"github.com"})]:[]}if(c&&c!=="GET"||u)return[m("claude.bash.external_write",`gh api ${c??"POST"} ${d}`,{target:d,is_local:!1,host:"github.com",...c==="DELETE"&&!kc.test(d)?{catastrophic:!0}:{}})]}return[]}var Gs=new Set(["-X","-H","-d","-F","-o","-u","-A","-e","-b","-c","-m","-w","-x","-T","-K","-r","-C","-Y","-y","-z","-E","-U","-P","-Q","--request","--header","--data","--data-raw","--data-binary","--data-ascii","--data-urlencode","--json","--form","--form-string","--output","--user","--user-agent","--referer","--cookie","--cookie-jar","--max-time","--connect-timeout","--write-out","--proxy","--upload-file","--config","--range","--retry","--retry-delay","--resolve","--cert","--key","--cacert","--limit-rate","--url","--oauth2-bearer"]),zt=["-d","--data","--data-raw","--data-binary","--data-ascii","--data-urlencode","--json","-F","--form","--form-string","-T","--upload-file"],Po=/(?:(?:https?:\/\/)?(?<![\w.-])(?:[\w-]{1,63}\.){0,5}anvilcontrol\.ai(?::\d+)?|ANVIL_API(?:_BASE)?_URL)[\s\S]{0,60}?(\/v1\/(?:modes|kill-switch)|\/anvil\/actions\/(?:mode|removal-confirm)|\/api\/control\/kill-switch)\b/;function jo(e){return e.includes("anvilcontrol.ai")||e.includes("ANVIL_API")}function wc(e,n,t){if(!jo(e))return null;let s=Po.exec(e)?.[1];return s===void 0?null:n==="DELETE"||s.endsWith("removal-confirm")?s:s.endsWith("kill-switch")?/\bon["']?\s*[:=]\s*(false|False)\b/.test(t)&&!/\bon["']?\s*[:=]\s*(true|True)\b/.test(t)?null:s:/\bmode["']?\s*[:=]\s*["']enforce["']/.test(t)&&!/["']ghost["']/.test(t)?null:s}function Sg(e){let n=e.argv,t=null,s=!1,r=!1,o=[];if(e.name==="curl"){for(let p=1;p<n.length;p++){let f=n[p];if(f==="-X"||f==="--request"?t=(n[p+1]??"").toUpperCase():/^-X[A-Za-z]+$/.test(f)?t=f.slice(2).toUpperCase():f.startsWith("--request=")?t=f.slice(10).toUpperCase():f[0]==="-"&&f[1]!=="-"&&f.includes("X")&&/^-[a-zA-Z]+X$/.test(f)?t=(n[p+1]??"").toUpperCase():f[0]==="-"&&f[1]!=="-"&&f.includes("X")&&/^-[a-zA-Z]+X[A-Z]+$/.test(f)&&(t=f.slice(f.indexOf("X")+1)),(zt.includes(f)||zt.some(h=>h.startsWith("--")&&f.startsWith(`${h}=`))||/^-d./.test(f))&&(s=!0),(f==="-G"||f==="--get")&&(r=!0),(f==="-I"||f==="--head")&&(t="HEAD"),f==="--url"&&n[p+1]&&o.push(n[p+1]),Gs.has(f)||f.endsWith("X")&&/^-[a-zA-Z]+X$/.test(f)){p++;continue}!f.startsWith("-")&&cn(f)&&o.push(f)}t||(t=s&&!r?"POST":"GET")}else if(e.name==="wget"){for(let[p,f]of n.entries())(f.startsWith("--post-data")||f.startsWith("--post-file")||f.startsWith("--body-data")||f.startsWith("--body-file"))&&(s=!0),f.startsWith("--method=")&&(t=f.slice(9).toUpperCase()),f==="--method"&&n[p+1]&&(t=n[p+1].toUpperCase()),p>0&&!f.startsWith("-")&&cn(f)&&o.push(f);t||(t=s?"POST":"GET")}else{let p=n.slice(1).filter((f,h)=>!f.startsWith("-")&&!((n[h]??"").startsWith("-")&&Ag.test(n[h])));p[0]&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(p[0])&&(t=p.shift().toUpperCase()),p[0]&&o.push(p[0]),t||(t=p.slice(1).some(f=>/^[^=:@]+(:?=|@)/.test(f))?"POST":"GET")}if(!["POST","PUT","PATCH","DELETE"].includes(t))return[];if(t==="POST"&&(Pg(n)||Wg(o,n)))return[];let i=o.filter(p=>!Re(p));if(o.length>0&&i.length===0)return[];let a=i[0]??o[0]??null,l=n.filter((p,f)=>f>0&&(zt.includes(n[f-1])||/^--(data|json)[\w-]*=/.test(p)||/^-d./.test(p))).join(" "),c=n.find(p=>jo(p)&&Po.test(p)),u=c!==void 0?wc(c,t,l):null;return c!==void 0&&u!==null?[m("claude.agent.controls",`changes your Anvil workspace's modes through its API (${t} ${u})`,{target:c,host:a?de(a):null,is_local:!1})]:(i.length>0?i.slice(0,64):[a]).flatMap(p=>Cg(p,t,n))}function Cg(e,n,t){let s=e?de(e):null;if(e&&/\/(batches|fine_tuning|fine-tunes|fine_tunes|predictions|training_jobs|jobs\/(create|submit))\b/.test(e))return[m("claude.bash.spend",`starts a paid job (${n} ${s??"an API"})`,{target:e,host:s,is_local:!1})];let r=n!=="DELETE"?null:s??/^\$\{?(\w+)/.exec(v(t.find((l,c)=>c>0&&!l.startsWith("-")&&C(l)&&!Gs.has(t[c-1])&&!/^(--(http-user|http-password|user|password|header|output-document|output-file)|-[oOU])$/.test(t[c-1]))??""))?.[1]??null,o=e?v(e).replace(/^[a-z]+:\/\/[^/?#]*/i,""):"",i=/\.(execute-api\.[\w-]+|elb(\.[\w-]+)?)\.amazonaws\.com$/i.test(r??"")||/^\/rest\/v1\/[^?]*\?[^#]*=/.test(o)||r==="api.github.com"&&kc.test(o.replace(/^\//,"")),a=r!==null&&!i&&!vc.test(r)&&(sl.test(r)||nr(r));return[m("claude.bash.external_write",a?`DELETE to ${s??`a URL in $${r}`} removes what it names (${sl.test(r)?"a provider's API":"a host named for production"})`:`${n} to ${s??"an external host"}`,{target:e,host:s,is_local:!1,service:s,...a?{catastrophic:!0}:{}})]}var kc=/(^|\/)(user\/(starred|following)|notifications|subscriptions?|actions\/caches|reactions)(\/|\?|$)/,vc=/^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$|\.(local|test|localhost)$/i,Ag=/^(-a|--auth|-A|--auth-type|--bearer|-o|--output|--session|--session-read-only|--cert|--cert-key|--verify|--proxy|--timeout|-s|--style|-p|--print|--pretty|--format-options|--default-scheme|--max-redirects)$/,sl=/(^|\.)(api\.github\.com|uploads\.github\.com|gitlab\.com|api\.bitbucket\.org|amazonaws\.com|googleapis\.com|management\.azure\.com|graph\.microsoft\.com|core\.windows\.net|api\.cloudflare\.com|api\.vercel\.com|api\.netlify\.com|api\.heroku\.com|api\.fly\.io|api\.machines\.dev|api\.render\.com|backboard\.railway\.(app|com)|supabase\.(co|com)|api\.planetscale\.com|neon\.tech|api\.digitalocean\.com|api\.linode\.com|api\.hetzner\.cloud|api\.vultr\.com|api\.scaleway\.com|upstash\.(com|io)|turso\.(tech|io)|cloud\.mongodb\.com|hub\.docker\.com)$/i;function $c(e){let n=[];for(let t=1;t<e.length;t++){let s=e[t];zt.includes(s)&&e[t+1]!==void 0?n.push(e[t+1]):zt.some(r=>r.startsWith("--")&&s.startsWith(`${r}=`))&&n.push(s.slice(s.indexOf("=")+1))}return n}var rl=new Set(["query","variables","operationName","extensions"]),Eg=new Set(["jsonrpc","method","params","id"]),Rg=/(^|[/._])(list|get|read|search|query|describe|status|ping|initialize|lookup|find)/i,ol=(e,n)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).every(t=>n.has(t));function Og(e){let n;try{n=JSON.parse(e)}catch{let s=e.split("&").map(o=>o.split("=")[0]??""),r="";try{r=decodeURIComponent((/^query=([^&]*)/.exec(e)?.[1]??"").replace(/\+/g," "))}catch{return!1}return s.every(o=>rl.has(o))&&/^\s*(query\b|\{)/.test(r)}let t=Array.isArray(n)?n:[n];return t.length>0&&t.every(s=>{if(ol(s,Eg)&&typeof s.method=="string"){if(s.method==="tools/call"){let r=s.params,o=typeof r=="object"&&r!==null?r.name:void 0;return typeof o=="string"&&Is(o)==="read"}return Rg.test(s.method)}return ol(s,rl)&&typeof s.query=="string"&&/^\s*(query\b|\{)/.test(s.query)})}function Pg(e){let n=$c(e);if(n.length===0)return!1;let t=n.join(" ");return/\bmutation\b/i.test(t)||/\bsubscription\b/i.test(t)||Wo.test(t)?!1:n.every(Og)}var Wo=/\b(drop\s+(table|database|schema|index|view)|truncate\s|delete\s+from|insert\s+into|update\s+[\w."]+\s+set|alter\s+table|create\s+(table|index|database)|grant\s|revoke\s)/i,jg=new Set(["query","queries","search","autocomplete","suggest","suggestions","lookup","find","list","get","fetch","load","read","info","describe","count","explain","preview"]);function Wg(e,n){if(e.length===0)return!1;let t=$c(n).join(" ");return Wo.test(t)||/\bmutation\b/i.test(t)?!1:e.every(s=>{if(C(s))return!1;let o=s.replace(/^[a-z]+:\/\/[^/]*/i,"").replace(/[?#].*$/,"").split("/").filter(Boolean),i=o.flatMap(l=>l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));if(i.some(l=>wt.has(l)||vt.has(l)||["redeem","subscribe","unsubscribe","enroll","register","signup","checkout","notify","verify","generate","run"].includes(l)))return!1;let a=(o[o.length-1]??"").toLowerCase();return i.some(l=>jg.has(l))||/(query|search|lookup|autocomplete)$/.test(a)})}function cn(e){return/^https?:\/\//i.test(e)||/^(localhost|127\.|\[::1\]|<host>|[\w-]+(\.[\w-]+)+)(:\d+)?(\/|$)/i.test(e)}function Re(e){if(/^(\[?::1\]?|0\.0\.0\.0)$/.test(e))return!0;let n=/^[a-z]+:\/\//i.test(e)?e:`http://${e}`;return ti(n)}function de(e){return/^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:[^@/]*@)?(\[[^\]]+\]|[^/:?#]+)/i.exec(e)?.[1]?.toLowerCase()??null}function Ng(e,n){let t=e.argv.slice(1);switch(e.name){case"pkill":case"killall":{if(t.includes("-0")||t.includes("-l")||t.length===0)return[];let s=new Set(["-u","-U","--euid","--uid","-g","-G","-t","-s","-P","--signal","-F"]),r=[];for(let d=0;d<t.length;d++)s.has(t[d])?d++:t[d].startsWith("-")||r.push(t[d]);let o=t.some(d=>["-u","-U","--euid","--uid"].includes(d));if(e.name==="pkill"&&t.some(d=>/^-[a-zA-Z]*v[a-zA-Z]*$/.test(d)||d.length>=4&&"--inverse".startsWith(d)))return[m("claude.bash.process.kill_by_name","pkill -v kills every process that does not match",{target:t.join(" "),service:"proc.all",is_local:!0})];if(o&&r.length===0)return[m("claude.bash.process.kill_by_name",`${e.name} -u kills every process the user owns`,{target:t.join(" "),service:"proc.all",is_local:!0})];let i=e.name==="pkill"&&t.some(d=>/^-[a-zA-Z]*f[a-zA-Z]*$/.test(d)||d==="--full");if(!o&&r.length>0&&r.every(d=>No(d,n,i)))return[];let a=t.some(d=>/^-[a-zA-Z]*i[a-zA-Z]*$/.test(d)||d==="--ignore-case"),l=e.name==="killall"&&t.some(d=>d==="-r"||d==="--regexp"||d==="-m"),c=o||$t(e)?null:Vl(r,{full:i,exact:e.name==="killall"&&!l||t.some(d=>/^-[a-zA-Z]*x[a-zA-Z]*$/.test(d)||d==="--exact"),fold:a},n);if(c==="own")return[];let u=e.name==="pkill"&&r.length===0&&t.some(d=>d==="-P"||d==="--parent"||d.startsWith("--parent=")||/^-P./.test(d));return e.name==="pkill"&&!o&&!$t(e)&&_c(t,e,n)?[]:u?[m("claude.bash.process.kill_by_name","pkill -P stops every process the named process started",{target:t.join(" "),is_local:!0})]:[m("claude.bash.process.kill_by_name",`${e.name} kills every process matching a name, other sessions' too`,{target:r.join(" "),is_local:!0,housekeeping:c==="some"})]}case"fuser":return t.some(s=>/^-[a-zA-Z]*k/.test(s))?[m("claude.bash.process.kill_by_name","fuser -k kills everything using the port or file, clients too",{target:t.filter(s=>!s.startsWith("-")).join(" "),is_local:!0})]:[];case"colima":return["stop","delete","restart","kill"].includes(t[0]??"")?[m("claude.bash.process.kill_by_name",`colima ${t[0]} stops the Docker VM other sessions share`,{target:"colima",is_local:!0})]:[];case"launchctl":return["stop","unload","bootout","kill","remove","disable"].includes(t[0]??"")||t[0]==="kickstart"&&t.includes("-k")?[m("claude.bash.process.kill_by_name",`launchctl ${t[0]} stops a system service`,{target:t.slice(1).join(" "),is_local:!0})]:[];case"tmux":return["kill-server","kill-session"].includes(t[0]??"")?[m("claude.bash.process.kill_by_name",`tmux ${t[0]} ends sessions it may not own`,{target:t.slice(1).join(" "),is_local:!0})]:[];case"systemctl":return["stop","restart","kill","disable","mask","poweroff","reboot","halt"].includes(t[0]??"")?[m("claude.bash.process.kill_by_name",`systemctl ${t[0]} stops a service`,{target:t.slice(1).join(" "),is_local:e.remote===null,host:e.remote})]:[];case"shutdown":case"reboot":case"halt":return[m("claude.bash.process.kill_by_name",`${e.name} stops the machine`,{target:e.name,service:"proc.all",is_local:e.remote===null,host:e.remote})];case"osascript":{let s=t.join(" ");return/\b(shut\s*down|restart|log\s*out)\b/i.test(s)&&/\b(System Events|Finder|loginwindow)\b/i.test(s)?[m("claude.bash.process.kill_by_name","osascript shuts down, restarts or logs out the machine",{target:s.slice(0,80),service:"proc.all",is_local:!0})]:/\bquit\b/i.test(s)?[m("claude.bash.process.kill_by_name","osascript quits an application",{target:s.slice(0,80),is_local:!0})]:[]}case"kill":return Tg(e,n);default:return[]}}function Tg(e,n){let t=e.argv.slice(1),s=0,r=!1;for(;s<t.length&&t[s].startsWith("-")&&!/^-\d+$/.test(t[s])||s<t.length&&/^-(\d+|[A-Z]+|s|n)$/.test(t[s])&&!(t[s]==="-1"&&s===t.length-1);){let l=t[s];(l==="-0"&&s===0||l==="-l"||l==="-L")&&(r=!0),(l==="-s"||l==="-n")&&s++,s++}if(r)return[];let o=t.slice(s),i=zg(e,n);if(e.via==="xargs"&&e.pipeFrom)return i?[]:qg(e.pipeFrom,n);if(e.via==="xargs"&&e.stdinFile)return i?[]:Ks(e.stdinFile,e,n);let a=[];for(let l of t.slice(0,s).filter((c,u)=>(u>0||o.length===0)&&c!=="-1"&&(/^-\d+$/.test(c)?u>0&&t[u-1]!=="-s"&&t[u-1]!=="-n":c.startsWith("-")&&C(c))))i||a.push(m("claude.bash.process.kill_by_name",`kills the whole process group ${v(l).slice(1)}`,{target:v(l),is_local:!0}));for(let l of o)if(l==="-1")a.push(m("claude.bash.process.kill_by_name",e.wrappers.some(c=>["sudo","doas","pkexec","run0"].includes(c))?"kill -1 as root kills every process on the machine":"kill -1 kills every process you own",{target:"-1",service:"proc.all",is_local:!0}));else{if(i)continue;if(/^-\d+$/.test(l))a.push(m("claude.bash.process.kill_by_name",`kills the whole process group ${l.slice(1)}`,{target:l,is_local:!0}));else{if(/^\d+$/.test(l)&&(n.ctx.session?.ownPids?.includes(l)||!$t(e)&&Bl(l,n)))continue;if(/^\d+$/.test(l))a.push(m("claude.bash.process.kill_by_name",`kills a hard-coded PID (${l}) this command did not start`,{target:l,is_local:!0}));else if(C(l)){let c=v(l);if(Ug(c,n)||!$t(e)&&Ig(c,e,n))continue;if(/\b(pgrep|pidof)\b|\bps\b/.test(c))a.push(m("claude.bash.process.kill_by_name","kills processes found by name",{target:c,is_local:!0}));else if(/\blsof\b/.test(c)&&!/-sTCP:LISTEN/.test(c)){let u=/^\$\(\s*lsof\s+([^()$`|;&]*?)\s*\)$/.exec(c.trim()),d=u&&!$t(e)?Zl(u[1].split(/\s+/),n):null;d!=="own"&&a.push(m("claude.bash.process.kill_by_name","kills by port without checking LISTEN, so clients die too",{target:c,is_local:!0,housekeeping:d==="some"}))}else if(/\bdocker\s+ps\b/.test(c))a.push(m("claude.bash.process.kill_by_name","kills every running container",{target:c,is_local:!0}));else{let u=xc(l,e,n);u&&a.push(...Ks(u,e,n))}}}}return a}function Lg(e,n,t){if(/\$\{(#|!|\w+[^\w}])/.test(n.text))return!1;let s=v(e).trim();if(/^\d+$/.test(s))return Number(s)>1&&(t.ctx.session?.ownPids?.includes(s)===!0||Bl(s,t));let r=/^(\$\(\s*(cat\s+|<\s*)|`\s*cat\s+)["']?[^\s;&|<>()`$"'\\]+["']?\s*[)`]$/.test(s)?xc(e,n,t):null;return r!==null&&!C(r)&&Ks(r,n,t).length===0}function _c(e,n,t){let s=[];return e.forEach((r,o)=>{let i=r==="-P"||r==="--parent"?e[o+1]??"":r.startsWith("--parent=")?r.slice(9):/^-P./.test(r)?r.slice(2):null;i!==null&&s.push(...C(i)?[i]:i.split(","))}),s.length>0&&s.length<=8&&!e.some(r=>/^-[a-zA-Z]*v[a-zA-Z]*$/.test(r)||r.length>=4&&"--inverse".startsWith(r))&&s.every(r=>Lg(r,n,t))}function Ig(e,n,t){let s=/^\$\(\s*pgrep\s+([^;&|\n`]*?)\s*\)$/.exec(e.trim());if(!s)return!1;let r=`pgrep ${s[1]}`,o=(t.lineCommands??[]).filter(a=>a.name==="pgrep"&&a.via==="substitution"&&a.text.trim()===r),i=o.length>0?o:Yn(r,n.cwd,t).commands.filter(a=>a.name==="pgrep").slice(0,1);return i.length>0&&i.every(a=>a.pipeTo===null&&_c(a.argv.slice(1),n,t))}function Ks(e,n,t){return C(e)?[]:qe(e,n,t).kind==="disposable"?[]:[m("claude.bash.process.kill_by_name",`kills the process in ${v(e)}, which this session did not start`,{target:v(e),is_local:!0})]}function xc(e,n,t){let s=v(e).trim(),r=/^\$\(([\s\S]*)\)$/.exec(s)??/^`([\s\S]*)`$/.exec(s);if(!r)return null;let o=Yn(r[1],n.cwd,t);for(let i of o.commands){let l=(["cat","head","tail","sort","uniq"].includes(i.name)?i.argv.slice(1).find(c=>!c.startsWith("-")&&!/^\d+$/.test(c)):["sed","awk","jq","grep","cut","tr"].includes(i.name)?Ut(i)[0]:void 0)??i.stdinFile??void 0;if(l)return l}return null}var Dg=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/scratchpad\b/i,Fg=/(^|[\s;&|({])(function\s+[\w-]+|[\w-]+\s*\(\)\s*\{|alias\s|unalias\s|hash\s|enable\s)/;function zg(e,n){if(e.guards.length===0||Fg.test(n.lineText))return!1;let t=String.raw`(lsof\b[^;|)]*\s-p\b|ps\b[^;|)]*\s-p\b|pwdx\b|(cat|readlink|ls)\b[^;|)]*\/proc\/)`,s=r=>new RegExp(`^${t}`).test(r)||new RegExp(String.raw`^(\[\[?|test)\s[^;|]*\$\(\s*${t}`).test(r);return e.guards.some(r=>{let o=/^case ([\s\S]*) in [\s\S]*$/.exec(r)?.[1];if(!s(o===void 0?r:v(o).replace(/^["']?\$\(\s*/,""))||/\bgrep\b[^;|]*\s-[a-zA-Z]*v|\[\[?\s*-z\b|\btest\s+-z\b|-eq\s*0\b|-lt\s*1\b|==?\s*0\b|(^|\s)!\s/.test(r))return!1;let i=/^case ([\s\S]*) in ([\s\S]*)$/.exec(r);return i?i[2].split("|").every(a=>uo(a,n)):uo(r,n)&&!/\\\||\s-e\s.*\s-e\s/.test(r)})}function No(e,n,t){let r=e.replace(/^["']|["']$/g,"").split(/(?<!\\)\|/);return r.length>8||r.some(o=>o.trim()==="")?!1:r.every(o=>Mg(o,n)||ca(o,Ul(n),t,ql(n)))}function Mg(e,n){let t=e.replace(/^["']|["']$/g,"");if(/(^|[^\\])\|/.test(t))return!1;let s=/^[^|()?*+[\]{}\\^$]*/.exec(t.replace(/\\\./g,"."))[0];return uo(s,n)&&/\/scratchpad\//.test(`${s}/`)&&/\/scratchpad\b/.test(s)}function uo(e,n){let t=e.toLowerCase(),s=n.sessionId?.toLowerCase()??null;return s?t.includes(s)||/^[0-9a-f]{8}/.test(s)&&new RegExp(`(^|[^0-9a-f])${s.slice(0,8)}([^0-9a-f]|$)`).test(t):Dg.test(t)}function Ug(e,n){let t=/^\$\(\s*pgrep\s+((?:-[a-zA-Z]+\s+)*)("[^"]*"|'[^']*'|\S+)\s*\)$/.exec(e.trim());if(!t||/[uUgGPtv]/.test(t[1]??""))return!1;let s=/f/.test(t[1]??"");return No(t[2],n,s)||Up([t[2]],{full:s,exact:/x/.test(t[1]??""),fold:/i/.test(t[1]??"")},n)}function qg(e,n){let t=[];for(let a=e;a&&t.length<8;a=a.pipeFrom)t.push(a);if(t.length===1&&e.name==="pgrep"){let a=e.argv.slice(1).filter(c=>c.startsWith("-")),l=e.argv.slice(1).filter(c=>!c.startsWith("-"));if(l.length===1&&!a.some(c=>/[uUgGPtv]/.test(c)||c==="--inverse")&&No(l[0],n,a.some(c=>c.includes("f"))))return[]}let s=t.map(a=>a.name),r=t.find(a=>a.name==="lsof");if(r){if(r.argv.some(l=>l==="-sTCP:LISTEN"||l.includes("TCP:LISTEN")))return[];let a=t.length===1&&!$t(r)&&!$t(e)?Zl(r.argv.slice(1),n):null;return a==="own"?[]:[m("claude.bash.process.kill_by_name","kills by port without checking LISTEN, so clients die too",{target:r.argv.slice(1).join(" "),is_local:!0,housekeeping:a==="some"})]}if(s.some(a=>a==="pgrep"||a==="pidof"||a==="ps"))return[m("claude.bash.process.kill_by_name","kills processes found by name",{target:t.map(a=>a.name).reverse().join(" | "),is_local:!0})];if(s.includes("docker"))return[m("claude.bash.process.kill_by_name","kills containers listed by docker",{target:"docker ps",is_local:!0})];let o=t[t.length-1],i=["cat","head","tail","sort","uniq","tr","cut"].includes(o.name)?o.argv.slice(1).find(a=>!a.startsWith("-")&&!/^\d+$/.test(a))??o.stdinFile:["awk","sed","jq","grep"].includes(o.name)?Ut(o)[0]??o.stdinFile:null;return i?Ks(i,o,n):(o.name==="echo"||o.name==="printf")&&o.argv.slice(1).some(a=>/^\d+$/.test(a))?[m("claude.bash.process.kill_by_name","kills a hard-coded PID this command did not start",{target:o.argv.slice(1).join(" "),is_local:!0})]:[]}var Hg=ie({aws:new Set(["--profile","--region","--output","--endpoint-url","--query","--color","--ca-bundle","--cli-read-timeout","--cli-connect-timeout"]),kubectl:new Set(["--context","--namespace","-n","--kubeconfig","--cluster","--user","-s","--server","--token","--as","--as-group","--request-timeout","-l","--selector","-o","--output","-f","--filename","-v"]),helm:new Set(["--kube-context","--namespace","-n","--kubeconfig","--repo","--version","-f","--values","--set","-o","--output"]),fly:new Set(["-a","--app","-c","--config","-r","--region","-o","--org"]),flyctl:new Set(["-a","--app","-c","--config","-r","--region","-o","--org"]),railway:new Set(["-s","--service","-e","--environment","-p","--project"]),ngrok:new Set(["--config","--authtoken","--log","--log-format","--log-level","--region","--api-key","--url","--domain"]),cloudflared:new Set(["--config","--loglevel","--logfile","--metrics","--origincert","--credentials-file","--protocol","--edge-ip-version","--region","--hostname","--url"]),sui:new Set(["--client.env","--client.config","--gas-budget","--gas","--gas-price"]),bq:new Set(["--location","--project_id","--dataset_id","--format","--api","--job_id","--destination_table","--parameter","--label","--maximum_bytes_billed","-n","--max_rows"]),eas:new Set(["--branch","--channel","--message","-m","--platform","-p","--profile","-e","--id","--group","--runtime-version","--percent"]),hardhat:new Set(["--network","--config"]),truffle:new Set(["--network","--config"]),brownie:new Set(["--network"]),solana:new Set(["--url","-u","--keypair","-k","--fee-payer","--commitment","--with-compute-unit-price","--program-id","--upgrade-authority","--buffer"]),"spl-token":new Set(["--url","-u","--fee-payer","--owner","--program-id"]),cast:new Set(["--rpc-url","-r","--private-key","--from","-f","--value","--gas-limit","--gas-price","--chain","--keystore","--account","--nonce"]),forge:new Set(["--rpc-url","-r","--fork-url","-f","--private-key","--sender","--chain","--etherscan-api-key","--verifier","--sig","-s","--account","--keystore","--constructor-args"]),fastlane:new Set(["--env"]),claude:new Set(["--transport","-t","--scope","-s","-e","--env","-H","--header","--model","--permission-mode","--allowedTools","--allowed-tools","--disallowedTools","--disallowed-tools","--output-format","--append-system-prompt","--add-dir","--mcp-config","--settings","--resume","-r"]),vercel:new Set(["--token","-t","--scope","-S","--cwd","-A","--local-config","--team","-T","--target","-e","--env","-b","--build-env","-m","--meta","--regions","--archive"]),gcloud:new Set(["--project","--account","--configuration","--zone","--region","--format","--impersonate-service-account"]),az:new Set(["--subscription","--output","-o","--query"]),doctl:new Set(["--context","-t","--access-token","-o","--output"]),heroku:new Set(["-a","--app","-r","--remote"]),wrangler:new Set(["-c","--config","-e","--env"]),supabase:new Set(["--project-ref","--workdir","--profile"]),modal:new Set(["-e","--env"]),docker:new Set(["-H","--host","--context","-c","--config","--log-level"]),terraform:new Set([]),pulumi:new Set(["-s","--stack","-C","--cwd"]),stripe:new Set(["--api-key","--project-name","-p"])}),w=e=>{let n=Hg[pe(e[0]??"")]??new Set,t=[];for(let s=1;s<e.length;s++){let r=e[s];if(r.startsWith("-")){n.has(r)&&s++;continue}t.push(r)}return t},re=(...e)=>n=>e.every((t,s)=>w(n)[s]===t),L=(e,...n)=>e.some(t=>n.includes(t)||n.some(s=>t.startsWith(`${s}=`))),Bg=new Set(["--dry-run","--force","--yes","-y","--atomic","--wait","--wait-for-jobs","--all","--debug","--verbose","-v","--quiet","-q","--json","--allow-dirty","--no-verify","--locked","--frozen","--offline","--install","--create-namespace","--reuse-values","--reset-values","--cleanup-on-fail","--recursive","-R","--prune","--server-side","--keep-history","--no-hooks","--skip-crds","--devel","--dependency-update","--provenance","--ignore-scripts","--workspaces","--include-workspace-root","--linked","--local","--include-all","--include-roles","--include-seed"]);function It(e,n,t=["true"]){let s=a=>a.replace(/^--/,"").replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`).replace(/_/g,"-"),r=n.map(s),o=a=>r.some(l=>l===a||l.replace(/-/g,"")===a.replace(/-/g,"")||a.length>=2&&l.startsWith(a)),i=null;for(let a=0;a<e.length;a++){let l=e[a];if(l==="--")break;if(!l.startsWith("--"))continue;let[c,...u]=l.slice(2).split("="),d=c.startsWith("no-")||/^no[A-Z]/.test(c),p=s(d?c.replace(/^no-?/,"").replace(/^./,y=>y.toLowerCase()):c);if(!o(p))continue;let f=n.includes(`--${c}`),h=e[a-1]??"",g=/^--?[a-zA-Z][\w-]*$/.test(h)&&!Bg.has(h);d?i="false":u.length?i=f?u.join("="):u.join("=")==="true"?null:"false":!f||g?i=i??null:i=e[a+1]==="false"?"false":"true"}return i!==null&&t.includes(i)}var Ae=e=>!It(e,["--dry-run","--dryrun","--plan","--preview"]),Sc=ie({railway:[{match:e=>["up","redeploy","deploy","down"].includes(w(e)[0]??""),action:"claude.bash.deploy",why:"railway deploys or removes a service"},{match:e=>["variables","variable","vars"].includes(w(e)[0]??"")&&(L(e,"--set")||["set","delete","remove"].includes(w(e)[1]??"")),action:"claude.bash.deploy",why:"railway changes production variables"},{match:e=>w(e)[0]==="domain",action:"claude.bash.deploy",why:"railway domain can create a public domain for a live service"},{match:e=>["service","environment","volume","project"].includes(w(e)[0]??"")&&["delete","remove","rm"].includes(w(e)[1]??""),action:"claude.bash.deploy",why:"railway deletes infrastructure"},{match:e=>w(e)[0]==="add",action:"claude.bash.deploy",why:"railway add creates a service"}],vercel:[{match:e=>["remove","rm"].includes(w(e)[0]??""),action:"claude.bash.deploy",why:"vercel removes a deployment"},{match:e=>w(e)[0]==="rollback",action:"claude.bash.deploy",why:"vercel rolls production back to an earlier deployment"},{match:e=>L(e,"--prod","--production")||w(e)[0]==="promote",action:"claude.bash.deploy",why:"vercel deploys to production"},{match:e=>w(e)[0]==="env"&&["add","rm","remove"].includes(w(e)[1]??"")||w(e)[0]==="alias"&&w(e)[1]==="set"||w(e)[0]==="domains"&&["add","rm","remove"].includes(w(e)[1]??""),action:"claude.bash.deploy",why:"vercel changes production settings"},{match:e=>j(e,"--target")!==null&&(w(e).length===0||w(e)[0]==="deploy"||/^[./~]/.test(w(e)[0])),action:"claude.bash.deploy",why:"vercel deploys to the environment --target names"}],wrangler:[{match:e=>["deploy","publish"].includes(w(e)[0]??"")&&!It(e,["--dry-run"])||w(e)[0]==="rollback"||re("pages","deploy")(e)||re("versions","deploy")(e)||w(e)[0]==="secret"&&["put","delete"].includes(w(e)[1]??""),action:"claude.bash.deploy",why:"wrangler deploys to Cloudflare"}],fly:[{match:e=>re("ssh","console")(e)&&/\b(printenv|env|set|export\s+-p|cat\s+\S*\.env)\b/.test(j(e,"-C","--command")??""),action:"claude.bash.secrets.print",why:"fly ssh console prints a live app's environment"},{match:e=>["deploy","scale","destroy"].includes(w(e)[0]??"")||["secrets","apps","machine","machines","volumes","postgres"].includes(w(e)[0]??"")&&["set","unset","destroy","delete","remove","stop","create"].includes(w(e)[1]??""),action:"claude.bash.deploy",why:"fly changes a live app"}],netlify:[{match:e=>w(e)[0]==="deploy"&&L(e,"--prod"),action:"claude.bash.deploy",why:"netlify deploys to production"}],firebase:[{match:e=>w(e)[0]==="deploy"||/^hosting:channel:deploy/.test(w(e)[0]??""),action:"claude.bash.deploy",why:"firebase deploys"},{match:e=>/^functions:delete/.test(w(e)[0]??""),action:"claude.bash.deploy",why:"firebase deletes live functions"},{match:e=>/^hosting:disable/.test(w(e)[0]??""),action:"claude.bash.deploy",why:"firebase takes the hosting site offline"},{match:e=>w(e)[0]==="appdistribution:distribute",action:"claude.bash.deploy",why:"firebase sends a build to testers"}],fastlane:[{match:Qy,action:"claude.bash.deploy",why:"fastlane uploads or releases an app"}],eas:[{match:eb,action:"claude.bash.deploy",why:"eas sends an app or an over-the-air update to users"}],expo:[{match:e=>w(e)[0]==="publish",action:"claude.bash.deploy",why:"expo publish sends an over-the-air update to users"}],xcrun:[{match:e=>w(e)[0]==="altool"&&L(e,"--upload-app","--upload-package")||w(e)[0]==="iTMSTransporter"&&j(e,"-m")==="upload",action:"claude.bash.deploy",why:"uploads an app to App Store Connect"}],altool:[{match:e=>L(e,"--upload-app","--upload-package"),action:"claude.bash.deploy",why:"altool uploads an app to App Store Connect"}],appcenter:[{match:e=>w(e)[0]==="codepush"&&/^(release|release-react|release-cordova|release-electron|promote|patch|rollback)$/.test(w(e)[1]??"")&&Qr(e)||re("distribute","release")(e),action:"claude.bash.deploy",why:"appcenter releases an app update to users"}],"code-push":[{match:e=>/^(release|release-react|release-cordova|release-electron|promote|patch|rollback)$/.test(w(e)[0]??"")&&Qr(e),action:"claude.bash.deploy",why:"code-push releases an app update to users"}],"code-push-standalone":[{match:e=>/^(release|release-react|release-cordova|release-electron|promote|patch|rollback)$/.test(w(e)[0]??"")&&Qr(e),action:"claude.bash.deploy",why:"code-push releases an app update to users"}],shorebird:[{match:e=>w(e)[0]==="patch"&&!/^(staging)$/i.test(j(e,"--track")??"")||re("patches","promote")(e),action:"claude.bash.deploy",why:"shorebird sends a patch to the app's users"}],capgo:[{match:e=>re("bundle","upload")(e)&&!ru.test(j(e,"--channel","-c")??""),action:"claude.bash.deploy",why:"capgo sends an over-the-air update to users"}],butler:[{match:e=>w(e)[0]==="push"&&Ae(e),action:"claude.bash.deploy",why:"butler pushes a build to itch.io"}],steamcmd:[{match:e=>e.some(n=>/^\+run_app_build(_http)?$|^\+set_?live/i.test(n)),action:"claude.bash.deploy",why:"steamcmd uploads a build to Steam"}],msstore:[{match:e=>w(e)[0]==="publish",action:"claude.bash.deploy",why:"msstore publishes to the Microsoft Store"}],"web-ext":[{match:e=>w(e)[0]==="sign"&&j(e,"--channel")==="listed",action:"claude.bash.deploy",why:"web-ext submits a listed add-on to addons.mozilla.org"}],"chrome-webstore-upload":[{match:e=>!["help"].includes(w(e)[0]??""),action:"claude.bash.deploy",why:"uploads an extension to the Chrome Web Store"}],gradlew:[{match:Cl,action:"claude.bash.deploy",why:"gradle publishes an app to Google Play"},{match:Al,action:"claude.bash.publish",why:"gradle publishes artifacts to a package repository"}],gradle:[{match:Cl,action:"claude.bash.deploy",why:"gradle publishes an app to Google Play"},{match:Al,action:"claude.bash.publish",why:"gradle publishes artifacts to a package repository"}],heroku:[{match:e=>/^apps:destroy$/.test(w(e)[0]??""),action:"claude.bash.deploy",why:"heroku deletes the app"},{match:e=>/^(config:set|config:unset|releases:rollback|ps:scale|ps:restart|ps:stop|maintenance:on|run)$/.test(w(e)[0]??""),action:"claude.bash.deploy",why:"heroku changes a live app"},{match:e=>/^pg:reset$/.test(w(e)[0]??""),action:"claude.bash.db.destructive",why:"heroku pg:reset wipes the database"}],kubectl:[{match:e=>w(e)[0]==="delete"&&!It(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"kubectl deletes from a cluster"},{match:e=>(["apply","create","delete","replace","patch","scale","set","edit","label","annotate","drain","cordon","uncordon","taint","expose","autoscale"].includes(w(e)[0]??"")||w(e)[0]==="run"&&!bc(e)||w(e)[0]==="rollout"&&["restart","undo","pause","resume"].includes(w(e)[1]??""))&&!It(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"kubectl changes a cluster"}],helm:[{match:e=>["uninstall","delete"].includes(w(e)[0]??"")&&!It(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"helm removes a release from a cluster"},{match:e=>["install","upgrade","rollback"].includes(w(e)[0]??"")&&!It(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"helm changes a cluster"}],terraform:[{match:e=>w(e)[0]==="import"||w(e)[0]==="state"&&["rm","mv","push","replace-provider"].includes(w(e)[1]??"")||["taint","untaint","force-unlock"].includes(w(e)[0]??""),action:"claude.bash.deploy",why:"terraform changes the shared state that every later apply works from"},{match:e=>w(e)[0]==="destroy"||w(e)[0]==="apply"&&L(e,"-destroy","--destroy"),action:"claude.bash.deploy",why:"terraform destroy deletes real infrastructure"},{match:e=>w(e)[0]==="apply",action:"claude.bash.deploy",why:"terraform changes real infrastructure"}],tofu:[{match:e=>w(e)[0]==="destroy"||w(e)[0]==="apply"&&L(e,"-destroy","--destroy"),action:"claude.bash.deploy",why:"tofu destroy deletes real infrastructure"},{match:e=>["apply","import","taint"].includes(w(e)[0]??""),action:"claude.bash.deploy",why:"tofu changes real infrastructure"}],pulumi:[{match:e=>w(e)[0]==="destroy",action:"claude.bash.deploy",why:"pulumi destroy deletes real infrastructure"},{match:e=>["up","update","cancel"].includes(w(e)[0]??""),action:"claude.bash.deploy",why:"pulumi changes real infrastructure"}],cdk:[{match:e=>w(e)[0]==="destroy",action:"claude.bash.deploy",why:"cdk destroy deletes real infrastructure"},{match:e=>w(e)[0]==="deploy",action:"claude.bash.deploy",why:"cdk changes real infrastructure"}],serverless:[{match:e=>w(e)[0]==="remove",action:"claude.bash.deploy",why:"serverless remove deletes the deployed service"},{match:e=>w(e)[0]==="deploy",action:"claude.bash.deploy",why:"serverless deploys"}],sls:[{match:e=>w(e)[0]==="remove",action:"claude.bash.deploy",why:"serverless remove deletes the deployed service"},{match:e=>w(e)[0]==="deploy",action:"claude.bash.deploy",why:"serverless deploys"}],modal:[{match:e=>w(e)[0]==="deploy"||["app","secret"].includes(w(e)[0]??"")&&["stop","create","delete"].includes(w(e)[1]??""),action:"claude.bash.deploy",why:"modal deploys or changes a live app"},{match:e=>["run","shell","launch"].includes(w(e)[0]??""),action:"claude.bash.spend",why:"modal starts a paid cloud run"},{match:e=>w(e)[0]==="volume"&&["rm","delete"].includes(w(e)[1]??""),action:"claude.bash.db.destructive",why:"modal deletes stored data"}],supabase:[{match:e=>re("db","push")(e)&&!L(e,"--local")&&!Cc(e)&&!It(e,["--dry-run"])||re("functions","deploy")(e)||re("secrets","set")(e)||re("functions","delete")(e),action:"claude.bash.deploy",why:"supabase changes a live project"},{match:e=>re("db","reset")(e)&&L(e,"--linked","--db-url"),action:"claude.bash.db.destructive",why:"supabase db reset wipes a linked database"}],prisma:[{match:e=>re("migrate","reset")(e)||re("db","push")(e)&&L(e,"--accept-data-loss","--force-reset"),action:"claude.bash.db.destructive",why:"prisma wipes or drops database data"},{match:e=>re("migrate","deploy")(e),action:"claude.bash.deploy",why:"prisma migrate deploy changes the target database"}],"drizzle-kit":[{match:e=>w(e)[0]==="push"||w(e)[0]==="drop",action:"claude.bash.db.destructive",why:"drizzle-kit push can drop columns and tables to match the schema"}],docker:[{match:e=>(w(e)[0]==="push"||w(e)[0]==="image"&&w(e)[1]==="push"||w(e)[0]==="buildx"&&L(e,"--push"))&&!um(e),action:"claude.bash.publish",why:"docker push publishes an image"},{match:e=>["stop","kill","rm","restart"].includes(w(e)[0]??"")&&e.some(n=>C(n)&&/docker\s+ps\b/.test(v(n))),action:"claude.bash.process.kill_by_name",why:"docker stops every container, other sessions' too"},{match:e=>re("system","prune")(e)&&L(e,"--volumes")||w(e)[0]==="volume"&&(w(e)[1]==="prune"||w(e)[1]==="rm"&&!Jg(w(e).slice(2)))||re("compose","down")(e)&&L(e,"-v","--volumes"),action:"claude.bash.fs.delete_recursive",why:"docker deletes volumes, and the data in them"},{match:e=>re("system","prune")(e)&&e.some(n=>/^-\w*f/.test(n)||n==="--force"),action:"claude.bash.fs.delete_recursive",why:"docker system prune deletes stopped containers and unused images"}],cargo:[{match:e=>(w(e)[0]==="publish"||w(e)[0]==="yank")&&Ae(e),action:"claude.bash.publish",why:"cargo publishes a crate"}],podman:[{match:e=>w(e)[0]==="push"||w(e)[0]==="image"&&w(e)[1]==="push"||w(e)[0]==="manifest"&&w(e)[1]==="push",action:"claude.bash.publish",why:"podman push publishes an image"}],buildah:[{match:e=>w(e)[0]==="push",action:"claude.bash.publish",why:"buildah push publishes an image"}],nerdctl:[{match:e=>w(e)[0]==="push",action:"claude.bash.publish",why:"nerdctl push publishes an image"}],glab:[{match:e=>w(e)[0]==="mr"&&w(e)[1]==="merge",action:"claude.bash.git.push_main",why:"glab mr merge merges into the default branch (a deploy)"},{match:e=>w(e)[0]==="release"&&w(e)[1]==="create",action:"claude.bash.publish",why:"glab release create publishes a release"}],twilio:[{match:e=>/:(buy|purchase)(:|$)/.test(w(e)[0]??"")||/^api:core:incoming-phone-numbers:create$/.test(w(e)[0]??""),action:"claude.bash.spend",why:"twilio buys a phone number"},{match:e=>/^api:[\w-]+:(messages|calls|conversations|notifications|verify[\w-]*):create$|^api:[\w-]+:[\w-]+:(messages|calls):create$/.test(w(e)[0]??""),action:"claude.bash.external_write",why:"twilio sends a message or places a call"}],twine:[{match:e=>w(e)[0]==="upload",action:"claude.bash.publish",why:"twine uploads a package"}],gem:[{match:e=>["push","yank"].includes(w(e)[0]??""),action:"claude.bash.publish",why:"gem publishes a package"}],poetry:[{match:e=>w(e)[0]==="publish"&&Ae(e),action:"claude.bash.publish",why:"poetry publishes a package"}],vsce:[{match:e=>["publish","unpublish"].includes(w(e)[0]??""),action:"claude.bash.publish",why:"vsce publishes an extension"}],ovsx:[{match:e=>w(e)[0]==="publish",action:"claude.bash.publish",why:"ovsx publishes an extension"}],changeset:[{match:e=>w(e)[0]==="publish",action:"claude.bash.publish",why:"changeset publishes packages"}],lerna:[{match:e=>w(e)[0]==="publish",action:"claude.bash.publish",why:"lerna publishes packages"}],jsr:[{match:e=>w(e)[0]==="publish"&&Ae(e),action:"claude.bash.publish",why:"jsr publishes a package"}],sky:[{match:e=>["launch","exec","jobs"].includes(w(e)[0]??""),action:"claude.bash.spend",why:"sky starts paid cloud machines"}],gcloud:[{match:e=>/\b(instances|clusters|tpus)\b/.test(w(e).join(" "))&&w(e).includes("create"),action:"claude.bash.spend",why:"gcloud starts paid machines"},{match:e=>w(e).includes("deploy")||w(e).includes("delete")&&!w(e).includes("describe"),action:"claude.bash.deploy",why:"gcloud changes cloud resources"},{match:e=>w(e).some(n=>/^(add|remove|set)-iam-policy(-binding)?$/.test(n)),action:"claude.bash.deploy",why:"gcloud changes who can reach cloud resources"},{match:e=>w(e)[0]==="auth"&&/^print-(access|identity)-token$/.test(w(e)[1]??"")||w(e)[0]==="secrets"&&w(e)[1]==="versions"&&w(e)[2]==="access",action:"claude.bash.secrets.print",why:"gcloud prints a credential"}],az:[{match:e=>re("vm","create")(e),action:"claude.bash.spend",why:"az starts a paid machine"},{match:e=>w(e).some(n=>["delete","deploy","create","update","set"].includes(n))&&!re("account","set")(e),action:"claude.bash.deploy",why:"az changes cloud resources"},{match:e=>re("account","get-access-token")(e),action:"claude.bash.secrets.print",why:"az prints an access token"}],doctl:[{match:e=>w(e).includes("create")||w(e).includes("delete"),action:"claude.bash.deploy",why:"doctl changes cloud resources"}],stripe:[{match:e=>["post","delete"].includes(w(e)[0]??"")||w(e).some(n=>["create","update","delete","cancel","refund","capture","pay","void"].includes(n)),action:"claude.bash.external_write",why:"stripe changes live payment data"}],mail:[{match:()=>!0,action:"claude.bash.external_write",why:"sends an email"}],uv:[{match:e=>w(e)[0]==="publish"&&Ae(e),action:"claude.bash.publish",why:"uv publishes a package"}],mvn:[{match:e=>w(e).some(n=>n==="deploy"||n==="release:perform"||n==="deploy:deploy-file"),action:"claude.bash.publish",why:"mvn deploy uploads artifacts to a package repository"}],mvnw:[{match:e=>w(e).some(n=>n==="deploy"||n==="release:perform"),action:"claude.bash.publish",why:"mvn deploy uploads artifacts to a package repository"}],argocd:[{match:e=>w(e)[0]==="app"&&["sync","rollback","delete","set","patch","terminate-op"].includes(w(e)[1]??"")&&Ae(e),action:"claude.bash.deploy",why:"argocd changes what a cluster runs"}],"ansible-playbook":[{match:e=>!L(e,"--check","-C","--syntax-check","--list-hosts","--list-tasks","--list-tags")&&!/^(?:localhost|127\.0\.0\.1),?$/.test(j(e,"-i","--inventory")??""),action:"claude.bash.deploy",why:"ansible-playbook changes the machines in its inventory"}],pm2:[{match:e=>["restart","reload","stop","delete","kill"].includes(w(e)[0]??"")&&(w(e)[0]==="kill"||w(e)[1]==="all"),action:"claude.bash.process.kill_by_name",why:"pm2 stops or restarts every process it manages"}],sendmail:[{match:()=>!0,action:"claude.bash.external_write",why:"sends an email"}],mailx:[{match:()=>!0,action:"claude.bash.external_write",why:"sends an email"}],mutt:[{match:e=>L(e,"-s","-a","-c","-b","-H","-i")||w(e).some(n=>n.includes("@")),action:"claude.bash.external_write",why:"sends an email"}],msmtp:[{match:e=>!L(e,"--help","--version","--serverinfo","-S","-P","--pretend","--rmqs"),action:"claude.bash.external_write",why:"sends an email"}],swaks:[{match:e=>!L(e,"--help","-h","--version"),action:"claude.bash.external_write",why:"sends an email"}]});function Cc(e){let n=e.findIndex(r=>r==="--db-url"||r==="--database-url"),t=n>=0?e[n+1]:e.find(r=>r.startsWith("--db-url=")||r.startsWith("--database-url="))?.split("=").slice(1).join("=");if(!t||C(t))return!1;let s=de(t);return s!==null&&Re(s)}var Vg=new Set(["--exclude","--include","--cache-control","--acl","--content-type","--content-encoding","--content-disposition","--content-language","--expires","--sse","--sse-kms-key-id","--sse-c","--sse-c-key","--storage-class","--metadata","--metadata-directive","--grants","--website-redirect","--profile","--region","--endpoint-url","--expected-size","--source-region","--request-payer","--output","--query","--page-size","--color","--ca-bundle","--cli-read-timeout","--cli-connect-timeout"]);function fo(e){let n=e.findIndex((t,s)=>s>0&&["cp","sync","mv"].includes(t)&&e[s-1]==="s3");return n<0?[]:ce(e,n+1,Vg)}var Zg=/^(run-instances|request-spot-instances|create-training-job|create-cluster|create-db-instance|create-endpoint|purchase-[\w-]+|create-capacity-reservation)$/,Gg=/^(delete-|terminate-|remove-|deregister-|revoke-|detach-|put-|update-|create-|deploy|attach-|modify-|stop-|reboot-|start-|replace-|disable-|enable-|change-|authorize-|associate-|disassociate-|set-|add-|apply-|import-|restore-|rotate-|schedule-|cancel-|purge-|batch-delete-|batch-write-|reset-|admin-|initiate-|promote-|failover-|reject-|accept-)/,Kg=/^(s3|s3api|s3control|kms|dynamodb|rds|backup|secretsmanager|ssm|ecr|ecr-public|sqs|kinesis|firehose|glacier|efs|fsx|elasticache|memorydb|redshift|redshift-serverless|docdb|neptune|opensearch|es|timestream-write|keyspaces|qldb|lightsail|athena|glue|logs|cloudtrail|codecommit|cognito-idp)$/,Yg=/^(get-secret-value|get-session-token|assume-role|get-federation-token|get-parameter|get-parameters)$/;function Ms(e){let n=e.argv,t=e.name,s=[],r=lm(e);if(r.length>0)return r;let o=tm(e);if(o.length>0)return o;if(t==="aws"){let[l="",c=""]=w(n),u=c.split("-").some(d=>["delete","deletion","purge","terminate","drop","destroy","wipe","truncate"].includes(d))||/^(disable-key|schedule-key-deletion|remove-objects?)$/.test(c);if(l==="s3"&&["rm","rb"].includes(c))s.push(m("claude.bash.db.destructive",`aws s3 ${c} deletes stored data`,{target:w(n)[2]??null,is_local:!1}));else if(Kg.test(l)&&u&&Ae(n))s.push(m("claude.bash.db.destructive",`aws ${l} ${c} deletes stored data`,{target:`${l} ${c}`,is_local:!1}));else if(l==="configure"&&c==="export-credentials")s.push(...oe(e)?[m("claude.bash.secrets.print","aws configure export-credentials prints AWS credentials",{target:"configure export-credentials",is_local:!0})]:[]);else if(/^authorize-security-group-ingress$|^modify-security-group-rules$/.test(c)&&n.some(d=>/(^|[=\s"'])(0\.0\.0\.0\/0|::\/0)\b/.test(d)))s.push(m("claude.bash.net.expose",`aws ${l} ${c} opens a port to the whole internet`,{target:`${l} ${c}`,is_local:!1}));else if(l==="s3"&&["cp","sync","mv"].includes(c)&&(fo(n).slice(-1)[0]??"").startsWith("s3://")&&fo(n).length>=2)s.push(m("claude.bash.deploy",`aws s3 ${c} writes to a bucket`,{target:w(n).slice(-1)[0]??null,is_local:!1}));else if(l==="configure"&&c==="get"&&/secret|key/i.test(w(n)[2]??""))s.push(...oe(e)?[m("claude.bash.secrets.print","prints an AWS credential",{target:w(n)[2]??null,is_local:!0})]:[]);else if(Yg.test(c)&&(c!=="get-parameter"&&c!=="get-parameters"||L(n,"--with-decryption")))s.push(...oe(e)?[m("claude.bash.secrets.print",`aws ${l} ${c} prints a secret`,{target:`${l} ${c}`,is_local:!0})]:[]);else if(l==="athena"&&c==="start-query-execution"){let d=ke(j(n,"--query-string")??""),p=be.exec(d)??qn.exec(d);p&&s.push(m("claude.bash.db.destructive",`aws athena runs destructive SQL (${p[1].replace(/\s+/g," ").toUpperCase()})`,{target:"athena",host:"athena",is_local:!1}))}else if(["redshift-data","rds-data"].includes(l)&&/execute-statement$/.test(c)){let d=ke([j(n,"--sql")??"",...n.filter((p,f)=>n[f-1]==="--sqls")].join(`
|
|
42
|
-
`));be.test(d)&&s.push(m("claude.bash.db.destructive",`aws ${l} runs destructive SQL (${(be.exec(d)?.[1]??"").replace(/\s+/g," ").toUpperCase()})`,{target:`${l} ${c}`,host:l,is_local:!1}))}else Zg.test(c)?s.push(m("claude.bash.spend",`aws ${l} ${c} starts paid resources`,{target:`${l} ${c}`,is_local:!1})):["ses","sesv2","sns","sqs"].includes(l)&&/^(send|publish)/.test(c)?s.push(m("claude.bash.external_write",`aws ${l} ${c} sends a message`,{target:`${l} ${c}`,is_local:!1})):Gg.test(c)&&Ae(n)&&s.push(m("claude.bash.deploy",`aws ${l} ${c} changes cloud resources`,{target:`${l} ${c}`,is_local:!1}));return s}if(["npm","pnpm","yarn","bun"].includes(t))return jc(e);if(["nx","turbo","mise","lerna","run-s","run-p","npm-run-all"].includes(t))return dm(e);if(["make","just","task","mise"].includes(t)){let l=w(n).find(c=>!c.includes("="));return l&&/^(deploy|release|publish|ship)([-:_].*)?$/.test(l)&&!Oc.test(l)&&Ae(n)&&!L(n,"-n","--just-print","--recon")?[m("claude.bash.deploy",`${t} ${l} runs a deploy or release target`,{target:l,is_local:!1})]:[]}let i=cm(e);if(i.length>0)return i;let a=am(e);if(a.length>0)return a;if(t==="python"||t==="python3"){let l=n.indexOf("-m");if(l>0&&n[l+1]==="twine"&&n[l+2]==="upload")return[m("claude.bash.publish","twine uploads a package",{is_local:!1})];if(n.includes("manage.py")&&["flush","reset_db","sqlflush"].some(u=>n.includes(u)))return[m("claude.bash.db.destructive","manage.py wipes the database",{is_local:null})];let c=n.indexOf("migrate");if(n.includes("manage.py")&&c>0){let u=n.slice(c+1).filter(d=>!d.startsWith("-"));if(u[1]==="zero")return[m("claude.bash.db.destructive","manage.py migrate APP zero drops the app's tables",{target:u[0]??null,is_local:null})]}return[]}if(t==="alembic"&&w(n).includes("downgrade")&&!L(n,"--sql")||t==="flask"&&re("db","downgrade")(n)&&!L(n,"--sql"))return[m("claude.bash.db.destructive",`${t} downgrades the database schema (drops what the migrations made)`,{target:w(n).slice(-1)[0]??null,is_local:null})];if(t==="rails"||t==="rake"||t==="bin/rails"){let l=(/(?:^|\s)(?:RAILS_ENV|RACK_ENV)=["']?(\w+)/.exec(e.text)?.[1]??j(n,"-e","--environment")??"").toLowerCase();return/^(test|development|dev)$/.test(l)?[]:n.some(c=>/^db:(drop|reset|schema:load|migrate:reset|purge|truncate_all)$/.test(c))?[m("claude.bash.db.destructive","rails wipes or rebuilds the database",{is_local:null})]:/^prod(uction)?$/.test(l)&&n.some(c=>/^db:(migrate|rollback|seed|setup)(:|$)/.test(c))?[m("claude.bash.deploy","rails changes the production database",{target:n.find(c=>c.startsWith("db:"))??null,is_local:!1})]:[]}for(let l of Sc[t==="flyctl"?"fly":t]??[])if(l.match(n)){if(l.action==="claude.bash.secrets.print"&&!oe(e))continue;s.push(m(l.action,l.why,{target:w(n).slice(0,3).join(" ")||t,is_local:!1,host:t}));break}return t==="railway"&&["variables","variable","vars"].includes(w(n)[0]??"")&&s.length===0&&oe(e)&&s.push(m("claude.bash.secrets.print","railway variables prints live production secrets",{target:"railway variables",is_local:!0,host:"railway"})),t==="heroku"&&/^config(:get)?$/.test(w(n)[0]??"")&&s.length===0&&oe(e)&&s.push(m("claude.bash.secrets.print","heroku config prints live secrets",{target:"heroku config",is_local:!0,host:"heroku"})),s.length===0&&s.push(...em(e),...Qg(e)),s.length===0&&s.push(...om(e),...im(e)),s}function Jg(e){return e.length>0&&e.every(n=>v(n).replace(/[${}"']/g,"").toLowerCase().split(/[-_.:]+/).some(t=>/^(cache|caches|test|tests|testing|tmp|temp|ci|fixture|fixtures|scratch)$/.test(t)))}var Ac=/^(delete|deletion|destroy|drop|purge|wipe|nuke|truncate|erase|rm|rb|remove|terminate|flush|flushall|flushdb|reset)$/i,Xg=e=>e.split(/[-:_.]/).some(n=>Ac.test(n)),il=/^(buckets?|blobs?|objects?|storage|tables?|datasets?|databases?|dbs?|collections?|documents?|docs|indexe?s|indices|topics?|queues?|streams?|keys?|kms|keyrings?|secrets?|backups?|snapshots?|volumes?|disks?|branch(es)?|firestore|datastore|bigtable|spanner|redis|memcache|memorystore|filestore|keyspaces?|schemas?|kv|keyvalue|file-?systems?|repositor(y|ies)|images?|vaults?|caches?|data|records?|rows?|partitions?|shards?|replicas?|buckets?|containers?)$/i,tr=new Set(["gsutil","bq","pscale","turso","neonctl","neon","upstash","xata","atlas","mongocli","snowsql","kafka-topics","kafka-topics.sh","kafka-configs","cqlsh","clickhouse-client","influx","cockroach","surreal","supabase","firebase","fauna","convex","rclone","restic","b2","mc","s3cmd","azcopy","cbq","couchbase-cli","arangosh","typesense","meilisearch","algolia","pinecone","weaviate","qdrant","chroma","elasticdump","curator","litestream","turso-cli","d1","pgbackrest","barman","wal-g"]),mn=new Set(["gcloud","az","doctl","linode-cli","hcloud","oci","ibmcloud","scw","vultr-cli","exo","aliyun","tccli","cf","render","koyeb","northflank","porter","qovery","okteto","nomad","consul","vault","eksctl","kops","flux","databricks","confluent","ccloud","heroku","fly","flyctl","railway","vercel","netlify","wrangler","glab","dokku","caprover","kamal","coolify","sst","amplify","copilot","crane","oras"]),Ec=new Set(["config","configure","auth","login","logout","components","alias","aliases","profile","profiles","context","contexts","completion","init","cache","plugin","plugins","extension","extensions","help","version"]);function Qg(e){let n=e.name,t=tr.has(n);if(!t&&!mn.has(n))return[];let s=e.argv;if(!Ae(s)||L(s,"--what-if","--validate-only","--check","--simulate","--no-execute"))return[];let r=w(s).slice(0,6);if(r.length>0&&Ec.has(r[0]))return[];if(n==="rclone"&&ce(s.map(h=>v(h)),1,tc).slice(1).every(h=>!Le(h)))return[];let o=r.findIndex(Xg),i=s.find(h=>/^--?(delete|drop|purge|wipe|truncate|destroy|flush|remove)(=|$)/.test(h));if(o<0&&!i)return[];if(o>0&&r.slice(0,o).some(h=>/^(list|ls|describe|get|show|info|logs?|cat|view|inspect|read|search|query)$/i.test(h)))return[];let a=r.slice(0,6),l=t||a.some(h=>il.test(h)||h.split(/[-:_.]/).some(g=>il.test(g))),c=o>=0?r[o]:i.split("=")[0],u=`${n} ${o>=0?r.slice(0,o+1).join(" "):c}`.trim(),d=o>=0?r.slice(o+1).find(h=>!h.includes("="))??null:r[0]??null,p=o>=0&&r[o].split(/[-:_.]/).every(h=>!Ac.test(h)||/^reset$/i.test(h));return!l&&o>=0&&r.slice(0,o+1).some(h=>h.split(/[-:_.]/).some(g=>/^(options?|configs?|settings?|labels?|tags?|annotations?|env|vars?|variables?|aliases?|metadata)$/i.test(g)))?[m("claude.bash.deploy",`${u} changes a live service's settings`,{target:d,is_local:!1,host:n})]:[l?m("claude.bash.db.destructive",`${u} ${p?"resets":"deletes"} stored data`,{target:d,is_local:!1,host:n}):m("claude.bash.deploy",`${u} ${p?"resets a cloud resource":"deletes cloud resources"}`,{target:d,is_local:!1,host:n})]}function em(e){let n=e.argv,t=s=>!!s&&!C(s)&&Mt(s.replace(/:\d+$/,""));if(e.name==="pg_restore"){if(L(n,"-l","--list","-f","--file"))return[];let s=n.some(l=>l==="--clean"||/^-[A-Za-z]+$/.test(l)&&l.includes("c")),r=j(n,"-d","--dbname");if(r===null)return[];let o=j(n,"-h","--host")??(/^postgres(ql)?:\/\//i.test(r)?de(r):null),i=Mc(e,"");if(i===null&&(t(o)||o===null&&!C(r)&&!/^postgres(ql)?:\/\//i.test(r)))return[];let a=i??(o!==null&&!C(o)?dn(o):null);return[m("claude.bash.db.destructive",s?`pg_restore --clean drops the database's objects before it restores${a?` (${a})`:""}`:`pg_restore writes a dump into ${a??"a database the command does not name"}`,{target:a??v(r),is_local:!1,catastrophic:s&&a!==null})]}if(e.name==="mongorestore"||e.name==="mongoimport"){if(!L(n,"--drop"))return[];let s=j(n,"--uri","--host","-h"),r=s?/^mongodb(\+srv)?:\/\//.test(s)?de(s):s:"localhost";return t(r)?[]:[m("claude.bash.db.destructive",`${e.name} --drop drops ${e.name==="mongoimport"?"the collection before it imports":"each collection before it restores"}`,{target:C(r??"")?"a database the command does not name":r,is_local:!1})]}return[]}function tm(e){if(!mn.has(e.name)&&!tr.has(e.name)&&!["aws","kubectl"].includes(e.name))return[];let n=e.argv,t=w(n);if(!Ae(n)||t.some(o=>/^(list|ls|describe|get|show|view|what-if)$/.test(o)))return[];let s=`${e.name} ${t.slice(0,3).join(" ")}`.trim();if(n.some(o=>/(^|[=:,\s"'])all(Authenticated)?Users\b/.test(o))&&!t.some(o=>/^remove-/.test(o))&&!(e.name==="gsutil"&&L(n,"-d")))return[m("claude.bash.net.expose",`${s} makes a cloud resource readable by anyone on the internet`,{target:t.slice(0,4).join(" ")||e.name,host:e.name,is_local:!1})];let r=j(n,"--public-access","--allow-blob-public-access");return r!==null&&/^(blob|container|true)$/i.test(r)?[m("claude.bash.net.expose",`${s} opens a storage container to anonymous reads`,{target:t.slice(0,4).join(" ")||e.name,host:e.name,is_local:!1})]:e.name!=="aws"&&t.some(o=>/^(create|update|add|authorize|allow|set)/.test(o))&&n.some(o=>/(^|[=\s"',])(0\.0\.0\.0\/0|::\/0)\b/.test(o))?[m("claude.bash.net.expose",`${s} admits the whole internet (0.0.0.0/0)`,{target:t.slice(0,4).join(" ")||e.name,host:e.name,is_local:!1})]:[]}var nm=/^(?:default|colima(?:-[\w-]+)?|orbstack|desktop-linux|docker-desktop|rancher-desktop|podman[\w-]*|minikube|lima[\w-]*|(?:unix|npipe):\/\/.*|(?:tcp:\/\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)$/;function sm(e,n){let t=e.argv,s=w(t),r=R.basename(e.name)==="docker-compose"?s:s[0]==="compose"?s.slice(1):null;if(!(r?r.some(c=>/^(up|deploy|start|restart|run|create)$/.test(c)):/^(run|start|restart|create)$/.test(s[0]??"")||s[0]==="service"&&/^(create|update|scale|rollback)$/.test(s[1]??"")))return[];let i=t.indexOf(s[0]??"\0"),l=[...t.slice(0,i<0?t.length:i).flatMap((c,u,d)=>/^(-H|--host|--context|-c)$/.test(d[u-1]??"")?[c]:/^--(host|context)=/.test(c)?[c.slice(c.indexOf("=")+1)]:[]),...[...n.matchAll(/\bDOCKER_(?:HOST|CONTEXT)=["']?([^\s"';&|)]+)/g)].map(c=>c[1])].find(c=>!nm.test(c));return l?[m("claude.bash.deploy",`${R.basename(e.name)} ${s.slice(0,2).join(" ")} runs on another machine's docker (${l})`,{target:l,is_local:!1,host:"docker"})]:[]}var rm=/^(deploy|deploys|deployment|deployments|promote|promotion|release|releases|rollout|rollback)$/i;function om(e){let n=e.argv,t=w(n).slice(0,6);if(e.name==="docker"||e.name==="podman"){if(t[0]==="stack"&&t[1]==="deploy")return[m("claude.bash.deploy",`${e.name} stack deploy rolls out a swarm stack`,{target:t[2]??null,is_local:!1})];if(t[0]==="compose"&&(t.includes("up")||t.includes("deploy"))){let a=[j(n,"-f","--file")??"",j(n,"-p","--project-name")??"",Gn(e)];if(a.some(l=>Kn.test(R.basename(l).toLowerCase().replace(/\.(ya?ml)$/,""))||/(^|[._-])prod(uction)?([._-]|$)/i.test(R.basename(l))))return[m("claude.bash.deploy",`${e.name} compose starts the production stack (${R.basename(a.find(l=>l)??"")})`,{target:a.find(l=>l)??null,is_local:!1})]}return[]}if(!mn.has(e.name)&&!tr.has(e.name))return[];if(!Ae(n)||L(n,"--what-if","--validate-only","--check","--simulate","--preview"))return[];if(t.length>0&&Ec.has(t[0]))return[];let s=t.findIndex(a=>/^(run|exec|ssh|shell|console|connect|--)$/.test(a)),r=(s<0?t:t.slice(0,s)).filter(a=>!/[/.]/.test(a)||/^[\w-]+:[\w:-]+$/.test(a)),o=r.findIndex(a=>a.split(/[-:_.]/).some(l=>rm.test(l)));if(o<0)return[];if(r.slice(0,o+1).some(a=>a.split(/[-:_.]/).some(l=>/^(tokens?|keys?|credentials?)$/i.test(l))))return[];if(t.some(a=>/^(list|ls|describe|get|show|info|logs?|status|history|view|inspect|what-if|validate|diff|plan|wait|cancel|close)$/i.test(a)))return[];if(/^(deploy|release)-(branch|key|keys|hook|hooks|setting|settings|config|target|env)$/i.test(r[o])&&r.slice(0,o).some(a=>/(^|:)(set|unset|config|configure)$/.test(a)))return[m("claude.bash.deploy",`${e.name} ${r.slice(0,o+1).join(" ")} changes a deploy setting`,{target:r.slice(o+1).find(a=>!a.includes("="))??null,host:e.name,is_local:!1})];let i=/(deploys|deployments?|deploy-requests?|releases)$/i.test(r[o])&&r[o+1]!==void 0?o+2:o+1;return[m("claude.bash.deploy",`${e.name} ${r.slice(0,i).join(" ")} starts a deploy`,{target:r.slice(i).find(a=>!a.includes("="))??null,host:e.name,is_local:!1})]}function im(e){let n=e.argv;return["np","release-it","semantic-release"].includes(e.name)?!Ae(n)||L(n,"--preview","--dry-run","-d","--no-ci","--help","-h")||w(n)[0]==="init"?[]:[m("claude.bash.publish",`${e.name} publishes a release`,{target:w(n)[0]??null,is_local:!1})]:[]}function am(e){let n=e.argv;return(e.name==="python"||e.name==="python3")&&n.includes("manage.py")&&n.includes("dumpdata")&&Kn.test(Gn(e))?[m("claude.bash.data.export","manage.py dumpdata copies the production database onto this machine",{target:"dumpdata",is_local:!1})]:e.name==="firebase"&&w(n)[0]==="auth:export"?[m("claude.bash.data.export","firebase auth:export copies every user account onto this machine",{target:w(n)[1]??null,host:"firebase",is_local:!1})]:e.name==="prisma"&&w(n)[0]==="db"&&w(n)[1]==="execute"&&(Kn.test(Gn(e))||/(?:^|\s)[A-Z_]*DATABASE_URL=["']?\$\{?[A-Z_]*PROD/i.test(e.text)||/prod/i.test(j(n,"--url")??""))?[m("claude.bash.deploy","prisma db execute runs SQL against the production database",{target:j(n,"--file")??null,is_local:!1})]:[]}function lm(e){let n=e.argv,t=w(n),s=(()=>{switch(e.name){case"gpg":case"gpg2":return n.some(o=>/^--export-secret-(sub)?keys$/.test(o))?"gpg prints a private key":null;case"security":return t[0]==="dump-keychain"?n.some(o=>/^-[a-z]*d/.test(o))?"security dumps the keychain with its secrets":null:/^find-(generic|internet)-password$/.test(t[0]??"")&&n.some(o=>/^-[a-z]*[wg]/.test(o))?"security prints a saved password":null;case"kubectl":case"oc":return t[0]==="config"&&t[1]==="view"&&L(n,"--raw","--flatten")?`${e.name} config view --raw prints the cluster credentials`:null;case"heroku":return t[0]==="auth:token"?"heroku auth:token prints an API token":null;case"stripe":return t[0]==="config"&&L(n,"--list")?"stripe config --list prints the API keys":null;case"az":return t[0]==="ad"&&t[1]==="sp"&&t[2]==="create-for-rbac"?"az ad sp create-for-rbac creates a service principal and prints its password":t[0]==="account"&&t[1]==="get-access-token"?"az account get-access-token prints a token":null;case"aws":return t[0]==="ecr"&&t[1]==="get-login-password"?"aws ecr get-login-password prints a registry password":t[0]==="iam"&&t[1]==="create-access-key"?"aws iam create-access-key creates a key and prints its secret":t[0]==="sts"&&/^(get-session-token|assume-role)$/.test(t[1]??"")?`aws sts ${t[1]} prints temporary credentials`:null;case"claude":return t[0]==="setup-token"?"claude setup-token prints a long-lived Claude token":null;case"glab":return t[0]==="auth"&&t[1]==="status"&&L(n,"-t","--show-token")?"glab auth status --show-token prints the GitLab token":null;case"firebase":return t[0]==="login:ci"?"firebase login:ci prints a CI token":null;case"neonctl":case"neon":return/^(connection-string|cs)$/.test(t[0]??"")?`${e.name} ${t[0]} prints a connection string with its password`:null;case"php":case"artisan":{let o=e.name==="artisan"?0:n.slice(1).findIndex(l=>/(^|\/)artisan$/.test(l))+1;if(e.name==="php"&&o<=0)return null;let[i="",a=""]=n.slice(o+1).filter(l=>!l.startsWith("-"));return i==="config:show"&&/^(app|database|mail|services|cache|queue|broadcasting|filesystems|session|logging)(\.|$)/.test(a)?`artisan config:show ${a} prints settings with their secrets`:null}default:return t.includes("diffsettings")&&(n.some(o=>/(^|\/)manage\.py$/.test(o))||R.basename(e.name)==="django-admin")?"manage.py diffsettings prints SECRET_KEY and the database password":t[0]==="auth"&&/^(token|print-token|show-token)$/.test(t[1]??"")?`${e.name} auth ${t[1]} prints a token`:t.slice(0,4).some(o=>/^print-(access|identity|id)-token$/.test(o))?`${e.name} prints an access token`:t[0]==="token"&&/^(create|new|generate)$/.test(t[1]??"")?`${e.name} token ${t[1]} makes a token and prints it`:null}})(),r=e.pipeTo;return r&&Rc(r)?[]:s!==null&&oe(e)?[m("claude.bash.secrets.print",s,{target:t.slice(0,3).join(" ")||e.name,is_local:!0,host:e.name})]:[]}function Rc(e){let n=w(e.argv);return["pbcopy","xclip","xsel","wl-copy","clip.exe","clip"].includes(e.name)?!0:["xargs","echo","printf","cat","tee"].includes(R.basename(e.name))||e.argv.some(s=>/^(-o|--output)(=|$)|^--dry-run(=|$)/.test(s))?!1:e.argv.includes("--password-stdin")&&n.includes("login")||["kubectl","oc"].includes(e.name)&&e.argv.some(s=>s==="--from-file=/dev/stdin")||(e.name==="gpg"||e.name==="gpg2")&&L(e.argv,"--import")?!0:["gh","glab"].includes(e.name)?(n[0]==="secret"||n[0]==="variable")&&n[1]==="set":e.name==="wrangler"?n[0]==="secret"&&(n[1]==="put"||n[1]==="bulk"):e.name==="fly"||e.name==="flyctl"?n[0]==="secrets"&&(n[1]==="set"||n[1]==="import"):e.name==="vercel"?n[0]==="env"&&n[1]==="add":!1}function Gn(e){return(/(?:^|\s)(?:NODE_ENV|APP_ENV|RAILS_ENV|RACK_ENV|MIX_ENV|FLASK_ENV|DJANGO_ENV|ENVIRONMENT|STAGE)=["']?([\w.-]+)/.exec(e.text)?.[1]??j(e.argv,"--env","--environment","--settings")??"").toLowerCase()}var Kn=/(^|[._-])(prod|production|live)($|[._-])/;function cm(e){let n=e.argv,t=w(n),s=Kn.test(Gn(e)),r=i=>[m("claude.bash.db.destructive",i,{target:t.join(" ")||e.name,is_local:!1})],o=i=>s?r(`${i} in production`):[m("claude.bash.db.destructive",`${i}, with no server shown`,{target:t.join(" ")||e.name,is_local:null})];switch(e.name){case"sequelize":case"sequelize-cli":return t[0]==="db:drop"?o("sequelize db:drop drops the database"):s&&/^db:(drop|migrate:undo(:all)?|seed:undo(:all)?)$/.test(t[0]??"")?r(`sequelize ${t[0]} drops data in production`):[];case"knex":return s&&/^migrate:(rollback|down)$/.test(t[0]??"")?r(`knex ${t[0]} runs migrations backwards in production`):[];case"typeorm":case"typeorm-ts-node-commonjs":case"typeorm-ts-node-esm":return t[0]==="schema:drop"?o("typeorm schema:drop drops every table"):t[0]==="schema:sync"?o("typeorm schema:sync drops what the entities no longer name"):s&&/^(schema:drop|migration:revert)$/.test(t[0]??"")?r(`typeorm ${t[0]} drops data in production`):[];case"mix":return/^ecto\.(drop|reset)$/.test(t[0]??"")?o(`mix ${t[0]} drops the database`):s&&/^ecto\.(drop|reset|rollback)$/.test(t[0]??"")?r(`mix ${t[0]} drops data in production`):[];case"flyway":return t.includes("clean")?r("flyway clean drops every object in the schema"):[];case"liquibase":return t.some(i=>/^drop-?all$/i.test(i))?r("liquibase dropAll drops every object in the database"):[];case"php":case"artisan":{let i=e.name==="artisan"?0:n.slice(1).findIndex(l=>/(^|\/)artisan$/.test(l))+1;if(i<0||e.name==="php"&&i===0)return[];let a=n.slice(i+1).find(l=>!l.startsWith("-"))??"";return a==="db:seed"?s||L(n,"--force")?r(`artisan db:seed writes seed data into the database${s?" in production":" (--force: even in production)"}`):[]:/^(db:wipe|migrate:(fresh|reset|refresh|rollback))$/.test(a)?s||L(n,"--force")?r(`artisan ${a} drops the database's tables${s?" in production":" (--force: even in production)"}`):a==="migrate:rollback"?[]:o(`artisan ${a} drops every table`):[]}default:return[]}}function um(e){let n=w(e).filter(t=>t.includes("/")||t.includes(":")).filter(t=>!["push","image","buildx","build"].includes(t));return n.length>0&&n.every(t=>/^(localhost|127\.0\.0\.1|\[::1\]|host\.docker\.internal)(:\d+)?\//.test(t))}var Oc=/^(deploy|release|publish|ship)[-:_](notes|changelog|log|check|verify|lint|dry(-?run)?|plan|diff|status|info|list|test|smoke)$|^build[-:_]release$/;function Pc(e){let n=new Set(["--filter","-F","--workspace","-w","--cwd","-C","--dir","--prefix","--scope","--filter-prod"]),t=[];for(let s=1;s<e.length;s++){let r=e[s];if(n.has(r)&&!(r==="-w"&&e[0]!=="npm")){s++;continue}if(r==="--")break;r.startsWith("-")||t.push(r)}return t[0]==="workspace"&&t.length>=3?[t[2],...t.slice(3)]:t[0]==="workspaces"&&t[1]==="foreach"?t.slice(2):t}function jc(e){let n=Pc(e.argv),t=n[0]??"",s=j(e.argv,"--registry");if(["publish","unpublish","deprecate"].includes(t)&&s!==null&&Re(v(s)))return[];if(["publish","unpublish","deprecate"].includes(t)&&Ae(e.argv))return[m("claude.bash.publish",`${e.name} ${t} changes a published package`,{target:n[1]??null,is_local:!1})];if(t==="dist-tag"&&["add","rm"].includes(n[1]??""))return[m("claude.bash.publish",`${e.name} dist-tag moves a published tag`,{target:n.slice(2).join(" "),is_local:!1})];if(t==="owner"&&["add","rm"].includes(n[1]??""))return[m("claude.bash.external_write",`${e.name} owner changes who can publish`,{is_local:!1})];if(R.basename(e.name)==="pnpm"&&t==="deploy")return[];let r=t==="run"||t==="run-script"?n[1]:e.name!=="npm"&&!To.has(t)?t:void 0;return r?Wc(r,e.argv):[]}function Wc(e,n){let t=!/^(check|verify|test|lint|validate|dry|preview|plan|diff|smoke|generate|prepare)([-:_]|$)/.test(e),s=Oc.test(e),r=n.indexOf("--"),o=r>=0&&!Ae(n.slice(r+1));return s||o?[]:/^(deploy|release|publish|ship)([-:_].*)?$/.test(e)||t&&/[-:_](deploy|release|publish)$/.test(e)?[m(/publish/.test(e)?"claude.bash.publish":"claude.bash.deploy",`the ${e} script deploys or releases`,{target:e,is_local:!1})]:t&&/^(promote|rollout|rollback)([-:_].*)?$|[-:_](promote|rollout|rollback)$/.test(e)?[m("claude.bash.deploy",`the ${e} script changes what is live`,{target:e,is_local:!1})]:/^db[-:_]?(push|reset|drop|wipe|nuke|truncate)\b|^(migrate|migration)[-:_]?(reset|fresh|drop)\b|[-:_](reset|drop|wipe)[-:_]?db$/.test(e)||/(^|[-:_])(db|database|schema|prisma|drizzle|clickhouse|postgres|mysql|mongo)[-:_](reset|drop|wipe|nuke|truncate|rollback|fresh)\b/.test(e)||/(^|[-:_])(migrate|migration|migrations)[-:_](deploy|prod|production|rollback|down|undo)\b/.test(e)?[m("claude.bash.db.destructive",`the ${e} script can drop, reset or change database data`,{target:e,is_local:null})]:[]}function dm(e){let n=R.basename(e.name),t=e.argv.slice(1).map(i=>v(i)),s=t.filter(i=>!i.startsWith("-")),r=(...i)=>t.flatMap((a,l)=>i.includes(a)?[t[l+1]??""]:i.some(c=>a.startsWith(`${c}=`))?[a.slice(a.indexOf("=")+1)]:[]).flatMap(a=>a.split(",")),o=[];if(n==="nx"){if(s[0]==="release"&&!t.includes("--dry-run")&&!t.includes("-d"))return[m("claude.bash.publish","nx release versions and publishes packages",{target:"nx release",is_local:!1})];o=s[0]==="run"?[(s[1]??"").split(":")[1]??""]:["run-many","affected"].includes(s[0]??"")?r("-t","--target","--targets"):s[0]?[s[0].includes(":")?s[0].split(":")[1]:s[0]]:[]}else if(n==="turbo"||n==="mise")o=s[0]==="run"?s.slice(1):n==="turbo"?s:[];else if(n==="lerna"){if(s[0]==="publish"&&!t.includes("--dry-run"))return[m("claude.bash.publish","lerna publish publishes packages",{target:"lerna publish",is_local:!1})];o=s[0]==="run"?s.slice(1,2):[]}else["run-s","run-p","npm-run-all"].includes(n)&&(o=s);for(let i of o.filter(Boolean)){let a=Wc(i,e.argv);if(a.length>0)return a.map(l=>({...l,why:`${l.why} (through ${n})`}))}return[]}var fm=new Set(["anvil","anvil-claude","hardhat","truffle","ape","forge","cast","anchor","prisma","drizzle-kit","supabase","wrangler","eas","expo","firebase","netlify","vercel","serverless","sls","cdk","dbt","ngrok","lt","untun","cloudflared","claude","codex","gemini","smithery","capgo","shorebird","web-ext","chrome-webstore-upload","changeset","lerna","vsce","ovsx","code-push","appcenter"]),To=new Set(["install","i","add","remove","rm","uninstall","update","up","upgrade","test","t","build","exec","dlx","x","create","init","link","unlink","list","ls","why","outdated","audit","config","cache","info","view","pack","run","start","dev","lint","format","typecheck","version","help","login","logout","whoami","ci","prune","dedupe","store","setup","workspaces","workspace"]),be=/\b(drop\s+(table|database|schema|keyspace|view|materialized\s+view|index|user|role|column|type|function|trigger|sequence|extension|owned|policy)\b|truncate\b|delete\s+from\b|alter\s+table\s+\S+\s+(drop|delete)\b|update\s+\S+\s+set\b(?![\s\S]*\bwhere\b))/i,pm=/\.(dropDatabase|drop|deleteMany|remove)\s*\(/;function al(e,n){let t=e.slice(n).search(/[\n\r]/);return t<0?e.length:n+t}function ke(e,n="postgres"){if(/\b(execute|exec|sp_executesql|do)\b/i.test(e))return e;let t=n!=="postgres",s=n==="mysql"||n==="bigquery",r="";for(let o=0;o<e.length;o++){let i=e[o],a=e[o+1];if(i==="-"&&a==="-"&&(n!=="mysql"||o+2>=e.length||/\s/.test(e[o+2])))o=al(e,o)-1;else if(i==="#"&&(n==="mysql"||n==="bigquery")||i==="/"&&a==="/"&&n==="snowflake")o=al(e,o)-1;else if(i==="/"&&a==="*"){let l=e.indexOf("*/",o+2);n==="mysql"&&e[o+2]==="!"?r+=` ${e.slice(o+3,l<0?e.length:l)} `:r+=" ",o=l<0?e.length:l+1}else if(i==='"'&&!s||i==="`"&&(n==="mysql"||n==="bigquery")){let l=o+1;for(;l<e.length;l++)if(e[l]===i&&e[l+1]===i)l++;else if(e[l]===i)break;if(l>=e.length)return e;r+=i+i,o=l}else if(i==="$"&&(n==="postgres"||n==="snowflake")&&!/[\w$]/.test(e[o-1]??"")&&/^\$([A-Za-z_]\w*)?\$/.test(e.slice(o,o+64))){let l=/^\$([A-Za-z_]\w*)?\$/.exec(e.slice(o,o+64))[0],c=e.indexOf(l,o+l.length);if(c<0)return e;r+="''",o=c+l.length-1}else if(i==="'"||i==='"'&&s){let l=t||i==="'"&&/(^|[^\w])[eE]$/.test(r),c=o+1;for(;c<e.length;c++)if(l&&e[c]==="\\")c++;else if(e[c]===i&&e[c+1]===i)c++;else if(e[c]===i)break;if(c>=e.length)return e;r+=i+i,o=c}else r+=i}return r}function yt(e){if(/(?<![\w-])ssh(?![\w-])[^\n;&|]{0,200}\s-[A-Za-z]*L\s*\S/.exec(e))return"ssh -L";let t=/\b(DOCKER_(?:HOST|CONTEXT)=\S+|(?:docker|podman)\b[^\n;&|]{0,100}\s(?:-H|--host|--context)[\s=]\S+|cloudflared\s+access\s+(?:tcp|rdp|ssh)|fly(?:ctl)?\s+proxy|(?:kubectl|oc)\b[^\n;&|]{0,200}\bport-forward|cloud[-_]sql[-_]proxy|cloud_sql_proxy|aws\s+ssm\s+start-session\b[^\n;&|]{0,200}PortForward|tsh\s+proxy\s+db|start-iap-tunnel|railway\s+connect)/i.exec(e);return t?t[1].replace(/\s+/g," ").slice(0,40):null}var hm=/\b(create\s+or\s+replace\s+(table|schema|database)|insert\s+overwrite|delete\s+(?!from\b)[\w.`"-]+\s+where)\b/i,qn={exec(e){let n=hm.exec(e);return n?[n[0],n[1]]:/\bmerge\b/i.test(e)&&/\bthen\s+delete\b/i.test(e)?["MERGE \u2026 THEN DELETE","MERGE \u2026 THEN DELETE"]:null},test(e){return this.exec(e)!==null}};function Lo(e,n){let t=Nc.has(e.name)?Lc(e):null,s=t!==null?{...e,stdin:t}:e;s!==e&&Ys.has(e)&&Ys.add(s);let r=s.argv,o=s.name,i=(...f)=>j(r,...f),a=s.pipeFrom&&["echo","printf","cat"].includes(s.pipeFrom.name)?s.pipeFrom.argv.slice(1).join(" ")+(s.pipeFrom.stdin??""):"",l="",c=null,u=null,d=!0;switch(o){case"psql":case"pgcli":{l=[...r.flatMap((g,y)=>g==="-c"||g==="--command"?[r[y+1]??""]:g.startsWith("--command=")?[g.slice(10)]:[]),s.stdin??"",a].join(`
|
|
43
|
-
`),c=
|
|
44
|
-
`);if(!
|
|
45
|
-
`),c=
|
|
46
|
-
`),c=
|
|
47
|
-
`),c=r.slice(1).find((
|
|
48
|
-
`),c="turso";break}case"prisma":{let
|
|
49
|
-
`);let h=
|
|
50
|
-
`),c="planetscale";break}case"trino":case"presto":l=
|
|
51
|
-
`),h=r.find(y=>/^mongodb(\+srv)?:\/\//i.test(y));h&&(u=de(h)),c=
|
|
52
|
-
`),s.stdin??"",
|
|
53
|
-
`),"bigquery"),$=be.exec(y)??
|
|
54
|
-
`),"snowflake"),g=be.exec(h)??
|
|
55
|
-
`));return/^(md|motherduck):/i.test(
|
|
56
|
-
`).replace(/\\(.)/g,"$1"));for(let r of e.matchAll(new RegExp(`(?:^|[?&])${s}=([^&]*)`,"gi")))try{
|
|
57
|
-
`).replace(/\\t/g," "):
|
|
58
|
-
`),P=[.../^(\s*\w+=("[^"]*"|'[^']*'|[^\s;&|]*))*/.exec(e.text)[0].matchAll(/(?:^|\s)(\w+)=("[^"]*"|'[^']*'|\S*)/g)].filter(z=>/(HOST|URL|URI|DSN|ADDR|SERVER|ENDPOINT)/i.test(z[1])||cl.test(z[2].replace(/^["']/,""))).map(z=>z[2].replace(/^["']|["']$/g,"")),S=j(s,"--host","-host","--hostname","--server","-server","--server_address","--vtctld_server","--url","-url","--uri","--dsn","--connection","--connection-string","--conn","--database-url","--db-url","--endpoint","--addr","--address","-h")??(t==="curl"||t==="wget"?s.find((z,Z)=>Z>0&&!z.startsWith("-")&&!Gs.has(s[Z-1])&&(cn(v(z))||C(z))):s.slice(1).find(z=>cl.test(v(z).replace(/^--?[\w-]+=/,""))))?.replace(/^--?[\w-]+=/,"")??P[0]??null,A=S===null?null:v(S),M=A!==null&&/^[^:[\]]+:\d+$/.test(A),I=A===null?u&&!L(s,"--local")?`${t}'s server`:null:/^[a-z][\w+.-]*:\/\//i.test(A)?ul(A):C(S)?S:M?A.replace(/:\d+$/,""):A,D=I===null?s.slice(1).map(z=>v(z).replace(/^--?[\w-]+=/,"")).find(z=>$m.test(z)):void 0;return D!==void 0?[m("claude.bash.db.destructive",`${t} runs destructive SQL (${rn(_)}) on a database file on this machine (${R.basename(D)})`,{target:D,is_local:!0})]:bt(e,I,!0,`${t} runs destructive SQL (${rn(_)})`,pl(n.lineText),_)}for(let _ of h){let k=Sm(_);if(k===null)continue;let P=/\b(?:postgres(?:ql)?|mysql|mariadb|clickhouse|mssql|sqlserver|cockroachdb|redshift|snowflake)(?:\+\w+)?:\/\/[^\s'"`]+/i.exec(_)?.[0],S=P!==void 0?ul(P):/\bhost(?:name)?['"]?\s*[:=]\s*(['"`])([^'"`\s]+)\1/i.exec(_)?.[2]??null,A=/(?:process\.env\.|process\.env\[\s*['"]|environ(?:\.get)?\s*[([]\s*['"]|getenv\(\s*['"]|env\.get\(\s*['"])(\w*(?:HOST|URL|URI|DSN|CONN|SERVER)\w*)/i.exec(_)?.[1];if(!(S===null&&A===void 0&&(P===void 0&&/sqlite|duckdb|:memory:/i.test(_))))return bt(e,S??(A!==void 0?`$${A}`:null),!0,`${t} runs destructive SQL (${k}) through a database driver`,pl(n.lineText),_)}return[]}function Rm(e){let n=pe(e[0]??"");if(n!=="heroku"&&n!=="netlify"&&n!=="vercel")return null;let t=/^(local|dev):(run|exec)$/.test(e[1]??"")?2:e[1]==="env"&&e[2]==="run"?3:-1;if(t<0)return null;let s=e.slice(e[t]==="--"?t+1:t);return s.length>0&&!s[0].startsWith("-")?s:null}function Ic(e){let n=new Set(["-c","--command","-f","--file","-h","--host","-p","--port","-U","--username","-d","--dbname","-v","--set","--variable","-o","--output","-L","--log-file","-P","--pset","-T","-F","-R"]),t=[];for(let s=1;s<e.length;s++){let r=e[s];n.has(r)?s++:r.startsWith("-")||t.push(r)}return t}function Mt(e){return e.startsWith("/")||Re(e)}function bt(e,n,t,s,r=null,o=""){let i=Fc(e),a=(e.remote===null||e.remote.startsWith("container:"))&&i===null,l=t&&!e.productionEnv&&a&&r===null&&(n===null||Mt(n))&&!(n!==null&&C(n)),c=Mc(e,o),u=n?dn(n):i??e.remote;if(c!==null)return[m("claude.bash.db.destructive",`${s}: ${c} is named for production`,{target:c,host:u,is_local:!1,catastrophic:!0})];if(l)return n!==null||e.remote!==null||Pm.has(e.name)||Ys.has(e)?[]:[m("claude.bash.db.destructive",`${s}, with no server shown`,{target:"no server shown",is_local:null,catastrophic:!1})];let d=r!==null&&(n===null||Mt(n))?`a database forwarded here (${r})`:n?dn(n):e.productionEnv?"production (railway run)":i!==null?`${i} (${e.remote?.replace(/^container:/,"container ")??"a container"})`:e.remote??"a database the command does not name";return[m("claude.bash.db.destructive",`${s} on ${d}`,{target:d,host:u,is_local:!1,catastrophic:!0})]}function Dc(e){return e.remote===null?null:e.remote.startsWith("container:")?Fc(e):e.remote==="kubernetes"?"a cluster's pod":e.remote}var hl=/^(reload|restart|stop|start|enable|disable|daemon-reload|mask|kill|try-restart|reload-or-restart|graceful|delete|down|up|rm|update)$/;function Om(e){let n=Dc(e);if(n===null)return[];let t=w(e.argv).map(a=>v(a)),s=R.basename(e.name),r=a=>[m("claude.bash.deploy",`${a} on ${n}`,{target:n,host:n,is_local:!1})];if(["rm","unlink","rmdir","shred","truncate"].includes(s)&&t.length>0)return r(`${s} deletes files`);if((s==="systemctl"||s==="service")&&t.some(a=>hl.test(a)))return r(`${s} ${t.find(a=>hl.test(a))} changes a service`);if(["docker","podman","docker-compose"].includes(s)){let a=t[0]==="compose"?1:0,l=t[a]==="exec"?void 0:t.slice(a,4).find(c=>/^(down|up|stop|rm|restart|kill|start|run|rmi|prune)$/.test(c));if(l)return r(`${s}${t[0]==="compose"?" compose":""} ${l} changes containers`)}let o=/^(\.{0,2}\/|~\/)|\.(sh|bash|py|rb)$/.test(e.argv[0]??"")||["bash","sh","zsh"].includes(s)&&/\.(sh|bash)$/.test(t[0]??""),i=t.find(a=>/^(remove|delete|destroy|uninstall|purge|drop|teardown|down)$/i.test(a));return o&&i?r(`runs ${R.basename(v(e.argv[0]??s))} ${i}`):[]}var Ys=new WeakSet,Pm=new Set(["redis-cli","mongosh","mongo"]);function Fc(e){if(e.remote===null||!e.remote.startsWith("container:"))return null;for(let n=e.parent;n;n=n.parent)if(n.remote!==null&&!n.remote.startsWith("container:"))return n.remote;return null}function nr(e){let n=e.split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])/);return n.some((t,s)=>/^(prod|prd|production|live)\d*$/i.test(t)&&!/^(non|pre|not|no|un)$/i.test(n[s-1]??""))}function jm(e){let n=[];for(let t=e;t;t=t.parent){let s=j(["",...t.wrapperArgs],"--config","--env","--environment","--stage","--profile");s!==null&&n.push(s)}return n}function zc(e){return[.../^(\s*\w+=("[^"]*"|'[^']*'|[^\s;&|]*))*/.exec(e.text)[0].matchAll(/(?:^|\s)(\w+)=("[^"]*"|'[^']*'|\S*)/g)].filter(t=>!/pass|pwd|secret|token|key|auth/i.test(t[1])).flatMap(t=>[t[1],t[2]])}function Mc(e,n){let t=e.argv.map(r=>v(r));return[...jm(e),...t.filter((r,o)=>o>0&&!/\s/.test(r)&&!/^-([UupPfoceqWaL]|-(user(name)?|pass(word)?|port|file|output|command|execute|eval|query|sql|log-file))$/.test(t[o-1])&&!/^(--?(user|pass|port|file|output)|-[UupP].)/.test(r)).map(r=>r.replace(/^--?[\w-]+=/,"")),...t.flatMap(r=>[...r.matchAll(/\b(?:dbname|host)=([^\s'"]+)/g)].map(o=>o[1])),...[...v(n).matchAll(/(?:\\c(?:onnect)?\s+|\b(?:drop\s+(?:database|schema|keyspace)\s+(?:if\s+exists\s+)?|use\s+|(?:table|from|into|update)\s+(?:if\s+exists\s+)?(?=[`"']?[\w$]+[`"']?\.)))[`"']?([\w$-]+)/gi)].map(r=>r[1]),...zc(e)].map(r=>r.replace(/(:\/\/)[^@/\s]+@/,"$1").replace(/\?.*$/,"")).find(r=>r.length<=200&&nr(r))?.slice(0,80)??null}var Uc=new Set(["firebase","xata","fauna","aws","gsutil","azd","upctl","yc","openstack","terraform","tofu","terragrunt","pulumi","cdk","cdktf","serverless","sls","ticloud","neon","neonctl","upstash","supabase","pscale","turso","atlas","mongocli","modal","bq","snow","snowsql","juju","rclone","s3cmd","mc","b2","argocd","velero","rancher","zeet","scaleway","civo"]),Wm=/^(delete|deletion|destroy|remove|rm|rb|uninstall|terminate|purge|teardown|deprovision|decommission|drop|wipe|nuke|erase|tombstone|truncate|flushall|flushdb)$/,Nm=/^(env|envs|vars?|variables?|configs?|settings?|labels?|tags?|annotations?|alias(es)?|metadata|options?|domains?)$/,Tm=/^(clusters?|serverless|instances?|buckets?|regions?|stores?|replicas?|shards?|partitions?|brokers?|namespaces?|volumes?|stacks?|deployments?|tombstone|vpcs?)$/,qc=/^(kind-|k3d-|minikube$|docker-desktop$|rancher-desktop$|orbstack$|colima)/,Lm=/\.aws\/credentials|\.azure\/|gcloud\/.*(credential|token)|application_default_credentials|service[-_]?account[^/]*\.json|-sa(-key)?\.json$|\.kube\/config|kubeconfig|\.oci\/|oci_api_key|doctl\/|credentials\.tfrc|\.s3cfg|\.boto$|\.vault-token/i,Im=/^\/(var\/lib\/(mysql|postgresql|pgsql|mongodb|redis|cassandra|clickhouse|elasticsearch|influxdb|etcd|mariadb)|(usr\/local|opt\/homebrew)\/var\/(postgres|mysql|mongodb))/;function Dm(e){if(qc.test(v(j(e.argv,"--context","--kube-context")??"")))return!1;let n=w(e.argv);if(e.name==="helm"||n[0]!=="delete"||L(e.argv,"-f","--filename","-k","--kustomize"))return!0;let t=n[1]??"";return!(t.includes("/")?n.slice(1).map(s=>s.split("/")[0]):t.split(",")).every(s=>/^(po|pods?|jobs?|events?|ev|rs|replicasets?|leases?)$/i.test(s))}function Fm(e,n){if(e.catastrophic!==void 0||e.housekeeping)return e;let t=e.action,s=n.name,r=n.argv.map(f=>v(f)),o=w(r).slice(0,6).flatMap(f=>f.toLowerCase().split(/[-_:]/)),i=f=>o.some(h=>f.test(h)),a=(i(Wm)||r.includes("-destroy")||r.includes("--destroy"))&&!i(Nm),l=["kubectl","oc","helm"].includes(s),c=l||Uc.has(s)||mn.has(s),u=t==="claude.bash.db.destructive",d=u||t==="claude.bash.deploy"?(l?a&&Dm(n):c?(a||u&&!/\bresets\b/.test(e.why))&&!L(n.argv,"--local"):a&&e.is_local===!1&&/read by its words/.test(e.why)&&i(Tm)&&!r.some(f=>qc.test(f)))||u&&(n.productionEnv||Kn.test(Gn(n))||zc(n).some(nr))||s==="heroku"&&r[1]==="run"&&/\b(db:(drop|reset|purge|schema:load)|flush|migrate:(fresh|reset|refresh)|ecto\.(drop|reset)|dropdb)\b/.test(r.join(" ")):t==="claude.bash.fs.delete_recursive"?r.some(f=>Im.test(f)):t==="claude.bash.secrets.print"&&(c||[e.target??"",...r,n.stdinFile??""].some(f=>Lm.test(v(f)))),p=c&&t!=="claude.bash.fs.delete_recursive"&&i(/^(credentials?|keys?|passwords?|tokens?|rbac)$/)&&i(/^(reset|create|rotate|new|regenerate|renew|for)$/)&&oe(n);return d||p?{...e,catastrophic:!0}:e}var zm=/(^|\/)(\.env(\.(?![\w.-]*\b(example|sample|template|tpl|tmpl|dist|defaults|schema)\b)[\w.-]+)?|\.envrc|[^/]*\.pem|[^/]*\.key|[^/]*\.p12|[^/]*\.pfx|[^/]*\.keystore|[^/]*\.jks|id_(rsa|dsa|ecdsa|ed25519)|\.npmrc|\.pypirc|\.netrc|\.git-credentials|credentials(\.json)?|[^/]*[-_.]credentials\.json|[^/]*service[-_]account[^/]*\.json|(key|keystore)\.properties|[\w-]*deploy[-_]key(\.pem)?|[^/]*serviceaccountkey[^/]*\.json|[^/]*\.p8|[^/]*keypair[^/]*\.json|\.config\/solana\/id\.json|\.dockercfg|kubeconfig(-[\w.-]+)?(\.(ya?ml|json|conf))?|[\w-]+[-_]kubeconfig(\.(ya?ml|json))?|\.pgpass|\.my\.cnf|credentials\.tfrc\.json|rclone\.conf|\.s3cfg|\.vault-token|\.dev\.vars|[^/]*firebase-admin[^/]*\.json|secrets?\.(ya?ml|json|toml)|terraform\.tfvars|authorized_keys|\.anvil\/workspace-keys\.json)$/i,Mm=/(^|\/)\.(aws|kube|docker|ssh|gnupg|config\/gh)\/(credentials|config(\.json)?|hosts\.yml|id_[a-z0-9_]+|[^/]*\.pem)$/i,Um=/(^|\/)\.ssh\/config$/;function po(e){return ye(e)&&!Um.test(v(e))}var qm=/(^|\/)\.ssh\/(?!known_hosts|authorized_keys|config$|environment$|rc$)[^/]+(?<!\.pub)$/;function ye(e){let n=v(e);return zm.test(n)||Mm.test(n)||qm.test(n)||Hm.test(n)&&!/\/memory(\/|$)/.test(n)}var Hm=/(^|\/)\.claude\/projects(\/[^/]+)?\/?$|(^|\/)\.claude\/projects\/[^/]+\/[^/]+\.jsonl$|(^|\/)\.claude\/projects\/[^/]+\/[^/]+\/subagents\/[^/]+\.jsonl$/,un=/(SECRET|TOKEN|PASSW(OR)?D|PASSPHRASE|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY|CREDENTIAL|AUTH|DSN|DATABASE_UR[IL]|DB_URL|REDIS_UR[IL]|POSTGRES(QL)?_UR[IL]|PG_?URL|MONGO(DB)?_UR[IL]|AMQP_URL|RABBITMQ_URL|CONNECTION_STRING|WEBHOOK_URL|CLIENT_SECRET|SIGNING|_PAT$|^PAT_|COOKIE|SESSION_KEY)/i,Hc=/^(PWD|OLDPWD|PATH|HOME|USER|SHELL|TERM|LANG|TMPDIR|LOGNAME|EDITOR|PAGER|HOSTNAME)$/;function oe(e){if(e.captured||e.redirects.some(r=>(r.op===">"||r.op===">>"||r.op==="&>"||r.op===">|"||r.op==="1>")&&(r.fd===null||r.fd===1)&&r.target&&!["/dev/stdout","/dev/tty","/dev/stderr"].includes(r.target)))return!1;let n=!1,t=e.pipeTo,s=!1;for(let r=e.pipeTo;r;r=r.pipeTo)if(t=r,r.name==="tee"&&(s=!0),r.name==="tee"&&r.argv.slice(1).some(o=>/^\/dev\/(stderr|tty|fd\/[12])$/.test(v(o))))return!0;if(t&&!s&&Rc(t))return!1;for(let r=e.pipeTo;r;r=r.pipeTo)if(["grep","rg","egrep"].includes(r.name)&&Vm(r.argv.slice(1))&&(n=!0),Bm(r)&&n||Bc(r)||r.redirects.some(o=>(o.op===">"||o.op===">>")&&(o.fd===null||o.fd===1)&&o.target&&o.target!=="/dev/stdout"))return!1;return e.parent?oe(e.parent):!0}function Bm(e){return e.name==="sed"&&/\[\^[^\]]*@[^\]]*\][*+]@/.test(e.argv.slice(1).join(" "))}function Vm(e){let n=e.find(s=>!s.startsWith("-"));if(!n)return!1;let t=n.replace(/[\^$()\\]/g,"").split("|").map(s=>s.trim().replace(/=$/,"")).filter(Boolean);return t.length>0&&t.every(s=>/^[A-Za-z0-9_]+$/.test(s)&&(/(URL|URI|DSN|POSTGRES|PG_?URL|REDIS|MONGO|DATABASE)/i.test(s)||/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/.test(s)&&!un.test(s)))}function Bc(e){let n=e.argv.slice(1),t=n.join(" ");switch(e.name){case"wc":case"sha256sum":case"shasum":case"md5":case"diff":case"cmp":return n.some(s=>s==="-q"||s==="--brief"||s==="--quiet");case"md5sum":case"pbcopy":case"xclip":case"true":return!0;case"grep":case"rg":case"egrep":return n.some(s=>/^-[a-zA-Z]*[clLq]/.test(s)||s==="--count"||s==="--quiet"||s==="--files-with-matches")||Zm(n)||Gm(n);case"cut":return/-d\s*=?\s*'?=/.test(t.replace(/\s+/g," "))&&/-f\s*1\b|-f1\b/.test(t);case"awk":return/\{\s*print\s+\$1\s*\}/.test(t)&&/-F\s*'?=|-F=/.test(t);case"sed":return/\bs([/|#,])=\.[*+]\$?\1[^\\&]*\1/.test(t);case"jq":return/\bkeys\b|\blength\b|\bhas\(/.test(t);case"node":case"python":case"python3":case"ruby":return/\bkeys\b|Object\.keys|\.keys\(\)|length/.test(t+(e.stdin??""));case"head":return n.includes("-c")&&n[n.indexOf("-c")+1]==="0";default:return!1}}function Zm(e){let n=e.find(s=>!s.startsWith("-"));if(!n)return!1;let t=n.replace(/[\^$()\\]/g,"").split("|").map(s=>s.trim().replace(/=$/,"")).filter(Boolean);return t.length>0&&t.every(s=>/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/.test(s)&&!un.test(s))}function Gm(e){if(!e.some(s=>/^-[a-zA-Z]*o[a-zA-Z]*$/.test(s)||s==="--only-matching"))return!1;let n=e.find(s=>!s.startsWith("-")),t=n?.endsWith("=")?n.slice(0,-1):n;return t!==void 0&&!/\.|\\S|\[\^|=|\\w\*/.test(t)}var Js=new Set(["cat","head","tail","less","more","bat","nl","tac","strings","grep","rg","egrep","sed","awk","cut","sort","uniq","xxd","od","base64","jq","yq","column","pr","paste","fold","rev","fmt","expand","unexpand","iconv","tr","tee","diff","hexdump","hd","comm"]);function Km(e,n){let t=n.secretCopies,s=e.argv,r=e.name,o=s.slice(1);if(r==="printenv"||(r==="env"||r==="set"||r==="export"||r==="declare")&&o.every(d=>d.startsWith("-")&&d!=="-c"))return r==="printenv"&&o.filter(d=>!d.startsWith("-")).length>0&&!o.some(d=>!d.startsWith("-")&&un.test(d))?[]:(r==="export"||r==="declare")&&!o.some(d=>d==="-p"||d==="-x"||o.length===0)?[]:r==="set"&&o.length>0?[]:!oe(e)||ty(e)==="no-secret"?[]:[m("claude.bash.secrets.print",`${r} prints the environment, secrets included`,{target:r,is_local:!0})];let i=d=>po(d)||t.has(Y(d,e.cwd,te(n)).path),l=(r==="xargs"?s.find((d,p)=>s[p-1]==="-a"||s[p-1]==="--arg-file")??s.find(d=>d.startsWith("--arg-file="))?.slice(11)??s.find(d=>/^-a./.test(d))?.slice(2):void 0)??e.stdinFile;if((r==="exec"||r==="xargs")&&l&&i(l))return[m("claude.bash.secrets.print",`${r==="exec"?"feeds a secrets file to the commands after it":"passes a secrets file to a command"} (${R.basename(v(l))})`,{target:v(l),is_local:!0})];if(r==="git"&&s.includes("--no-index")&&s.slice(1).some(d=>!d.startsWith("-")&&i(d))&&oe(e)){let d=s.slice(1).find(p=>!p.startsWith("-")&&i(p));return[m("claude.bash.secrets.print",`prints a secrets file (${R.basename(v(d))})`,{target:v(d),is_local:!0})]}let c=r==="dd"?s.find(d=>d.startsWith("if="))?.slice(3):void 0,u=s.find(d=>d.startsWith("of="))?.slice(3);if(c&&i(c)&&(u===void 0?oe(e):["/dev/stdout","/dev/stderr","/dev/tty","/dev/fd/1","/dev/fd/2"].includes(u)))return[m("claude.bash.secrets.print",`prints a secrets file (${R.basename(v(c))})`,{target:v(c),is_local:!0})];if(Js.has(r)){let d=["-","/dev/stdin","/dev/fd/0"],p=r==="tr"||r==="tee"?[]:Ut(e).filter(P=>!d.includes(P)),f=r==="tr"||r==="tee"||e.argv.slice(1).some(P=>d.includes(P))||Ut(e).length===0,h=e.stdinFile!==null&&f?[...p,e.stdinFile]:p,g=["sed","gsed"].includes(r)&&e.argv.slice(1).some(P=>/^(-i\S*|--in-place(=.*)?|-[A-Za-z]*i)$/.test(v(P)))||/^g?awk$/.test(r)&&/(^| )(-i ?|--include[= ])inplace\b/.test(e.argv.map(v).join(" ")),y=h.filter(P=>(g?ye(P):po(P))||t.has(Y(P,e.cwd,te(n)).path)),$=r==="tee"&&Ut(e).some(P=>["/dev/stderr","/dev/tty","/dev/fd/2","/dev/stdout"].includes(P)),E=["sed","gsed"].includes(r)&&e.argv.slice(1).some(P=>/^(-i\S*|--in-place(=.*)?|-[A-Za-z]*i)$/.test(v(P))),_=P=>Y(P,e.cwd,te(n)).path||v(P);if(y.length&&E)return y.slice(0,8).map(P=>m("claude.file.write_secret",`edits a secrets file in place (${R.basename(v(P))})`,{target:_(P),is_local:!0}));if(y.length&&(oe(e)||$)&&!Bc({...e,pipeTo:null}))return y.slice(0,8).map(P=>m("claude.bash.secrets.print",`prints a secrets file (${R.basename(v(P))})`,{target:_(P),is_local:!0}));let k=e.stdinExpands&&oe(e)?gl(e.stdin??"",e,n):null;return k?[m("claude.bash.secrets.print",`prints a secret through $(\u2026) (${R.basename(k)})`,{target:k,is_local:!0})]:[]}if(r==="security"&&/^find-(generic|internet)-password$/.test(o[0]??"")&&o.some(d=>d==="-w"||d==="-g"||/^-[a-z]*[wg]$/.test(d)))return oe(e)?[m("claude.bash.secrets.print","prints a keychain password",{target:"keychain",is_local:!0})]:[];if(r==="kubectl"&&["get","describe"].includes(w(s)[0]??"")&&/^secrets?$/.test(w(s)[1]??"")&&s.some((d,p)=>/^-o(yaml|json|jsonpath|go-template)|^--output/.test(d)||["yaml","json"].includes(d)||/^(jsonpath|go-template|custom-columns)=/.test(d)||s[p-1]==="-o"&&/^(yaml|json|jsonpath|go-template)/.test(d)))return oe(e)?[m("claude.bash.secrets.print","kubectl prints a secret",{target:"kubectl secret",is_local:!1})]:[];if(r==="op"&&(o[0]==="read"||o[0]==="item"&&o.includes("--reveal"))||r==="vault"&&(o[0]==="read"||o[0]==="kv"&&o[1]==="get")||r==="doppler"&&o[0]==="secrets"&&(o.length===1||["get","download"].includes(o[1]??"")||(o[1]??"").startsWith("-"))||r==="infisical"&&(o[0]==="secrets"&&(o.length===1||o[1]==="get"||o[1].startsWith("-"))||o[0]==="export"&&!s.some(d=>d.startsWith("--output-file")))||r==="az"&&w(s)[0]==="keyvault"&&w(s)[1]==="secret"&&w(s)[2]==="show"||r==="dotenv"&&["list","get"].includes(ce(s,1,new Set(["-f","--file","-e","-c","-v","-p"]))[0]??""))return oe(e)?[m("claude.bash.secrets.print",`${r} prints a secret`,{target:r,is_local:!0})]:[];if((r==="echo"||r==="printf"||r==="print"||e.stdinKind==="here-string"&&Js.has(r))&&oe(e)){let d=[...s.slice(1),e.stdinKind==="here-string"?e.stdin??"":""].map(p=>gl(p,e,n)).find(p=>p!==null);if(d)return[m("claude.bash.secrets.print",`prints a secret through $(\u2026) (${R.basename(d)})`,{target:d,is_local:!0})]}if(r==="echo"||r==="printf"||r==="print"){let d=Vc(e.text);for(let p of d.matchAll(/\$(?:\{(#?)([A-Za-z_][A-Za-z0-9_]*)([^}]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g)){let f=p[2]??p[4],h=p[3]??"";if(!(p[1]==="#"||/^:?\+/.test(h)||/^:\s*0?\s*:\s*[1-8]$/.test(h))&&un.test(f.replace(/AUTHOR(?!IZ)/gi,""))&&!Hc.test(f)&&oe(e))return[m("claude.bash.secrets.print",`echoes a secret variable (${f})`,{target:f,is_local:!0})]}}return[]}function Ym(e){let n=[];for(let t=0;t<e.length;t++)if(e[t]==="`"){let s=e.indexOf("`",t+1);if(s<0)break;n.push(e.slice(t+1,s)),t=s}else if(e[t]==="$"&&e[t+1]==="("){let s=0,r=t+1;for(;r<e.length;r++)if(e[r]==="(")s++;else if(e[r]===")"&&--s===0)break;n.push(e.slice(t+2,r)),t=r}return n}function gl(e,n,t){if(!e.includes("$(")&&!e.includes("`"))return null;for(let s of Ym(e)){let r=s.trim(),o=/^<\s*["']?([^"'\s]+)["']?$/.exec(r);if(o){if(ye(o[1]))return o[1];continue}for(let i of Yn(r,n.cwd,t).commands){let a=Zn(i,t).find(l=>l.action==="claude.bash.secrets.print"&&!l.why.startsWith("echoes a secret variable"));if(a)return a.target??i.name}}return null}function Ut(e){let n=e.argv.slice(1),t=n.filter((o,i)=>!o.startsWith("-")&&!["-e","-f","--regexp","--file","-m","-A","-B","-C","--max-count"].includes(n[i-1]??"")),s=n.some(o=>o==="-e"||o==="--regexp"||o.startsWith("--regexp=")||o==="-f"||o==="--file");return["grep","rg","egrep","sed","awk","jq","yq"].includes(e.name)&&!(e.name!=="sed"&&e.name!=="awk"&&e.name!=="jq"&&e.name!=="yq"&&s)&&!(e.name==="sed"&&s)?t.slice(1):t}var Jm=/(^|\/)(public|static|www|htdocs|wwwroot|public_html)(\/|$)/;function Xm(e,n){if(["cp","mv","install","rsync","ditto"].includes(e.name)){let t=e.argv.slice(1).filter(o=>!o.startsWith("-")),s=t.at(-1),r=t.slice(0,-1).find(o=>ye(o));if(s!==void 0&&r!==void 0&&!C(s)&&Jm.test(U(s,e.cwd,n.ctx))&&qe(s,e,n).kind!=="disposable")return[m("claude.bash.secrets.expose",`copies a secrets file (${R.basename(v(r))}) into a folder a web server serves (${v(s)})`,{target:v(s),is_local:!0})]}if(["echo","printf","print"].includes(e.name)){let t=e.redirects.find(s=>[">",">>",">|","1>","&>"].includes(s.op)&&(s.fd===null||s.fd===1)&&s.target)?.target;if(t&&!t.startsWith("/dev/")&&!C(t)&&!ye(t)&&!rt.test(t)){let s=[...Vc(e.text).matchAll(/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g)].map(r=>r[1]??r[2]).find(r=>un.test(r)&&!Hc.test(r));if(s!==void 0&&qe(t,e,n).kind!=="disposable")return[m("claude.bash.secrets.expose",`writes the value of ${s} into ${R.basename(v(t))}`,{target:v(t),is_local:!0})]}}return[]}var Qm=/\.(pem|key|crt|cer|der|p12|pfx|jks|keystore|p8)$/i;function ey(e,n){let t=n.replace(/(?<!\/)\/+$/,""),s=e.startsWith(`${t}/`)?e.slice(t.length+1):null;return s!==null?/^\.(ssh|aws|kube|gnupg|docker|azure|oci|helm|minikube|config\/(gcloud|gh|helm|doctl))(\/|$)/.test(s):/^\/(etc|usr|System|Library|private\/etc|opt\/homebrew\/etc|var\/lib)(\/|$)/.test(e)||!e.startsWith("/")}function Vc(e){let n="",t=!1;for(let s=0;s<e.length;s++){let r=e[s];if(r==="\\"&&!t)n+=e.slice(s,s+2),s++;else if(r==='"')t=!t,n+=r;else if(r==="'"&&!t){let o=e.indexOf("'",s+1),i=o===-1?e.length:o;n+=" ".repeat(i-s+1),s=i}else n+=r}return n}function ty(e){let n=e.pipeTo;if(!n||!["grep","rg","egrep"].includes(n.name))return"none";let t=n.argv.slice(1).find(s=>!s.startsWith("-"))??"";return un.test(t)||t===""?"secret":"no-secret"}function ml(e,n){let t=[];for(let u of e.redirects)[">",">>","&>",">|","1>"].includes(u.op)&&u.target&&t.push(u.target);e.name==="tee"&&t.push(...e.argv.slice(1).filter(u=>!u.startsWith("-")));let s=e.argv.slice(1).flatMap(u=>u==="--no-clobber"||/^--update=none(-fail)?$/.test(u)?["n"]:u==="--force"?["f"]:u==="--interactive"?["i"]:/^-[A-Za-z]+$/.test(u)?[...u.slice(1)].filter(d=>"nfi".includes(d)):[]).pop(),r=(e.name==="cp"||e.name==="mv")&&s==="n";(e.name==="cp"||e.name==="mv"||e.name==="install")&&e.argv.length>=3&&!r&&t.push(e.argv[e.argv.length-1]);let o=u=>{let d=R.basename(v(u)).toLowerCase();return/\.(pem|crt|cer)$/.test(d)&&/(^|[-_.])(ca|cacert|cert|certs|certificate|certificates|chain|fullchain|bundle|root|intermediate|public|pub)([-_.]|$)/.test(d)&&!/key|priv|secret|p12|pfx|keystore|jks|id_/.test(d)},i=u=>{let d=Y(u,e.cwd,te(n)).path,p=n.projectRoot&&!C(n.projectRoot)?n.projectRoot.replace(/(?<!\/)\/+$/,""):null,f=n.ctx.home.replace(/(?<!\/)\/+$/,"");return p!==null&&p!==""&&p!=="/"&&p!==f&&!f.startsWith(`${p}/`)&&d.startsWith(`${p}/`)},a=t.find(u=>ye(u)&&!u.startsWith("/dev/")&&!(o(u)&&i(u)));if(!a)return[];if(qe(a,e,n).kind==="disposable")return[];let c=R.basename(v(a));return Qm.test(c)&&e.remote===null&&!ey(Y(a,e.cwd,te(n)).path,n.ctx.home)?[]:[m("claude.file.write_secret",`writes ${/\.(pem|crt|cer|der|p12|pfx|key)$/i.test(c)?"a key or certificate file":"a secrets file"} (${c})`,{target:v(a),is_local:!0})]}function Us(e,n){let t=e.findIndex((s,r)=>r>0&&new RegExp(`^-[A-Za-z]*${n}$`).test(s));return t>0?e[t+1]??null:null}function dn(e){let n=v(e).replace(/^["']|["']$/g,"");return/^[a-z][a-z0-9+.-]*:\/\//i.test(n)||/^[\w.-]+\.[a-z]{2,}\//i.test(n)?de(n)??n.replace(/\/.*/,""):n.replace(/(:\/\/)[^@/\s]+@/g,"$1***@")}function j(e,...n){for(let t=1;t<e.length;t++){let s=e[t];for(let r of n){if(s===r&&e[t+1]!==void 0)return e[t+1];if(r.startsWith("--")&&s.startsWith(`${r}=`))return s.slice(r.length+1);if(!r.startsWith("--")&&r.length===2&&s.startsWith(r)&&s.length>2)return s.slice(2)}}return null}function Te(e,n=!1){let t=v(e).replace(/(?<!\/)\/+$/,""),s=R.basename(t);return/\.(enc|sops|encrypted|gpg|age|asc)(\.[\w-]+)?$|\.enc\.|\.sops\./i.test(s)||/^(package(-lock)?\.json|tsconfig[\w.-]*\.json|readme[\w.-]*|license[\w.-]*|changelog[\w.-]*|\.gitkeep|\.keep|\.gitignore)$/i.test(s)||n&&/^\.(npmrc|envrc)$/.test(s)||/(^|\/)templates\//.test(t)&&/^secrets?\.ya?ml$/.test(s)||s==="debug.keystore"||/\.(pem|crt)$/i.test(s)&&/(bundle|chain|cacert|ca-cert|^ca[-_.]|root|intermediate|cert|public|pub)/i.test(s)&&!/key|priv/i.test(s)?!1:/^[^/]+\.env$/.test(s)&&!/^(example|sample|template|tpl)\.env$/i.test(s)?!0:ye(t)||ye(t.replace(/\*+$/,""))||/(^|\/)\.(ssh|aws|gnupg|kube|docker|config\/gh)$|(^|\/)(secrets?|credentials)$/i.test(t)||/(^|\/)(secrets?|credentials)\//i.test(t)&&(!/\./.test(s)||/\.(json|ya?ml|env|toml|ini|txt|pem|key|p12|pfx|crt|cer|properties|conf|cfg|xml|plist|csv|jks|keystore)$/i.test(s))}var ny=/^\/\.claude(\/settings(\.local)?\.json|\/hooks(\/.*)?|\/plugins(\/.*)?)?$|^\/\.claude\.json$|^\/\.mcp\.json$|^\/\.anvil(\/claude(\/.*)?|\/rules\.(?:json|md)|\/workspace-keys\.json|\/telemetry-notice)?$/i,sy=/(^|\/)managed-(settings|mcp)\.json$/i,ry=/(^|\/)library\/launch(agents|daemons)(\/|$)|^\/etc\/systemd\/|(^|\/)\.config\/systemd\/user(\/|$)|^\/(usr\/)?lib\/systemd\/system(\/|$)|^\/etc\/cron(\.(d|hourly|daily|weekly|monthly)(\/|$)|tab$)|^\/(private\/)?(var\/spool\/cron|usr\/lib\/cron\/tabs)(\/|$)/;function Io(e,n,t=[]){return Do(e,n,t).place}function Do(e,n,t=[]){let s=Jr(e,n,t);if(s==="agent")return{place:s,at:e};let r=c=>{for(let[u,d]of Object.entries(n.controlLinks??{})){if(C(c)||!(c===u||c.startsWith(`${u}/`)))continue;let p=d+c.slice(u.length);if(Jr(p,n,t)==="agent")return p}return null},o=r(e);if(o!==null)return{place:"agent",at:o};if(!n.onDisk)return{place:s,at:e};let i=bs(e,n.onDisk,!0),a=i!==null?r(i):null;if(a!==null)return{place:"agent",at:a};let l=i===null?null:Jr(i,n,t);return i!==null&&(l==="agent"||s===null)?{place:l,at:i}:{place:s,at:e}}function Jr(e,n,t){let s=v(e),r=t.filter(u=>u!==null&&u!==""&&!C(u)),o=s.toLowerCase();if((r.length>1?[...new Set(r)].map(u=>o.startsWith(`${u.toLowerCase()}/`)?s.slice(u.length):null).filter(u=>u!==null):[s.replace(/^.*(?=\/\.claude(\/|\.json$|$)|\/\.mcp\.json$|\/\.anvil(\/|$))/,"")]).some(u=>ny.test(u))||sy.test(s))return"agent";let a=n.claudeConfigDir?.replace(/(?<!\/)\/+$/,"").toLowerCase();if(a&&(o===a||o===`${a}/settings.json`||o===`${a}/settings.local.json`||o===`${a}/.claude.json`||o===`${a}/hooks`||o.startsWith(`${a}/hooks/`)||o===`${a}/plugins`||o.startsWith(`${a}/plugins/`)))return"agent";let l=R.dirname(s);if(Oo(l)||Y(l,null,{home:n.home,tmpdir:n.tmpdir,projectRoot:null}).kind==="disposable")return null;if(ry.test(s.toLowerCase()))return"jobs";let c=n.home;return[`${c}/.gitconfig`,`${c}/.config/git/config`,"/etc/gitconfig"].some(u=>u.toLowerCase()===o)?"gitconfig":null}function oy(e,n){let t=[],s=i=>{i&&i!=="-"&&!i.startsWith("/dev/")&&t.push(U(Ie(i,e,n),e.cwd,n.ctx))};for(let i of e.redirects)i.target&&i.op.includes(">")&&!(i.op.endsWith("&")&&/^(\d+|-)$/.test(i.target))&&s(i.target);let r=e.argv.slice(1),o=r.filter(i=>!i.startsWith("-"));switch(e.name){case"tee":case"sponge":case"truncate":case"rm":case"unlink":case"trash":case"srm":case"shred":case"mkfifo":o.forEach(s);break;case"mknod":o[0]&&s(o[0]);break;case"touch":for(let i=0;i<r.length;i++)/^(-[tdrA]|--(date|reference|time))$/.test(r[i])?i++:r[i].startsWith("-")||s(r[i]);break;case"cp":case"mv":case"install":case"ln":case"ditto":case"gcp":case"gmv":{let i=j(e.argv,"-t","--target-directory"),a=i!==null?o.filter(c=>c!==i):o.slice(0,-1),l=i??(o.length>=2?o[o.length-1]:e.name==="ln"&&o.length===1?".":null);if(l!==null){s(l);for(let c of a)s(R.join(l,R.basename(v(c))))}e.name==="ln"&&a.forEach(s),(e.name==="mv"||e.name==="gmv")&&a.forEach(s);break}case"sed":case"gsed":case"perl":case"ruby":case"yq":{if(!r.some(c=>c==="--in-place"||c.startsWith("--in-place=")||c==="--inplace"||/^-[A-Za-z]*i/.test(c)&&!c.startsWith("--")))break;let a=[],l=!1;for(let c=0;c<r.length;c++){let u=r[c];["-e","--expression","-f","--file"].includes(u)||(e.name==="perl"||e.name==="ruby")&&/^-[A-Za-z]*e$/.test(u)?(l=!0,c++):u.startsWith("-")||a.push(u)}(l?a:a.slice(1)).forEach(s);break}case"dd":s(r.find(i=>i.startsWith("of="))?.slice(3));break;case"chmod":case"chown":case"chgrp":case"chflags":if(e.name==="chmod"){let i=r.filter(a=>!/^-[RHLPfhvcECNiI]+$/.test(a)&&!a.startsWith("--"));(r.some(a=>a.startsWith("--reference"))?i:i.slice(1)).forEach(s)}else(r.some(i=>i.startsWith("--reference"))?o:o.slice(1)).forEach(s);break;case"curl":s(j(e.argv,"-o","--output")??Us(e.argv,"o"));break;case"scp":{let i=new Set(["-P","-i","-F","-o","-c","-l","-S","-J","-D","-X"]),a=r.filter((c,u)=>!c.startsWith("-")&&!i.has(r[u-1]??"")),l=a.length>=2?a[a.length-1]:null;l!==null&&!/^[^/]*:/.test(l)&&s(l);break}case"wget":s(j(e.argv,"-O","--output-document")??Us(e.argv,"O")??j(e.argv,"-P","--directory-prefix"));break;case"rsync":{let i=ce(e.argv,1,Fo),a=i.length>=2?i[i.length-1]:null;if(a!==null&&!Le(a)){s(a);for(let l of i.slice(0,-1))s(R.join(a,R.basename(v(l).replace(/(?<!\/)\/+$/,""))))}break}case"tar":case"gtar":case"bsdtar":case"unzip":{let i=e.name==="unzip"?j(e.argv,"-d"):j(e.argv,"-C","--directory");(e.name==="unzip"?!r.some(l=>/^-[A-Za-z]*[ltpZ]/.test(l)):r.some(l=>/^-?[A-Za-z]*x/.test(l)||l==="--extract"||l==="--get"))&&s(i??".");break}case"7z":case"7za":case"7zr":case"7zz":["x","e"].includes(o[0]??"")&&s(r.find(i=>i.startsWith("-o"))?.slice(2)||".");break;case"sort":s(j(e.argv,"-o","--output")??Us(e.argv,"o"));break;case"base64":s(j(e.argv,"-o","--output"));break;case"openssl":s(j(e.argv,"-out"));break;case"awk":case"gawk":case"mawk":case"nawk":{let i=Tr(e.argv)??"";if(r.some((a,l)=>a==="-i"&&r[l+1]==="inplace"||a==="-iinplace"||a==="--include=inplace")){let a=ce(e.argv,1,new Set(["-i","--include","-F","-v","-f","-e","-l"]));(i&&a[0]===i?a.slice(1):a).forEach(s)}for(let a of i.matchAll(/\b(?:print|printf)\b(?:"(?:\\.|[^"\\])*"|[^;}|"])*?>{1,2}\s*"((?:\\.|[^"\\])+)"/g))s(a[1]);break}case"ed":case"red":case"ex":case"vi":case"vim":case"nvim":case"emacs":{if(r.some(a=>a==="-R"||a==="-M"||a==="--read-only")||e.name==="emacs"&&!r.some(a=>a==="--batch"||a==="-batch"||a==="--script"))break;let i=e.name==="ed"||e.name==="red"?new Set(["-p"]):new Set(["-c","--cmd","-S","-u","-U","-i","-T","-w","-W","-t","-q","--eval","-l","--load","-f","--funcall","--script"]);ce(e.argv,1,i).filter(a=>!a.startsWith("+")).forEach(s);break}case"patch":s(ce(e.argv,1,new Set(["-i","--input","-p","-d","-o","--output","-r","-B","-z","-V","-F"]))[0]);break;case"plutil":r.some(i=>/^-(replace|insert|remove|convert)$/.test(i))&&s(o[o.length-1]);break;case"git":{let i=xt(e);if(i&&i.sub==="clone"&&s(ce(["git",...i.args],1,new Set(["-b","--branch","-o","--origin","--depth","-c","--config","--reference","--template","-j","--jobs","--filter"]))[1]),i&&["checkout","restore"].includes(i.sub)){let a=i.args.indexOf("--");(i.sub==="restore"&&i.args.some(u=>u==="--staged"||u==="-S")&&!i.args.some(u=>u==="--worktree"||u==="-W")?[]:a>=0?i.args.slice(a+1):i.sub==="restore"?i.args.filter(u=>!u.startsWith("-")):[]).forEach(s)}break}default:break}return t}var Zc=/permissionMode:\s*['"]?bypassPermissions\b|allowed-tools:[^\n]*\bBash(\(\*\))?(?![\w(])|allowed-tools:[ \t]*\n(?:[ \t]*-[^\n]*\n)*?[ \t]*-[ \t]*['"]?Bash(\(\*\))?['"]?[ \t]*(?:\n|$)/;function yl(e){if(!e||typeof e!="object")return"";let n=e,t=Array.isArray(n.edits)?n.edits.map(s=>s&&typeof s=="object"&&typeof s.new_string=="string"?s.new_string:""):[];return[n.content,n.new_string,...t].filter(s=>typeof s=="string").join(`
|
|
59
|
-
`)}function
|
|
60
|
-
`))}var
|
|
61
|
-
`):
|
|
62
|
-
`):null),s=(e.groupWriters??[]).map(r=>
|
|
63
|
-
`);return
|
|
27
|
+
`))}if(a===null)return;let i=M(o,e.cwd,n);t.files.set(i,s?.op===">>"?(t.files.get(i)??"")+a:a)}function Pf(e,t,n){if(t.files.size===0&&!n.wantFiles&&!n.unreadableFiles?.length)return null;let s=l=>l&&!S(l)?M(l,e.cwd,n):null,r=l=>{let c=s(l),u=c===null?void 0:t.files.get(c);return u===void 0&&c!==null&&!S(c)&&(n.wantFiles?.add(c),n.unreadableFiles?.includes(c)&&(e.unreadableCode=`${ue(c)}, a script this session wrote that could not be read`)),u===void 0||c===null?null:{text:u,path:c}};if(e.argv[0].includes("/")){let l=r(e.argv[0]);if(l!==null){let c=/^#!\s*(\S+)(?:\s+(\S+))?/.exec(l.text),u=c?ue(c[1])==="env"?c[2]??"":ue(c[1]):"sh";return{...l,shell:Yt.has(u),direct:!0}}}if(e.name==="source"||e.name==="."){let l=r(e.argv[1]);return l===null?null:{...l,shell:!0,direct:!1}}let o=e.argv.slice(1),a=o.slice(0,Math.max(0,o.findIndex(l=>!l.startsWith("-"))));if(Yt.has(e.name)&&a.some(l=>/^-[a-zA-Z]*n[a-zA-Z]*$/.test(l))||e.name==="node"&&a.some(l=>l==="--check"||l==="-c")||["ruby","perl"].includes(e.name)&&a.includes("-c")||e.name==="php"&&a.includes("-l"))return null;if(Yt.has(e.name)||tf.has(e.name)){let l=e.name==="deno"&&e.argv.slice(1).find(u=>!u.startsWith("-"))==="run"?e.argv.slice(2).find(u=>!u.startsWith("-")):e.argv.slice(1).find(u=>!u.startsWith("-")),c=r(l);return c===null?null:{...c,shell:Yt.has(e.name),direct:!1}}return null}function Wf(e,t){let n="",s=t,r=0;for(;r<e.length;){let o=e[r];if(s){o==='"'?(s=!1,r++):o==="\\"&&r+1<e.length&&'$`"\\\n'.includes(e[r+1])?(e[r+1]!==`
|
|
28
|
+
`&&(n+=e[r+1]),r+=2):(n+=o,r++);continue}if(o==="'"){let a=e.indexOf("'",r+1),i=a===-1?e.length:a;n+=e.slice(r+1,i),r=i+1;continue}if(o==="$"&&e[r+1]==="'"){let a=Nf(e,r+2);n+=a.text,r=a.next;continue}if(o==='"'){s=!0,r++;continue}if(o==="\\"){r+1<e.length&&e[r+1]!==`
|
|
29
|
+
`&&(n+=e[r+1]),r+=2;continue}n+=o,r++}return{text:n,inDouble:s}}function Nf(e,t){let n={n:`
|
|
30
|
+
`,t:" ",r:"\r","\\":"\\","'":"'",'"':'"',a:"\x07",b:"\b",e:"\x1B",E:"\x1B",f:"\f",v:"\v",0:"\0"},s="",r=t;for(;r<e.length&&e[r]!=="'";){if(e[r]==="\\"&&r+1<e.length){let o=e[r+1];if(o==="x"){let a=/^[0-9a-fA-F]{1,2}/.exec(e.slice(r+2))?.[0]??"";s+=a?String.fromCharCode(parseInt(a,16)):"x",r+=2+a.length;continue}s+=n[o]??o,r+=2;continue}s+=e[r],r++}return{text:s,next:r+1}}var On="what this session made earlier";function ks(e,t,n){if(!t||S(e)||!e.startsWith("/"))return null;let s=n?"full":"parent";t.touched?.[s].add(e);let r=t.real?.[s][e];return r!==void 0&&r!==e?r:null}var la={catastrophic:3,normal:2,disposable:1},ua=new Set(["node_modules","dist","build","out",".next",".nuxt",".output",".svelte-kit",".turbo",".parcel-cache",".vite",".cache","coverage",".nyc_output","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".venv","venv","target",".gradle","tmp",".tmp","temp",".vscode-test",".vscode-test-web","test-results","playwright-report","storybook-static",".docusaurus",".angular",".expo",".astro",".wrangler",".serverless",".terraform",".dart_tool",".stack-work","htmlcov",".hypothesis",".benchmarks",".pnpm-store",".webpack",".esbuild",".vinxi",".contentlayer",".velite",".nx",".yarn-cache",".eslintcache",".vitest-reports"]),Lf=/^\.?(tmp|temp)([-_.].*)?$|[-_.](tmp|temp)$/i,da=new Set(["Desktop","Documents","Downloads","Library","Pictures","Movies","Music","Applications","Public",".ssh",".gnupg",".aws",".config",".claude",".local",".kube",".docker"]),fa=new Set(["/bin","/sbin","/usr","/etc","/var","/opt","/System","/Library","/Applications","/Users","/private","/Volumes","/home","/root","/lib","/boot","/srv","/cores","/dev"]);function pa(e){let t=["/tmp","/private/tmp","/var/tmp","/private/var/tmp","/var/folders","/private/var/folders"],n=e.tmpdir.replace(/(?<!\/)\/+$/,"");return n&&t.push(n,n.startsWith("/private/")?n.slice(8):`/private${n}`),V()&&t.push("/c/windows/temp"),t}function Tf(e,t){if(Fi(e))return{kind:"catastrophic",path:e,token:"fs.root",why:e.startsWith("/unc/")?`a network share (${us(e)})`:`the drive ${us(e)}`};let n=/^\/[a-z]\/(.+)$/s.exec(e);return n&&Er.includes(n[1])?{kind:"catastrophic",path:e,token:"fs.system",why:`the system folder ${us(e)}`}:xe.dirname(e)===t&&Rr.has(xe.basename(e))?{kind:"catastrophic",path:e,token:"fs.home",why:`the ${xe.basename(e)} folder in home`}:null}var If=[..."abcdefghijklmnopqrstuvwxyz"].map(e=>`/${e}`).concat(Er.map(e=>`/c/${e}`)),ha=(e,t)=>e===t||e.startsWith(t.endsWith("/")?t:`${t}/`);function X(e,t,n){let s=ca(e,t,n);if(!n.onDisk)return s;let r=M(e,t??n.base??n.projectRoot,n),o=xe.basename(e.replace(/(?<!\/)\/+$/,"")),a=ks(r,n.onDisk,e.endsWith("/")||/[*?[]/.test(o));if(a===null)return s;let i=ca(a,null,n);return la[i.kind]>la[s.kind]?{...i,why:`${i.why}, through a link`}:s}function ca(e,t,n){let s=M(e,t??n.base??n.projectRoot,n),r=s.replace(new RegExp(`[${ie}${le}]`,"g"),"");return s.startsWith("/dev/")&&!["/dev/null","/dev/stdout","/dev/stderr","/dev/tty"].includes(s)&&!cs(s)?{kind:"catastrophic",path:r,token:"fs.device",why:`a raw device (${r})`}:S(s)?zf(s,r,n,t??n.base??null):ga(s,n)}function Df(e){let t="",n=!1;for(let r=0;r<e.length;r++){let o=e[r];if(o==="*"||o==="?"){t+=o==="*"?"[^/]*":"[^/]",n=!0;continue}if(o==="["){let a=e.indexOf("]",r+(e[r+1]==="!"||e[r+1]==="^"?3:2));if(a>r){let i=e.slice(r+1,a),l=i.startsWith("!")||i.startsWith("^"),c=(l?i.slice(1):i).replace(/[\\\]^]/g,"\\$&");t+=`[${l?"^/":""}${c}]`,n=!0,r=a;continue}}t+=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}if(!n)return null;let s;try{s=new RegExp(`^${t}$`,"s")}catch{return()=>!1}return r=>(!r.startsWith(".")||e.startsWith("."))&&s.test(r)}function Ff(e,t){let n=e.split("/").filter(Boolean),s=n.map(Df);if(s.every(i=>i===null))return null;let r=t.home.replace(/(?<!\/)\/+$/,""),o=t.projectRoot&&!S(t.projectRoot)?t.projectRoot.replace(/(?<!\/)\/+$/,""):null,a=[];if(o){a.push(`${o}/.git`);for(let i=o;i.length>1;i=xe.dirname(i))a.push(i)}r&&a.push(r,...[...V()?Rr:da].map(i=>`${r}/${i}`)),a.push(...fa),V()&&a.push(...If);for(let i of a){let l=i.split("/").filter(Boolean);if(l.length!==n.length||!l.every((p,d)=>s[d]?s[d](p):p===n[d]))continue;let c=ga(i,t),u=e.split("/"),f=u.slice(Math.max(0,u.findIndex(p=>/[*?[]/.test(p)))).join("/");if(c.kind==="catastrophic")return{...c,path:e,why:`${c.why} (${f} matches it)`}}return null}function ga(e,t){if(/[*?[]/.test(e)){let o=Ff(e,t);if(o)return o}let n=t.home.replace(/(?<!\/)\/+$/,"");if(e==="/"||e==="")return{kind:"catastrophic",path:"/",token:"fs.root",why:"the filesystem root"};if(V()){let o=Tf(e,n);if(o)return o}if(e===n)return{kind:"catastrophic",path:e,token:"fs.home",why:"the home folder"};if(xe.dirname(e)===n&&da.has(xe.basename(e)))return{kind:"catastrophic",path:e,token:"fs.home",why:`the ${xe.basename(e)} folder in home`};for(let o of pa(t)){if(ha(e,o)&&e!==o)return{kind:"disposable",path:e,token:null,why:"a temp folder"};if(e===o)return{kind:"catastrophic",path:e,token:"fs.system",why:`the system temp root ${o}`}}if(/\/scratchpad(\/|$)/.test(e))return{kind:"disposable",path:e,token:null,why:"a session scratchpad"};if(e.startsWith(`${n}/Library/Caches/`))return{kind:"disposable",path:e,token:null,why:"an app cache folder"};if(xe.basename(e)===".git")return{kind:"catastrophic",path:e,token:"fs.git_dir",why:"a .git folder (the repository history)"};if(t.projectRoot&&e===t.projectRoot.replace(/(?<!\/)\/+$/,"")&&e!==n)return{kind:"catastrophic",path:e,token:"fs.project_root",why:"the project root"};if(t.projectRoot&&t.projectRoot.replace(/(?<!\/)\/+$/,"").startsWith(`${e}/`)&&e!==n)return{kind:"catastrophic",path:e,token:"fs.project_root",why:`a folder holding the project (${e})`};let s=e.split("/").filter(Boolean);if(s.some(o=>ua.has(o)))return{kind:"disposable",path:e,token:null,why:"build or cache output"};if(/\.tsbuildinfo$/.test(xe.basename(e)))return{kind:"disposable",path:e,token:null,why:"build output"};if(xe.basename(e)===".auth"&&/(^|\/)(e2e|playwright|tests?|cypress)(\/|$)/.test(xe.dirname(e)))return{kind:"disposable",path:e,token:null,why:"a browser test's saved sign-in state"};if(s.some(o=>Lf.test(o)))return{kind:"disposable",path:e,token:null,why:"a folder named as temporary"};if(/\.lock$/.test(xe.basename(e))&&!/(^|\/)(Cargo|Gemfile|poetry|uv|yarn|pnpm-lock|package-lock|composer|Pipfile|flake|mix|pubspec)\.lock$/.test(e))return{kind:"disposable",path:e,token:null,why:"a lock folder (a convention, not data)"};if(fa.has(e))return{kind:"catastrophic",path:e,token:"fs.system",why:`the system folder ${e}`};if(t.made&&t.made.some(o=>e===o||e.startsWith(`${o}/`)))return{kind:"disposable",path:e,token:null,why:On};let r=xe.basename(e);return(r==="bin"||r==="obj")&&t.projectRoot&&t.projectRoot.replace(/(?<!\/)\/+$/,"")!==n&&e.startsWith(`${t.projectRoot.replace(/(?<!\/)\/+$/,"")}/`)&&t.ignored?.(e)?{kind:"disposable",path:e,token:null,why:"build output git ignores"}:{kind:"normal",path:e,token:null,why:/\.[A-Za-z0-9]{1,8}$/.test(xe.basename(e))&&!/\/$/.test(e)?"a real file":"a real folder"}}function zf(e,t,n,s){let r=new RegExp(`^${ie}([^${le}]*)${le}(/.+)$`).exec(e);if(r&&/tmpdir\(\)|gettempdir\(\)|\bmktemp\b|\$TMPDIR\b|\$\{TMPDIR\}/.test(r[1])&&!r[2].split("/").includes(".."))return{kind:"disposable",path:t,token:null,why:"a temp folder (computed)"};let o=e.replace(new RegExp(`^${ie}[^${le}]*${le}`),"");if(e.startsWith(ie)&&(o==="/"||o==="/*"||o==="/.*"))return{kind:"catastrophic",path:t,token:"fs.root",why:`${t}: if the variable is empty, this is the filesystem root`};let a=e.replace(new RegExp(`${ie}[^${le}]*${le}`,"g"),"");if(a.split("/").filter(c=>c&&!c.includes("")).some(c=>ua.has(c))||/\/scratchpad(\/|$)/.test(a))return{kind:"disposable",path:t,token:null,why:"build, cache or scratch output under a variable"};let l=e.slice(0,e.indexOf(ie));return l&&pa(n).some(c=>ha(l.replace(/\/$/,""),c))?{kind:"disposable",path:t,token:null,why:"a temp folder"}:{kind:"normal",path:t,token:null,why:`a path that could not be resolved (${t})`}}function _e(e){let t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}var Mf=/^--(?:count|instance-count|num-nodes|nodes|num-workers|replicas|max-count|node-count)$/,Uf=/^--(?:max-run-duration|max-duration|duration|time-limit|hours)$/,qf=/^--(?:gpus?|accelerators?|accelerator-type|gpu-type|gpu-count)$/,Hf=/gpu|a100|h100|h200|v100|l40|a10g|b200|tpu/i,Bf=/(?:^|[^a-z0-9])(?:t4|l4)(?:$|[^a-z0-9])/i,ma=e=>Hf.test(e)||Bf.test(e),Vf=/^--(?:machine-type|instance-type|vm-size|size)$/;function Zf(e,t){let n=/^(\d{1,3}):(\d{2})(?::(\d{2}))?$/.exec(e);if(n)return Number(n[1])+Number(n[2])/60+Number(n[3]??0)/3600;let s=/^(\d+(?:\.\d+)?)(h|m|s|d)?$/i.exec(e);if(!s)return null;let r=Number(s[1]),o=(s[2]??(t==="hours"?"h":"s")).toLowerCase(),a=o==="h"?r:o==="m"?r/60:o==="d"?r*24:r/3600;return Number.isFinite(a)&&a>0?a:null}function ya(e){let t=(e??"").split(/\s+/).filter(Boolean).slice(0,400),n=null,s=null,r=null,o=a=>{let i=t[a],l=i.indexOf("=");return l>0?[i.slice(0,l),i.slice(l+1)]:[i,t[a+1]]};for(let a=0;a<t.length;a++){let[i,l]=o(a);if(l===void 0)continue;let c=l.replace(/^["']|["']$/g,"");Mf.test(i)&&/^\d{1,5}$/.test(c)&&Number(c)>0?n=Math.max(n??0,Number(c)):Uf.test(i)?s=Math.max(s??0,Zf(c,i==="--hours"?"hours":"seconds")??0)||s:(qf.test(i)||Vf.test(i)&&ma(c))&&(r=!0)}for(let a=0;a<t.length;a++){if(t[a]!=="create"||!t.slice(Math.max(0,a-3),a).includes("instances"))continue;let i=0;for(let l=a+1;l<t.length&&!t[l].startsWith("-")&&!/^(?:&&|\|\|?|;|&)$/.test(t[l])&&(i++,!t[l].endsWith(";"));l++);i>0&&(n=Math.max(n??0,i))}return r===null&&t.some(ma)&&(r=!0),{machines:n??1,hours:s??1,gpu:r,estimated:n===null||s===null}}import{posix as tt}from"path";var vs={paths:[],launched:[]},jn=600;function ba(e,t,n){if(!e||S(e)||e.startsWith("-")||/[*?[\]{}]/.test(e))return null;let s=M(e,t.cwd,n).replace(/(?<!\/)\/+$/,"");return!s.startsWith("/")||s==="/"||s===n.home||s.startsWith("/dev/")?null:tt.normalize(s)}function Xt(e,t=new Set){let n=[],s=!1;for(let r=1;r<e.length;r++){let o=e[r];if(!s&&o==="--"){s=!0;continue}if(!s&&o.startsWith("-")){t.has(o)&&r++;continue}n.push(o)}return n}var Gf=new Set(["--out","--output","--out-dir","--outdir","--output-dir","--dest","--destination","--target-dir","--results-dir","--report-dir","--save-dir","--log-dir","--out-file","--output-file","--pack-destination"]),Kf=new Set(["gcc","clang","cc","go","rustc","esbuild","tsc","curl","wget","pandoc","ffmpeg"]);function Yf(e,t){let n=[],s=r=>{let o=r?ba(r,e,t):null;o&&n.push(o)};for(let r of e.redirects)r.target&&/^(>|>>|>\||&>|&>>)$/.test(r.op)&&(r.fd===null||r.fd===1||r.fd===2)&&s(r.target);for(let r=1;r<e.argv.length;r++){let o=e.argv[r],a=o.indexOf("="),i=a>0?o.slice(0,a):o;!Gf.has(i)&&!(i==="-o"&&(qr.has(tt.basename(e.name))||Kf.has(e.name)))||s(a>0?o.slice(a+1):e.argv[r+1])}switch(e.name){case"mkdir":for(let r of Xt(e.argv,new Set(["-m","--mode"])))s(r);break;case"touch":for(let r of Xt(e.argv,new Set(["-r","-t","-d","--reference","--date"])))s(r);break;case"tee":for(let r of Xt(e.argv))s(r);break;case"cp":case"rsync":case"ditto":case"install":{let r=Xt(e.argv,new Set(["-t","--target-directory","-e","--exclude","--include","-m","--mode","-o","-g","--chmod","--rsh"]));r.length>=2&&s(r[r.length-1]);break}case"git":{let r=e.argv.slice(1),o=0,a=null;for(;o<r.length&&r[o].startsWith("-");)r[o]==="-C"&&(a=r[o+1]??null),o+=r[o]==="-C"||r[o]==="-c"?2:1;let i=a===null?e:{...e,cwd:S(a)?null:M(a,e.cwd,t)},l=c=>{let u=c?ba(c,i,t):null;u&&n.push(u)};if(r[o]==="worktree"&&r[o+1]==="add"&&l(Xt(["git",...r.slice(o+2)],new Set(["-b","-B","--reason"]))[0]),r[o]==="clone"){let c=Xt(["git",...r.slice(o+1)],new Set(["-b","--branch","--depth","-o","--origin","--reference","-c","--config","--filter","--separate-git-dir"]));c.length>=2?l(c[1]):c[0]&&l(tt.basename(c[0]).replace(/\.git$/,""))}break}case"npm":case"pnpm":case"yarn":{let r=e.argv.indexOf("--pack-destination");r>0&&s(e.argv[r+1]);break}case"tar":{let r=e.argv.findIndex(a=>a==="-C"||a==="--directory");r>0&&e.argv.slice(1).some(a=>/^-?[a-zA-Z]*x/.test(a)||a==="--extract")&&s(e.argv[r+1]);let o=e.argv.findIndex(a=>a==="-f"||a==="--file"||/^-[a-zA-Z]*c[a-zA-Z]*f$/.test(a));o>0&&e.argv.slice(1).some(a=>/^-?[a-zA-Z]*c/.test(a)||a==="--create")&&s(e.argv[o+1]);break}default:break}return n}function ka(e,t,n,s){let r=t&&typeof t=="object"?t:{};if(e==="Write"||e==="NotebookEdit"){let c=typeof r.file_path=="string"?r.file_path:typeof r.notebook_path=="string"?r.notebook_path:null;return c&&c.startsWith("/")&&c!==s.home?{paths:[tt.normalize(c)],launched:[]}:vs}if(e!=="Bash"||typeof r.command!="string")return vs;let o=r.command;if(o.length>64*1024)return vs;let a;try{a=dt(o,{home:s.home,tmpdir:s.tmpdir,cwd:n,projectDir:s.projectDir??null})}catch{return vs}let i=new Set,l=[];for(let c of a.commands){let u=Hr(c,s);for(let f of u.paths)i.add(f);l.push(...u.launched)}if(r.run_in_background===!0){l.push(o.slice(0,jn));for(let c of a.commands)!S(c.argv.join(" "))&&c.argv.length>1&&l.push(c.argv.map(u=>k(u)).join(" ").slice(0,jn))}return{paths:[...i].slice(0,64),launched:[...new Set(l)].slice(0,16)}}var $s=new Set(["serve","server","start","preview","develop","watch","install","update","build","test","tests","runner","worker","workers","python3","python","module","script","scripts","index.js","main.py","app.py","server.js","index.ts","main.ts","railway","vercel","heroku","kubectl","supabase","wrangler","netlify","firebase","stripe","ngrok","monitor","stream","follow","logs","runserver","uvicorn","gunicorn","hypercorn","daphne","nodemon","webpack","webpack-dev-server","http-server","live-server","browser-sync","celery","sidekiq","puma","unicorn","rackup","flask","rails","manage.py","artisan","storybook","jupyter","notebook","streamlit","gradio"]),qr=new Set(["node","nodejs","npx","tsx","ts-node","python","python3","uv","bun","deno","ruby","perl","bash","sh","zsh","pnpm","yarn","npm"]);function Hr(e,t){let n=[];if(e.background||e.wrappers.includes("nohup")||e.wrappers.includes("setsid")){n.push(e.text.slice(0,jn));let s=e.argv.map(r=>k(r)).join(" ");s!==e.text&&!S(e.argv.join(" "))&&n.push(s.slice(0,jn))}else!S(e.argv.join(" "))&&(qr.has(tt.basename(e.name))?e.argv.slice(1).some(s=>!s.startsWith("-")&&Pn(s)):Pn(e.argv[0]??"")&&(e.argv[0]??"").includes("/"))&&n.push(e.argv.join(" ").slice(0,jn));return{paths:Yf(e,t),launched:n}}var xs=new Set(["node","nodejs","python","python3","python2","ruby","perl","php","java","go","deno","bun","uv","npm","npx","pnpm","yarn","sh","bash","zsh","fish","dash","claude","code","docker","postgres","redis-server","mysqld","vite","next","tsx","ts-node","vitest","jest","make","cargo","git","ssh","tail","sleep","cat","less","watch","top","login","launchd","kernel_task","Finder","Dock"]);function va(e,t,n,s){if((!t||t.length===0)&&(!s||s.length===0))return!1;let r=e.replace(/^["']|["']$/g,"").trim();if(r.length<4||xs.has(r)||/[|()?*+[\]{}\\^$]/.test(r.replace(/\\\./g,"."))||/^\.?\w{1,6}$/.test(r)&&r.startsWith("."))return!1;let o=r.split(/\s+/).some(i=>i.length>=6&&!i.startsWith("-")&&!xs.has(tt.basename(i))&&!qr.has(i)&&!$s.has(i)&&!$s.has(tt.basename(i))&&!_s.test(tt.basename(i))&&!/^[\d.:]+$|^(localhost|0\.0\.0\.0|127\.0\.0\.1)(:\d+)?$|^[\w.]+:(app|application|server|api|asgi|wsgi|main)$/i.test(i));if((n?o&&(/[/.]/.test(r)&&/\w{3}[/.]|[/.]\w{3}/.test(r)||r.length>=8&&/\s/.test(r)||r.length>=10):!xs.has(r)&&!$s.has(r)&&!_s.test(r)&&r.length>=4)&&t&&Ur(r.replace(/\\\./g,"."),t))return!0;if(!n)return!1;for(let i of r.split(/\s+/)){let l=i.replace(/\\\./g,".").replace(/^\.\//,"");if(!(l.startsWith("-")||l.includes("="))){if(l.includes("/")&&s&&wa(l,s))return!0;if(Pn(l)&&(t&&Ur(l,t)||s&&wa(l,s)))return!0}}return!1}function Pn(e){let t=tt.basename(e);return e.length>=6&&/\.[A-Za-z0-9]{1,5}$/.test(t)&&!xs.has(t)&&!$s.has(t)&&!_s.test(t)&&!/^\.[A-Za-z0-9]+$/.test(t)&&!e.includes("node_modules/.bin/")}var _s=/^(server|app|main|index|worker|run|start|dev|cli|manage|setup|test|tests|build|serve|api|bot|job|task|script|wsgi|asgi|entry|entrypoint|bootstrap)\.[A-Za-z0-9]{1,5}$/i;function Ur(e,t){let n=new RegExp(`(^|[\\s/'"=])${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}($|[\\s'";&|)@])`);return t.some(s=>n.test(s))}function wa(e,t){for(let n of t){if(e.startsWith("/")&&(e===n||e.startsWith(`${n}/`)))return!0;let s=n.split("/").filter(r=>r!=="");for(let r=1;r<=s.length;r++){let o=s.slice(-r).join("/");if(!(o.length<6||r===1&&!Pn(o))&&(e===o||e.startsWith(`${o}/`)||e.endsWith(`/${o}`)))return!0}}return!1}function $a(e,t){let n=a=>a.replace(/\s+/g," ").trim(),s=n(e);if(t.some(a=>n(a).length>=24&&s.includes(n(a))))return!0;let r=a=>{let i=n(a),l=i.indexOf(" ");if(l<0)return null;let c=(i.slice(0,l).split("/").pop()??"").toLowerCase(),u=c.length;for(;u>0&&"0123456789.".includes(c[u-1]);)u--;return{prog:c.slice(0,u),args:i.slice(l+1)}},o=r(e);if(o&&t.some(a=>{let i=r(a);return i!==null&&i.args.length>=24&&i.prog===o.prog&&i.args===o.args}))return!0;for(let a of t)if(a.split(/\s+/).map(l=>l.replace(/^["']+|["';&|)]+$/g,"").replace(/^(\.\.?\/)+/,"")).flatMap(l=>{let c=l.split("/").filter(u=>u!=="");return c.length>2?[l,c.slice(-2).join("/")]:[l]}).filter(l=>!l.startsWith("-")&&!l.includes("=")&&Pn(l)&&!/^\/(dev|tmp|var|usr|bin|opt)\b/.test(l)).some(l=>new RegExp(`(^|\\s${l.includes("/")?"|/":""})${l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`).test(e)))return!0;return!1}function Jf(e,t){return[...new Set(t.flatMap(s=>s.split(/\s+/).map(r=>r.replace(/^["']+|["';&|)]+$/g,"").split("/").pop()??"")).filter(s=>_s.test(s)))].some(s=>Ur(s,[e]))}var Br=e=>e.trim().split(/\s+/).filter(t=>t!=="");function ft(e){let t=(e.split("/").pop()??"").toLowerCase(),n=t.length;for(;n>0&&"0123456789.".includes(t[n-1]);)n--;return t.slice(0,n)}function xa(e){let t=[],n=Br(e.replace(/["']/g,""));for(let s=0;s<n.length;s++){let r=n[s].endsWith("&")&&!/[<>]&$/.test(n[s])?n[s].slice(0,-1):n[s];/^\d*(>>?|<)&?$/.test(r)?s++:r!==""&&!/^\d*(>>?|<)/.test(r)&&!(t.length===0&&(/^\w+=/.test(r)||r==="nohup"))&&t.push(r)}return t}function Vr(e,t){let n=Br(e);if(n.length===0)return!1;let s=ft(n[0]),r=n[1]?ft(n[1]):"";return t.some(o=>{let a=xa(o);return a.length>0&&(ft(a[0])===s||ft(a[0])===r)})}function _a(e,t){let n=r=>r.replace(/\s+/g," ").trim(),s=n(e);return t.some(r=>n(r).length>=24&&s.includes(n(r)))}function Sa(e,t){if(Jf(e,t)&&Vr(e,t))return!0;let n=Br(e);return t.some(s=>{let r=xa(s);if(r.length===0||r.length===1&&!r[0].includes("/"))return!1;let o=n.length>r.length&&ft(n[1])===ft(r[0])?n.slice(1):n;if(o.length!==r.length||ft(o[0])!==ft(r[0]))return!1;let a=r.length===1;for(let i=1;i<r.length;i++)if(r[i].includes("$")){if(!Xf(r[i],o[i]))return!1}else{if(r[i]!==o[i])return!1;a=!0}return a})}function Xf(e,t){let n=[],s=0,r="";for(;s<e.length;){if(e[s]!=="$"){r+=e[s++];continue}if(n.push(r),r="",s++,e[s]==="{"){let a=e.indexOf("}",s);if(a<0)return!1;s=a+1}else if(e[s]==="("){let a=e.indexOf(")",s);if(a<0)return!1;s=a+1}else for(;s<e.length&&/\w/.test(e[s]);)s++}if(n.push(r),!t.startsWith(n[0])||!t.endsWith(n[n.length-1])||t.length<n[0].length+n[n.length-1].length)return!1;let o=n[0].length;for(let a of n.slice(1,-1)){let i=t.indexOf(a,o);if(i<0)return!1;o=i+a.length}return o<=t.length-n[n.length-1].length}var Pv=10080*60*1e3;var Wv=3600*1e3;var Wn=e=>`${e.kind}\0${e.cwd??""}\0${e.arg??""}`;import{realpathSync as Yv}from"fs";import{readdir as Xv,stat as Qv}from"fs/promises";import{homedir as t$}from"os";import{join as s$,relative as r$,resolve as o$,sep as i$}from"path";import{closeSync as Iv,openSync as Dv,readSync as Fv}from"fs";var Ca=64*1024*1024;var zv=Buffer.from('"tool_use"'),Mv=Buffer.from('"tool_result"'),Uv=Buffer.from('"permissionMode"'),qv=1024*1024;var Hv=256*1024;var l$=3600*1e3;function Aa(e){return e.replace(/[^A-Za-z0-9]/g,"-")}var Nn="anvil-claude",Qf=new Set(["login","logout","open"]);function Ea(e){let t=e[0];return t==="claude"||t!==void 0&&Qf.has(t)?[...e]:["claude",...e]}function Se(e){let t=e.trim();return t===Nn||t.endsWith(` ${Nn}`)||t.endsWith(`/${Nn}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}function Ln(e){return e[0]==="logout"?"anvil logout signs this machine out, so its rules stop following your workspace":e[0]==="remove"?"anvil remove puts an action in ghost in your workspace and hides it":e[0]==="login"?"anvil login changes the workspace whose rules this machine follows":e[0]==="control"&&e[1]==="kill-switch"&&!["off","status","show"].includes(e[2]??"")?"anvil control kill-switch puts every action in ghost, this agent's included":e[0]==="control"&&["set-action-mode","set-service-mode","set-mode"].includes(e[1]??"")&&e.includes("ghost")?`anvil control ${e[1]} ghost switches off a rule your workspace enforces`:e[0]!=="claude"?null:e[1]==="allow"?"anvil claude allow approves a call Anvil held":e[1]==="off"||e[1]==="ghost"?`anvil claude ${e[1]} switches off Anvil's checks on this agent`:e[1]==="rules"&&e[2]==="remove"?"anvil claude rules remove deletes one of the developer's rules":e[1]==="sync"?"anvil claude sync applies changes to your rules.md":e[1]==="rules"&&(e[2]==="add"||e[2]==="import")?`anvil claude rules ${e[2]} changes your rules`:e[1]===void 0||e[1].startsWith("-")?"anvil claude opens the screen that changes your rules":e[1]==="rules"&&e[2]==="edit"?"anvil claude rules edit opens the screen that changes your rules":e[1]==="on"?"anvil claude on reinstalls Anvil and recompiles your rules":e[1]==="statusline"?"anvil claude statusline feeds the meter your budgets count":null}function Ss(e,t=e){if(e.length===0&&t.some(s=>s==="--version"||s==="-v"||s==="--help"||s==="-h"))return null;let n=Ln(Ea(e));return n===null?null:n.replace(/^anvil( claude)?\b/,Nn)}var ep=["prod","production","prd","live","main","master"],tp=["staging","stage","dev","development","preview","test","qa","sandbox"],Ce=e=>new Set(e.split(" ")),np=new Set(ep),Ra=new Set(tp),Nt={environment:null,said:null};function Da(e,t){try{return Rp(e,t)}catch{return Nt}}function Fa(e,t,n){try{return Dp(e,t,n)}catch{return Nt}}function Es(e){return e.normalize("NFKC").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var Oa="\u0430a\u0435e\u043Eo\u0440p\u0441c\u0456i\u0455s\u0501d\u04CFl\u043Cm\u0442t\u043Fn\u0443u\u03BDv\u03BFo\u03C1p\u03B9i\u03B1a\u03B5e\u03C4t\u03C5u\u03BCm",sp=e=>e.normalize("NFKC").replace(new RegExp("\\p{Cf}","gu"),"").replace(/[^\u0000-\u007f]/g,t=>{let n=Oa.indexOf(t.toLowerCase());return n>=0&&n%2===0?Oa[n+1]:t}),rp=/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=\d)|(?<=\d)(?=[A-Za-z])/;function Tt(e){for(let t of sp(e).split(/[^A-Za-z0-9]+/))for(let n of[t,...t.split(rp)])if(np.has(n.toLowerCase()))return n.toLowerCase();return null}function en(e){let t=e.normalize("NFKC").replace(/^([a-z][\w+.-]*:\/\/)?[^@/\s:]*@/i,"$1");if(/[^\u0000-\u007f]/.test(t))return!1;if(t.includes("/")&&(/^(\/|~|\$\{?HOME\b)/.test(t)||t.split("/").includes(".."))){let n=t.replace(/\/+$/,"").split("/"),s=n.pop()??"";return Es(s).some(r=>Ra.has(r)&&(!/^(dev|test)$/.test(r)||/^(envs?|environments?|stages?|deploy(ments?)?|overlays?)$/.test(n.pop()??"")))}return Es(t).some(n=>Ra.has(n))}var It=e=>/[$`*]|\{[^}]*(,|\.\.)|[<>]\(/.test(e),op=Ce("env environment stage target tier profile context namespace ns cluster app application project stack site service alias workspace destination dest channel track deployment inventory limit host hosts server to config configuration"),za=e=>e.replace(/^-+/,"").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().split(/[-_.]/).filter(t=>!["name","id","file"].includes(t)).pop()??"",Rs=e=>!/^(NODE|BABEL|RAILS|RACK|FLASK|MIX|SENTRY|APP|ASPNETCORE|DOTNET|SPRING|DJANGO)_/i.test(e)&&op.has(za(e)),ip=Ce("app application project stack site cluster host hosts server destination dest deployment to target"),ap=e=>/^-[ap]$/.test(e)||ip.has(za(e)),lp=/^-[esadncpPESADilHCfF]$/,ja=e=>/^-[A-Za-z]$/.test(e)?lp.test(e):Rs(e),cp=/^--?(staging|preview|qa|sandbox|dev|development)$/i,up={frame:[],guards:[],first:!0,cond:!1,fresh:!1},dp=/(?:^|[\s;&|(){}])(?:function\s+[^\s(){};&|]+|[^\s(){};&|]+\s*\(\s*\))\s*[{(]/,fp=e=>({pipes:0,ids:0,frames:0,compound:0,functions:dp.test(e)}),pp=Ce("if while until case select for"),hp=Ce("fi done esac");function Gr(e,t,n,s){let r=s.length,o=[],a=[],i="",l=!1,c="word",u=[],f=[{frame:n.frame,base:n.guards,first:n.first}],p={guards:n.guards,first:n.first,joined:""},d=()=>{l&&(c==="heredoc"?u.push({end:i,fed:a}):c==="fed"?a.push(i):c==="word"&&o.push(i),i="",l=!1,c="word")},h=y=>{d();let $=f[f.length-1];if(o.length>0||a.length>0){let E=t.compound,x=!1;for(let j of o)if(pp.has(j))E++,x=!0;else if(hp.has(j))E=Math.max(0,E-1);else if(!Ua.has(j))break;let b={words:o,fed:a,pipe:t.pipes,id:t.ids++,frame:y==="&"?[...$.frame,t.frames++]:[...$.frame],guards:p.guards,first:p.first,cond:n.cond||t.functions||x||t.compound>0,fresh:n.fresh};t.compound=E,s.push(b),y==="&&"?p={guards:p.joined==="||"?$.base:[...b.guards,b.id],first:!1,joined:"&&"}:y==="||"?p={guards:$.base,first:!1,joined:"||"}:y==="|"?p={guards:b.guards,first:!1,joined:p.joined}:p={guards:$.base,first:$.first,joined:""}}else y==="list"||y==="&"?p={guards:$.base,first:$.first,joined:""}:(y==="&&"||y==="||")&&(p={guards:y==="||"?$.base:p.guards,first:!1,joined:y});o=[],a=[],y!=="|"&&t.pipes++};for(let y=0;y<e.length;y++){let $=e[y],E=e[y+1]??"";if($==="\\")E!==`
|
|
31
|
+
`&&(i+=E),l||=E!==`
|
|
32
|
+
`,y++;else if($==="'"){let x=Os(e,y+1,"'");i+=e.slice(y+1,x),l=!0,y=x}else if($==='"'){let x=y+1;for(;x<e.length&&e[x]!=='"';x++)e[x]==="\\"&&/["\\$`]/.test(e[x+1]??"")&&x++,i+=e[x]??"";l=!0,y=x}else if(E==="("&&($==="$"||$==="<"||$===">")||$==="$"&&E==="{"){let x=Ma(e,y+1);i+=e.slice(y,x+1),l=!0,y=x}else if($==="`"){let x=Os(e,y+1,"`");i+=e.slice(y,x+1),l=!0,y=x}else if($==="#"&&!l){let x=e.indexOf(`
|
|
33
|
+
`,y);y=(x<0?e.length:x)-1}else if($===" "||$===" "||$==="\r")d();else if($===`
|
|
34
|
+
`)h("list"),y=gp(e,y,u);else if($==="<"||$===">"||$==="&"&&E===">")if(l&&/^\d+$/.test(i)?(i="",l=!1):d(),e.startsWith("<<<",y))c="fed",y+=2;else if(e.startsWith("<<",y))c="heredoc",y+=e[y+2]==="-"?2:1;else for(c=$==="<"?"fed":"drop";/[<>&|]/.test(e[y+1]??"");)y++;else if($==="&"&&E==="&")h("&&"),y++;else if($==="|"&&E==="|")h("||"),y++;else if($==="|")E==="&"&&y++,h("|");else if($==="&")h("&");else if($===";")(E===";"||E==="&")&&y++,h("list");else if($==="("){d(),(o.length>0||a.length>0)&&h("list");let x=f[f.length-1];f.push({frame:[...x.frame,t.frames++],base:p.guards,first:p.first}),p={...p,joined:""}}else $===")"?(h("list"),f.length>1&&f.pop(),p={guards:f[f.length-1].base,first:!1,joined:""}):(i+=$,l=!0)}h("list");let g=new Map;for(let y of s.slice(r))g.set(y.pipe,(g.get(y.pipe)??0)+1);for(let y of s.slice(r))(g.get(y.pipe)??0)>1&&(y.frame=[...y.frame,t.frames++]);return s}function Os(e,t,n){let s=e.indexOf(n,t);return s<0?e.length:s}function Ma(e,t){let n=e[t],s=n==="("?")":"}",r=0;for(let o=t;o<e.length;o++){let a=e[o];if(a==="\\")o++;else if(a==="'")o=Os(e,o+1,"'");else if(a===n)r++;else if(a===s&&--r===0)return o}return e.length}function gp(e,t,n){let s=t;for(let r of n.splice(0)){let o=[];for(;s<e.length;){let a=e.indexOf(`
|
|
35
|
+
`,s+1),i=e.slice(s+1,a<0?e.length:a);if(s=a<0?e.length:a,i.replace(/^\t+/,"")===r.end)break;o.push(i)}r.fed.push(o.join(`
|
|
36
|
+
`))}return s}var Lt=/^[A-Za-z_][A-Za-z0-9_]*=/,Ua=Ce("if then else elif fi do done while until esac ! { } time"),Pa=Ce("sh bash zsh dash ksh ash"),Wa=oe({sudo:"-u -g -C -D -h -p -r -t -U --user --group --chdir",doas:"-u -C",env:"-u -C -S --unset --chdir",nohup:"",nice:"-n",timeout:"-s -k --signal --kill-after",command:"",builtin:"",exec:"-a",xargs:"-I -n -P -L -d -E -s -a",watch:"-n -d",flock:"-w -E",npx:"-p --package -c --call",bunx:"-p --package",op:"--env-file --account",doppler:"-c --config -p --project --token",infisical:"--env --projectId --path --token",dotenv:"-e -c -v",dotenvx:"-f --env-file","aws-vault":"--duration -d","cross-env":""}),mp=oe({timeout:1,flock:1,"aws-vault":2,op:1,doppler:1,infisical:1,dotenvx:1}),Kr=Ce("op doppler infisical dotenv dotenvx aws-vault mise asdf"),yp=oe({npm:"exec",pnpm:"dlx exec",yarn:"dlx exec",bun:"x",uv:"run",poetry:"run",pipenv:"run",bundle:"exec",mise:"exec x",asdf:"exec",railway:"run"}),bp=oe({flyctl:"fly","netlify-cli":"netlify","firebase-tools":"firebase","@railway/cli":"railway",tofu:"terraform",terragrunt:"terraform","docker-compose":"docker",oc:"kubectl",kubecolor:"kubectl"});function Ze(e){let t=/^((?:@[^/@\s]+\/)?[^@\s=/]+)(?:@[^\s/]*|==\S*)$/.exec(e),n=t?t[1]:e.startsWith("@")?e:e.slice(e.lastIndexOf("/")+1);return bp[n]??n}function Na(e,t,n){let s=n.split(" "),r=t;for(;r<e.length&&e[r].startsWith("-")&&e[r]!=="--";)r+=!e[r].includes("=")&&s.includes(e[r])?2:1;return e[r]==="--"?r+1:r}function qa(e){let t=0;for(let n=0;n<12&&t<e.length;n++){let s=e[t];if(Lt.test(s)){t++;continue}let r=Ze(s),o=e.indexOf("--",t);if(yp[r]?.split(" ").includes(e[t+1]??""))t=Kr.has(r)&&o>t?o+1:Na(e,t+2,"");else if(Wa[r]!==void 0)Kr.has(r)&&o>t?t=o+1:(t=Na(e,t+1,Wa[r])+(mp[r]??0),e[t]==="--"&&t++);else return(r==="yarn"||r==="pnpm")&&tn[Ze(e[t+1]??"")]&&t++,t}return t<e.length?t:-1}function Yr(e,t,n){return e.flatMap(s=>{let r=0;for(;r<s.words.length&&Ua.has(s.words[r]);)r++;let o=s.words.slice(r);if(n>=3)return[{...s,words:o}];let a=(h,g)=>({frame:g?[...s.frame,t.frames++]:s.frame,guards:s.guards,first:s.first&&!s.cond,cond:s.cond,fresh:s.fresh||h}),i=o.flatMap(wp).flatMap(h=>Yr(Gr(h,t,a(!1,!0),[]),t,n+1)),l=qa(o),c=l<0?"":Ze(o[l]),u=null;if(Pa.has(c)){let h=o.findIndex((g,y)=>y>l&&/^-[a-zA-Z]*c[a-zA-Z]*$/.test(g));u=h>0?o[h+1]??null:null}else c==="eval"&&(u=o.slice(l+1).join(" "));if(u===null)return[...i,{...s,words:o}];let f=o.slice(0,l).filter(h=>Lt.test(h)),p=Pa.has(c)?a(!0,!0):a(!1,!1),d=c==="eval"&&It(u)?[{...s,words:[],wild:!0}]:[];return[...i,...d,...Yr(Gr(u,t,p,[]),t,n+1).map(h=>({...h,words:[...f,...h.words]}))]})}function wp(e){let t=[];for(let n=0;n<e.length;n++)if("$<>".includes(e[n])&&e[n+1]==="("&&e[n+2]!=="("){let s=Ma(e,n+1);t.push(e.slice(n+2,s)),n=s}else if(e[n]==="`"){let s=Os(e,n+1,"`");t.push(e.slice(n+1,s)),n=s}return t}var js=(e,t)=>e.frame.length<=t.frame.length&&e.frame.every((n,s)=>t.frame[s]===n),Ha=(e,t)=>js(e,t)&&!e.cond&&(t.guards.includes(e.id)||e.first),st="${?}";function Ba(e,t,n){let s=n.filter(l=>(l.name===e||l.name==="*")&&js(l.part,t)&&(!t.fresh||l.part.fresh||l.exported||l.name==="*"));if(!s.some(l=>l.name===e))return null;let r=-1;for(let l=s.length-1;l>=0;l--){let c=s[l];if(c.name===e&&!c.unknown&&(c.loop||Ha(c.part,t))){r=l;break}}let o=r>=0?[...s[r].values]:[],a=r>=0;for(let l of s.slice(r+1))l.unknown?a=!1:o.push(...l.values);let i=s.filter(l=>l.name===e).pop().said;return{values:[...new Set(o)].slice(0,16),certain:a,said:i}}var kp=(e,t,n)=>e.replace(/\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g,(s,r,o)=>{let a=Ba(r??o,t,n);return!a||a.values.length===0?s:a.certain&&a.values.length===1&&!/\s/.test(a.values[0])?a.values[0]:`${a.values.join(st)}${st}`}),Tn=e=>e.slice(0,e.indexOf("=")),In=e=>e.slice(e.indexOf("=")+1),vp=Ce("export declare typeset local readonly");function $p(e){let t=[];return e.map(n=>{let s=n.words.map(u=>kp(u,n,t)),r=qa(s),o=r<0?"":Ze(s[r]),a=new Map,i=s.slice(0,Math.max(r,0)).some(u=>/^(-[a-zA-Z]*[iu]|--unset.*|--ignore-environment|-)$/.test(u)||["sudo","doas"].includes(Ze(u)));for(let u of i?[]:new Set(t.filter(f=>f.exported&&f.name!=="*").map(f=>f.name))){let f=Ba(u,n,t);f&&f.values.length>0&&a.set(u,{said:f.said,value:f.certain&&f.values.length===1?f.values[0]:`${f.values.join(" ")}${st}`})}for(let u of r<0?[]:s.slice(0,r))Lt.test(u)&&a.set(Tn(u),{said:u,value:In(u)});let l=u=>t.some(f=>f.name===u&&f.exported&&js(f.part,n)),c=(u,f,p,d={})=>{t.push({name:u,values:f,unknown:d.unknown??!1,exported:(d.exported??!1)||l(u),loop:d.loop??!1,part:n,said:p})};if(n.wild)c("*",[],"eval",{unknown:!0});else if(r<0)for(let u of s.filter(f=>Lt.test(f)))c(Tn(u),[In(u)],u);else if(vp.has(o)){let u=s.slice(r+1).filter(d=>/^[-+]/.test(d)),f=o==="export"||u.some(d=>/^-[a-zA-Z]*x/.test(d)),p=u.some(d=>/^(-[a-zA-Z]*n|\+[a-zA-Z]*x)/.test(d));for(let d of s.slice(r+1))p&&/^[A-Za-z_]\w*(=|$)/.test(d)?c(d.replace(/=.*/s,""),[],o,{unknown:!0}):Lt.test(d)?c(Tn(d),[In(d)],`${o} ${d}`,{exported:f}):f&&/^[A-Za-z_]\w*$/.test(d)&&t.push(...t.filter(h=>h.name===d).slice(-1).map(h=>({...h,exported:!0,part:n})))}else if(o==="for"&&s[r+2]==="in")c(s[r+1],s.slice(r+3),s.slice(r).join(" "),{loop:!0});else if(o==="source"||o==="."||o==="eval"&&s.slice(r+1).some(It)||o==="set"&&s.slice(r+1).some(u=>/^-[a-zA-Z]*a/.test(u)))c("*",[],o,{unknown:!0});else for(let u of s.slice(r+1))/^[A-Za-z_]\w*$/.test(u)&&t.some(f=>f.name===u)&&c(u,[],o,{unknown:!0});return{part:n,words:s,fed:n.fed,pipe:n.pipe,at:r,tool:o,env:a}})}var xp=(e,t)=>Ha(e.part,t.part)&&t.part.guards.includes(e.part.id),_p=Ce("version help status logs log list ls info show get describe whoami auth login logout doctor history inspect open ps top explain plan validate fmt init output graph providers preview diff synth config context use link pull build template lint package search repo dependency dep workspace stack"),Sp=Ce("cd pushd popd export declare typeset local readonly unset source . echo printf sleep true false set test [ [[ for case git cat ls grep tee read wait exit return mkdir cp mv rm touch chmod which pwd date kubectx kubens alias unalias"),Cp=[Ce("deploy deploys deploying deployment deployments redeploy"),Ce("release releases ship publish rollout promote apply provision rollback destroy")],Ap=e=>Wt(e.words.slice(e.at+1),Ve[e.tool]??"")[0]??"";function Ep(e,t){let n=e.map((i,l)=>l),s=i=>!_p.has(Ap(e[i]))||e[i].words.some(l=>/^(delete|rm|remove|destroy|drop|purge|prune|uninstall|reset)$/.test(l)),r=t?Ze(t.toLowerCase()):null;if(r){let i=n.filter(l=>e[l].at>=0&&e[l].tool===r);if(i.length>0)return i.some(s)?i.filter(s):i;for(let l of e){let c=l.words.findIndex((u,f)=>f>l.at&&Ze(u)===r);if(l.at>=0&&c>0)return l.at=c,l.tool=r,[e.indexOf(l)]}}let o=n.filter(i=>e[i].at>=0&&!Sp.has(e[i].tool)),a=o.filter(i=>e[i].words.some(l=>Es(l).some(Xr))||tn[e[i].tool]!==void 0&&s(i));return a.length>0?a:o}function Va(e){let t=fp(e);return $p(Yr(Gr(e,t,up,[]),t,0))}function Rp(e,t){let n=Va(e),s=Ep(n,t);if(s.length===0){for(let l of n)for(let c of[...l.words,...l.fed])if(Tt(c))return{environment:"production",said:pt(c)};return Nt}let r=s.map(l=>Wp(n,l,t)),o=r.find(l=>l.environment==="production")??(r.some(l=>l.environment===null)?Nt:r[0]);if(o.environment!=="non-production")return o;let a=e.replace(/["']/g,"").split(/[\s`;&|()<>{}$\\]+/),i=[t?Ze(t.toLowerCase()):"",...s.map(l=>n[l].tool)].some(l=>l&&a.filter(c=>Ze(c)===l).length>n.filter(c=>c.tool===l).length);return Tt(e)||i||n.some(l=>l.tool==="alias")?Nt:o}var pt=e=>{let t=e.split(st).join("");return t.length>80?`${t.slice(0,79)}\u2026`:t};function La(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(!Tt(s))continue;let r=e[n-1]??"",o=r.startsWith("-")&&!r.includes("=")&&!s.startsWith("-")&&(t===void 0||t.split(" ").includes(r));return pt(o?`${r} ${s}`:s)}return null}var Za="terraform workspace select|terraform workspace new|terraform init:-backend-config|kubectl config use-context|kubectx|pulumi stack select|firebase use|gcloud config set project|gcloud config configurations activate|docker context use|railway environment|railway link:-e --environment".split("|").map(e=>{let[t,n]=e.split(":"),s=t.split(" ")[0];return[s==="kubectx"?"kubectl":s,t,n]}),Op=Ce("terraform pulumi fly vercel netlify wrangler firebase railway docker");function jp(e,t){let n=e.tool,s=n==="helm"?"kubectl":n,r=[],o=[],a=i=>[{said:i,value:st}];for(let i of t){if(i.at<0||!js(i.part,e.part))continue;let l=xp(i,e),c=i.words.slice(i.at),u=pt(c.join(" "));if(["cd","pushd","popd"].includes(i.tool)||(i.tool==="source"||i.tool===".")&&!tn[n]){let p=Wt(c.slice(1),"")[0];r=l&&p&&p!=="-"&&i.tool!=="popd"?[{said:u,value:p}]:a(u)}let f=Za.filter(([p,d])=>p===s&&d.split(" ").every((h,g)=>(g>0?c[g]:i.tool)===h)).flatMap(([,p,d])=>{let h=c.slice(p.split(" ").length);return d?he(h,d):Wt(h,"").slice(0,1).map(g=>({said:u,value:g}))});f.length>0&&(o=l?f:a(u))}return r.length>0&&e.words.some((i,l)=>i==="-C"||l<e.at&&i==="-D"||i==="-d"&&/^(task|just)$/.test(e.tool)||/^--(chdir|cwd|prefix|dir|directory|working-dir)(=|$)/.test(i))&&(r=a("")),{folders:Op.has(n)||!tn[n]?r:[],picks:o}}var Pp=Ce("cd pushd export declare typeset local readonly source . test [ [[ kubectx kubens case alias");function Wp(e,t,n){let s=e[t],r=e.slice(0,t),o=s.tool==="helm"?"kubectl":s.tool,a=r.filter(d=>d.at<0||Pp.has(d.tool)||d.tool===s.tool&&tn[s.tool]||Za.some(([h,g])=>h===o&&`${g} `.startsWith(`${d.tool} `))),i=La(s.words,Ve[s.tool]);if(i)return{environment:"production",said:i};for(let d of[...s.fed,...r.filter(h=>h.pipe===s.pipe).flatMap(h=>[...h.words,...h.fed])]){let h=Tt(d);if(h)return{environment:"production",said:h}}for(let d of a)if(La(d.words))return{environment:"production",said:pt(d.words.slice(Math.max(d.at,0)).join(" "))};if(n&&Tt(n))return{environment:"production",said:n};let l=jp(s,r),c={args:s.words.slice(s.at+1),env:s.env,chosen:[...l.folders,...l.picks],folders:l.folders,picks:l.picks},u=tn[s.tool]?.(c)??Tp(c,s.words.slice(Math.max(0,s.words.findIndex((d,h)=>h===s.at||Kr.has(Ze(d))))),s.tool);if(u.production)return{environment:"production",said:u.production};let f=u.first?u.sels.filter(d=>d.rank===u.sels[0].rank):u.sels,p=f.length>0&&f.every(d=>!It(d.value)&&en(d.value))?f[0]:void 0;return p?{environment:"non-production",said:pt(p.said)}:u.preview?{environment:"non-production",said:u.preview}:Nt}function he(e,t){let n=t.split(" "),s=[];return e.forEach((r,o)=>{let a=r.indexOf("=");a>0&&n.includes(r.slice(0,a))?s.push({said:r,value:r.slice(a+1)}):n.includes(r)&&o+1<e.length?s.push({said:`${r} ${e[o+1]}`,value:e[o+1]}):/^-[A-Za-z]$/.test(r.slice(0,2))&&r.length>2&&!r.startsWith("--")&&n.includes(r.slice(0,2))&&s.push({said:r,value:r.slice(2)})}),s}function Wt(e,t){let n=t.split(" "),s=[];for(let r=0;r<e.length;r++){let o=e[r];if(o==="--")return[...s,...e.slice(r+1)];!o.startsWith("-")||o==="-"?s.push(o):!o.includes("=")&&n.includes(o)&&r++}return s}function Np(e,t){let n=t.split(" "),s=[];for(let r=0;r<e.length;r++){let o=e[r];if(o==="--")return[...s,...e.slice(r+1)];!o.startsWith("-")||o==="-"?/^-./.test(e[r-1]??"")&&!e[r-1].includes("=")||s.push(o):!o.includes("=")&&n.includes(o)&&r++}return s}var Cs=e=>e.map(t=>({said:t,value:t})),Qt=(e,t)=>t.split(" ").flatMap(n=>e.env.get(n)??[]),Ta=(e,t)=>he(e.args,t).map(n=>({...n,value:st})),Ia=e=>e.env.has("KUBECONFIG")||e.args.some(t=>t.startsWith("--kubeconfig"))?[]:e.picks,nt=(...e)=>{let t=e.findIndex(n=>n.length>0);return{sels:t<0?[]:e[t].map(n=>({...n,rank:t})),first:!0}},Jr=e=>e.flatMap(t=>{let n=t.value.split(/[\s,]+/).filter(s=>Lt.test(s));return n.length===0?[t]:n.filter(s=>Rs(Tn(s))).map(s=>({said:t.said,value:In(s)}))}),Zr=(e,t)=>{let n=t.split(" ");return e.every((s,r)=>!It(s)||s.startsWith("-")||n.includes(e[r-1]??""))},Ve=oe({vercel:"--token -t --scope -S --cwd --local-config -A --global-config -Q --team -T --build-env -b --env -e --meta -m --regions --archive --target --name -n",netlify:"--dir -d --functions -f --site -s --auth --alias --branch -b --context --message -m --filter --timeout",fly:"-a --app -c --config -i --image -e --env --build-arg --build-secret --dockerfile --strategy -r --region --vm-size --wait-timeout --image-label -t --access-token -o --org",terraform:"-var -var-file -target -replace -state -state-out -backup -lock-timeout -parallelism",firebase:"-P --project --only --except -m --message --token --account --expires -e"}),tn=oe({vercel:e=>{let t=Wt(e.args,Ve.vercel),n=/^(deploy)?$|[/.]/.test(t[0]??"")?"deploy":t[0];if(n==="rollback"||n==="promote")return{sels:[],production:n};let s=[...he(e.args,"--target"),...Zr(e.args,Ve.vercel)?[]:[{said:"",value:st}]];return n!=="deploy"?{sels:[...s,...Cs(n==="env"?t.slice(3,4):t.slice(1)),...e.chosen]}:{sels:s,...s.length===0?{preview:"no --prod"}:{}}},netlify:e=>e.args.some(n=>/^-[a-z]*p[a-z]*$/.test(n))?{sels:[],production:"-p"}:{sels:[...he(e.args,"--context --alias --branch -b --site -s"),...e.chosen],...Wt(e.args,Ve.netlify)[0]==="deploy"&&Zr(e.args,Ve.netlify)?{preview:"no --prod"}:{}},fly:e=>{let t=Wt(e.args,Ve.fly),n=t[0]==="apps"||t[0]==="app"?t.slice(2,3):[];return nt([...he(e.args,"-a --app"),...Cs(n)],Qt(e,"FLY_APP"),he(e.args,"-c --config"),t[0]==="deploy"&&t[1]?[{said:"",value:st}]:[],e.folders)},railway:e=>nt(he(e.args,"-e --environment"),e.picks),kubectl:e=>nt(he(e.args,"--context --cluster --server -s"),Ia(e)),helm:e=>nt([...he(e.args,"--kube-context --kube-apiserver"),...Qt(e,"HELM_KUBEAPISERVER")],Qt(e,"HELM_KUBECONTEXT"),Ia(e)),terraform:e=>{let t=Np(e.args,Ve.terraform),n=["apply","destroy"].includes(t[0]??"")?t.slice(1):[],s=[...he(e.args,"-chdir --chdir --terragrunt-working-dir --working-dir"),...Qt(e,"TF_WORKSPACE"),...Cs(n),...e.chosen];return{sels:s.length>0?[...s,...he(e.args,"-var-file --var-file"),...Jr(he(e.args,"-var --var"))]:[]}},pulumi:e=>nt(he(e.args,"-s --stack"),e.picks,[...he(e.args,"-C --cwd"),...e.folders]),firebase:e=>{let t=Wt(e.args,Ve.firebase),n=/^hosting:channel:deploy/.test(t[0]??"");return{sels:[...nt(he(e.args,"-P --project"),e.picks,Ta(e,"--config"),e.folders).sels,...n?Cs(t.slice(1,2)).map(r=>({...r,rank:9})):[]],first:!0,...n&&Zr(e.args,Ve.firebase)?{preview:t[0]}:{}}},wrangler:e=>nt(he(e.args,"--name --route --routes"),he(e.args,"-e --env --branch --project-name"),Ta(e,"-c --config"),e.chosen),docker:e=>{let t=e.args.findIndex((n,s)=>!n.startsWith("-")&&!["-c","--context","-H","--host","--config"].includes(e.args[s-1]??""));return nt([...he(t<0?e.args:e.args.slice(0,t),"-c"),...he(e.args,"--context -H --host")],Qt(e,"DOCKER_HOST DOCKER_CONTEXT"),e.picks)},modal:e=>nt(he(e.args,"-e --env"),Qt(e,"MODAL_ENVIRONMENT"))}),Lp=Ce("make gmake rake just task cap"),Xr=e=>Cp.some(t=>t.has(e.toLowerCase()));function Tp(e,t,n){let s=[],r=[],o=(d,h)=>{s.push(...h),ap(d)&&r.push(...h)},a=[],i=!1;for(let d=0;d<t.length;d++){let h=t[d];if(h==="--")i=!0;else if(h.startsWith("-")&&h.length>1){let g=h.indexOf("="),y=n==="npm"&&!i;h==="--all"&&r.push({said:h,value:h}),g>0?o(h.slice(0,g),ja(h.slice(0,g))&&!y?Jr([{said:h,value:h.slice(g+1)}]):[]):cp.test(h)?s.push(...y?[]:[{said:h,value:h}]):t[d+1]!==void 0&&!t[d+1].startsWith("-")&&(d++,ja(h)&&!y&&o(h,Jr([{said:`${h} ${t[d]}`,value:t[d]}])))}else Lt.test(h)?Lp.has(n)&&Rs(Tn(h))&&s.push({said:h,value:In(h)}):(It(h)||!/\s/.test(h)&&!/^v?\d+(\.\d+)+/.test(h))&&(s.push({said:h,value:d>0?h:h.slice(h.lastIndexOf("/")+1)}),d>0&&a.push(h))}for(let[d,h]of e.env)Rs(d)&&o(d,[h]);let l=[...s,...e.chosen],c=a.filter(d=>Es(d).some(Xr)),u=a.findIndex(Xr),f=a.slice(u<0?a.length:u+1).filter(d=>!/[/.]/.test(d));return{sels:l.some(d=>It(d.value))||[c,f].some(d=>d.length>1&&!d.every(en))||!r.every(d=>en(d.value))?[{said:"",value:st}]:l.filter(d=>en(d.value))}}function Qr(e){let t=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/\s]*@)?([^/?#\s]*)(\/[^?#\s]*)?/i.exec(e.trim());return t?`${t[1]??""} ${(t[2]??"").replace(/^\//,"")}`:e}var As=null;function Ip(e){if(As?.command===e)return As;let t=Va(e).flatMap(s=>[...s.words,...s.fed]),n=t.flatMap((s,r)=>[.../^(-h|--host)$/.test(t[r-1]??"")?[s]:[],...[...s.matchAll(/(?:^--host=|^-h(?=.)|(?:^|[\s;='"])host(?:addr)?=|^\w*HOST(?:ADDR)?=)([^\s;]*)|[a-z][\w+.-]*:\/\/\S*/gi)].map(o=>o[1]??o[0])]);return As={command:e,prod:t.find(s=>Tt(s))??null,servers:n.every(s=>!It(s)&&s.split(",").every(r=>en(Qr(r))))},As}function Dp(e,t,n){let s=[n,t].filter(a=>typeof a=="string"&&a.length>0);for(let a of s)if(Tt(Qr(a)))return{environment:"production",said:pt(a)};let r=Ip(e);if(r.prod!==null)return{environment:"production",said:pt(r.prod)};let o=s.find(a=>en(Qr(a)));return o&&r.servers?{environment:"non-production",said:pt(o)}:Nt}var Fp=["fs.root","fs.home","fs.system","fs.project_root","fs.git_dir","fs.device","git.main","proc.all"],zp=new Set(Fp),uo={"claude.bash.fs.delete_recursive":10,"claude.bash.db.destructive":9,"claude.bash.git.force_push":9,"claude.bash.git.discard":8,"claude.bash.git.push_main":8,"claude.bash.deploy":8,"claude.bash.publish":7,"claude.bash.secrets.print":7,"claude.bash.privilege":7,"claude.file.write_secret":6,"claude.file.read_secret":6,"claude.bash.process.kill_by_name":6,"claude.bash.external_write":6,"claude.bash.spend":6,"claude.bash.crypto.transaction":8,"claude.bash.secrets.expose":9,"claude.agent.controls":7,"claude.bash.net.expose":6,"claude.bash.data.export":6,"claude.bash.persistence":6,"claude.mcp.side_effect":6,"claude.bash.fs.delete_disposable":1,"claude.agent.helper":1,"claude.mcp.call":0,"claude.tool.other":0,"claude.bash.unclassified":0};var mt=new Set(["Write","Edit","MultiEdit","NotebookEdit"]),fo=new Set(["Read","Grep","NotebookRead"]),Mp=new Set(["Agent","Task","Workflow"]),Up=new Set(["Agent","Task"]),qp="claude.agent.helper";function Jl(e,t){return mn({tool:e.tool,command:e.command_local,target:e.target,cwd:e.cwd,git_branch:e.git_branch,project_dir:Hp(e),session_id:e.session_id??null},t)}function Hp(e){let t=e.source_file.split("/")[0];if(!t||!e.cwd)return null;for(let n=e.cwd;;n=R.dirname(n)){if(Aa(n)===t)return n;if(n==="/"||n==="."||n===R.dirname(n))return null}}function Bp(e,t){let n=r=>typeof r=="string"&&r!==""?Ne(r):r??null,s=typeof e.target=="string"&&(mt.has(e.tool)||fo.has(e.tool))?We(e.target)??e.target:e.target;return{input:{...e,cwd:n(e.cwd),...e.project_dir===void 0?{}:{project_dir:n(e.project_dir)},target:s},ctx:{...t,home:Ne(t.home),tmpdir:Ne(t.tmpdir),claudeConfigDir:n(t.claudeConfigDir)}}}function mn(e,t){let{input:n,ctx:s}=V()?Bp(e,t):{input:e,ctx:t},r=typeof s.claudeConfigDir=="string"&&s.claudeConfigDir.startsWith("/")?_e(s.claudeConfigDir):s.claudeConfigDir??null,o=s.home!==_e(s.home)||s.tmpdir!==_e(s.tmpdir)||(s.claudeConfigDir??null)!==r?{...s,home:_e(s.home),tmpdir:_e(s.tmpdir),claudeConfigDir:r}:s,a=I=>typeof I=="string"&&I.startsWith("/")?_e(I):I??null,i=n.cwd!==a(n.cwd)||(n.project_dir??null)!==a(n.project_dir)?{...n,cwd:a(n.cwd),project_dir:a(n.project_dir)}:n,l=uh(i),c=new Map,u=(I,D=!1)=>{let z=I.action==="claude.bash.db.destructive";if(i.tool!=="Bash"||!i.command||!z&&I.action!=="claude.bash.deploy")return{};if(D)return{environment:null,environment_said:null};let B=z?Fa(i.command,I.target,I.host):c.get(I.host);return B||c.set(I.host,B=Da(i.command,I.host)),{environment:B.environment,environment_said:B.said}},f=(I,D,z=[],B=[])=>{let Q=I??{action:"claude.bash.unclassified",service:null,target:null,branch:null,host:null,is_local:null,why:"no rule applies"},ce=B.find(K=>K.catastrophic),te=ce&&B.indexOf(ce)>15?[...B.slice(0,15),ce]:B.slice(0,16),ze=K=>u(K,B.length>16),Oe=K=>K.push&&B.length>16?{...K.push,repo_dir:null}:K.push;return{action:Q.action,service:Q.service,attributes:{target:Q.target,branch:Q.branch,host:Q.host,is_local:Q.is_local,args_hash:l,...ze(Q),...Oe(Q)},why:Q.why,parse:D,also:z,...B.length>1?{findings:te.map(K=>({action:K.action,service:K.service,target:K.target,why:K.why,...K.catastrophic?{catastrophic:!0}:{},...ze(K),...Oe(K),...K.host?{host:K.host}:{}}))}:{},...Q.catastrophic?{catastrophic:!0}:{},...i.tool==="Bash"&&(Q.action==="claude.bash.spend"||z.includes("claude.bash.spend"))?{units:ya(i.command)}:{},...(B.length>1?B.filter(K=>K.action===Q.action).every(K=>K.housekeeping):Q.housekeeping)?{housekeeping:!0}:{}}},p=i.tool;if(Up.has(p))return f(ch(i.args),"not-shell");if(Mp.has(p))return f(eo(p,"a subagent or workflow launch (its text is never read)"),"not-shell");if(p.startsWith("mcp__")){let I={hit:!1},D=Ch(i,o,I);return D.also&&D.also.length>0?f(D,I.hit?"limited":"not-shell",[...new Set(D.also.filter(z=>z!==D.action))]):f(D,I.hit?"limited":"not-shell")}if(mt.has(p)||fo.has(p)){let I=i.target??fh(i.args),D=I!==null&&V()?We(I)??I:I,z=[i.cwd,i.project_dir??null].find(te=>typeof te=="string"&&te.startsWith("/")&&!S(te))??null,B=D?D.startsWith("/")||D.startsWith("~")?M(D,null,o):z!==null?M(D,z,o):null:null,Q=te=>({...te,attributes:{...te.attributes,path:B!==null&&B.startsWith("/")&&!S(B)?B:null}});if(D&&mt.has(p)&&V()&&/^\/dev\/(?!(?:null|stdout|stderr|tty)$)/.test(D)&&!cs(D))return Q(f({action:"claude.bash.fs.delete_recursive",service:"fs.device",target:D,branch:null,host:null,is_local:!0,why:`writes a raw disk or volume (${D})`},"not-shell"));let ce=D&&mt.has(p)?Vn(D,o,[i.project_dir??null,i.cwd]):null;if(ce)return Q(f(ce,"not-shell"));if(D&&mt.has(p)&&lu(D,o)&&au.test(Rl(i.args)))return Q(f({action:"claude.agent.controls",service:null,target:D,branch:null,host:null,is_local:!0,why:`gives a subagent, command or skill its own bypass or unrestricted shell (${R.basename(D)})`},"not-shell"));if(D&&mt.has(p)&&(ot.test(D)||ot.test(Ey(D,o)))&&(pn(Rl(i.args))||pn(JSON.stringify(i.args??""))))return Q(f({action:"claude.agent.controls",service:null,target:D,branch:null,host:null,is_local:!0,why:`changes how every later Claude Code session starts (${R.basename(D)})`},"not-shell"));if(B!==null&&fo.has(p)&&!S(B)&&xu(B,o.home,p==="Grep"))return Q(f({action:"claude.agent.controls",service:null,target:B,branch:null,host:null,is_local:!0,why:$u},"not-shell"));if(D&&(mt.has(p)?ye(D):ko(D))){let te=mt.has(p);return Q(f({action:te?"claude.file.write_secret":"claude.file.read_secret",service:null,target:D,branch:null,host:null,is_local:!0,why:`${te?"writes":"reads"} a secrets file (${R.basename(D)})`},"not-shell"))}return Q(f(eo(p,`${p} of a regular file`),"not-shell"))}if(p==="PowerShell"&&i.command){let I=Vt(i.command,{cwd:i.cwd!==null?Je(i.cwd):null});return I.kind==="unreadable"?f(m("claude.bash.privilege",`runs PowerShell Anvil can't read (${I.why})`,{target:i.command.slice(0,200),is_local:null}),"partial"):mn({...i,tool:"Bash",command:I.text},o)}if(p!=="Bash"||!i.command)return f(eo(p,`the ${p} tool`),"not-shell");let d=i.project_dir??null,h=dt(i.command,{home:o.home,tmpdir:o.tmpdir,cwd:i.cwd,projectDir:d,claudeConfigDir:o.claudeConfigDir??null,...Ao(o)}),g={ctx:o,projectRoot:d,base:i.cwd,branch:i.git_branch,branchDir:i.cwd,createdBranches:new Map,stashApplied:new Set,stashCreated:!1,stashPushes:0,sessionId:i.session_id??null,lineText:i.command,lineMade:[],lineLaunched:[],secretCopies:new Set,links:new Map,downloads:new Set,cut:{hit:!1}},y=[];g.lineCommands=h.commands;for(let I of h.commands){Ng(I,g);for(let D of Gn(I,g))y.push(ty(D,I));Ft(g,()=>lh(I,g)),eh(I,g),th(I,g),nh(I,g)}Qp(i.command)&&y.push(m("claude.agent.controls","runs a command without Claude Code's session marker (CLAUDECODE), which Anvil uses to tell this session from the person's own terminal",{target:"CLAUDECODE",is_local:!0}));let $=g.cut.hit?"limited":h.status;if(y.length===0)return f(null,$);let E=[...y].sort((I,D)=>Ka(D)-Ka(I)),x=E[0],b=[...new Set(E.slice(1).map(I=>I.action).filter(I=>I!==x.action&&uo[I]>1))],j=f(x,$,b,E.filter(I=>uo[I.action]>1)),C=x.is_local===!0||x.host!==null&&Pc.test(x.host),A=Vp.has(x.action)&&x.catastrophic!==!0&&!x.housekeeping&&!C?Yp(i.args,x.target==="no server shown"):null;if(A===null)return j;let U=`${j.why} (Claude's description says ${A})`;return{...j,why:U,catastrophic:!0,...j.findings?{findings:j.findings.map((I,D)=>D===0?{...I,why:U,catastrophic:!0}:I)}:{}}}var Vp=new Set(["claude.bash.deploy","claude.bash.db.destructive","claude.bash.external_write","claude.bash.git.push_main","claude.bash.git.force_push","claude.bash.publish","claude.bash.secrets.print","claude.bash.secrets.expose","claude.bash.data.export","claude.bash.crypto.transaction","claude.bash.spend","claude.bash.net.expose"]),Zp=/(?<![A-Za-z0-9])(?<!(?:non|pre|not|no|un)[\s_-]?)(?:(?:prod|production)(?![A-Za-z0-9])(?![\s_-]+(?:build|bundle|ready|grade|quality|mode|deps|dependencies|code|like|image|assets|shape|parity|optimi[sz]\w*)\b)|go(?:es|ing)?[\s-]+live\b|went[\s-]+live\b|live[\s-]+(?:site|app|application|environment|env|database|db|cluster|servers?|system|stack|account|customers?|users?|traffic|instance|deployment|mode|store|services?|keys?)\b)/i,Gp=/\b(?:drop|wipe|truncate|destroy|erase|purge|nuke|delete)\w*\s+(?:(?:the|all|every|entire|whole)\s+)*(?:(?:all|every|entire|whole)\s+(?:\w+\s+)?(?:tables|databases?|dbs?|schemas?|collections|keyspaces?|clusters?)|(?:database|db|cluster)\b(?![.-]\w)(?!\s+(?:file|connection|client|config|entry|row|record|column|migration|pod|node|member|replica|shard|user|role|secret|namespace|context)s?\b))/i,Kp=/\b(local|localhost|dev|development|test|testing|tests|sandbox|scratch|temp|tmp|throwaway)\b/i;function Yp(e,t=!1){let n=e!==null&&typeof e=="object"?e.description:void 0;if(typeof n!="string")return null;let s=Math.min(n.length,500);if(n.length>500)for(;s>0&&/[A-Za-z0-9_]/.test(n[s-1]);)s--;let r=n.slice(0,s),o=r.toLowerCase();return(o.includes("prod")||o.includes("prd")||o.includes("live"))&&Zp.test(r)?"production":!t&&["drop","wipe","truncate","destroy","erase","purge","nuke","delete"].some(a=>o.includes(a))&&Gp.test(r)&&!Kp.test(r)?"a whole database or cluster is wiped":null}var Jp=/(^|\/)\.git\/(worktrees\/[^/]+\/)?((logs|refs)(\/|$)|(packed-refs|HEAD|ORIG_HEAD|FETCH_HEAD)$)/,Dn="(?:CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)",Ps=String.raw`(?:^|[;&|(\n{]\s*|\$\(\s*)(?:(?:nohup|sudo|exec|command|time|nice|builtin)\s+)*`,Xp=new RegExp([String.raw`${Ps}(?:(?:export|declare\s+-x|typeset\s+-x|local|readonly)\s+)?(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:CLAUDECODE=(?!1(?:[\s;&|)]|$))|CLAUDE_CODE_ENTRYPOINT=)`,String.raw`${Ps}setenv\s+${Dn}\b`,String.raw`${Ps}unset\s+(?:-[vf]\s+)?(?:\w+\s+){0,8}${Dn}\b`,String.raw`${Ps}env\s+(?:\S+\s+){0,8}?(?:-u\s*${Dn}\b|--unset[=\s]\s*${Dn}\b|CLAUDECODE=(?!1(?:\s|$))|CLAUDE_CODE_ENTRYPOINT=)`,String.raw`(?:del\s+os\.environ|delete\s+process\.env|environ\.pop|unsetenv|Remove-Item\s+Env:)[^;\n]{0,24}${Dn}`].join("|"));function Qp(e){return Xp.test(e.slice(0,65536))}function Ao(e){return{knownFiles:e.session?.scripts??null,unreadableFiles:e.session?.unreadableScripts??null,wantFiles:e.wantScripts??null}}function Jn(e,t,n,s=n.projectRoot){let r=dt(e,{home:n.ctx.home,tmpdir:n.ctx.tmpdir,cwd:t,projectDir:s,claudeConfigDir:n.ctx.claudeConfigDir??null,...Ao(n.ctx)});return r.status==="limited"&&(n.cut.hit=!0),r}function Xl(e,t){let n=t.lineMade.length+t.lineLaunched.length>0?{...t.ctx,session:{...t.ctx.session??{made:[],launched:[]},made:ec(t),launched:Ql(t)}}:t.ctx,s=mn(e,n);return s.parse==="limited"&&(t.cut.hit=!0),s}var Ga=200;function Ge(e,t){return e.length>Ga&&(t.hit=!0),e.slice(0,Ga)}function eh(e,t){let n=e.argv;if(e.name!=="ln"||!n.slice(1).some(l=>/^-[a-zA-Z]*s/.test(l)||l==="--symbolic"))return;let s=n.findIndex(l=>l==="--target-directory"||/^-[a-zA-Z]*t$/.test(l)),r=s>0?n[s+1]:n.find(l=>l.startsWith("--target-directory="))?.slice(19),o=n.slice(1).filter((l,c)=>!l.startsWith("-")&&c+1!==s+1&&!["-S","--suffix"].includes(n[c]??""));if(o.some(S)||r!==void 0&&S(r))return;let a=(l,c)=>R.normalize(X(l,c,se(t)).path??l),i=r!==void 0?o.map(l=>[l,R.join(r,R.basename(l))]):o.length===1?[[o[0],R.basename(o[0])]]:o.length===2?[[o[0],o[1]]]:[];for(let[l,c]of i){let u=a(c,e.cwd);t.links.set(u,a(l,R.dirname(u)))}}function th(e,t){if(!nr.has(e.name))return;let n=e.argv,s=n.find(a=>un(a));if(!s||Re(s))return;let r=e.name==="wget"?["-O","--output-document"]:["-o","--output"],o=n.find((a,i)=>r.includes(n[i-1]??""))??n.find(a=>a.startsWith(`${r[1]}=`))?.split("=")[1];o&&!S(o)&&o!=="-"&&t.downloads.add(X(o,e.cwd,se(t)).path)}function nh(e,t){if(t.lineMade.length+t.lineLaunched.length>64)return;let n=Hr(e,{home:t.ctx.home,tmpdir:t.ctx.tmpdir,projectDir:t.projectRoot});t.lineMade.push(...n.paths),t.lineLaunched.push(...n.launched)}function Ql(e){let t=e.ctx.session?.launched??[];return e.lineLaunched.length>0?[...t,...e.lineLaunched]:t}function ec(e){let t=e.ctx.session?.made??[];return e.lineMade.length>0?[...t,...e.lineMade]:t}function it(e,t){let n=e.ctx.session?.probed,s=Wn(t);if(n&&s in n)return n[s]??null;e.ctx.wantProbes?.set(s,t)}function Eo(e){let t=e.ctx.session?.startedAt;return typeof t=="number"&&t>0?t-1e3:null}function tc(e){let t=r=>{if(!r||S(r)||_e(r)===_e(e.ctx.home))return null;let o=it(e,{kind:"file",arg:r});return typeof o=="string"?o.split(" ")[0]:o},n=t(e.base),s=e.projectRoot?t(e.projectRoot):null;return n===void 0||s===void 0?null:{here:n,project:s}}function sh(e,t,n){let s=o=>o.replace(/^\/private(?=\/(?:var|tmp)\/)/,""),r=s(e);return an(r,t.here&&s(t.here))||an(r,t.project&&s(t.project))||(n.ctx.session?.made??[]).some(o=>an(r,s(o)))}var $t=e=>e.wrappers.some(t=>["sudo","doas","pkexec","run0"].includes(t)),an=(e,t)=>!!t&&(e===t||e.startsWith(`${t}/`));function Ro(e){let t=it(e,{kind:"ps"});if(typeof t!="string")return null;let n=new Map;for(let s of t.split(`
|
|
37
|
+
`)){let r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(s);r&&n.set(r[1],{ppid:r[2],command:r[3]})}return n.size>0?n:null}function sr(e,t,n,s=0){let r=n.ctx.session?.launched??[],o=t.get(e);if(!o||r.length===0||s>8)return!1;if($a(o.command,r)&&(_a(o.command,r)||Vr(o.command,r))||Sa(o.command,r)){let i=it(n,{kind:"cwd",arg:e}),l=tc(n);if(typeof i=="string"&&l&&sh(i,l,n))return!0}return o.ppid!=="0"&&o.ppid!=="1"&&o.ppid!==e&&sr(o.ppid,t,n,s+1)}function nc(e,t){let n=Ro(t);return n!==null&&(!n.has(e)||sr(e,n,t))}function rh(e,t,n){return sc(e,t,n)==="own"}function sc(e,t,n){let s=Ro(n);if(!s||e.length===0)return null;let r=!1;return e.every(a=>{let i=a.replace(/^["']|["']$/g,"");if(i===""||S(i)||/\\[A-Za-z]|\[:/.test(i))return!1;let l;try{l=new RegExp(t.exact?`^${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`:i,t.fold?"i":"")}catch{return!1}let c=[...s].filter(([,f])=>l.test(t.full?f.command:(f.command.split(/\s/)[0]??"").split("/").pop()));if(c.length===0)return t.full&&!t.exact&&/^[\w./ :=@,-]+$/.test(i);let u=c.slice(0,16).filter(([f])=>sr(f,s,n));return u.length>0&&(r=!0),c.length<=16&&u.length===c.length})?"own":r?"some":null}function rc(e,t){let n=null,s=!1;for(let l=0;l<e.length;l++){let c=e[l],u=/^-([nPtw]*)i(.*)$/.exec(c);if(u){u[1].includes("t")&&(s=!0);let f=/^(?:tcp|udp)?:(\d{2,5})$/i.exec(u[2]!==""?u[2]:e[++l]??"");if(!f||n!==null)return null;n=f[1]}else if(/^-[nPtw]+$/.test(c))c.includes("t")&&(s=!0);else return null}if(n===null||!s)return null;let r=it(t,{kind:"port",arg:n}),o=Ro(t);if(typeof r!="string"||!o)return null;let a=[...new Set(r.split(`
|
|
38
|
+
`).map(l=>l.trim()).filter(l=>/^\d+$/.test(l)))];if(a.length===0)return"own";let i=a.filter(l=>sr(l,o,t));return i.length===a.length?"own":i.length>0?"some":null}function oh(e,t,n,s,r){if((s.lineText.match(/\bstash\s+(drop|pop|clear)\b/g)??[]).length!==1||s.stashPushes>1||r.via==="xargs"||/\b(for|while|until|select)\b[\s\S]*\bdo\b|\bxargs\b|\bparallel\b/.test(s.lineText))return!1;let a=Eo(s),i=a!==null&&n?it(s,{kind:"stashes",cwd:n}):null;if(typeof i!="string")return!1;let l=i.split(`
|
|
39
|
+
`).filter(f=>f!=="").map(f=>Number(/@\{(\d+)\}/.exec(f)?.[1]??NaN)*1e3);if(l.some(f=>Number.isNaN(f)))return!1;if(t)return l.every(f=>f>=a);let c=/^stash@\{(\d+)\}$/.exec(e)?.[1];if(c===void 0)return!1;let u=l[Number(c)]??(s.stashCreated?l[Number(c)-1]:void 0);return u===void 0||u>=a}function ih(e,t,n){let s=Eo(n);if(/\bbranch\b[^;&|\n]*\s(-[a-zA-Z]*[mMcC][a-zA-Z]*|--move|--copy)(\s|$)/.test(n.lineText)||s===null||!t||!/^[\w./-]+$/.test(e)||e.startsWith("-"))return!1;let r=it(n,{kind:"branch",arg:e,cwd:t}),o=typeof r=="string"?r.trim().split(`
|
|
40
|
+
`).pop()??"":"",a=/@\{(\d+)\} branch: Created from /.exec(o);return a!==null&&Number(a[1])*1e3>=s}function oc(e,t){return it(t,{kind:"ignored",arg:e,cwd:R.dirname(e)})===""}function ah(e,t){if(S(e))return null;let n=Eo(t),s=it(t,{kind:"file",arg:e}),r=tc(t),o=oc(e,t);if(typeof s!="string"||!r||!o)return null;let[a,i]=s.split(" ");return!an(a,r.here)&&!an(a,r.project)?null:n!==null&&Number(i)>=n?"own":"dev"}function Ie(e,t,n){if(n.links.size===0||S(e))return e;let s=e.startsWith("/")?e:e.startsWith("~/")?n.ctx.home+e.slice(1):t.cwd?`${t.cwd}/${e}`:e;if(!s.startsWith("/"))return e;let r=s.split("/").filter(i=>i!==""),o="/",a=!1;for(let[i,l]of r.entries()){if(l===".")continue;o=l===".."?R.dirname(o):R.join(o,l);let c=i===r.length-1&&!s.endsWith("/");for(let u=0;!c&&u<8&&n.links.has(o);u++)o=n.links.get(o),a=!0}return a?o+(s.endsWith("/")?"/":""):e}function lh(e,t){let n=e.argv.slice(1).filter(a=>!a.startsWith("-")),s=a=>t.secretCopies.add(X(a,e.cwd,se(t)).path);if(["cp","mv","install","ditto","rsync"].includes(e.name)&&n.length>=2&&n.slice(0,-1).some(a=>ye(a)||t.secretCopies.has(X(a,e.cwd,se(t)).path))&&s(n[n.length-1]),e.name==="cat"&&n.some(a=>ye(a)))for(let a of e.redirects)(a.op===">"||a.op===">>")&&a.target&&s(a.target);let r=[];for(let a=1,i=!1;a<e.argv.length;a++){let l=e.argv[a];if(["--exclude","--exclude-from","-X"].includes(l))a++;else{if(l.startsWith("--exclude"))continue;e.name==="zip"&&(l==="-x"||l==="--exclude")?i=!0:l.startsWith("-")?i=!1:i||r.push(l)}}if(["tar","gtar","bsdtar","zip","7z"].includes(e.name)&&r.some(a=>ye(a)||/(^|\/)\.(ssh|aws|gnupg|kube)\/?$/.test(k(a)))){let a=/^[A-Za-z]+$/.test(e.argv[1]??"")&&(e.argv[1]??"").includes("f")?e.argv[2]:void 0,i=P(e.argv,"-f","--file")??Bs(e.argv,"f")??a??(e.name==="zip"||e.name==="7z"?n.find(l=>/\.(zip|7z)$/.test(l)):n[0]);i&&s(i)}let o=e.stdinFile!==null&&ye(e.stdinFile)||e.pipeFrom!==null&&e.pipeFrom.name==="cat"&&e.pipeFrom.argv.slice(1).some(a=>ye(a));if(e.name==="tee"&&o)for(let a of n)s(a)}function Ka(e){return(e.service&&zp.has(e.service)?100:0)+uo[e.action]}function ch(e){let t=e&&typeof e=="object"?e:{},n=typeof t.subagent_type=="string"&&t.subagent_type.trim()?t.subagent_type.trim():"general-purpose",s=/^[A-Za-z0-9_.:-]{1,64}$/.test(n)?n:`type-${Yl("sha256").update(n).digest("hex").slice(0,8)}`,r=typeof t.model=="string"&&/^[a-z0-9.\-[\]]{1,40}$/i.test(t.model)?t.model:null;return{action:qp,service:null,target:s,branch:null,host:null,is_local:null,why:`launches a helper agent (${s}${r?`, ${r}`:""})`}}function eo(e,t){return{action:"claude.tool.other",service:null,target:e,branch:null,host:null,is_local:null,why:t}}function uh(e){if(e.args===void 0&&e.command===null&&e.tool.startsWith("mcp__"))return null;let t=e.args!==void 0?po(e.args):e.command??e.target??"";return Yl("sha256").update(JSON.stringify([e.tool,t])).digest("hex").slice(0,16)}var dh=64;function po(e,t=0){return t>dh?"[nested too deep]":Array.isArray(e)?e.map(n=>po(n,t+1)):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,po(e[n],t+1)])):e}function fh(e){if(!e||typeof e!="object")return null;let t=e;for(let n of["file_path","notebook_path","path"])if(typeof t[n]=="string")return t[n];return null}var zn=new Set(["ask","get","list","search","read","fetch","find","query","describe","view","show","lookup","check","count","browse","preview","inspect","status","info","details","stats","history","logs","index","guide","help","export","download","screenshot","validate","diff","compare","estimate","explain","summarize","extract","scrape","research","retrieve","whoami","analyze","analyse","aggregate","size","health","usage","schema","metadata","metrics","overview","summary","parse"]),wt=new Set(["send","reply","forward","post","publish","deploy","merge","delete","remove","destroy","purge","trash","wipe","drop","purchase","buy","pay","payout","refund","charge","transfer","withdraw","cancel","revoke","archive","unpublish","create","update","write","insert","append","upload","share","grant","execute","exec","upsert","submit","invite","modify","patch","put","replace","schedule","approve","provision","trigger","enable","disable","assign","import","add","set","close","stop","scale","rollout","transition","restore","invoke","fork","move","rename","clear","discard","clean","edit","run","change","save","store","commit","push","start","restart","pause","resume","reopen","resolve","mark","pin","unpin","react","star","follow","subscribe","unsubscribe","link","unlink","attach","detach","lock","unlock","block","ban","mute","duplicate","copy","sync","apply","rebase","draft","notify","reserve","register","claim","redeem","capture","void","mint","broadcast","swap","stake","activate","deactivate","suspend","reset","rotate","generate","train","launch","spawn","kill","terminate","reboot","shutdown","setup","manage","configure","initialize","init","install","uninstall","upgrade","migrate","seed","reindex"]),vt=new Set(["delete","remove","destroy","purge","trash","wipe","drop","terminate","reset","flush","rollback","revert","rotate","revoke","kill","truncate","erase","push","apply","merge","deploy","publish","refund","charge","pay","payout","transfer","clear","restore","discard"]),ph=/^(ccd_(turn|view|window|sidebar|session|directory)|visualize|claude_browser|claude_in_chrome|computer_use)$/,hh=/^ccd_pr__(set_monitor|bind_pr|unbind_pr|get_status)$/,Ya=/^(playwright|puppeteer|browser|browsermcp|browser_use|chrome_devtools|chrome|everything|filesystem|fs|files|desktop_commander|desktopcommander|git|docker|sqlite)$/,gh=/^(memory|sequential_thinking|sequentialthinking|time)$/,mh=new Set(["push","delete","clean","force","rebase","prune","gc","filter"]),yh=new Set(["env","environment","secret","secrets","credential","credentials","password","passwords"]),bh=new Set(["backups","deployments","releases","migrations","payments","payouts","refunds","transfers","charges","subscriptions","jobs","runs","builds","workflows","stacks","instances","clusters","resources","records","messages","emails","invites","invitations","webhooks","keys","tokens","secrets","domains","dns","databases","tables","volumes","buckets","users","members","roles","permissions"]),wh=new Set(["hget","hgetall","hexists","hkeys","hvals","hlen","lrange","llen","lindex","smembers","sismember","scard","zrange","zscore","zcard","exists","ttl","pttl","type","dbsize","xrange","xlen","mget","scan","keys"]),kh=/^(context7|brave_search|brave|fetch|deepwiki|ref|microsoft_docs|aws_docs|mcp_registry)$/,vh=/^(filesystem|fs|files|desktop_commander|desktopcommander)$/;function ic(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function zs(e){let t=ic(e);if(t.length===0)return"unknown";let n=t[0],s=t[t.length-1],r=t.find(a=>zn.has(a)||wt.has(a)||vt.has(a))??n;return t.some(a=>vt.has(a))&&!zn.has(r)||t.findIndex((a,i)=>i>0&&["or","and","then"].includes(a)&&t.slice(i+1).some(l=>wt.has(l)||vt.has(l)))>0?"write":zn.has(r)||zn.has(s)&&!t.slice(0,-2).some(a=>wt.has(a))&&!wt.has(n)?"read":t.some(a=>wt.has(a))?"write":t.length===1&&wh.has(n)||t.length>1&&/[a-z]{3}s$/.test(s)&&!/(ss|us|is)$/.test(s)&&!bh.has(s)?"read":"unknown"}function $h(e){return e.length===1?["bash","shell","terminal","sh","zsh"].includes(e[0]):(e.includes("write")||e.includes("send"))&&e.includes("terminal")||e.includes("bash")&&e.includes("command")?!0:e.some(t=>["run","exec","execute","start","interact"].includes(t))&&e.some(t=>["command","commands","terminal","shell","script","cmd","bash","process"].includes(t))}function xh(e){let t=e.args!==void 0?e.args:e.command?ac(e.command):void 0;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ac(e){try{return JSON.parse(e)}catch{return}}function nn(e,t){for(let n of t)if(e&&typeof e[n]=="string")return e[n];return null}function Ja(e){if(!e)return[];let t=[];for(let n of["path","file_path","filePath","relative_path","relativePath","pathInProject","repo_path","repoPath","source","destination","target","targetPath","sourcePath","destinationPath","file","filename","dest","from","to","old_path","new_path","oldPath","newPath","paths","files"]){let s=e[n];if(typeof s=="string")t.push(s);else if(Array.isArray(s))for(let r of s.slice(0,64))typeof r=="string"&&t.push(r)}return V()?t.map(n=>We(n)??n):t}function lc(e,t){if(e.action==="claude.bash.unclassified")return[];let n={action:e.action,service:e.service,target:e.attributes.target,branch:e.attributes.branch,host:e.attributes.host,is_local:e.attributes.is_local,why:`${e.why} ${t}`};return[n,...e.also.filter(s=>s!==e.action).map(s=>({...n,action:s,service:null}))]}var _h=new Set(["supabase","neon","planetscale","turso","bigquery","snowflake","databricks","motherduck","xata","cloudflare","d1","upstash","spanner","redshift","tinybird","firebase","railway","render","heroku","vercel","nile","tidb","aiven","aws","azure","gcp"]),Sh=/^(database|db|database_?name|db_?name|branch|branch_?name|branch_?id|project|project_?id|project_?ref|env|environment|schema|catalog|dataset|instance)$/i;function Ch(e,t,n){let[,s="",r=""]=e.tool.split("__"),o=Qa(s),a=`mcp.${o}.${Qa(r)}`,i=ic(r),l=xh(e),c=p=>({action:"claude.mcp.call",service:null,target:a,branch:null,host:o,is_local:null,why:p}),u=p=>({action:"claude.mcp.side_effect",service:null,target:a,branch:null,host:o,is_local:null,why:p});if($h(i)||nn(l,["cli_command"])!==null){let p=l?.action_json,d=typeof p=="string"?ac(p):p,h=nn(l,["command","cmd","script","input","code","cli_command"])??nn(d&&typeof d=="object"&&!Array.isArray(d)?d:null,["command","cmd"]);if(h===null)return u(`an MCP tool that runs shell commands, with no command to read (${a})`);let g=nn(l,["cwd","workdir","directory"])??e.cwd,y=mn({tool:"Bash",command:h,target:null,cwd:g,git_branch:e.git_branch,project_dir:e.project_dir??null,session_id:e.session_id??null},t);return y.parse==="limited"&&(n.hit=!0),ku(h,g,t,e.project_dir??null,n,i.includes("terminal"))?y.action==="claude.bash.unclassified"?c(`an MCP tool running a command no rule flags (${a})`):{action:y.action,service:y.service,target:y.attributes.target,branch:y.attributes.branch,host:y.attributes.host,is_local:y.attributes.is_local,why:`${y.why} (run by ${a})`,also:y.also}:{action:"claude.agent.controls",service:null,target:a,branch:null,host:o,is_local:!0,why:`hands a command to ${a}, which may run it outside this session, and Anvil cannot read that command here`}}if(zs(r)!=="read"){let p=Ja(l).map(h=>Vn(h,t,[e.project_dir??null,e.cwd])).filter(h=>h!==null),d=p.find(h=>h.action==="claude.agent.controls")??p[0];if(d)return{...d,host:o,also:[...new Set(p.map(h=>h.action))]};for(let h of Ja(l))if(ot.test(h)&&pn(JSON.stringify(l)))return{action:"claude.agent.controls",service:null,target:h,branch:null,host:o,is_local:!0,why:`changes how every later Claude Code session starts (${R.basename(h)}, through ${a})`}}if(vh.test(o)){let p=nn(l,["path","file_path","filePath","destination","target"]),d=zs(r);if(p&&ye(p)){let h=d!=="read";return{action:h?"claude.file.write_secret":"claude.file.read_secret",service:null,target:p,branch:null,host:o,is_local:!0,why:`${h?"writes":"reads"} a secrets file (${R.basename(p)}) through ${a}`}}}if(i.some(p=>["sql","query"].includes(p))&&i.some(p=>["run","execute","exec","query"].includes(p))){let p=nn(l,["sql","query","statement"]);if(p!==null&&!(Mo.test(p)||be.test(p)))return c(`an MCP tool running a read-only query (${a})`);let d=on(p),h=o.split("_").some(y=>_h.has(y))&&!o.split("_").includes("local"),g=d===null?void 0:[...Object.entries(l??{}).filter(([y,$])=>Sh.test(y)&&typeof $=="string"&&$.length<200&&!/\s/.test($)).map(([,y])=>y)].find(or);if(p!==null)return d!==null&&(h||g!==void 0)?{...u(`an MCP tool running destructive SQL (${d}) on ${g!==void 0?`${g}, named for production`:`${o}'s hosted database`} (${a})`),catastrophic:!0}:u(`an MCP tool running SQL that writes (${a})`)}if((i.includes("sql")||i.includes("query")&&i.some(p=>["database","db","d1","sql"].includes(p)))&&!Ya.test(o))return u(`an MCP tool that runs SQL, with no statement to read (${a})`);if(hh.test(`${o}__${r}`))return c(`a setting of this machine's own app (${a})`);if(ph.test(o)){let p=i.find(d=>["upload","send","submit","purchase","buy","publish"].includes(d));return p?u(`a browser tool that ${p}s something to a website (${a})`):c(`a tool of this machine's own app (${a})`)}if(gh.test(o))return c(`the agent's own notes or thinking (${a})`);let f=zs(r);if(i.some(p=>yh.has(p))&&f!=="write")return u(`an MCP tool that reads secrets or the environment (${a})`);if(kh.test(o)){let p=i.find(d=>vt.has(d)||["upload","send","submit","publish","post","create","update","write"].includes(d));return p?u(`an MCP tool that ${p}s (${a})`):c(`a documentation tool (${a})`)}if(Ya.test(o)){let p=o==="git"?i.find(h=>mh.has(h)):i.find(h=>vt.has(h));if(p&&!zn.has(i[0]??""))return u(`a local MCP tool that ${p}s (${a})`);if(o==="docker"&&i.some(h=>["run","exec","execute"].includes(h)))return u(`a local MCP tool that runs a container or a command in one (${a})`);let d=i.find(h=>["upload","send","submit","purchase","buy","publish","post"].includes(h));return d?u(`a local MCP tool that ${d}s something to another service (${a})`):f==="write"&&i.some(h=>["config","configuration","settings","setting","permission","permissions","policy"].includes(h))?u(`a local MCP tool that changes its own configuration (${a})`):c(`a tool that acts on this machine (${a})`)}return f==="read"?c(`an MCP tool that reads (${a})`):Ph(i,l)?c(`an MCP edit to a document's content (${a})`):f==="unknown"&&["profile","me","whoami"].includes(i[i.length-1]??"")&&!i.some(p=>wt.has(p)||vt.has(p))?c(`an MCP tool that returns the caller's profile (${a})`):u(f==="write"?`an MCP tool that ${i.find(p=>vt.has(p))??i.find(p=>wt.has(p))}s (${a})`:`an MCP tool whose name does not say it only reads (${a})`)}var Ah=new Set(["update","edit","append","insert","write","replace","patch","save","create","batch","add","set","modify","change","draft","rename"]),Eh=new Set(["doc","docs","document","documents","page","pages","block","blocks","note","notes","section","sections","tab","tabs","paragraph","paragraphs","wiki","article","articles","markdown","prose"]),Rh=new Set(["delete","remove","destroy","purge","trash","archive","share","unshare","publish","unpublish","send","post","comment","invite","grant","permission","permissions","move","transfer","email","notify","export"]),Oh=/^(share|shares|sharing|shared_with|permission|permissions|visibility|public|is_public|publish|published|invite|invites|invitees|recipient|recipients|to|cc|bcc|email|emails|role|roles|grant|grants|notify|send|send_notification|acl|access|access_level|link_sharing)$/i,Xa=/share|publish|permission|invite|send|notify|email|trash|archive|transfer|(delete|remove)[-_ ]?(doc|document|page|file|project)/i,jh=/^(page_?id|document_?id|doc_?id|block_?id|note_?id|documentId|pageId|docId|blockId|noteId)$/i;function Ph(e,t){if(!t||e.length===0||!e.some(a=>Ah.has(a))||e.some(a=>Rh.has(a)))return!1;let n=!1,s=!1,r=!1,o=(a,i)=>{if(!(n||i>12||a===null||typeof a!="object")){if(Array.isArray(a)){for(let l of a.slice(0,500))o(l,i+1);return}for(let[l,c]of Object.entries(a))Oh.test(l)&&(n=!0),jh.test(l)&&(s=!0),["op","type","action","operation"].includes(l)&&typeof c=="string"&&Xa.test(c)&&(n=!0),(l==="kind"&&typeof c=="string"&&/^(blocks?|text|tabs?|range|paragraphs?|sections?|heading|inline|markdown)$/.test(c)||l==="engine"&&typeof c=="string")&&(r=!0),i===0&&l==="container"&&c&&typeof c=="object"&&typeof c.kind=="string"&&(r=!0),i===0&&l==="ref"&&c&&typeof c=="object"&&/^(project|tab|node|doc|document|page|block)$/.test(String(c.object))&&(r=!0),l==="kind"&&typeof c=="string"&&Xa.test(c)&&(n=!0),o(c,i+1)}};return o(t,0),n?!1:e.some(a=>Eh.has(a))||s||r}function Qa(e){return e.toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"")||"unknown"}var cc=new Set(["main","master"]),Wh=new Set(["production","prod","live"]);function m(e,t,n={}){let s=t.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g,""),r=s.length>300?`${s.slice(0,297)}\u2026`:s,o=typeof n.target=="string"&&n.target.length>200?{...n,target:`${n.target.slice(0,197)}\u2026`}:n;return{action:e,service:null,target:null,branch:null,host:null,is_local:null,why:r,...o}}function Nh(e,t){if(!S(e.argv[0]??""))return[];let n=e.argv.slice(1),s=[];n.some(o=>/^-[rRfviIdP]*[rR][rRfviIdP]*$/.test(o)||o==="--recursive")&&n.some(o=>!o.startsWith("-"))&&s.push(...Io({...e,name:"rm",argv:["rm",...n]},t)),(n.includes("manage.py")||n.some(o=>/^db:(drop|reset)/.test(o)))&&s.push(...Hs({...e,name:"python",argv:["python",...n]}));let r=o=>({...e,name:o,argv:[o,...n]});return["push","reset","clean","branch","stash","checkout","restore"].includes(n[0]??"")&&s.push(...Ac(r("git"),t)),["destroy","apply"].includes(n[0]??"")&&n.some(o=>o.startsWith("-auto-approve")||o==="-auto-approve")&&s.push(...Hs(r("terraform"))),["delete","apply","replace","drain"].includes(n[0]??"")&&s.push(...Hs(r("kubectl"))),["publish","unpublish"].includes(n[0]??"")&&s.push(...qc(r("npm"))),n.includes("-c")&&be.test(ke(n.join(" ")))&&s.push(...Ho(r("psql"),t)),s.map(o=>o.why.includes("cannot name")?o:{...o,why:`${o.why} (by a program it cannot name: ${k(e.argv[0])})`})}function Gn(e,t){if(e.functionCall)return[...Kl(e,t),...El(e,t),...tr(e,t)];let n=Bm(e.argv);if(n!==null)return Gn({...e,name:ue(n[0]),argv:n},t);if(["pnpm","yarn","bun"].includes(e.name)){let{sub:o,at:a}=bs(e.argv);if(a>0&&!qo.has(o)&&Em.has(o))return Gn({...e,name:o,argv:[o,...e.argv.slice(a+1)]},t)}if(e.argv.slice(1).some((o,a)=>(o==="--help"||o==="--version"&&a===0)&&!/^-/.test(e.argv[a]??""))||["help","--help"].includes(e.argv[1]??""))return e.redirects.length>0?tr({...e,name:"echo",argv:["echo"]},t):[];let s=[];s.push(...Bb(e,t)),s.push(...ew(e)),s.push(...lw(e,t)),s.push(...Nh(e,t)),s.push(...Kl(e,t));let r=e.name;switch(r){case"rm":case"unlink":case"shred":case"srm":case"rimraf":s.push(...Io(e,t));break;case"rsync":s.push(...$c(e,t));break;case"find":s.push(...Rg(e,t));break;case"fd":case"fdfind":s.push(...jg(e,t));break;case"dd":case"mkfs":case"diskutil":case"wipefs":case"fdisk":case"newfs_apfs":case"newfs_hfs":s.push(...fl(e,t));break;case"git":s.push(...Ac(e,t));break;case"gh":s.push(...zg(e,t.lineText,t));break;case"curl":case"wget":case"http":case"https":case"xh":s.push(...Mg(e));break;case"pkill":case"killall":case"kill":case"fuser":case"colima":case"launchctl":case"tmux":case"systemctl":case"shutdown":case"reboot":case"halt":case"osascript":s.push(...Yg(e,t));break;default:break}if(r.startsWith("mkfs.")&&s.push(...fl(e,t)),s.length===0&&s.push(...Mh(e,t)),s.push(...Hs(e)),(r==="docker"||r==="podman"||r==="docker-compose")&&!s.some(o=>o.action==="claude.bash.deploy")&&s.push(...wm(e,t.lineText)),s.length===0&&s.push(...Uh(e)),s.push(...Ho(e,t)),s.push(...Ft(t,()=>dy(e,t))),s.push(...El(e,t)),s.push(...Ft(t,()=>hy(e,t))),s.push(...qb(e,t)),s.push(...Yb(e,t)),V()&&s.push(...lb(e,t)),s.push(...fg(e)),s.length===0&&s.push(...Vm(e)),s.length===0&&s.push(...Lh(e)),s.length===0&&s.push(...Bh(e)),s.length===0&&s.push(...Ft(t,()=>kg(e,t))),!s.some(o=>o.action==="claude.bash.db.destructive"&&!o.why.includes(" runs SQL that changes data ("))){let o=Hm(e,t);if(o.length>0){for(let a=s.length-1;a>=0;a--)s[a].why.includes(" runs SQL that changes data (")&&s.splice(a,1);s.push(...o)}}return["aws","gcloud","az"].includes(e.name)&&e.argv.some(o=>o==="update-kubeconfig"||o==="get-credentials")&&P(e.argv,"--file","-f")!=="-"&&!T(e.argv,"--dry-run")?s.filter(o=>o.action!=="claude.bash.deploy"&&o.action!=="claude.bash.secrets.print"):s}var Oo=new Set(["npm","pnpm","yarn","bun","npx","pnpx","bunx","deno","node","nodejs","pip","pip3","pipx","poetry","uv","pdm","hatch","rye","conda","mamba","micromamba","brew","apt","apt-get","yum","dnf","pacman","apk","port","nix","nix-env","flatpak","snap","cargo","rustup","gem","bundle","bundler","go","composer","pod","carthage","flutter","dart","dotnet","mvn","gradle","make","cmake","ninja","bazel","xcodebuild","xcrun","swift","nvm","fnm","volta","asdf","mise","rbenv","pyenv","sdk","direnv","pre-commit","husky","lefthook","git","hg","svn","docker","podman","colima","minikube","kind","k3d","vagrant","tmux","screen","code","cursor","vim","nvim","emacs","jest","vitest","pytest","mocha","eslint","prettier","tsc","python","python3","ruby","perl","php","java","echo","printf","ls","cat","grep","rg","sed","awk","jq","yq","sort","uniq","head","tail","wc","cut","tr","tee","touch","mkdir","cp","mv","ln","chmod","chown","tar","zip","unzip","gzip","gunzip","open","say","defaults","du","df","stat","file","which","type","command","test","true","false","sleep","wait","date","seq","basename","dirname","realpath","readlink","cd","export","unset","set","source","eval","exec","trap","read","history","sqlite3","redis-server","pg_ctl","initdb","ollama","anvil","anvil-claude","claude","pm2","nodemon","turbo","nx","lerna","changeset","rimraf","trash","kubectx","kubens","corepack","tsx","ts-node","esbuild","vite","next","webpack","rollup","parcel","storybook","playwright","cypress","lsof","ps","top","pgrep","pkill","kill"]),el=null;function Zs(e){return el??=new Set([...Object.keys(Tc),...nr,"aws","az","gcloud","gsutil","bq","kubectl","helm","terraform","tofu","pulumi","psql","mysql","mariadb","mongosh","mongo","mongoimport","mongorestore","pg_restore","pg_dump","redis-cli","clickhouse","clickhouse-client","cqlsh","snowsql","snow","beeline","impala-shell","spark-sql","heroku","railway","vercel","wrangler","fly","flyctl","firebase","doppler","infisical","vault","op","security","gpg","gpg2","prisma","alembic","artisan","rails","rake","flask","rsync","find","fd","dd","gh","ssh","scp","sftp","crontab","systemctl","launchctl","ngrok","cloudflared","tailscale","stripe","cast","forge","solana","fastlane","eas","7z","7za","7zr","7zz","aider","amp","anchor","anvil","anvil-claude","ape","aptos","artisan","at","autossh","awk","aws","az","azcopy","base64","batch","bcp","beeline","bitcoin-cli","bore","bq","branch","brew","brownie","bsdtar","bun","cardano-cli","cast","checkout","chflags","chgrp","chmod","chown","claude","clean","clickhouse","clickhouse-client","cloudflared","cmp","cockroach","code","code-insiders","codex","colima","copilot","cp","cqlsh","croc","crontab","crush","curl","cursor-agent","cut","databricks","dbt","dd","ddev","deno","devtunnel","diff","diskutil","ditto","docker","droid","dropdb","dropuser","duckdb","ed","egrep","emacs","ex","expo","fastmcp","fd","fdfind","fdisk","ffsend","filter-branch","filter-repo","find","firebase","fish","fly","flyctl","flyway","forge","frpc","fuser","gawk","gc","gcloud","gcp","gemini","gh","git","glab","gmv","gpg","gpg2","grep","gsed","gsutil","gtar","halt","hardhat","head","herd","heroku","http","https","impala-shell","install","install-mcp","jq","kill","killall","knex","kubectl","launchctl","liquibase","ln","lncli","localxpose","loclx","lt","mariadb","mariadb-dump","mawk","mc","mcp-get","md5","md5sum","mix","mkfifo","mkfs","mknod","mongo","mongodump","mongoexport","mongosh","mv","mydumper","mysql","mysqladmin","mysqldump","mysqlpump","nawk","nc","ncat","near","neon","neonctl","netcat","newfs_apfs","newfs_hfs","ngrok","node","nvim","oc","openssl","osascript","patch","pbcopy","perl","pg_basebackup","pg_dump","pg_dumpall","pgcli","php","pkill","plutil","pm2","podman","powershell","powershell.exe","presto","prisma","pscale","psql","push","pwsh","pwsh.exe","python","python3","q","qwen","rclone","reboot","red","redis-cli","reflog","reset","restore","rg","rimraf","rm","rsync","ruby","s3cmd","schtasks","schtasks.exe","scp","security","sed","sequelize","sequelize-cli","set","sftp","sha256sum","shasum","shred","shutdown","smithery","snow","snowsql","socat","solana","soroban","sort","spark-sql","spl-token","sponge","sqlcmd","sqlite","sqlite3","srm","ssh","starkli","stash","stellar","stripe","sui","supabase","switch","symbolic-ref","systemctl","tailscale","tar","tee","telnet","tmole","tmux","touch","trash","trino","true","truffle","truncate","ts-node","tsx","tunnelmole","turso","typeorm","typeorm-ts-node-commonjs","typeorm-ts-node-esm","unlink","untun","unzip","update-ref","valet","vi","vim","wc","wget","wipefs","worktree","wormhole","wrangler","xclip","xh","yq","zrok","format","format-volume","clear-disk","initialize-disk","remove-partition","clear-recyclebin","diskpart","vssadmin","wmic","wbadmin","wsl","bcdedit","reg","set-itemproperty","new-itemproperty","remove-itemproperty","remove-item","sc","new-service","remove-service","set-service","stop-service","register-scheduledtask","set-scheduledtask","unregister-scheduledtask","new-scheduledtask","set-executionpolicy","set-mppreference","add-mppreference","netsh","set-netfirewallprofile","new-netfirewallrule","disable-netfirewallrule","remove-netfirewallrule","takeown","icacls","taskkill","runas","gsudo","mountvol","robocopy","setx","forfiles"]),ab.has(e)?V():el.has(e)}var rn=new Set(["delete","destroy","drop","purge","wipe","terminate","nuke","erase","truncate","flushall","flushdb","teardown","decommission","deprovision","deregister","tombstone"]),to=new Set(["rm","remove","reset","revoke"]),uc=new Set(["app","apps","application","applications","project","projects","bucket","buckets","database","databases","db","dbs","cluster","clusters","service","services","instance","instances","volume","volumes","branch","branches","environment","environments","env","envs","secret","secrets","domain","domains","zone","zones","record","records","dns","repo","repos","repository","repositories","deployment","deployments","function","functions","table","tables","queue","queues","topic","topics","stream","streams","namespace","namespaces","org","orgs","organization","organizations","team","teams","user","users","member","members","workspace","workspaces","site","sites","server","servers","machine","machines","vm","vms","droplet","droplets","pool","pools","stack","stacks","schema","schemas","collection","collections","keyspace","keyspaces","storage","backup","backups","snapshot","snapshots","token","tokens","webhook","webhooks","subscription","subscriptions","account","accounts","pg","postgres","mysql","redis","kv","d1","r2","s3","index","indexes","indices","key","keys","certificate","certificates","cert","certs","distribution","distributions","role","roles","policy","policies","vpc","subnet","subnets","gateway","node","nodes","worker","workers","job","jobs","pipeline","pipelines","model","models","endpoint","endpoints","volume-snapshot","organization-member","tenant","tenants","serverless","store","stores","region","regions","replica","replicas","shard","shards","partition","partitions","tablet","tablets","broker","brokers","changefeed","changefeeds","network","networks","firewall","firewalls","disk","disks","peer","peers","keyring","keyrings","vault","vaults"]),jo=new Set(["database","databases","db","dbs","table","tables","schema","schemas","collection","collections","keyspace","keyspaces","pg","postgres","mysql","redis","kv","d1","index","indexes","indices","backup","backups","snapshot","snapshots","bucket","buckets","storage","r2","s3","volume","volumes","store","stores","region","regions","replica","replicas","shard","shards","partition","partitions","tablet","tablets","disk","disks","vault","vaults"]),Po=/^--?(dry-?run|plan|preview|what-?if|check|diff|validate|help|version|list|ls)$/i;function dc(e){let t=[];for(let n=1;n<e.length&&t.length<6;n++){let s=k(e[n]);if(!s.startsWith("-")&&/^[a-z][a-z0-9_-]*(:[a-z0-9_-]+)*$/.test(s))for(let r of s.split(":"))r&&t.push(r)}return t}function Wo(e){let t=R.basename(e.name);return["const","let","var"].includes(t)&&k(e.argv[2]??"")==="="?!0:/^[A-Z][a-z]+$/.test(t)&&e.argv.length>=4&&e.argv.slice(1).some(n=>/[a-z]\.$/.test(k(n)))}function Lh(e){let t=R.basename(e.name);if(!t||Oo.has(t)||Zs(t)||e.functionCall||e.via==="substitution"||S(e.argv[0]??"")||e.argv[0]?.includes("/"))return[];if(Wo(e))return[];let n=dc(e.argv);if(n.length===0||e.argv.some(u=>Po.test(u)))return[];let s=u=>rn.has(u)||to.has(u)?u:rn.has(u.split("-")[0]??"")||to.has(u.split("-")[0]??"")&&!Ks.has(u.split("-").slice(1).join("-"))?u.split("-")[0]:null,r=n.findIndex(u=>s(u)!==null);if(r>=0){let u=s(n[r]);n[r].includes("-")&&!rn.has(n[r])&&n.splice(r+1,0,n[r].slice(u.length+1));let f=n.flatMap(h=>[h,...h.split("-")]).find(h=>uc.has(h)),p=n.filter((h,g)=>g!==r||h.includes("-")).flatMap(h=>h.split("-")).filter(h=>h!==u);if(f===void 0&&p.length>0&&p.every(h=>mc.has(h)))return[];let d=n.length>r+1||e.argv.some(h=>/^--?(app|project|name|id|db|database|bucket|cluster|service|instance|env|environment|org|zone|branch)(=|$)/.test(h)||Lo.test(k(h)));if(rn.has(u)&&(f!==void 0||d)||to.has(u)&&f!==void 0){let h=jo.has(f??"")||["drop","truncate","flushall","flushdb","purge","wipe"].includes(u);return[m(h?"claude.bash.db.destructive":"claude.bash.deploy",`${t} ${qs(u)} ${f?mo(f):"what it names"} (a command with no rule of its own, read by its words)`,{target:`${t} ${n.slice(0,3).join(" ")}`,is_local:!1})]}}let o="(a command with no rule of its own, read by its words)",a=e.argv.some(u=>/\b(localhost|127\.0\.0\.1|::1)\b|^--local$/.test(k(u))),i=e.argv.map(u=>k(u)),l=i.slice(1).find((u,f)=>/\s/.test(u)&&!/^(i?like|=|!=|<>)$/i.test(i[f]??"")&&be.test(ke(u)));if(l!==void 0&&!a)return[m("claude.bash.db.destructive",`${t} runs SQL that changes data (${(be.exec(ke(l))?.[1]??"").replace(/\s+/g," ").toUpperCase()}) ${o}`,{target:t,is_local:!1})];let c=n.findIndex(u=>Ks.has(u));return c>=0&&n.some(u=>kc.has(u))&&ae(e)?[m("claude.bash.secrets.print",`${t} prints ${mo(n[c])} ${o}`,{target:`${t} ${n.slice(0,3).join(" ")}`,is_local:!0})]:n.slice(0,3).some(u=>_u.test(u))?[m("claude.bash.deploy",`${t} ${n.slice(0,2).join(" ")} deploys or publishes ${o}`,{target:`${t} ${n.slice(0,2).join(" ")}`,is_local:!1})]:n.some(u=>["tunnel","expose","funnel"].includes(u))&&e.argv.some(u=>/^(\d{2,5}|localhost:\d{2,5}|127\.0\.0\.1:\d{2,5}|https?:\/\/(localhost|127\.0\.0\.1):\d{2,5})$/.test(k(u)))?[m("claude.bash.net.expose",`${t} opens a local port to the internet ${o}`,{target:t,is_local:!1})]:[]}var Th=new Set(["-c","-F","-i","-J","-l","-o","-P","-S","-D","-X"]),Ih=new Set(["-e","-f","-T","-B","-M","--rsh","--exclude","--include","--filter","--exclude-from","--include-from","--files-from","--rsync-path","--password-file","--chmod","--chown","--log-file","--temp-dir","--partial-dir","--backup-dir","--suffix","--port","--bwlimit","--timeout","--max-size","--min-size","--compare-dest","--copy-dest","--link-dest"]),fc=new Set(["--config","--transfers","--checkers","--include","--exclude","--filter","--include-from","--exclude-from","--filter-from","--files-from","--max-age","--min-age","--max-size","--min-size","--log-file","--log-level","--bwlimit","--backup-dir","--suffix","--max-depth","--order-by","--tpslimit","--retries"]),Dh=/^(localhost|127\.0\.0\.1|\[::1\]|::1)$/i,Fh=new Set(["copy","copyto","move","moveto","sync","bisync","rcat","copyurl","delete","deletefile","purge","rmdir","rmdirs","cleanup","dedupe"]),zh=new Set(["rcat","delete","deletefile","purge","rmdir","rmdirs","cleanup","dedupe"]);function Mh(e,t){let n=R.basename(e.name);if(!["scp","rsync","rclone"].includes(n))return[];let s=e.argv.map(u=>k(u));if(s.some(u=>u==="-n"||u==="--dry-run"||n==="rsync"&&/^-[a-zA-Z]*n[a-zA-Z]*$/.test(u)))return[];let o=pe(s,1,n==="scp"?Th:n==="rsync"?Ih:fc),a=u=>Te(u)&&!Dh.test(Zn(u));if(n==="rclone"){let u=o.findIndex(g=>Fh.has(g));if(u<0)return[];let f=o[u],p=o.slice(u+1,u+1+(zh.has(f)?1:2));if(p.length===0)return[];if(p.every(g=>!Te(g))){if(["delete","deletefile","purge","rmdir","rmdirs"].includes(f))return Io({...e,name:"rm",argv:["rm","-rf",...p]},t).map(g=>({...g,why:`rclone ${f}: ${g.why}`}));if(f==="sync"&&p.length>=2){let g=Ys(p[p.length-1],e,t);return g.kind==="disposable"?[]:[{...xt([g],e),why:`rclone sync replaces what is in ${g.why}`}]}return[]}let d=p[p.length-1];if(f==="sync"&&p.length===2&&Te(p[0])&&!Te(d)){let g=Ys(d,e,t);return g.kind==="disposable"?[]:[{...xt([g],e),why:`rclone sync replaces what is in ${g.why}`}]}if(!["copy","copyto","move","moveto","sync","bisync","rcat","copyurl"].includes(f)||f!=="rcat"&&p.length<2||!a(d))return[];let h=d.split(":")[0];return f==="sync"||f==="bisync"?[m("claude.bash.db.destructive",`rclone ${f} makes ${h}: match the source, deleting what is not in it`,{target:d,host:h,is_local:!1})]:[m("claude.bash.external_write",`rclone ${f} copies files to ${h}:`,{target:d,host:h,is_local:!1})]}let i=o.filter(u=>Te(u)||/[/.~]/.test(u));if(i.length<2)return[];let l=i[i.length-1];if(!a(l))return[];let c=Zn(l);return[m("claude.bash.external_write",`${n} copies files to another machine (${c})`,{target:l,host:c,is_local:!1})]}function Uh(e){let t=Un.has(R.basename(e.name))?e.argv.slice(1).map(a=>k(a)).find(a=>!a.startsWith("-"))??"":k(e.argv[0]??""),n=R.basename(t).replace(/\.sh$/,"");if(!/^kafka-[a-z-]+$/.test(n)||["kafka-server-start","kafka-server-stop","kafka-storage","kafka-run-class","kafka-console-consumer","kafka-dump-log"].includes(n))return[];let s=e.argv.map(a=>k(a));if(s.some(a=>/^--(help|version|dry-run)$/.test(a)))return[];let r=n==="kafka-delete-records"?"(its one action)":s.find(a=>/^--(delete|delete-[a-z-]+|purge)$/.test(a));if(r)return[m("claude.bash.db.destructive",`${n} ${r} deletes from a live Kafka cluster`,{target:n,is_local:!1})];if(n==="kafka-leader-election")return[m("claude.bash.deploy","kafka-leader-election moves partition leaders on a live Kafka cluster",{target:n,is_local:!1})];let o=s.find(a=>/^--(create|alter|add|remove|execute|reset-offsets|reassign|elect|grant|revoke|expire|renew|cancel)$/.test(a));return o&&!(o==="--reset-offsets"&&!s.includes("--execute"))?[m("claude.bash.deploy",`${n} ${o} changes a live Kafka cluster`,{target:n,is_local:!1})]:n==="kafka-console-producer"?[m("claude.bash.external_write","kafka-console-producer writes messages to a topic",{target:n,is_local:!1})]:[]}var qh=/^--?(?!no-|skip-|keep-|without-|dry-|preview-|show-|list-|exclude-|disable-|dont-|don-t-|prevent-|protect-|avoid-|never-)([a-z0-9]+-)*(purge|destroy|wipe|drop|nuke|erase|truncate|delete)(-(all|data|tables?|database|databases|db|volumes?|everything|existing|objects?|records?|rows?|keys?|files?|snapshots?|backups?|indexes|indices|schemas?|clusters?|namespaces?|buckets?|branch(es)?|resources?|old))?(=.*)?$/,Hh=new Set(["magick","convert","mogrify","montage","composite","gm"]);function Bh(e){let t=R.basename(e.name);if(!t||Oo.has(t)||Hh.has(t)||e.functionCall||e.via==="substitution"||S(e.argv[0]??"")||Wo(e))return[];let n=e.argv.map(u=>k(u));if(n.some(u=>Po.test(u)))return[];let s="(what its own words say it does)",r=dc(n),o=Zs(t)?-1:r.findIndex(u=>u.split("-").includes("unsafe"));if(o>=0&&(r[o].includes("-")||r.length>o+1)&&!r.slice(o+1).some(u=>ln.has(u)))return[m("claude.bash.db.destructive",`${t} runs a subcommand it calls unsafe (${r.slice(0,3).join(" ")}) ${s}`,{target:`${t} ${r.slice(0,3).join(" ")}`,is_local:!1})];if(Zs(t))return[];let i=n.slice(1).find((u,f)=>qh.test(u)&&!/=(false|0|no|none|off|never)$/i.test(u)&&!/^(false|0|no|none|off|never)$/i.test(n[f+2]??""));if(i===void 0)return[];let l=/(purge|destroy|wipe|drop|nuke|erase|truncate|delete)/.exec(i)[1],c=["drop","truncate","purge","wipe"].includes(l)||r.flatMap(u=>[u,...u.split("-")]).some(u=>jo.has(u));return[m(c?"claude.bash.db.destructive":"claude.bash.deploy",`${t} is told to ${l} (${i.split("=")[0]}) ${s}`,{target:`${t} ${r.slice(0,2).join(" ")}`.trim(),is_local:!1})]}var ho=new Set([...rn,"rollback","unpublish"]),Ms=new Set(["rm","remove","reset","revoke","uninstall"]),Vh=new Set(["cluster","clusters","kube","k8s","kubernetes","infra","infrastructure","eks","gke","aks"]),Zh=new Set(["kind","minikube","k3d","microk8s","local","dev","docker","compose"]),no=new Set(["drop","truncate","flushall","flushdb","teardown","deprovision","decommission"]),go=new Set(["deploy","release","publish","promote","rollout","ship"]),pc=new Set(["create","add","set","update","put","attach","scale","enable","disable","rotate"]),Ws=new Set(["bucket","buckets","cluster","clusters","database","databases","db","namespace","namespaces","instance","instances","volume","volumes","service","services","function","functions","fn","lambda","addon","addons","lifecycle","environment","environments","domain","domains","zone","zones","record","records","dns","app","apps","deployment","deployments","queue","queues","topic","topics","stack","stacks","vpc","subnet","subnets","gateway","pool","pools","certificate","certificates","distribution","distributions","worker","workers","machine","machines","droplet","droplets","server","servers","site","sites","project","projects","table","tables","schema","schemas","identity","identities","layer","layers","kv","d1","r2","s3","broker","brokers","partition","partitions","replica","replicas","shard","shards","region","regions","store","stores","serverless","tablet","tablets"]),ln=new Set(["plan","verify","check","validate","list","ls","status","diff","extract","describe","view","lint","test","tests","dry","dryrun","notes","changelog","preview","smoke","inspect","show","get","help","download","fetch","pull","template","render","history","logs","log","info","url","urls","open","browse","wait","watch","tail","search","find","explain"]),No=new Set([...ln,"doctor","whoami","version","completion","login","logout","install","init"]),hc=new Set(["test","tests","e2e","spec","specs","check","checks","verify","validate","lint","dry","plan","diff","preview","smoke","generate","gen","codegen","mock","mocks","fake","stub","example","examples","sample","docs","notes","changelog","build","watch","dev","local","list","ls","status","show","get","inspect","count","find","search","report","help","storybook","bench","benchmark","prepare","eval","evals","evaluate","scan","audit","probe","probes"]),Gh=new Set(["detect","find","get","next","determine","should","is","has","needs","parse","extract","wait","print","read","info"]),Kh=new Set([...hc,"start","serve","bundle","compile","analyze","typecheck","format","copy","env","logs","log"]),Yh=new Set(["prod","production"]),Jh=new Set(["fn","func","lambda","lambdas","addon","addons","identity","identities","layer","layers","relationship","relationships","lifecycle","data","migrate","migration","migrations","seed","seeds"]),tl=new Set([...jo,"data","migrate","migration","migrations","seed","seeds"]),Us=new Set(["config","configure","configuration","context","profile","alias","completion","completions","auth","login","local"]),Lo=/^--?(app|project|project-?id|db|database|bucket|cluster|service|instance|env|environment|org|zone|branch|deployment|deployment-?id|identity|stack|namespace|site|([a-z][a-z0-9]*[-.])+(id|ids|name|arn|uri))(=|$)/,Xh=new Set(["ssh","scp","sftp","mosh","autossh","rsync","curl","wget","http","https","xh","git","nc","ncat","netcat","telnet","socat","xargs","env","sudo","doas","time","timeout","nohup","watch","nice","caffeinate","stdbuf","command","builtin","exec"]),sn=/\.(sh|bash|zsh|py|rb|js|mjs|cjs|ts|mts|cts|pl|ps1)$/,Qh=new Set(["dotenv","dotenvx","env-cmd","cross-env","with-env","mise","asdf","op","doppler","infisical","railway","kubectl","oc","uv","poetry","pipenv","direnv","nix","nix-shell","devbox","flox","aws-vault","sops","chamber","teller","envchain"]),Gs=/\$\{?[A-Za-z_]*(TOKEN|API_?KEY|SECRET|PAT|PASSWORD|CREDENTIALS?)[A-Za-z_]*\}?/,gc=new Set(["skill","skills","plugin","plugins","completion","completions","toolchain","toolchains","font","fonts","venv","virtualenv","shim","shims"]),mc=new Set([...Us,...gc,"cache","caches","history","log","logs","tmp","temp","session-cache","settings","setting","shell","workspace-cache","extension","extensions","download","downloads"]),eg=new Set(["repo","repos","remote","remotes","source","sources","registry","registries","tap","taps","channel","channels","index","indexes"]);function nl(e){return e.argv.some(t=>{let n=k(t);return Gs.test(t)||Gs.test(n)||Lo.test(n)||/^[a-z][a-z0-9+.-]*:\/\//.test(n)&&!Re(n)})}var tg=/\b(claude|anvil|mcp|codex|cursor|copilot|gemini|aider|settings|permissions?)\b/i,sl=/(^|[-_.:/])(prod|production|live|mainnet)([-_.:/]|$)/i,rl=/^(\w+:\/\/)?([^@/\s]*@)?(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/\S*)?$/i;function ng(e){let t=e.text,n=[],s=i=>i===" "||i===" ",r=i=>i!==void 0&&(i>="A"&&i<="Z"||i>="a"&&i<="z"||i==="_"),o=i=>r(i)||i!==void 0&&i>="0"&&i<="9",a=0;for(;n.length<32;){for(;s(t[a]);)a++;let i=a;if(!r(t[i]))break;for(;o(t[i]);)i++;if(t[i]!=="=")break;let l=t.slice(a,i);i++;let c;if(t[i]==='"'||t[i]==="'"){let u=t.indexOf(t[i],i+1);if(u<0)break;c=t.slice(i+1,u),i=u+1}else{let u=i;for(;u<t.length&&!s(t[u])&&t[u]!==`
|
|
41
|
+
`;)u++;c=t.slice(i,u),i=u}if(i<t.length&&!s(t[i]))break;n.push([l,c]),a=i}return n}function sg(e,t){let n=e.argv.map(x=>k(x)),s=x=>/^--?[a-z][\w-]*=/i.test(x)?x.slice(x.indexOf("=")+1):x;if(n.some(x=>Po.test(x)||/^--dry-?run=(true|1|yes|client|server|all)$/i.test(x)))return{strict:!0,ship:!0};if(n.some(x=>/^--(snapshot|skip-publish|no-publish|skip-push)$|^--skip=([\w,]*,)?(publish|push)\b/.test(x)))return{strict:!1,ship:!0};if(["make","gmake"].includes(R.basename(e.name))&&n.some(x=>/^-[a-zA-Z]*n[a-zA-Z]*$|^--(just-print|recon)$/.test(x)))return{strict:!0,ship:!0};let r=ng(e);if(n.slice(1).some(x=>sl.test(s(x)))||r.some(([,x])=>sl.test(x)))return{strict:!1,ship:!1};let o=x=>n.flatMap((b,j)=>x.test(b)?[n[j+1]??""]:/^--?[a-z][\w-]*=/i.test(b)&&x.test(b.slice(0,b.indexOf("=")))?[s(b)]:[]),a=n.findIndex((x,b)=>b>0&&!x.startsWith("-")),i=o(/^--?(db-url|database-url|url|host|registry|endpoint|server|api-url|connection|connection-string|dsn)$/i),l=r.some(([x,b])=>/(DATABASE|DB|POSTGRES|PG|MYSQL|MONGO|REDIS)_?(URL|URI|HOST)$/i.test(x)&&!rl.test(b)),c=r.some(([x,b])=>/^(NODE_ENV|APP_ENV|RAILS_ENV|RACK_ENV|MIX_ENV|FLASK_ENV|DJANGO_ENV|ENVIRONMENT|STAGE)$/.test(x)&&/^(test|testing|dev|development|local)$/i.test(b))&&!l;if(n.slice(1,a<0?void 0:a).includes("--local")||i.length>0&&i.every(x=>rl.test(x))||c)return{strict:!0,ship:!0};let f=o(/^--?(channel|track|deployment|network|net|chain)$/i),p=o(/^--?([\w-]+\.)?cluster$/i),h=n.some(x=>/^code-?push(-standalone)?$/.test(x))||/code-?push/.test(R.basename(e.name))?o(/^-d$/):[],g=[...f.map(x=>ol.test(x)),...p.map(x=>og.test(x)),...h.map(x=>ol.test(x))],y=g.length>0&&g.every(Boolean),$=t.lineText.indexOf(e.text),E=R.basename(e.name);if(!y&&g.length===0&&$>0&&/^[a-z][a-z0-9_-]*$/.test(E)){let x=[...t.lineText.slice(0,$).matchAll(new RegExp(`\\b${E}\\s[^;&|]*\\b(?:config\\s+set|switch|use)\\b[^;&|]*\\s--?(?:url|u|env|network|cluster)[= ]([\\w:/.-]+)`,"g"))],b=x[x.length-1]?.[1];y=b!==void 0&&/^(devnet|testnet|localnet|localhost|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)$/.test(b)}return{strict:!1,ship:y}}var rg=new Set(["sequelize","sequelize-cli","knex","typeorm","typeorm-ts-node-commonjs","typeorm-ts-node-esm","mix","artisan","php","rails","rake","alembic","flask","flyway","liquibase"]),ol=/^([\w-]+:)?(staging|stage|stg|dev|develop|development|test|testing|qa|uat|preview|sandbox|devnet|testnet|localnet|local|ci|sepolia|goerli|holesky|hoodi|mumbai|amoy|fuji|chiado|alfajores|shasta|nile)$/i,og=/^([\w-]+:)?(devnet|testnet|localnet|sepolia|goerli|holesky|hoodi|mumbai|amoy|fuji|chiado|alfajores|shasta)$/i,il=/^--(publish|deploy|promote)(=true)?$/,ig=new Set(["npx","pnpx","bunx"]),ag=new Set(["--import","--require","-r","--loader","--experimental-loader","--env-file","--project","-P","--tsconfig","--inspect-port"]);function mo(e){return/s$/.test(e)?e:`a ${e}`}function rt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().split(/[-:_./]+/).filter(t=>/^[a-z][a-z0-9]*$/.test(t))}function al(e,t,n=!1){let s=[],r=t;for(;n&&r<e.length&&k(e[r]).startsWith("-")&&k(e[r])!=="--";){let a=k(e[r]);r+=!a.includes("=")&&r+1<e.length&&/[/.$~=]|^\d/.test(k(e[r+1]))&&!k(e[r+1]).startsWith("-")?2:1}for(let a=0;a<2&&r<e.length&&/^\$/.test(k(e[r]));a++)r++;for(;r<e.length&&s.length<6;r++){let a=k(e[r]);if(a==="--"||a.startsWith("-")||a.includes("://")||a.includes("@")||!/^[a-z][a-z0-9_.:/-]*$/.test(a)||a.includes("/")||/\.[a-z0-9]{1,5}(:[\d,-]+)?$/.test(a))break;let i=rt(a);i.length>0&&s.push(i)}let o=0;for(;r<e.length;r++){let a=k(e[r]);if(a==="--")break;a.startsWith("-")||o++}return{groups:s,values:o}}function lg(e){let t=e.argv.map(f=>k(f)),n=R.basename(e.name),s=[],r=[],o=(f,p)=>({...e,name:f,argv:[f,...p]}),a=(f,p)=>{let d=al(t,p),h=t.flatMap((g,y)=>y>=p&&/^--?(command|cmd|action|task|step|op|operation|job)$/.test(g)?[rt(t[y+1]??"")]:/^--?(command|cmd|action|task|step|op|operation|job)=/.test(g)?[rt(g.slice(g.indexOf("=")+1))]:[]).filter(g=>g.length>0);return{name:R.basename(f),groups:[rt(R.basename(f).replace(/\.[^.]+$/,"")),...d.groups.slice(0,1),...h],values:d.values+Math.max(0,d.groups.length-1),script:!0}},i=f=>({name:f,groups:[rt(f)],values:0,script:!0});if(t[0]?.includes("/")&&sn.test(t[0]))return{readings:[a(t[0],1)],nested:r};if((n==="."||n==="source")&&sn.test(t[1]??""))return{readings:[a(t[1],2)],nested:r};let l=t.indexOf("--");if(Qh.has(n)&&l>0&&/^[a-z][a-z0-9._-]*$/.test(t[l+1]??"")){let f=o(t[l+1],t.slice(l+2));(n==="kubectl"||n==="oc"||n==="railway")&&/^(exec|run)$/.test(v(t)[0]??"")&&Qs.add(f),r.push(f)}if(Qo.has(n)||n==="zsh"){for(let f=1;f<t.length;f++){let p=t[f];if(["-c","-e","--eval","-p","--print","-m"].includes(p))return{readings:s,nested:r};if(ag.has(p)){f++;continue}if(!p.startsWith("-")){if(sn.test(p))return Su(n,t.slice(1,f))?{readings:s,nested:r}:{readings:[a(p,f+1)],nested:r};break}}if(n!=="bun")return{readings:s,nested:r}}let c=ig.has(n)?1:["npm","pnpm","yarn","bun"].includes(n)&&["exec","dlx","x"].includes(t[1]??"")?2:-1;if(c>0){let f=c;for(;f<t.length&&t[f].startsWith("-");)f+=["-p","--package"].includes(t[f])?2:1;let p=(t[f]??"").replace(/^@[^/]+\//,"").replace(/@[^/]*$/,"");return/^[a-z][a-z0-9._-]*$/i.test(p)&&r.push(o(p,t.slice(f+1))),{readings:s,nested:r}}if(["npm","pnpm","yarn","bun"].includes(n)){let f=Uc(t),p=f[0]??"";if((p==="run"||p==="run-script")&&f[1])s.push(n==="bun"&&sn.test(f[1])?a(f[1],t.indexOf(f[1])+1):i(f[1])),n!=="npm"&&/^[a-z][a-z0-9._-]*$/.test(f[1])&&!sn.test(f[1])&&r.push(o(f[1],t.slice(t.indexOf(f[1])+1)));else if(p==="npm"&&n==="yarn")r.push(o("npm",t.slice(t.indexOf("npm")+1)));else{if(n==="pnpm"&&p==="deploy")return{readings:s,nested:r};n!=="npm"&&p&&!qo.has(p)&&(s.push(i(p)),/^[a-z][a-z0-9._-]*$/.test(p)&&r.push(o(p,t.slice(t.indexOf(p)+1))))}let d=t.indexOf("--");return d>0&&/^[a-z][a-z0-9._-]*$/.test(t[d+1]??"")&&r.push(o(t[d+1],t.slice(d+2))),{readings:s,nested:r}}if(["nx","turbo","mise","make","just","task","lerna","run-s","run-p","npm-run-all"].includes(n)){let p=n==="mise"&&!["run","r","watch","w"].includes(t[1]??"")&&!/^(\/\/|:)/.test(t[1]??"")?[]:t.slice(1).filter((h,g,y)=>!h.startsWith("-")&&!h.includes("=")&&!h.startsWith("$")&&!["-C","-f","--file","-j","--projects","-p"].includes(y[g-1]??"")),d=t.flatMap((h,g)=>["-t","--target","--targets"].includes(h)?(t[g+1]??"").split(","):/^--targets?=/.test(h)?h.slice(h.indexOf("=")+1).split(","):[]);for(let h of[...p,...d])h&&h!=="run"&&h!=="run-many"&&h!=="affected"&&!["-t","--target","--targets"].includes(h)&&s.push(i(h));return{readings:s,nested:r}}if(Oo.has(n)||Xh.has(n)||!/^[a-z][a-z0-9._-]*$/.test(n)||/^\/[a-z-]+$/.test(t[0]??""))return{readings:s,nested:r};if(rt(n).some(f=>No.has(f)||["print","echo"].includes(f)))return{readings:s,nested:r};let u=al(t,1,!0);return s.push({name:n,groups:u.groups.slice(0,4),values:u.values+Math.max(0,u.groups.length-4),script:!1}),{readings:s,nested:r}}var cg=oe({mix:["release","assets.deploy"]});function ug(e,t){let n=e.groups.flat();if(n.length===0||!e.script&&cg[e.name]?.includes(e.groups[0].join(".")))return null;let s=e.script?`runs ${e.name}`:`${e.name} ${e.groups.map(C=>C.join("-")).slice(0,4).join(" ")}`,r=e.script?"(read by its name)":"(read by its words)",o=e.script?e.name:s,a=t.argv.some(C=>Gs.test(C)||Gs.test(k(C))),i=a||t.argv.some(C=>Lo.test(k(C)));if(e.script&&(n.some(C=>hc.has(C))||Gh.has(n[0]??"")))return null;if(e.script&&t.argv.some(C=>il.test(k(C))))return m("claude.bash.deploy",`${s}, told to ${t.argv.map(C=>k(C)).find(C=>il.test(C)).slice(2).replace(/=true$/,"")} ${r}`,{target:o,is_local:!1});if(!e.script){if(e.groups[0].length===1&&No.has(n[0])&&!Ks.has(n[1]??""))return null;let C=n.findIndex(A=>Ks.has(A));if(C>=0&&!n.slice(0,C).some(A=>Us.has(A))){if(n.some(A=>kc.has(A))&&ae(t))return m("claude.bash.secrets.print",`${s} prints ${mo(n[C])} ${r}`,{target:o,is_local:!0});if(n.some(A=>["create","lease","issue","generate","mint"].includes(A))&&ae(t))return m("claude.bash.secrets.print",`${s} makes a credential and prints it ${r}`,{target:o,is_local:!1});if(n.some(A=>["set","update","put","add","rotate","delete","remove","rm","unset","revoke","reset","reencrypt","rekey"].includes(A)))return m("claude.bash.deploy",`${s} changes a secret a service keeps ${r}`,{target:o,is_local:!1})}if(["post","put","patch"].includes(n[0]??"")&&t.argv.slice(2).some(A=>k(A).includes("/")))return m("claude.bash.external_write",`${e.name} ${n[0]} sends a write to its service's API ${r}`,{target:o,is_local:!1})}if(e.script&&n.includes("down")&&n.some(C=>Vh.has(C))&&!n.some(C=>Zh.has(C)))return m("claude.bash.deploy",`${s}: named to take down ${n.some(C=>C.startsWith("infra"))?"its infrastructure":"a cluster"} ${r}`,{target:o,is_local:!1});let l=-1;for(let C=0;C<n.length;C++){let A=n[C];(ho.has(A)||Ms.has(A)||go.has(A)||!e.script&&(pc.has(A)||A==="apply"||A==="push"))&&(l=C)}let c=e.script&&n.some(C=>Yh.has(C))&&!n.some(C=>Kh.has(C)||ln.has(C)),u=t.argv.some(C=>["--force","-f","--yes","-y","--overwrite"].includes(k(C))||k(C)==="--force=true"),f=t.argv.some(C=>/\.(tar|tgz|tar\.gz|sql|dump|bak|gz|zip|bson|archive)$/i.test(k(C)));if(!e.script&&l<0&&u&&n.some(C=>["import","restore","load"].includes(C))&&(f||n.some(C=>tl.has(C)))&&!n.some(C=>ln.has(C)))return m("claude.bash.db.destructive",`${s}: forced, over the data it holds ${r}`,{target:o,is_local:!1});if(l<0)return c?m("claude.bash.deploy",`${s}, named for production ${r}`,{target:o,is_local:!1,host:"production"}):null;let p=n[l];if(n.slice(l+1).some(C=>ln.has(C)))return null;let d=C=>uc.has(C)||Jh.has(C),h=[...n.slice(0,l)].reverse().find(d)??n.slice(l+1).find(d)??n.find(d),g=n.some(C=>tl.has(C)),y=C=>/s$/.test(C)?C:`a ${C}`,$=e.groups.flatMap((C,A)=>C.map(()=>A))[l]??0,E=e.groups.length-1-$,x=t.argv.some((C,A)=>/^--?[a-z][\w-]*=./.test(k(C))||/^--?[a-z][\w-]*$/.test(k(C))&&/^[^-]/.test(k(t.argv[A+1]??"-")));if(ho.has(p)||Ms.has(p)){if(!e.script&&n.slice(0,l).some(U=>Us.has(U))||!e.script&&h===void 0&&n.length>1&&n.every((U,I)=>I===l||mc.has(U))||!e.script&&["remove","rm"].includes(p)&&n.slice(0,l).some(U=>eg.has(U))&&!nl(t))return null;let C;if(Ms.has(p)?C=h!==void 0||(e.script?no.has(p):!1):e.script?$>0?C=["nuke","wipe","purge","destroy","erase",...no].includes(p)||h!==void 0||e.values>0||x||a:C=no.has(p)||h!==void 0||p==="destroy"||["purge","wipe","nuke","erase"].includes(p)&&e.groups[0].length>1:C=h!==void 0||e.values>0||i||E>0||l>0&&rn.has(p),!C||h===void 0&&n.some(U=>gc.has(U))&&!nl(t)&&!tg.test(t.text))return null;let A=g||["drop","truncate","flushall","flushdb","purge","wipe"].includes(p)?"claude.bash.db.destructive":"claude.bash.deploy";return m(A,`${s}: ${e.script?`named to ${p}`:qs(p)} ${h?y(h):"what it names"} ${r}`,{target:o,is_local:!1})}if(go.has(p))return["build","gen","generate","new","scaffold","init","template"].includes(n[l-1]??"")?null:m(p==="publish"?"claude.bash.publish":"claude.bash.deploy",`${s}: ${e.script?`named to ${p}`:qs(p)} ${r}`,{target:o,is_local:!1});if(p==="push"){if(t.argv.some(A=>["--force","-f","--yes","-y"].includes(k(A))))return m("claude.bash.deploy",`${s}: a forced push to its service ${r}`,{target:o,is_local:!1});let C=t.argv.map(A=>k(A)).find(A=>/^[a-z][a-z0-9+.-]*:\/\//.test(A)&&!Re(A));return C?m("claude.bash.publish",`${s}: pushes to ${C.split("/").slice(0,3).join("/")} ${r}`,{target:o,is_local:!1}):null}if(p==="apply")return m("claude.bash.deploy",`${s}: applies a configuration to its service ${r}`,{target:o,is_local:!1});if(n.slice(0,l).some(C=>Us.has(C)))return null;let b=[...n.slice(0,l)].reverse().find(C=>Ws.has(C))??n.slice(l+1).find(C=>Ws.has(C))??(a?"a service it signs in to":void 0);if(b===void 0)return null;let j=Ws.has(b)?/\d/.test(b)||b.length<=2?`changes ${b.toUpperCase()}, a live service`:`${qs(p)} ${y(b)} on a live service`:b;return m("claude.bash.deploy",`${s}: ${Ws.has(b)?j:`changes something on ${b}`} ${r}`,{target:o,is_local:!1})}function yc(e,t,n){return[e,...n!==void 0&&n!==e?[n]:[]].map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).some(r=>new RegExp(`(^|[^>\\w./-])(>|\\btee\\s+)\\s*["']?${r}["']?(\\s|;|&|\\||$)`).test(t.lineText))&&/<<-?\s*['"]?\w+|\bprintf\b|\becho\b|\btee\b/.test(t.lineText)}function bc(e,t){let n=R.basename(t);return e.text.split(/\s+/).map(s=>s.replace(/^["']|["']$/g,"")).find(s=>s===t||s.endsWith(`/${n}`)||s===n)}function dg(e,t,n){let s=t.argv.map(a=>k(a)).find(a=>R.basename(a)===e.name);if(s===void 0)return!1;let r=X(s,t.cwd,se(n)).path??"",o=n.sessionId;return o!==null&&/^[\w-]{8,}$/.test(o)&&new RegExp(`^/(private/)?tmp/claude-\\d+/[^/]+/${o}/scratchpad/`).test(r)}function qs(e){return{rollback:"rolls back",rollout:"rolls out",teardown:"tears down",rm:"removes",push:"pushes",flushall:"flushes all of",flushdb:"flushes",set:"sets",put:"puts"}[e]??(/(sh|ch|s|x)$/.test(e)?`${e}es`:`${e}s`)}function fg(e){let t=R.basename(e.name),n=e.argv.map(r=>k(r)),s=r=>[m("claude.agent.controls",`sends keystrokes into a terminal or another app (${r}), which can answer prompts meant for the person`,{target:r,is_local:!0})];return t==="tmux"&&n.some(r=>/^(send-keys|send|send-prefix|paste-buffer|pasteb)$/.test(r))?s("tmux send-keys"):t==="screen"&&n.some((r,o)=>r==="-X"&&/^(stuff|paste|readbuf)$/.test(n[o+1]??""))?s("screen -X stuff"):t==="osascript"&&n.some(r=>/\b(keystroke|key code|key down)\b/i.test(r))?s("osascript keystrokes"):["xdotool","ydotool","wtype","dotool"].includes(t)&&n.slice(1).some(r=>/^(type|key|keydown|keyup)$/.test(r)||t==="wtype")?s(t):t==="kitty"&&n.includes("@")&&n.some(r=>/^send-(text|key)$/.test(r))?s("kitty @ send-text"):t==="wezterm"&&n.includes("cli")&&n.includes("send-text")?s("wezterm cli send-text"):[]}var wc=new Set(["dokku","kamal","fly","flyctl","netlify","serverless","sls","caprover","cap","flux","argocd","eb","doctl","hcloud","linode-cli","scw","vultr-cli","civo","koyeb","okteto","porter","northflank","render","sst","amplify"]),ll=new Set([...No,"get","describe","logs","log","top","explain","versions","info","port","forward","proxy","wait","diff","events","kustomize","completion","options","print","docs","open","whoami","status","ls","list","show","current","help","version","doctor","details","audit","lint","validate","template","render","search","history","watch","tail","metrics","inspect","check","report","dashboard","export","can","login","logout","auth","context","contexts","use","switch","link","unlink","plugin","console","ssh","exec","shell","debugger","dev","build","test","package"]),pg=new Set(["local","offline","mock"]),hg=new Set(["api","resources","cluster","config","apps","domains","certs","volumes","ps","releases","storage","secrets","env","i"]),gg=new Set([...ho,...Ms,...go,...pc,"apply","prune","import","fork","mount","unmount","clear","set","unset","restart","reboot","boot","stop","start","scale","invoke","run","rolling","reconcile","cordon","drain","taint","label","annotate","patch","replace","expose","autoscale","launch","reset","uninstall","upgrade","sync","suspend","resume","enable","disable","detach","attach","join","leave","rotate","renew","issue","revoke","promote","release","redeploy","restore","backup","move","rename","transfer","swap","bootstrap","extend","resize","allocate","clone"]),mg=new Set(["apply","create","delete","edit","patch","replace","scale","autoscale","label","annotate","taint","drain","cordon","uncordon","expose","run","debug","set","rollout","certificate","new-app","new-project","new-build","start-build","cancel-build","rollback","tag","import-image","policy","adm","idle"]),yg=new Set(["-n","--namespace","--context","--cluster","--kubeconfig","--user","-o","--output","-l","--selector","-a","--app","-c","--config","-r","--region","--org","-s","--stage","--profile","--token","--project","--server","-e","--env","--environment","--team","--site","-f","--filename","--function","-d","--destination","--field-selector","--tail","--since","--container","--host","-H","--as","--request-timeout"]);function cl(e,t){let n=[];for(let s=1;s<e.length&&n.length<t;s++){let r=e[s];if(r==="--")break;if(r.startsWith("-")){!r.includes("=")&&yg.has(r)&&s++;continue}if(r.includes("://")||r.includes("@")||r.includes("/")||!/^[a-z][a-z0-9_.:-]*$/.test(r))break;n.push(r)}return n}function bg(e){let t=R.basename(e.name);if(t!=="docker"&&t!=="docker-compose"&&t!=="podman")return[];let n=e.argv.map(l=>k(l)),s=n.slice(1).filter((l,c,u)=>!l.startsWith("-")&&!["-f","--file","-p","--project-name","--context","-c","-H","--host","--env-file"].includes(u[c-1]??"")),r=t==="docker-compose"||s[0]==="compose",o=r&&t==="docker"?s.slice(1):s,a=o[0]??"",i=(l,c)=>[m(l,`${t} ${o.slice(0,2).join(" ")} ${c}`,{target:`${t} ${o.slice(0,2).join(" ")}`,is_local:!1})];return r?a==="down"&&n.some(l=>l==="-v"||l==="--volumes"||/^-[a-z]*v[a-z]*$/.test(l)&&l!=="-v"&&!l.startsWith("--"))?i("claude.bash.fs.delete_recursive","deletes the project's data volumes"):a==="publish"?i("claude.bash.publish","publishes the project to a registry"):[]:["service","stack","node","secret","config"].includes(a)&&["create","rm","remove","update","scale","deploy","rollback","promote","demote"].includes(o[1]??"")?i("claude.bash.deploy","changes a live swarm"):a==="swarm"&&["join","leave","init","update","unlock-key","ca"].includes(o[1]??"")?i("claude.bash.deploy","changes swarm membership"):a==="buildx"&&o[1]==="imagetools"&&o[2]==="create"&&!n.includes("--dry-run")?i("claude.bash.publish","pushes a manifest to a registry"):a==="trust"&&(["sign","revoke"].includes(o[1]??"")||o[1]==="signer"&&["add","remove"].includes(o[2]??""))?i("claude.bash.publish","changes who can sign images in a registry"):a==="scout"&&o[1]==="repo"&&["enable","disable"].includes(o[2]??"")?i("claude.bash.external_write","changes a registry setting"):[]}function wg(e,t){let n=R.basename(e.name);if(t.ship)return[];let s=e.argv.map(u=>k(u));if(n==="kubectl"||n==="oc"){let[u="",f=""]=cl(s,2);if(!mg.has(u))return[];if(u==="run"&&Rc(s))return[];if((u==="rollout"||u==="adm")&&ll.has(rt(f)[0]??""))return[];if(u==="certificate"&&!["approve","deny"].includes(f))return[];let p=["rollout","set","certificate","adm","create"].includes(u)&&f?`${n} ${u} ${f}`:`${n} ${u}`;return[m("claude.bash.deploy",`${p} changes a live cluster`,{target:p,is_local:!1})]}if(!wc.has(n))return[];let r=cl(s,3).filter(u=>!/^\d/.test(u)),o=r.flatMap(u=>rt(u));if(o.length===0||o.some(u=>pg.has(u)))return[];if(o.find(u=>["deploy","create","issue","mint","add","generate"].includes(u))!==void 0&&o.some(u=>/^(tokens?|keys?|credentials?)$/.test(u))){let u=`${n} ${r.slice(0,2).join(" ")}`;return[ae(e)?m("claude.bash.secrets.print",`${u} makes a credential and prints it`,{target:u,is_local:!1}):m("claude.bash.deploy",`${u} makes a credential for a live account`,{target:u,is_local:!1})]}if(o.includes("secrets")&&o.some(u=>["extract","print","fetch","get","show"].includes(u)))return ae(e)?[m("claude.bash.secrets.print",`${n} ${r.slice(0,2).join(" ")} prints a secret`,{target:`${n} ${r.slice(0,2).join(" ")}`,is_local:!0})]:[];if(n!=="dokku"&&o.some(u=>u==="plugin"||u==="plugins"))return[];let i=o.find(u=>gg.has(u));if(i===void 0&&o.some(u=>ll.has(u)))return[];if(i===void 0&&o.every(u=>hg.has(u)))return[];if(i!==void 0&&ln.has(o[o.indexOf(i)+1]??""))return[];let l=i!==void 0?r.findIndex(u=>rt(u).includes(i)):0,c=`${n} ${r.slice(0,Math.max(l,0)+1).join(" ")}`;return[m("claude.bash.deploy",i!==void 0?`${c} changes a live deployment`:`${c} is not a read, and ${n} works on live deployments`,{target:c,is_local:!1})]}function kg(e,t){let n=e.argv.map(c=>k(c)).find((c,u)=>u<=3&&sn.test(c));if(n!==void 0){let c=X(n,e.cwd,se(t)).path;if(c&&t.lineMade.includes(c)&&yc(n,t,bc(e,n)))return[]}if(e.functionCall||S(e.argv[0]??""))return[];if(Wo(e))return[];let s=e.argv.slice(1).map(c=>k(c)).find(c=>!c.startsWith("-")&&!/^[A-Za-z_]\w*=/.test(c))??"";if(rg.has(R.basename(e.name))&&(/^(db|migrate|migration|migrations|seed|schema|ecto)([:.]|$)/i.test(s)||["manage.py","artisan"].includes(R.basename(s))))return[];let r=sg(e,t);if(r.strict)return[];let o=bg(e);if(o.length>0)return o;let a=wg(e,r);if(a.length>0)return a;let{readings:i,nested:l}=lg(e);for(let c of i){if(c.script&&dg(c,e,t))continue;let u=ug(c,e);if(!(u&&r.ship&&(u.action==="claude.bash.publish"||/: (named to )?(deploy|release|publish|promote|rollout|ship)/.test(u.why)))&&u)return[u]}for(let c of l){if(c.argv.length>=e.argv.length&&c.name===e.name)continue;let u=Gn(c,t);if(u.length>0)return u.map(f=>({...f,why:`${f.why} (run by ${R.basename(e.name)})`}))}return[]}var Ks=new Set(["secret","secrets","token","tokens","credential","credentials","password","passwords","apikey","api-key","api_key","apikeys","api-keys"]),kc=new Set(["get","show","reveal","print","read","view","cat","dump","export","decrypt","download","value","access"]),To=/(^|\/)\*\.(egg-info|pyc|pyo|log|tmp|o|class|orig|rej|bak|swp|tsbuildinfo)$|(^|\/)\*~$/,vc=/^(node_modules|dist|build|out|\.next|coverage|__pycache__|\.pytest_cache|\.mypy_cache|\.ruff_cache|\.cache|\.turbo|\.DS_Store|target|\.tox|\.venv|venv|[\w.-]*\.tsbuildinfo|\*\.(egg-info|pyc|pyo|log|tmp|o|class|orig|rej|bak|swp|tsbuildinfo))$/;function Io(e,t){let n=e.argv.slice(1),s=e.name==="rimraf",r=!1,o=[],a=new Map;for(let[f,p]of n.entries()){if(!r&&p==="--"){r=!0;continue}if(!r&&p.startsWith("--")){p==="--recursive"&&(s=!0);continue}if(!r&&/^-[A-Za-z]+$/.test(p)){/[rR]/.test(p)&&(s=!0);continue}e.via==="find-exec"&&p==="{}"||(o.push(p),a.set(p,f+1))}e.via==="xargs"&&e.pipeFrom&&o.push(...xg(e.pipeFrom,t));let i=new Map;for(let f of o){let p=qn(f),d=xc(f,e,a.get(f)).flatMap(qn);for(let h of p)i.set(h,d)}if(o.splice(0,o.length,...o.flatMap(qn)),o.length===0)return[];let l=o.find(f=>$g(Ie(f,e,t),e,t));if(l!==void 0)return[m("claude.bash.fs.delete_recursive",`${e.name==="shred"?"shreds":"deletes"} a key or credentials file (${k(l)})`,{target:k(l),is_local:e.remote===null,host:e.remote})];let c=f=>f==="*"||f===".*"||f.endsWith("/*")||f.endsWith("/.*");if(!s&&!o.some(c))return[];let u=o.map(f=>{if(To.test(f))return{kind:"disposable",path:f,token:null,why:"build or cache artifacts"};let p=Ie(f,e,t),d=h=>c(h)?h==="*"||h===".*"?"./":`${h.replace(/\/\.?\*$/,"")}/`:h;return He(d(p),e,t,(i.get(f)??[]).map(h=>d(Ie(h,e,t))))});return[xt(u,e)]}var vg=/^\.(ssh\/(?!known_hosts(\.old)?$|config$)[^/]+|gnupg\/.+|aws\/(credentials|config)|kube\/config|docker\/config\.json|config\/gcloud\/.+|azure\/.+|netrc|git-credentials|npmrc|pypirc)$/;function $g(e,t,n){let s=M(e,t.cwd,n.ctx);if(S(s))return!1;let r=n.ctx.home.replace(/(?<!\/)\/+$/,""),o=s.startsWith(`${r}/`)?s.slice(r.length+1):null;if(o!==null&&vg.test(o))return!0;if(!ye(s)||X(s,null,se(n)).kind==="disposable")return!1;let a=n.projectRoot;return!(a&&!S(a)&&(s===a||s.startsWith(`${a}/`)))}var ul=64;function qn(e){let t=[],n=!1,s=r=>{if(t.length>=ul){n=!0;return}let o=/^(.*?)\{([^{}]*,[^{}]*)\}(.*)$/s.exec(r);if(!o){t.push(r);return}for(let a of o[2].split(","))s(`${o[1]}${a}${o[3]}`)};return s(e),n?[...t.slice(0,ul-1),`${ie}(more words from a brace expansion)${le}`]:t}function $c(e,t){let n=e.argv.slice(1);if(!n.some(a=>a==="--del"||a.startsWith("--delete")||a==="--remove-source-files"))return[];if(n.some(a=>a==="-n"||a==="--dry-run"||/^-[a-zA-Z]*n[a-zA-Z]*$/.test(a)))return[];let s=n.filter(a=>!a.startsWith("-")),r=s[s.length-1];if(!r||s.length<2)return[];if(/^[^/]*:/.test(r)&&!r.startsWith("/")&&!(V()&&/^[A-Za-z]:(?:[\\/]|$)/.test(r)))return[m("claude.bash.fs.delete_recursive",`rsync --delete removes files on ${r.split(":")[0]}`,{target:r,host:r.split(":")[0]??null,is_local:!1})];let o=He(r,e,t);return[{...xt([o],e),why:`rsync --delete into ${o.why}`}]}function xg(e,t){if(e.name==="echo"||e.name==="printf")return e.argv.slice(1).filter(n=>!n.startsWith("-")||n==="-");if(e.name==="find"){let n=_c(e);return n.disposableFilter?["/tmp/__find_matches_disposable__"]:n.roots}return[`${ie}(paths from ${e.name})${le}`]}function xt(e,t){let n={catastrophic:2,normal:1,disposable:0},s=[...e].sort((o,a)=>n[a.kind]-n[o.kind])[0],r=t.remote!==null;return s.kind==="disposable"&&!r?m("claude.bash.fs.delete_disposable",`deletes ${e.length>1?"temp, build or scratch paths":s.why}`,{target:s.path,is_local:!0}):m("claude.bash.fs.delete_recursive",`deletes ${s.why}${r?` on ${t.remote}`:""}`,{target:s.path,service:s.kind==="catastrophic"&&!r?s.token:null,is_local:!r,host:t.remote})}function He(e,t,n,s=xc(e,t)){let r=Ie(e,t,n),o=X(r,t.cwd,se(n));if(o.kind==="catastrophic")return o;for(let a of t.cwdFallbacks){let i=X(r,a,se(n));if(i.kind==="catastrophic")return{...i,why:`${i.why} if the cd before it failed`}}for(let a of s){if(a===""||a===e)continue;let i=X(Ie(a,t,n),t.cwd,se(n)),l=t.cwdFallbacks.some(c=>c!==null&&(a===c||a.startsWith(`${c}/`)));if(i.kind==="catastrophic")return{...i,why:`${i.why} ${l?"if the cd before it failed":"if an assignment before it did not run"}`}}return o}function xc(e,t,n){let s=n??t.argv.indexOf(e);return t.altArgvs.flatMap(r=>r.length===t.argv.length&&s>=0?[r[s]]:r.slice(1))}function se(e){return{home:e.ctx.home,tmpdir:e.ctx.tmpdir,projectRoot:e.projectRoot,base:e.base,onDisk:e.ctx.onDisk??null,made:e.ctx.session?.made??null,ignored:t=>oc(t,e)}}function cn(e,t,n=e.base){let s=e.ctx.onDisk,r=S(t)&&!t.startsWith("/")&&!t.startsWith(ie)&&n!==null&&n.startsWith("/")&&!S(n)?R.join(n,t):t;S(r)?s?.unknown?.add(r):r.startsWith("/")&&s?.written?.add(r)}function Ft(e,t){let n=e.ctx.onDisk;if(!n?.touched||!n.read)return t();let s=new Set([...n.touched.full,...n.touched.parent]),r=t();for(let o of[...n.touched.full,...n.touched.parent])s.has(o)||n.read.add(o);return r}var _g=new Set(["go","cargo","docker","podman","gradle","gradlew","mvn","mvnw","deno","poetry","uv","pipenv","dotnet","swift","flutter","dart","mix","npx","bunx","pnpx"]),Sg=new Set(["npm","pnpm","yarn","bun"]),Cg=new Set(["make","gmake","just","task","rake","mage"]);function Ag(e){let t=ue(e.name),n=e.argv.slice(1).filter(r=>!r.startsWith("-")),s=r=>/^[\w:@+-]+$/.test(r);return Cg.has(t)?new Set(n.filter(s)):Sg.has(t)?new Set((["run","run-script"].includes(n[0]??"")?n.slice(0,2):n.slice(0,1)).filter(s)):_g.has(t)?new Set(n.slice(0,1).filter(s)):new Set}function Ys(e,t,n){return cn(n,M(Ie(e,t,n),t.cwd??n.base??n.projectRoot,n.ctx)),He(e,t,n)}var dl=new Set(["-name","-iname","-path","-ipath","-wholename","-iwholename","-regex","-iregex","-empty","-mtime","-mmin","-atime","-amin","-ctime","-cmin","-newer","-anewer","-cnewer","-size","-user","-group","-perm","-links","-inum","-samefile","-nouser","-nogroup"]);function Eg(e){let t=[[]];for(let a of e)a==="-o"||a==="-or"||a===","?t.push([]):t[t.length-1].push(a);let n=[],s=!1,r=!0,o=!0;for(let a of t){let i=!1,l=!1;for(let c=0;c<a.length;c++){let u=a[c];if(u==="!"||u==="-not"){(a[c+1]==="("||a[c+1]==="\\(")&&(s=!0),c+=dl.has(a[c+1]??"")||["-type","-maxdepth","-mindepth"].includes(a[c+1]??"")?2:1;continue}dl.has(u)&&(i=!0,["-name","-iname","-path","-ipath","-wholename"].includes(u)&&a[c+1]!==void 0&&(n.push(a[c+1]),l=!0))}i||(r=!1,a.some(c=>c==="!"||c==="-not")&&(s=!0)),l||(o=!1)}return t.length>1&&!r&&(s=!0),{names:n,narrows:r&&!s,everyBranchNamed:o,invertible:s}}function _c(e){let t=e.argv.slice(1),n=[],s=0;for(;s<t.length&&!/^[-(!]/.test(t[s]);)n.push(t[s++]);n.length===0&&n.push(".");let r=!1;for(let g=s;g<t.length;g++){let y=t[g];y==="-delete"&&(r=!0),["-exec","-execdir","-ok","-okdir"].includes(y)&&["rm","unlink","shred","rmdir"].includes(ue(t[g+1]??""))&&(r=!0)}let o=t.slice(s),a=Eg(o),i=a.names,l=i.length>0&&i.every(g=>vc.test(R.basename(g.replace(/\/$/,"")))||To.test(g))&&!a.invertible&&a.everyBranchNamed,c=a.invertible,u=a.narrows,f=u&&o.includes("-empty"),p=o.some((g,y)=>g==="-type"&&o[y+1]==="d"),d=g=>/[*?[]/.test(g),h=u?f?p?"empty folders":"empty files and folders":i.length>0?`${i.every(g=>!d(g))?(i.length===1,"every file named"):"the files matching"} ${i.slice(0,3).join(", ")}${i.length>3?", \u2026":""}`:"the files its filters match":null;return{roots:n,deletes:r,disposableFilter:l,narrowed:h,emptyOnly:f,filesOnly:!u&&o.some((g,y)=>g==="-type"&&o[y+1]==="f"),invertible:c}}function Rg(e,t){let n=_c(e);if(!n.deletes)return[];let s=n.roots.map(l=>Ys(l,e,t)),r=s.find(l=>l.token==="fs.root"||l.token==="fs.home"||l.token==="fs.system");if(n.disposableFilter&&r)return[m("claude.bash.fs.delete_recursive",`find deletes matching files under ${r.path}`,{target:n.roots.join(" "),is_local:!0})];if(n.disposableFilter)return[m("claude.bash.fs.delete_disposable","find deletes build or cache artifacts",{target:n.roots.join(" "),is_local:!0})];let o=r??s.find(l=>l.kind==="catastrophic")??s.find(l=>l.kind==="normal")??s[0],a=o.token==="fs.home"&&o.path===t.ctx.home.replace(/(?<!\/)\/+$/,"")?"your home folder":o.token==="fs.project_root"?"the project":o.token==="fs.root"?"the whole disk":k(o.path);if(n.narrowed!==null){let l=`find deletes ${n.narrowed} under ${a}`;return n.emptyOnly&&!r?[m("claude.bash.fs.delete_disposable",l,{target:n.roots.join(" "),is_local:!0})]:s.every(c=>c.kind==="disposable")?[m("claude.bash.fs.delete_disposable",l,{target:n.roots.join(" "),is_local:!0})]:[m("claude.bash.fs.delete_recursive",l,{target:n.roots.join(" "),is_local:!0})]}let i=xt(s,e);return i.action==="claude.bash.fs.delete_recursive"&&n.filesOnly?[{...i,why:`find deletes every file under ${a}`}]:i.action==="claude.bash.fs.delete_recursive"&&n.invertible?[{...i,why:`find deletes everything under ${a} except what its filter keeps`}]:[i]}var Og=new Set(["-t","--type","-e","--extension","-d","--max-depth","--min-depth","--exact-depth","-E","--exclude","-S","--size","--changed-within","--changed-before","-o","--owner","-j","--threads","--path-separator","-c","--color","--ignore-file","--max-results","--batch-size"]);function jg(e,t){let n=e.argv.slice(1),s=n.findIndex(g=>["-x","--exec","-X","--exec-batch"].includes(g));if(s<0||!["rm","unlink","shred","rmdir"].includes(ue(n[s+1]??"")))return[];if(ue(n[s+1]??"")==="rmdir")return[];let r=n.slice(0,s).flatMap((g,y)=>g==="-t"||g==="--type"?[n[y+1]??""]:/^-t./.test(g)?[g.slice(2)]:g.startsWith("--type=")?[g.slice(7)]:[]);if(r.some(g=>g==="e"||g==="empty"))return[m("claude.bash.fs.delete_disposable","fd deletes empty files or folders",{target:".",is_local:!0})];let o=[],a=[],i=[],l=!1;for(let g=0;g<s;g++){let y=n[g];y==="--search-path"||y==="--base-directory"?(n[g+1]!==void 0&&a.push(n[g+1]),g++):y==="-e"||y==="--extension"?(n[g+1]!==void 0&&i.push(`*.${n[g+1].replace(/^\./,"")}`),g++):y.startsWith("--extension=")?i.push(`*.${y.slice(12).replace(/^\./,"")}`):y==="-g"||y==="--glob"?l=!0:y.startsWith("-")?Og.has(y)&&g++:o.push(y)}let c=o[0]??"";if(c!==""&&c!=="."&&c!=="^"){let g=/^\\?\.([\w-]+)\$$/.exec(c);i.push(l?c:g?`*.${g[1]}`:c.replace(/^\^|\$$/g,"").replace(/\\(.)/g,"$1"))}let u=[...o.slice(1),...a];u.length===0&&u.push(".");let f=u.map(g=>Ys(g,e,t)),p=f.find(g=>g.token==="fs.root"||g.token==="fs.home"||g.token==="fs.system"),d=i.length>0&&i.every(g=>vc.test(R.basename(g))||To.test(g));return d&&p?[m("claude.bash.fs.delete_recursive",`fd deletes matching files under ${p.path}`,{target:u.join(" "),is_local:!0})]:d?[m("claude.bash.fs.delete_disposable","fd deletes build or cache artifacts",{target:u.join(" "),is_local:!0})]:i.length>0||r.length>0||n.slice(0,s).some(g=>/^(-S|--size|--changed-(within|before)|--newer|--older)(=|$)/.test(g))?[m("claude.bash.fs.delete_recursive",`fd deletes the files matching ${i.join(", ")||"its filters"} under ${u.join(" ")}`,{target:u.join(" "),is_local:!0})]:[xt(f,e)]}function fl(e,t){let n=e.argv.slice(1);if(e.name==="dd"){let s=n.find(o=>o.startsWith("of="))?.slice(3);if(!s)return[];let r=He(s,e,t);return r.token==="fs.device"?[m("claude.bash.fs.delete_recursive",`overwrites a raw disk (${s})`,{target:s,service:"fs.device",is_local:!0})]:Cu.test(s)&&r.kind!=="disposable"?[m("claude.bash.fs.delete_recursive",`dd overwrites a data file (${R.basename(s)})`,{target:r.path,is_local:!0})]:[]}return e.name==="diskutil"?n.some(s=>/^(erase|zeroDisk|randomDisk|secureErase|partitionDisk|reformat)/i.test(s))?[m("claude.bash.fs.delete_recursive","erases a disk",{target:n.join(" "),service:"fs.device",is_local:!0})]:[]:[m("claude.bash.fs.delete_recursive",`formats or repartitions a disk (${e.name})`,{target:n.join(" "),service:"fs.device",is_local:!0})]}function _t(e){let t=e.argv,n=1,s=null;for(;n<t.length;){let o=t[n];if(o==="-C"&&t[n+1])s=t[n+1],n+=2;else if(o==="-c"||o==="--git-dir"||o==="--work-tree"||o==="--namespace")o==="--work-tree"&&t[n+1]&&(s=t[n+1]),n+=2;else if(o.startsWith("--work-tree="))s=o.slice(12),n++;else if(o.startsWith("-"))n++;else break}let r=t[n];return r?{sub:r,args:t.slice(n+1),dir:s}:null}function Sc(e,t){return e.cwdFallbacks.length>0||e.altArgvs.length>0||/\bgit\s+(?:-[cC]\s+\S+\s+|--?[\w-]+=\S+\s+|-(?![cC]\s)[\w-]+\s+)*(?:remote\s+(?:add|set-url|rename|remove|rm|set-head|set-branches)\b|config\s+(?!--get|--list|-l\b)|clone\b|init\b|submodule\b)|\bgh\s+repo\s+(?:clone|set-default|create|fork)\b|\b(?:HOME|XDG_CONFIG_HOME)=|\bGIT_(?:CONFIG|DIR|WORK_TREE|COMMON_DIR)|--git-dir|--work-tree/.test(t)}function zt(e,t,n){if(/\bGIT_(DIR|WORK_TREE|COMMON_DIR)\b|--git-dir/.test(n.lineText)||e.wrappers.includes("env")&&e.wrapperArgs.some(r=>/^-C/.test(r)||r.startsWith("--chdir")))return null;let s=t.dir?Ec(t.dir,e,n):e.cwd;return s===null||S(s)?null:s}function Pg(e,t,n){let s=e[t];if(!/^-[a-zA-Z]/.test(s))return null;for(let r=1;r<s.length;r++)if(n.includes(s[r]))return{letter:s[r],value:s.slice(r+1)||e[t+1]};return null}function Cc(e,t){let[n,s,r]=t==="switch"?["c","C","--create"]:["b","B",""],o=[];for(let a=0;a<e.length;a++){let i=e[a];if(i==="--")break;if(i==="--force-create"&&e[a+1])o.push({letter:s,branch:e[++a]});else if(i.startsWith("--force-create="))o.push({letter:s,branch:i.slice(15)});else if(r&&i===r&&e[a+1])o.push({letter:n,branch:e[++a]});else if(r&&i.startsWith(`${r}=`))o.push({letter:n,branch:i.slice(r.length+1)});else{let l=Pg(e,a,n+s);l&&l.value!==void 0&&(o.push({letter:l.letter,branch:l.value}),l.value===e[a+1]&&a++)}}return o}function Wg(e,t){return Cc(e,t).at(-1)??null}function Ng(e,t){if(e.name!=="git")return;let n=_t(e);if(!n)return;let s=n.dir??e.cwd;if(n.sub==="stash"){let r=n.args[0];(r===void 0||r==="push"||r==="save"||r.startsWith("-"))&&(t.stashCreated=!0,t.stashPushes++),r==="apply"&&t.stashApplied.add(yo(n.args.slice(1)))}if(n.sub==="worktree"&&n.args[0]==="add"){let r=n.args.lastIndexOf("-b");r>=0&&n.args[r+1]&&t.createdBranches.set(n.args[r+1],{by:Rn(e),repo:zt(e,n,t)})}if(n.sub==="checkout"||n.sub==="switch"){if(n.args.includes("--"))return;let r=Wg(n.args,n.sub);if(r){t.branch=r.branch,t.branchDir=s,(r.letter==="b"||r.letter==="c")&&t.createdBranches.set(t.branch,{by:Rn(e),repo:zt(e,n,t)});return}let o=n.args.find(a=>!a.startsWith("-"));o&&!o.includes("/")&&o!=="."&&!S(o)&&(t.branch=o,t.branchDir=s)}}function Lg(e,t){return t===e.branchDir?e.branch:null}function Do(e){return e!==null&&/\/scratchpad(\/|$)/.test(e)}function kt(e,t){return e===null?!1:Do(e)?!0:X(e,null,se(t)).kind==="disposable"}function pl(e,t,n,s){let r=t!==null&&!S(t)?t.replace(/(?<!\/)\/+$/,""):null,a=(n.ctx.projectControls??[]).filter(l=>typeof l=="object"&&l!==null&&typeof l.path=="string").filter(l=>(r===null||l.path.startsWith(`${r}/`))&&(l.staged===!0?s.staged:l.ignored===!0?s.ignored:s.untracked)).map(l=>l.path);if(a.length===0)return[];let i=k(a[0]);return[m("claude.agent.controls",`${e} takes this project's own ${R.basename(i)} away, so later sessions here run without it`,{target:i,is_local:!0})]}function Ac(e,t){let n=_t(e);if(!n)return[];let s=n.dir?Ec(n.dir,e,t):e.cwd,r=i=>n.args.some(l=>i.includes(l)),o=i=>n.args.some(l=>/^-[a-zA-Z]+$/.test(l)&&l.includes(i)),a=n.sub.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();if(/(^|-)(delete|del|remove|rm|prune|purge|drop|nuke|wipe|clean|cleanup)(-|$)/.test(a)&&/(^|-)(branch|branches|tag|tags|gone|merged|stale|worktree|worktrees)(-|$)/.test(a))return[m("claude.bash.git.discard",`git ${n.sub}: a command named for deleting branches or tags (an alias or extension)`,{target:[n.sub,...n.args.filter(i=>!i.startsWith("-"))].join(" "),is_local:!0})];switch(n.sub){case"push":{let i=Sc(e,t.lineText)||e.argv.filter(l=>l==="-C").length>1||e.argv.some(l=>/^(-c|--config-env)/.test(l))?null:zt(e,n,t);return Tg(n.args,t,e,Lg(t,n.dir??e.cwd),i)}case"reset":return r(["--hard"])&&!Do(s)?[m("claude.bash.git.discard","git reset --hard discards uncommitted work",{target:n.args.find(i=>!i.startsWith("-"))??"HEAD",branch:t.branch,is_local:!0})]:[];case"checkout":{let i=n.args.indexOf("--"),l=i>=0?n.args.slice(i+1):n.args.filter(u=>!u.startsWith("-"));return(l.some(u=>u==="."||u==="./"||u===":/"||u==="*"||u===":(top)")||r(["-f","--force"]))&&!kt(s,t)?[m("claude.bash.git.discard","git checkout discards every uncommitted change",{target:l.join(" ")||".",branch:t.branch,is_local:!0})]:hl(n.args,"checkout",e,t)}case"rm":{let i=n.args.filter(c=>!c.startsWith("-"));return i.some(c=>c==="."||c==="./"||c==="./*"||c===":/"||c==="*"||c===":(top)")&&(r(["-f","--force"])||o("f"))&&!r(["--cached","-n","--dry-run"])&&!o("n")&&!kt(s,t)?[m("claude.bash.git.discard","git rm -f deletes every tracked file, uncommitted changes too",{target:i.join(" "),branch:t.branch,is_local:!0})]:[]}case"restore":{if((r(["--staged"])||o("S"))&&!r(["--worktree"])&&!o("W"))return[];let i=n.args.filter(l=>!l.startsWith("-"));return i.some(l=>l==="."||l==="./"||l===":/"||l==="*")&&!kt(s,t)?[m("claude.bash.git.discard","git restore discards every uncommitted change",{target:i.join(" "),branch:t.branch,is_local:!0})]:[]}case"branch":{let i=n.args.filter(d=>!d.startsWith("-")),l=r(["-f","--force"])||o("f"),c=r(["-d","--delete","-D"])||n.args.some(d=>/^-[a-zA-Z]*[dD]/.test(d)&&/^-[a-zA-Z]+$/.test(d)),u=c&&(r(["-D"])||n.args.some(d=>/^-[a-zA-Z]*D/.test(d))||l);if(u&&i.length>0&&i.every(d=>Mn(d,e,t)||ih(d,zt(e,n,t),t)))return[];if(u)return[m("claude.bash.git.discard","git branch force-deletes a branch",{target:i.join(" "),is_local:!0})];let f=d=>n.args.some(h=>/^-[a-zA-Z]{2,}$/.test(h)&&d.test(h.slice(1))),p=r(["-m","--move","-c","--copy"])||f(/[mc]/);return r(["-M","-C"])||f(/[MC]/)||l&&p?[m("claude.bash.git.discard","git branch -M / -C overwrites a branch",{target:i.join(" "),is_local:!0})]:l&&!c&&i[0]!==void 0&&!Mn(i[0],e,t)?[m("claude.bash.git.discard",`git branch -f moves ${i[0]}`,{target:i.join(" "),branch:i[0],is_local:!0})]:[]}case"stash":{if(n.args[0]==="drop"){let u=yo(n.args.slice(1));if(t.stashApplied.has(u))return[];if(u.startsWith("computed:")&&t.stashCreated&&t.stashApplied.size>0)return[]}if((n.args[0]==="drop"||n.args[0]==="clear")&&oh(yo(n.args.slice(1)),n.args[0]==="clear",zt(e,n,t),t,e))return[];if(n.args[0]==="drop"||n.args[0]==="clear")return[m("claude.bash.git.discard",`git stash ${n.args[0]} deletes stashed work`,{target:n.args.slice(1).join(" ")||"stash",is_local:!0})];let i=n.args.length===0||["push","save"].includes(n.args[0])||n.args[0].startsWith("-"),l=r(["--all"])||o("a"),c=/\bgit\s+add\s+(?:[^;&|\n]*\s)?(-A|--all|\.)(\s|$)/.test(t.lineText.slice(0,65536));return i?pl("git stash",null,t,{untracked:l||c||r(["--include-untracked"])||o("u"),ignored:l,staged:!0}):[]}case"clean":{if(r(["--dry-run"])||o("n"))return[];if(!(r(["--force"])||o("f"))||kt(s,t))return[];let i={untracked:!o("X"),ignored:o("x")||o("X"),staged:!1},l=s??e.cwd;return[m("claude.bash.git.discard","git clean -f deletes untracked files",{target:s??".",is_local:!0,housekeeping:l!==null&&t.lineMade.some(c=>an(c,l))}),...pl("git clean -f",s,t,i)]}case"reflog":return n.args[0]==="delete"||n.args[0]==="expire"&&n.args.some(i=>/^--expire=(now|all|0)/.test(i)||i==="--all")?[m("claude.bash.git.discard",`git reflog ${n.args[0]} removes the record of lost commits`,{is_local:!0})]:[];case"gc":return n.args.some(i=>i==="--prune=now"||i==="--prune=all")?[m("claude.bash.git.discard","git gc --prune=now makes lost commits unrecoverable",{is_local:!0})]:[];case"filter-branch":case"filter-repo":return[m("claude.bash.git.discard",`git ${n.sub} rewrites history`,{is_local:!0})];case"symbolic-ref":{let i=n.args.filter(l=>!l.startsWith("-"));return!r(["-d","--delete"])&&i.length>=2&&i[0]!=="HEAD"?[m("claude.bash.git.discard",`git symbolic-ref points ${i[0]} at ${i[1]}`,{target:i[0],is_local:!0})]:[]}case"update-ref":{if(r(["-d"]))return[m("claude.bash.git.discard","git update-ref -d deletes a ref",{target:n.args.find(l=>!l.startsWith("-"))??null,is_local:!0})];let i=n.args.filter((l,c)=>!l.startsWith("-")&&n.args[c-1]!=="-m")[0]??"";return r(["--stdin"])||i.startsWith("refs/heads/")&&!Mn(i.slice(11),e,t)?[m("claude.bash.git.discard",`git update-ref moves ${i||"refs from stdin"}`,{target:i||"stdin",is_local:!0})]:[]}case"worktree":if(n.args[0]==="add"){let i=n.args.findIndex(c=>c==="-B"),l=i>0?n.args[i+1]:void 0;if(l!==void 0&&!Mn(l,e,t))return[m("claude.bash.git.discard",`git worktree add -B resets ${l}`,{target:l,branch:l,is_local:!0})]}if(n.args[0]==="remove"&&(r(["--force"])||o("f"))){let i=n.args.slice(1).find(u=>!u.startsWith("-"))??"",l=n.dir&&!S(n.dir)?X(n.dir,e.cwd,se(t)).path??e.cwd:e.cwd,c=X(i,l,se(t));return kt(c.path,t)||c.why===On?[]:e.guards.some(u=>/\bgit\b[^;&|]*\bworktree\s+add\b/.test(u)&&u.split(/\s+/).some(f=>f.replace(/^["']|["']$/g,"")===i))?[]:[m("claude.bash.git.discard","git worktree remove --force discards its changes",{target:i,is_local:!0})]}return[];case"switch":return r(["--discard-changes","-f","--force"])?[m("claude.bash.git.discard","git switch discards uncommitted changes",{branch:t.branch,is_local:!0})]:hl(n.args,"switch",e,t);default:return[]}}function hl(e,t,n,s){let r=Cc(e,t).find(o=>(o.letter==="B"||o.letter==="C")&&!Mn(o.branch,n,s));return r?[m("claude.bash.git.discard",`git ${t} -${r.letter} resets ${r.branch}`,{target:r.branch,branch:r.branch,is_local:!0})]:[]}function Mn(e,t,n){let s=n.createdBranches.get(e),r=_t(t),o=r?zt(t,r,n):null;return s!==void 0&&t.guards.includes(s.by)&&s.repo!==null&&s.repo===o}function yo(e){let t=e.find(n=>!n.startsWith("-"));return t===void 0?"stash@{0}":/^\d+$/.test(t)?`stash@{${t}}`:S(t)?`computed:${k(t)}`:t}function Ec(e,t,n){let s=`${e.replace(/\/$/,"")}/_`,r=Ie(s,t,n);return X(r!==s&&r.endsWith("/_")?r.slice(0,-2):e,t.cwd,se(n)).path}function Tg(e,t,n,s,r=null){let o=!1,a=!1,i=!1,l=[],c=null,u=new Set(["--repo","--receive-pack","--exec","-o","--push-option","--signed"]);for(let y=0;y<e.length;y++){let $=e[y];if($==="-n"||$==="--dry-run")return[];if($==="-f"||$==="--force"||$.startsWith("--force-with-lease")||$==="--force-if-includes"||$==="--mirror")o=!0;else if($==="-d"||$==="--delete")a=!0;else if($==="--all"||$==="--branches")i=!0;else if(/^-[a-zA-Z]+$/.test($)){if($.includes("f")&&(o=!0),$.includes("n"))return[];$.includes("d")&&(a=!0)}else $==="--repo"?c=e[++y]??null:$.startsWith("--repo=")?c=$.slice(7):u.has($)?y++:$.startsWith("-")||l.push($)}let f=l[0]??c,p={repo_dir:r===null||S(r)?null:r,repo_remote:f===null?null:S(f)?"$?":k(f),repo_via:"git"};if(e.includes("--mirror"))return[m("claude.bash.git.force_push","mirrors every branch and tag to the remote, overwriting or deleting what differs (main included)",{branch:null,target:"every branch and tag",service:null,is_local:!1})];let d=l.slice(1),h=[];d.length===0&&h.push({branch:i?"main":s,plus:!1,deleting:!1});for(let y of d){let $=y.startsWith("+"),E=$?y.slice(1):y,x=E.indexOf(":"),b=x>=0?E.slice(0,x):E,j=x>=0?E.slice(x+1):E,C=x===0,A=U=>S(U)&&/git\s+(branch\s+--show-current|rev-parse\s+--abbrev-ref\s+HEAD|symbolic-ref\s+--short\s+HEAD)/.test(k(U));(j==="HEAD"||x<0&&b==="HEAD"||A(j))&&(j=s??""),j=j.replace(/^refs\/heads\//,""),h.push({branch:j||null,plus:$,deleting:C||a})}let g=[];for(let y of h){let $=y.branch!==null&&cc.has(y.branch),E=y.branch??"the current branch";y.deleting?g.push($?m("claude.bash.git.force_push",`deletes the remote ${E} branch`,{branch:y.branch,target:E,service:"git.main",is_local:!1}):m("claude.bash.git.discard",`deletes the remote branch ${E}`,{branch:y.branch,target:E,is_local:!1})):o||y.plus?g.push(m("claude.bash.git.force_push",`force-pushes ${E}`,{branch:y.branch,target:E,service:$?"git.main":null,is_local:!1})):$?g.push(m("claude.bash.git.push_main",`pushes to ${y.branch} (a deploy)`,{branch:y.branch,target:y.branch,is_local:!1,push:p})):y.branch!==null&&Wh.has(y.branch)&&g.push(m("claude.bash.deploy",`pushes to ${y.branch} (a deploy branch)`,{branch:y.branch,target:y.branch,is_local:!1}))}return g}function Rc(e){let t=e.indexOf("--"),s=(t<0?e:e.slice(0,t)).filter(r=>r==="--rm"||r.startsWith("--rm="));return s.length>0&&!/^--rm=(false|0)$/i.test(s[s.length-1])}function Ig(e,t){let n=t.ctx.session?.repoRemotes;if(!n||!e.cwd||S(e.cwd))return null;let s=Object.keys(n).filter(r=>e.cwd===r||e.cwd.startsWith(`${r}/`)).sort((r,o)=>o.length-r.length)[0];return s===void 0?null:n[s]??null}function Dg(e,t){let n=Ig(e,t)?.filter(Boolean);if(!n||n.length===0)return!1;let s=[];return e.argv.forEach((r,o)=>{r==="-R"||r==="--repo"?s.push(e.argv[o+1]??null):r.startsWith("--repo=")?s.push(r.slice(7)):/^-R\S/.test(r)&&s.push(r.slice(2))}),s.length===0?!1:s.every(r=>!r||S(r)?!1:n.includes((Fg(r)??r).toLowerCase().replace(/^github\.com\//,"")))}function Fg(e){let t=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(e.trim());return t?`${t[1]}/${t[2]}`:null}function Ns(e,t){let n=[];e.argv.forEach((l,c)=>{l==="-R"||l==="--repo"?n.push(e.argv[c+1]??""):l.startsWith("--repo=")?n.push(l.slice(7)):/^-R\S/.test(l)?n.push(l.slice(2).replace(/^=/,"")):/^-[A-Za-z]+R/.test(l)&&n.push("$?")});let s=e.argv.slice(3).find(l=>/^https?:\/\/[^/]+\/[^/]+\/[^/]+\/(?:pulls?|issues)\/\d+/.test(k(l))),o=[...e.text.slice(0,Math.max(0,e.text.search(/(?:^|\s)(?:\S*\/)?gh\s/))).matchAll(/\bGH_REPO=("[^"]*"|'[^']*'|[^\s;&|)]+)/g)].pop()?.[1]?.replace(/^["']|["']$/g,""),a=s??n[n.length-1]??o??null;return{repo_dir:e.cwd!==null&&!S(e.cwd)&&(a!==null||!(Sc(e,t)||/\bGH_REPO\b/.test(t)))?e.cwd:null,repo_remote:a===null?null:S(a)?"$?":k(a),repo_via:"gh"}}function zg(e,t,n){let[,s="",r=""]=e.argv,o=e.argv.slice(3),a=(...l)=>e.argv.some(c=>l.includes(c)||l.some(u=>c.startsWith(`${u}=`)));if(s==="pr"&&r==="merge")return[m("claude.bash.git.push_main","gh pr merge merges a pull request into its base branch (main, unless it says otherwise: a deploy)",{target:o.find(l=>!l.startsWith("-"))??"current PR",branch:"main",is_local:!1,host:"github.com",push:Ns(e,t)})];if(s==="pr"&&(r==="create"||r==="edit"))if(a("-R","--repo")||e.argv.some(c=>/^-R\S/.test(c))||/\bGH_REPO=/.test(t)){if(n&&!/\bGH_REPO=/.test(t)&&Dg(e,n))return[]}else return[];let i={pr:new Set(["create","comment","review","close","reopen","edit","ready","lock","unlock"]),issue:new Set(["create","comment","close","reopen","edit","delete","transfer","lock","unlock","pin","unpin","develop"]),release:new Set(["delete","edit","upload","delete-asset"]),repo:new Set(["create","delete","edit","fork","rename","archive","unarchive"]),secret:new Set(["set","delete","remove"]),variable:new Set(["set","delete"]),workflow:new Set(["run","enable","disable"]),run:new Set(["cancel","delete"]),gist:new Set(["create","edit","delete"]),label:new Set(["create","edit","delete","clone"]),cache:new Set(["delete"])};if(s==="release"&&r==="create")return a("--draft","-d")?[m("claude.bash.external_write","gh release create makes a draft release on GitHub (nothing is published until someone publishes it)",{target:o.find(l=>!l.startsWith("-"))??null,is_local:!1,host:"github.com",push:Ns(e,t)})]:[m("claude.bash.publish","gh release create publishes a release",{target:o.find(l=>!l.startsWith("-"))??null,is_local:!1,host:"github.com",push:Ns(e,t)})];if(s==="workflow"&&r==="run"){let l=e.argv.findIndex(h=>h==="--ref"||h==="-r"),c=l>=0?e.argv[l+1]:e.argv.find(h=>h.startsWith("--ref="))?.slice(6),u=e.argv.slice(3).some(h=>!h.startsWith("-")&&/deploy|release|publish|prod/i.test(h)),f="";for(let h=3;h<e.argv.length&&!f;h++)/^(--ref|-r|-f|-F|--field|--raw-field|--repo|-R)$/.test(e.argv[h])?h++:e.argv[h].startsWith("-")||(f=e.argv[h]);let p=/deploy|release|publish|promot|rollout|(?:^|[^a-z])(?:prod(?:uction)?|ship)(?:[^a-z]|$)/i.test(f),d=e.argv.flatMap((h,g)=>/^(-f|-F|--field|--raw-field)$/.test(e.argv[g-1]??"")?[h]:/^(--field|--raw-field)=/.test(h)?[h.slice(h.indexOf("=")+1)]:[]);if(p||d.some(h=>/^(environment|env|stage|deploy_env|target)=/i.test(h)))return[m("claude.bash.deploy",p?"gh workflow run starts a deploy or release workflow":"gh workflow run starts a workflow for an environment",{target:o.find(h=>!h.startsWith("-"))??null,is_local:!1,host:"gh"})];if(c&&!S(c)&&!cc.has(c.replace(/^refs\/heads\//,""))&&!u)return[]}if(s==="run"&&r==="rerun"&&/(?<![\w-])[\w-]*(deploy|release|publish|prod)[\w-]*\.ya?ml\b|--workflow[= ]+['"]?[\w -]*(deploy|release|publish|prod)/i.test(t))return[m("claude.bash.external_write","gh run rerun next to a deploy or release workflow can redo a release",{target:"run rerun",is_local:!1,host:"github.com"})];if(i[s]?.has(r))return[m("claude.bash.external_write",`gh ${s} ${r} changes GitHub`,{target:`${s} ${r}`,is_local:!1,host:"github.com",push:Ns(e,t),...s==="repo"&&r==="delete"?{catastrophic:!0}:{}})];if(s==="auth"&&r==="setup-git")return[m("claude.bash.persistence","gh auth setup-git makes gh the git credential helper for every repository",{target:"credential.helper",is_local:!0})];if(s==="auth"&&(r==="token"||r==="status"&&a("-t","--show-token")))return ae(e)?[m("claude.bash.secrets.print","prints the GitHub token",{target:"gh auth token",is_local:!0})]:[];if(s==="api"){let l=e.argv.findIndex(p=>p==="-X"||p==="--method"),c=(l>=0?e.argv[l+1]:e.argv.find(p=>p.startsWith("--method="))?.slice(9)??e.argv.find(p=>/^-X[A-Z]+$/.test(p))?.slice(2)??null)?.toUpperCase()??null,u=a("-f","-F","--field","--raw-field","--input"),f=e.argv.slice(2).find((p,d,h)=>!p.startsWith("-")&&!["-X","--method"].includes(h[d-1]??""))??"";if(c==="GET"||c==="HEAD")return[];if(f==="graphql"){let p=e.argv.join(" ");return/\bmutation\b/.test(p)?[m("claude.bash.external_write","gh api runs a GraphQL mutation",{target:"graphql",is_local:!1,host:"github.com"})]:[]}if(c&&c!=="GET"||u)return[m("claude.bash.external_write",`gh api ${c??"POST"} ${f}`,{target:f,is_local:!1,host:"github.com",...c==="DELETE"&&!jc.test(f)?{catastrophic:!0}:{}})]}return[]}var Js=new Set(["-X","-H","-d","-F","-o","-u","-A","-e","-b","-c","-m","-w","-x","-T","-K","-r","-C","-Y","-y","-z","-E","-U","-P","-Q","--request","--header","--data","--data-raw","--data-binary","--data-ascii","--data-urlencode","--json","--form","--form-string","--output","--user","--user-agent","--referer","--cookie","--cookie-jar","--max-time","--connect-timeout","--write-out","--proxy","--upload-file","--config","--range","--retry","--retry-delay","--resolve","--cert","--key","--cacert","--limit-rate","--url","--oauth2-bearer"]),Mt=["-d","--data","--data-raw","--data-binary","--data-ascii","--data-urlencode","--json","-F","--form","--form-string","-T","--upload-file"],Fo=/(?:(?:https?:\/\/)?(?<![\w.-])(?:[\w-]{1,63}\.){0,5}anvilcontrol\.ai(?::\d+)?|ANVIL_API(?:_BASE)?_URL)[\s\S]{0,60}?(\/v1\/(?:modes|kill-switch)|\/anvil\/actions\/(?:mode|removal-confirm)|\/api\/control\/kill-switch)\b/;function zo(e){return e.includes("anvilcontrol.ai")||e.includes("ANVIL_API")}function Oc(e,t,n){if(!zo(e))return null;let s=Fo.exec(e)?.[1];return s===void 0?null:t==="DELETE"||s.endsWith("removal-confirm")?s:s.endsWith("kill-switch")?/\bon["']?\s*[:=]\s*(false|False)\b/.test(n)&&!/\bon["']?\s*[:=]\s*(true|True)\b/.test(n)?null:s:/\bmode["']?\s*[:=]\s*["']enforce["']/.test(n)&&!/["']ghost["']/.test(n)?null:s}function Mg(e){let t=e.argv,n=null,s=!1,r=!1,o=[];if(e.name==="curl"){for(let p=1;p<t.length;p++){let d=t[p];if(d==="-X"||d==="--request"?n=(t[p+1]??"").toUpperCase():/^-X[A-Za-z]+$/.test(d)?n=d.slice(2).toUpperCase():d.startsWith("--request=")?n=d.slice(10).toUpperCase():d[0]==="-"&&d[1]!=="-"&&d.includes("X")&&/^-[a-zA-Z]+X$/.test(d)?n=(t[p+1]??"").toUpperCase():d[0]==="-"&&d[1]!=="-"&&d.includes("X")&&/^-[a-zA-Z]+X[A-Z]+$/.test(d)&&(n=d.slice(d.indexOf("X")+1)),(Mt.includes(d)||Mt.some(h=>h.startsWith("--")&&d.startsWith(`${h}=`))||/^-d./.test(d))&&(s=!0),(d==="-G"||d==="--get")&&(r=!0),(d==="-I"||d==="--head")&&(n="HEAD"),d==="--url"&&t[p+1]&&o.push(t[p+1]),Js.has(d)||d.endsWith("X")&&/^-[a-zA-Z]+X$/.test(d)){p++;continue}!d.startsWith("-")&&un(d)&&o.push(d)}n||(n=s&&!r?"POST":"GET")}else if(e.name==="wget"){for(let[p,d]of t.entries())(d.startsWith("--post-data")||d.startsWith("--post-file")||d.startsWith("--body-data")||d.startsWith("--body-file"))&&(s=!0),d.startsWith("--method=")&&(n=d.slice(9).toUpperCase()),d==="--method"&&t[p+1]&&(n=t[p+1].toUpperCase()),p>0&&!d.startsWith("-")&&un(d)&&o.push(d);n||(n=s?"POST":"GET")}else{let p=t.slice(1).filter((d,h)=>!d.startsWith("-")&&!((t[h]??"").startsWith("-")&&qg.test(t[h])));p[0]&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(p[0])&&(n=p.shift().toUpperCase()),p[0]&&o.push(p[0]),n||(n=p.slice(1).some(d=>/^[^=:@]+(:?=|@)/.test(d))?"POST":"GET")}if(!["POST","PUT","PATCH","DELETE"].includes(n))return[];if(n==="POST"&&(Zg(t)||Kg(o,t)))return[];let a=o.filter(p=>!Re(p));if(o.length>0&&a.length===0)return[];let i=a[0]??o[0]??null,l=t.filter((p,d)=>d>0&&(Mt.includes(t[d-1])||/^--(data|json)[\w-]*=/.test(p)||/^-d./.test(p))).join(" "),c=t.find(p=>zo(p)&&Fo.test(p)),u=c!==void 0?Oc(c,n,l):null;return c!==void 0&&u!==null?[m("claude.agent.controls",`changes your Anvil workspace's modes through its API (${n} ${u})`,{target:c,host:i?de(i):null,is_local:!1})]:(a.length>0?a.slice(0,64):[i]).flatMap(p=>Ug(p,n,t))}function Ug(e,t,n){let s=e?de(e):null;if(e&&/\/(batches|fine_tuning|fine-tunes|fine_tunes|predictions|training_jobs|jobs\/(create|submit))\b/.test(e))return[m("claude.bash.spend",`starts a paid job (${t} ${s??"an API"})`,{target:e,host:s,is_local:!1})];let r=t!=="DELETE"?null:s??/^\$\{?(\w+)/.exec(k(n.find((l,c)=>c>0&&!l.startsWith("-")&&S(l)&&!Js.has(n[c-1])&&!/^(--(http-user|http-password|user|password|header|output-document|output-file)|-[oOU])$/.test(n[c-1]))??""))?.[1]??null,o=e?k(e).replace(/^[a-z]+:\/\/[^/?#]*/i,""):"",a=/\.(execute-api\.[\w-]+|elb(\.[\w-]+)?)\.amazonaws\.com$/i.test(r??"")||/^\/rest\/v1\/[^?]*\?[^#]*=/.test(o)||r==="api.github.com"&&jc.test(o.replace(/^\//,"")),i=r!==null&&!a&&!Pc.test(r)&&(gl.test(r)||or(r));return[m("claude.bash.external_write",i?`DELETE to ${s??`a URL in $${r}`} removes what it names (${gl.test(r)?"a provider's API":"a host named for production"})`:`${t} to ${s??"an external host"}`,{target:e,host:s,is_local:!1,service:s,...i?{catastrophic:!0}:{}})]}var jc=/(^|\/)(user\/(starred|following)|notifications|subscriptions?|actions\/caches|reactions)(\/|\?|$)/,Pc=/^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|0\.0\.0\.0|host\.docker\.internal)$|\.(local|test|localhost)$/i,qg=/^(-a|--auth|-A|--auth-type|--bearer|-o|--output|--session|--session-read-only|--cert|--cert-key|--verify|--proxy|--timeout|-s|--style|-p|--print|--pretty|--format-options|--default-scheme|--max-redirects)$/,gl=/(^|\.)(api\.github\.com|uploads\.github\.com|gitlab\.com|api\.bitbucket\.org|amazonaws\.com|googleapis\.com|management\.azure\.com|graph\.microsoft\.com|core\.windows\.net|api\.cloudflare\.com|api\.vercel\.com|api\.netlify\.com|api\.heroku\.com|api\.fly\.io|api\.machines\.dev|api\.render\.com|backboard\.railway\.(app|com)|supabase\.(co|com)|api\.planetscale\.com|neon\.tech|api\.digitalocean\.com|api\.linode\.com|api\.hetzner\.cloud|api\.vultr\.com|api\.scaleway\.com|upstash\.(com|io)|turso\.(tech|io)|cloud\.mongodb\.com|hub\.docker\.com)$/i;function Wc(e){let t=[];for(let n=1;n<e.length;n++){let s=e[n];Mt.includes(s)&&e[n+1]!==void 0?t.push(e[n+1]):Mt.some(r=>r.startsWith("--")&&s.startsWith(`${r}=`))&&t.push(s.slice(s.indexOf("=")+1))}return t}var ml=new Set(["query","variables","operationName","extensions"]),Hg=new Set(["jsonrpc","method","params","id"]),Bg=/(^|[/._])(list|get|read|search|query|describe|status|ping|initialize|lookup|find)/i,yl=(e,t)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).every(n=>t.has(n));function Vg(e){let t;try{t=JSON.parse(e)}catch{let s=e.split("&").map(o=>o.split("=")[0]??""),r="";try{r=decodeURIComponent((/^query=([^&]*)/.exec(e)?.[1]??"").replace(/\+/g," "))}catch{return!1}return s.every(o=>ml.has(o))&&/^\s*(query\b|\{)/.test(r)}let n=Array.isArray(t)?t:[t];return n.length>0&&n.every(s=>{if(yl(s,Hg)&&typeof s.method=="string"){if(s.method==="tools/call"){let r=s.params,o=typeof r=="object"&&r!==null?r.name:void 0;return typeof o=="string"&&zs(o)==="read"}return Bg.test(s.method)}return yl(s,ml)&&typeof s.query=="string"&&/^\s*(query\b|\{)/.test(s.query)})}function Zg(e){let t=Wc(e);if(t.length===0)return!1;let n=t.join(" ");return/\bmutation\b/i.test(n)||/\bsubscription\b/i.test(n)||Mo.test(n)?!1:t.every(Vg)}var Mo=/\b(drop\s+(table|database|schema|index|view)|truncate\s|delete\s+from|insert\s+into|update\s+[\w."]+\s+set|alter\s+table|create\s+(table|index|database)|grant\s|revoke\s)/i,Gg=new Set(["query","queries","search","autocomplete","suggest","suggestions","lookup","find","list","get","fetch","load","read","info","describe","count","explain","preview"]);function Kg(e,t){if(e.length===0)return!1;let n=Wc(t).join(" ");return Mo.test(n)||/\bmutation\b/i.test(n)?!1:e.every(s=>{if(S(s))return!1;let o=s.replace(/^[a-z]+:\/\/[^/]*/i,"").replace(/[?#].*$/,"").split("/").filter(Boolean),a=o.flatMap(l=>l.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));if(a.some(l=>wt.has(l)||vt.has(l)||["redeem","subscribe","unsubscribe","enroll","register","signup","checkout","notify","verify","generate","run"].includes(l)))return!1;let i=(o[o.length-1]??"").toLowerCase();return a.some(l=>Gg.has(l))||/(query|search|lookup|autocomplete)$/.test(i)})}function un(e){return/^https?:\/\//i.test(e)||/^(localhost|127\.|\[::1\]|<host>|[\w-]+(\.[\w-]+)+)(:\d+)?(\/|$)/i.test(e)}function Re(e){if(/^(\[?::1\]?|0\.0\.0\.0)$/.test(e))return!0;let t=/^[a-z]+:\/\//i.test(e)?e:`http://${e}`;return fi(t)}function de(e){return/^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:[^@/]*@)?(\[[^\]]+\]|[^/:?#]+)/i.exec(e)?.[1]?.toLowerCase()??null}function Yg(e,t){let n=e.argv.slice(1);switch(e.name){case"pkill":case"killall":{if(n.includes("-0")||n.includes("-l")||n.length===0)return[];let s=new Set(["-u","-U","--euid","--uid","-g","-G","-t","-s","-P","--signal","-F"]),r=[];for(let f=0;f<n.length;f++)s.has(n[f])?f++:n[f].startsWith("-")||r.push(n[f]);let o=n.some(f=>["-u","-U","--euid","--uid"].includes(f));if(e.name==="pkill"&&n.some(f=>/^-[a-zA-Z]*v[a-zA-Z]*$/.test(f)||f.length>=4&&"--inverse".startsWith(f)))return[m("claude.bash.process.kill_by_name","pkill -v kills every process that does not match",{target:n.join(" "),service:"proc.all",is_local:!0})];if(o&&r.length===0)return[m("claude.bash.process.kill_by_name",`${e.name} -u kills every process the user owns`,{target:n.join(" "),service:"proc.all",is_local:!0})];let a=e.name==="pkill"&&n.some(f=>/^-[a-zA-Z]*f[a-zA-Z]*$/.test(f)||f==="--full");if(!o&&r.length>0&&r.every(f=>Uo(f,t,a)))return[];let i=n.some(f=>/^-[a-zA-Z]*i[a-zA-Z]*$/.test(f)||f==="--ignore-case"),l=e.name==="killall"&&n.some(f=>f==="-r"||f==="--regexp"||f==="-m"),c=o||$t(e)?null:sc(r,{full:a,exact:e.name==="killall"&&!l||n.some(f=>/^-[a-zA-Z]*x[a-zA-Z]*$/.test(f)||f==="--exact"),fold:i},t);if(c==="own")return[];let u=e.name==="pkill"&&r.length===0&&n.some(f=>f==="-P"||f==="--parent"||f.startsWith("--parent=")||/^-P./.test(f));return e.name==="pkill"&&!o&&!$t(e)&&Nc(n,e,t)?[]:u?[m("claude.bash.process.kill_by_name","pkill -P stops every process the named process started",{target:n.join(" "),is_local:!0})]:[m("claude.bash.process.kill_by_name",`${e.name} kills every process matching a name, other sessions' too`,{target:r.join(" "),is_local:!0,housekeeping:c==="some"})]}case"fuser":return n.some(s=>/^-[a-zA-Z]*k/.test(s))?[m("claude.bash.process.kill_by_name","fuser -k kills everything using the port or file, clients too",{target:n.filter(s=>!s.startsWith("-")).join(" "),is_local:!0})]:[];case"colima":return["stop","delete","restart","kill"].includes(n[0]??"")?[m("claude.bash.process.kill_by_name",`colima ${n[0]} stops the Docker VM other sessions share`,{target:"colima",is_local:!0})]:[];case"launchctl":return["stop","unload","bootout","kill","remove","disable"].includes(n[0]??"")||n[0]==="kickstart"&&n.includes("-k")?[m("claude.bash.process.kill_by_name",`launchctl ${n[0]} stops a system service`,{target:n.slice(1).join(" "),is_local:!0})]:[];case"tmux":return["kill-server","kill-session"].includes(n[0]??"")?[m("claude.bash.process.kill_by_name",`tmux ${n[0]} ends sessions it may not own`,{target:n.slice(1).join(" "),is_local:!0})]:[];case"systemctl":return["stop","restart","kill","disable","mask","poweroff","reboot","halt"].includes(n[0]??"")?[m("claude.bash.process.kill_by_name",`systemctl ${n[0]} stops a service`,{target:n.slice(1).join(" "),is_local:e.remote===null,host:e.remote})]:[];case"shutdown":case"reboot":case"halt":return[m("claude.bash.process.kill_by_name",`${e.name} stops the machine`,{target:e.name,service:"proc.all",is_local:e.remote===null,host:e.remote})];case"osascript":{let s=n.join(" ");return/\b(shut\s*down|restart|log\s*out)\b/i.test(s)&&/\b(System Events|Finder|loginwindow)\b/i.test(s)?[m("claude.bash.process.kill_by_name","osascript shuts down, restarts or logs out the machine",{target:s.slice(0,80),service:"proc.all",is_local:!0})]:/\bquit\b/i.test(s)?[m("claude.bash.process.kill_by_name","osascript quits an application",{target:s.slice(0,80),is_local:!0})]:[]}case"kill":return Jg(e,t);default:return[]}}function Jg(e,t){let n=e.argv.slice(1),s=0,r=!1;for(;s<n.length&&n[s].startsWith("-")&&!/^-\d+$/.test(n[s])||s<n.length&&/^-(\d+|[A-Z]+|s|n)$/.test(n[s])&&!(n[s]==="-1"&&s===n.length-1);){let l=n[s];(l==="-0"&&s===0||l==="-l"||l==="-L")&&(r=!0),(l==="-s"||l==="-n")&&s++,s++}if(r)return[];let o=n.slice(s),a=nm(e,t);if(e.via==="xargs"&&e.pipeFrom)return a?[]:om(e.pipeFrom,t);if(e.via==="xargs"&&e.stdinFile)return a?[]:Xs(e.stdinFile,e,t);let i=[];for(let l of n.slice(0,s).filter((c,u)=>(u>0||o.length===0)&&c!=="-1"&&(/^-\d+$/.test(c)?u>0&&n[u-1]!=="-s"&&n[u-1]!=="-n":c.startsWith("-")&&S(c))))a||i.push(m("claude.bash.process.kill_by_name",`kills the whole process group ${k(l).slice(1)}`,{target:k(l),is_local:!0}));for(let l of o)if(l==="-1")i.push(m("claude.bash.process.kill_by_name",e.wrappers.some(c=>["sudo","doas","pkexec","run0"].includes(c))?"kill -1 as root kills every process on the machine":"kill -1 kills every process you own",{target:"-1",service:"proc.all",is_local:!0}));else{if(a)continue;if(/^-\d+$/.test(l))i.push(m("claude.bash.process.kill_by_name",`kills the whole process group ${l.slice(1)}`,{target:l,is_local:!0}));else{if(/^\d+$/.test(l)&&(t.ctx.session?.ownPids?.includes(l)||!$t(e)&&nc(l,t)))continue;if(/^\d+$/.test(l))i.push(m("claude.bash.process.kill_by_name",`kills a hard-coded PID (${l}) this command did not start`,{target:l,is_local:!0}));else if(S(l)){let c=k(l);if(rm(c,t)||!$t(e)&&Qg(c,e,t))continue;if(/\b(pgrep|pidof)\b|\bps\b/.test(c))i.push(m("claude.bash.process.kill_by_name","kills processes found by name",{target:c,is_local:!0}));else if(/\blsof\b/.test(c)&&!/-sTCP:LISTEN/.test(c)){let u=/^\$\(\s*lsof\s+([^()$`|;&]*?)\s*\)$/.exec(c.trim()),f=u&&!$t(e)?rc(u[1].split(/\s+/),t):null;f!=="own"&&i.push(m("claude.bash.process.kill_by_name","kills by port without checking LISTEN, so clients die too",{target:c,is_local:!0,housekeeping:f==="some"}))}else if(/\bdocker\s+ps\b/.test(c))i.push(m("claude.bash.process.kill_by_name","kills every running container",{target:c,is_local:!0}));else{let u=Lc(l,e,t);u&&i.push(...Xs(u,e,t))}}}}return i}function Xg(e,t,n){if(/\$\{(#|!|\w+[^\w}])/.test(t.text))return!1;let s=k(e).trim();if(/^\d+$/.test(s))return Number(s)>1&&(n.ctx.session?.ownPids?.includes(s)===!0||nc(s,n));let r=/^(\$\(\s*(cat\s+|<\s*)|`\s*cat\s+)["']?[^\s;&|<>()`$"'\\]+["']?\s*[)`]$/.test(s)?Lc(e,t,n):null;return r!==null&&!S(r)&&Xs(r,t,n).length===0}function Nc(e,t,n){let s=[];return e.forEach((r,o)=>{let a=r==="-P"||r==="--parent"?e[o+1]??"":r.startsWith("--parent=")?r.slice(9):/^-P./.test(r)?r.slice(2):null;a!==null&&s.push(...S(a)?[a]:a.split(","))}),s.length>0&&s.length<=8&&!e.some(r=>/^-[a-zA-Z]*v[a-zA-Z]*$/.test(r)||r.length>=4&&"--inverse".startsWith(r))&&s.every(r=>Xg(r,t,n))}function Qg(e,t,n){let s=/^\$\(\s*pgrep\s+([^;&|\n`]*?)\s*\)$/.exec(e.trim());if(!s)return!1;let r=`pgrep ${s[1]}`,o=(n.lineCommands??[]).filter(i=>i.name==="pgrep"&&i.via==="substitution"&&i.text.trim()===r),a=o.length>0?o:Jn(r,t.cwd,n).commands.filter(i=>i.name==="pgrep").slice(0,1);return a.length>0&&a.every(i=>i.pipeTo===null&&Nc(i.argv.slice(1),t,n))}function Xs(e,t,n){return S(e)?[]:He(e,t,n).kind==="disposable"?[]:[m("claude.bash.process.kill_by_name",`kills the process in ${k(e)}, which this session did not start`,{target:k(e),is_local:!0})]}function Lc(e,t,n){let s=k(e).trim(),r=/^\$\(([\s\S]*)\)$/.exec(s)??/^`([\s\S]*)`$/.exec(s);if(!r)return null;let o=Jn(r[1],t.cwd,n);for(let a of o.commands){let l=(["cat","head","tail","sort","uniq"].includes(a.name)?a.argv.slice(1).find(c=>!c.startsWith("-")&&!/^\d+$/.test(c)):["sed","awk","jq","grep","cut","tr"].includes(a.name)?qt(a)[0]:void 0)??a.stdinFile??void 0;if(l)return l}return null}var em=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/scratchpad\b/i,tm=/(^|[\s;&|({])(function\s+[\w-]+|[\w-]+\s*\(\)\s*\{|alias\s|unalias\s|hash\s|enable\s)/;function nm(e,t){if(e.guards.length===0||tm.test(t.lineText))return!1;let n=String.raw`(lsof\b[^;|)]*\s-p\b|ps\b[^;|)]*\s-p\b|pwdx\b|(cat|readlink|ls)\b[^;|)]*\/proc\/)`,s=r=>new RegExp(`^${n}`).test(r)||new RegExp(String.raw`^(\[\[?|test)\s[^;|]*\$\(\s*${n}`).test(r);return e.guards.some(r=>{let o=/^case ([\s\S]*) in [\s\S]*$/.exec(r)?.[1];if(!s(o===void 0?r:k(o).replace(/^["']?\$\(\s*/,""))||/\bgrep\b[^;|]*\s-[a-zA-Z]*v|\[\[?\s*-z\b|\btest\s+-z\b|-eq\s*0\b|-lt\s*1\b|==?\s*0\b|(^|\s)!\s/.test(r))return!1;let a=/^case ([\s\S]*) in ([\s\S]*)$/.exec(r);return a?a[2].split("|").every(i=>bo(i,t)):bo(r,t)&&!/\\\||\s-e\s.*\s-e\s/.test(r)})}function Uo(e,t,n){let r=e.replace(/^["']|["']$/g,"").split(/(?<!\\)\|/);return r.length>8||r.some(o=>o.trim()==="")?!1:r.every(o=>sm(o,t)||va(o,Ql(t),n,ec(t)))}function sm(e,t){let n=e.replace(/^["']|["']$/g,"");if(/(^|[^\\])\|/.test(n))return!1;let s=/^[^|()?*+[\]{}\\^$]*/.exec(n.replace(/\\\./g,"."))[0];return bo(s,t)&&/\/scratchpad\//.test(`${s}/`)&&/\/scratchpad\b/.test(s)}function bo(e,t){let n=e.toLowerCase(),s=t.sessionId?.toLowerCase()??null;return s?n.includes(s)||/^[0-9a-f]{8}/.test(s)&&new RegExp(`(^|[^0-9a-f])${s.slice(0,8)}([^0-9a-f]|$)`).test(n):em.test(n)}function rm(e,t){let n=/^\$\(\s*pgrep\s+((?:-[a-zA-Z]+\s+)*)("[^"]*"|'[^']*'|\S+)\s*\)$/.exec(e.trim());if(!n||/[uUgGPtv]/.test(n[1]??""))return!1;let s=/f/.test(n[1]??"");return Uo(n[2],t,s)||rh([n[2]],{full:s,exact:/x/.test(n[1]??""),fold:/i/.test(n[1]??"")},t)}function om(e,t){let n=[];for(let i=e;i&&n.length<8;i=i.pipeFrom)n.push(i);if(n.length===1&&e.name==="pgrep"){let i=e.argv.slice(1).filter(c=>c.startsWith("-")),l=e.argv.slice(1).filter(c=>!c.startsWith("-"));if(l.length===1&&!i.some(c=>/[uUgGPtv]/.test(c)||c==="--inverse")&&Uo(l[0],t,i.some(c=>c.includes("f"))))return[]}let s=n.map(i=>i.name),r=n.find(i=>i.name==="lsof");if(r){if(r.argv.some(l=>l==="-sTCP:LISTEN"||l.includes("TCP:LISTEN")))return[];let i=n.length===1&&!$t(r)&&!$t(e)?rc(r.argv.slice(1),t):null;return i==="own"?[]:[m("claude.bash.process.kill_by_name","kills by port without checking LISTEN, so clients die too",{target:r.argv.slice(1).join(" "),is_local:!0,housekeeping:i==="some"})]}if(s.some(i=>i==="pgrep"||i==="pidof"||i==="ps"))return[m("claude.bash.process.kill_by_name","kills processes found by name",{target:n.map(i=>i.name).reverse().join(" | "),is_local:!0})];if(s.includes("docker"))return[m("claude.bash.process.kill_by_name","kills containers listed by docker",{target:"docker ps",is_local:!0})];let o=n[n.length-1],a=["cat","head","tail","sort","uniq","tr","cut"].includes(o.name)?o.argv.slice(1).find(i=>!i.startsWith("-")&&!/^\d+$/.test(i))??o.stdinFile:["awk","sed","jq","grep"].includes(o.name)?qt(o)[0]??o.stdinFile:null;return a?Xs(a,o,t):(o.name==="echo"||o.name==="printf")&&o.argv.slice(1).some(i=>/^\d+$/.test(i))?[m("claude.bash.process.kill_by_name","kills a hard-coded PID this command did not start",{target:o.argv.slice(1).join(" "),is_local:!0})]:[]}var im=oe({aws:new Set(["--profile","--region","--output","--endpoint-url","--query","--color","--ca-bundle","--cli-read-timeout","--cli-connect-timeout"]),kubectl:new Set(["--context","--namespace","-n","--kubeconfig","--cluster","--user","-s","--server","--token","--as","--as-group","--request-timeout","-l","--selector","-o","--output","-f","--filename","-v"]),helm:new Set(["--kube-context","--namespace","-n","--kubeconfig","--repo","--version","-f","--values","--set","-o","--output"]),fly:new Set(["-a","--app","-c","--config","-r","--region","-o","--org"]),flyctl:new Set(["-a","--app","-c","--config","-r","--region","-o","--org"]),railway:new Set(["-s","--service","-e","--environment","-p","--project"]),ngrok:new Set(["--config","--authtoken","--log","--log-format","--log-level","--region","--api-key","--url","--domain"]),cloudflared:new Set(["--config","--loglevel","--logfile","--metrics","--origincert","--credentials-file","--protocol","--edge-ip-version","--region","--hostname","--url"]),sui:new Set(["--client.env","--client.config","--gas-budget","--gas","--gas-price"]),bq:new Set(["--location","--project_id","--dataset_id","--format","--api","--job_id","--destination_table","--parameter","--label","--maximum_bytes_billed","-n","--max_rows"]),eas:new Set(["--branch","--channel","--message","-m","--platform","-p","--profile","-e","--id","--group","--runtime-version","--percent"]),hardhat:new Set(["--network","--config"]),truffle:new Set(["--network","--config"]),brownie:new Set(["--network"]),solana:new Set(["--url","-u","--keypair","-k","--fee-payer","--commitment","--with-compute-unit-price","--program-id","--upgrade-authority","--buffer"]),"spl-token":new Set(["--url","-u","--fee-payer","--owner","--program-id"]),cast:new Set(["--rpc-url","-r","--private-key","--from","-f","--value","--gas-limit","--gas-price","--chain","--keystore","--account","--nonce"]),forge:new Set(["--rpc-url","-r","--fork-url","-f","--private-key","--sender","--chain","--etherscan-api-key","--verifier","--sig","-s","--account","--keystore","--constructor-args"]),fastlane:new Set(["--env"]),claude:new Set(["--transport","-t","--scope","-s","-e","--env","-H","--header","--model","--permission-mode","--allowedTools","--allowed-tools","--disallowedTools","--disallowed-tools","--output-format","--append-system-prompt","--add-dir","--mcp-config","--settings","--resume","-r"]),vercel:new Set(["--token","-t","--scope","-S","--cwd","-A","--local-config","--team","-T","--target","-e","--env","-b","--build-env","-m","--meta","--regions","--archive"]),gcloud:new Set(["--project","--account","--configuration","--zone","--region","--format","--impersonate-service-account"]),az:new Set(["--subscription","--output","-o","--query"]),doctl:new Set(["--context","-t","--access-token","-o","--output"]),heroku:new Set(["-a","--app","-r","--remote"]),wrangler:new Set(["-c","--config","-e","--env"]),supabase:new Set(["--project-ref","--workdir","--profile"]),modal:new Set(["-e","--env"]),docker:new Set(["-H","--host","--context","-c","--config","--log-level"]),terraform:new Set([]),pulumi:new Set(["-s","--stack","-C","--cwd"]),stripe:new Set(["--api-key","--project-name","-p"])}),v=e=>{let t=im[ue(e[0]??"")]??new Set,n=[];for(let s=1;s<e.length;s++){let r=e[s];if(r.startsWith("-")){t.has(r)&&s++;continue}n.push(r)}return n},re=(...e)=>t=>e.every((n,s)=>v(t)[s]===n),T=(e,...t)=>e.some(n=>t.includes(n)||t.some(s=>n.startsWith(`${s}=`))),am=new Set(["--dry-run","--force","--yes","-y","--atomic","--wait","--wait-for-jobs","--all","--debug","--verbose","-v","--quiet","-q","--json","--allow-dirty","--no-verify","--locked","--frozen","--offline","--install","--create-namespace","--reuse-values","--reset-values","--cleanup-on-fail","--recursive","-R","--prune","--server-side","--keep-history","--no-hooks","--skip-crds","--devel","--dependency-update","--provenance","--ignore-scripts","--workspaces","--include-workspace-root","--linked","--local","--include-all","--include-roles","--include-seed"]);function Dt(e,t,n=["true"]){let s=i=>i.replace(/^--/,"").replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`).replace(/_/g,"-"),r=t.map(s),o=i=>r.some(l=>l===i||l.replace(/-/g,"")===i.replace(/-/g,"")||i.length>=2&&l.startsWith(i)),a=null;for(let i=0;i<e.length;i++){let l=e[i];if(l==="--")break;if(!l.startsWith("--"))continue;let[c,...u]=l.slice(2).split("="),f=c.startsWith("no-")||/^no[A-Z]/.test(c),p=s(f?c.replace(/^no-?/,"").replace(/^./,y=>y.toLowerCase()):c);if(!o(p))continue;let d=t.includes(`--${c}`),h=e[i-1]??"",g=/^--?[a-zA-Z][\w-]*$/.test(h)&&!am.has(h);f?a="false":u.length?a=d?u.join("="):u.join("=")==="true"?null:"false":!d||g?a=a??null:a=e[i+1]==="false"?"false":"true"}return a!==null&&n.includes(a)}var Ae=e=>!Dt(e,["--dry-run","--dryrun","--plan","--preview"]),Tc=oe({railway:[{match:e=>["up","redeploy","deploy","down"].includes(v(e)[0]??""),action:"claude.bash.deploy",why:"railway deploys or removes a service"},{match:e=>["variables","variable","vars"].includes(v(e)[0]??"")&&(T(e,"--set")||["set","delete","remove"].includes(v(e)[1]??"")),action:"claude.bash.deploy",why:"railway changes production variables"},{match:e=>v(e)[0]==="domain",action:"claude.bash.deploy",why:"railway domain can create a public domain for a live service"},{match:e=>["service","environment","volume","project"].includes(v(e)[0]??"")&&["delete","remove","rm"].includes(v(e)[1]??""),action:"claude.bash.deploy",why:"railway deletes infrastructure"},{match:e=>v(e)[0]==="add",action:"claude.bash.deploy",why:"railway add creates a service"}],vercel:[{match:e=>["remove","rm"].includes(v(e)[0]??""),action:"claude.bash.deploy",why:"vercel removes a deployment"},{match:e=>v(e)[0]==="rollback",action:"claude.bash.deploy",why:"vercel rolls production back to an earlier deployment"},{match:e=>T(e,"--prod","--production")||v(e)[0]==="promote",action:"claude.bash.deploy",why:"vercel deploys to production"},{match:e=>v(e)[0]==="env"&&["add","rm","remove"].includes(v(e)[1]??"")||v(e)[0]==="alias"&&v(e)[1]==="set"||v(e)[0]==="domains"&&["add","rm","remove"].includes(v(e)[1]??""),action:"claude.bash.deploy",why:"vercel changes production settings"},{match:e=>P(e,"--target")!==null&&(v(e).length===0||v(e)[0]==="deploy"||/^[./~]/.test(v(e)[0])),action:"claude.bash.deploy",why:"vercel deploys to the environment --target names"}],wrangler:[{match:e=>["deploy","publish"].includes(v(e)[0]??"")&&!Dt(e,["--dry-run"])||v(e)[0]==="rollback"||re("pages","deploy")(e)||re("versions","deploy")(e)||v(e)[0]==="secret"&&["put","delete"].includes(v(e)[1]??""),action:"claude.bash.deploy",why:"wrangler deploys to Cloudflare"}],fly:[{match:e=>re("ssh","console")(e)&&/\b(printenv|env|set|export\s+-p|cat\s+\S*\.env)\b/.test(P(e,"-C","--command")??""),action:"claude.bash.secrets.print",why:"fly ssh console prints a live app's environment"},{match:e=>["deploy","scale","destroy"].includes(v(e)[0]??"")||["secrets","apps","machine","machines","volumes","postgres"].includes(v(e)[0]??"")&&["set","unset","destroy","delete","remove","stop","create"].includes(v(e)[1]??""),action:"claude.bash.deploy",why:"fly changes a live app"}],netlify:[{match:e=>v(e)[0]==="deploy"&&T(e,"--prod"),action:"claude.bash.deploy",why:"netlify deploys to production"}],firebase:[{match:e=>v(e)[0]==="deploy"||/^hosting:channel:deploy/.test(v(e)[0]??""),action:"claude.bash.deploy",why:"firebase deploys"},{match:e=>/^functions:delete/.test(v(e)[0]??""),action:"claude.bash.deploy",why:"firebase deletes live functions"},{match:e=>/^hosting:disable/.test(v(e)[0]??""),action:"claude.bash.deploy",why:"firebase takes the hosting site offline"},{match:e=>v(e)[0]==="appdistribution:distribute",action:"claude.bash.deploy",why:"firebase sends a build to testers"}],fastlane:[{match:kb,action:"claude.bash.deploy",why:"fastlane uploads or releases an app"}],eas:[{match:vb,action:"claude.bash.deploy",why:"eas sends an app or an over-the-air update to users"}],expo:[{match:e=>v(e)[0]==="publish",action:"claude.bash.deploy",why:"expo publish sends an over-the-air update to users"}],xcrun:[{match:e=>v(e)[0]==="altool"&&T(e,"--upload-app","--upload-package")||v(e)[0]==="iTMSTransporter"&&P(e,"-m")==="upload",action:"claude.bash.deploy",why:"uploads an app to App Store Connect"}],altool:[{match:e=>T(e,"--upload-app","--upload-package"),action:"claude.bash.deploy",why:"altool uploads an app to App Store Connect"}],appcenter:[{match:e=>v(e)[0]==="codepush"&&/^(release|release-react|release-cordova|release-electron|promote|patch|rollback)$/.test(v(e)[1]??"")&&oo(e)||re("distribute","release")(e),action:"claude.bash.deploy",why:"appcenter releases an app update to users"}],"code-push":[{match:e=>/^(release|release-react|release-cordova|release-electron|promote|patch|rollback)$/.test(v(e)[0]??"")&&oo(e),action:"claude.bash.deploy",why:"code-push releases an app update to users"}],"code-push-standalone":[{match:e=>/^(release|release-react|release-cordova|release-electron|promote|patch|rollback)$/.test(v(e)[0]??"")&&oo(e),action:"claude.bash.deploy",why:"code-push releases an app update to users"}],shorebird:[{match:e=>v(e)[0]==="patch"&&!/^(staging)$/i.test(P(e,"--track")??"")||re("patches","promote")(e),action:"claude.bash.deploy",why:"shorebird sends a patch to the app's users"}],capgo:[{match:e=>re("bundle","upload")(e)&&!bu.test(P(e,"--channel","-c")??""),action:"claude.bash.deploy",why:"capgo sends an over-the-air update to users"}],butler:[{match:e=>v(e)[0]==="push"&&Ae(e),action:"claude.bash.deploy",why:"butler pushes a build to itch.io"}],steamcmd:[{match:e=>e.some(t=>/^\+run_app_build(_http)?$|^\+set_?live/i.test(t)),action:"claude.bash.deploy",why:"steamcmd uploads a build to Steam"}],msstore:[{match:e=>v(e)[0]==="publish",action:"claude.bash.deploy",why:"msstore publishes to the Microsoft Store"}],"web-ext":[{match:e=>v(e)[0]==="sign"&&P(e,"--channel")==="listed",action:"claude.bash.deploy",why:"web-ext submits a listed add-on to addons.mozilla.org"}],"chrome-webstore-upload":[{match:e=>!["help"].includes(v(e)[0]??""),action:"claude.bash.deploy",why:"uploads an extension to the Chrome Web Store"}],gradlew:[{match:Dl,action:"claude.bash.deploy",why:"gradle publishes an app to Google Play"},{match:Fl,action:"claude.bash.publish",why:"gradle publishes artifacts to a package repository"}],gradle:[{match:Dl,action:"claude.bash.deploy",why:"gradle publishes an app to Google Play"},{match:Fl,action:"claude.bash.publish",why:"gradle publishes artifacts to a package repository"}],heroku:[{match:e=>/^apps:destroy$/.test(v(e)[0]??""),action:"claude.bash.deploy",why:"heroku deletes the app"},{match:e=>/^(config:set|config:unset|releases:rollback|ps:scale|ps:restart|ps:stop|maintenance:on|run)$/.test(v(e)[0]??""),action:"claude.bash.deploy",why:"heroku changes a live app"},{match:e=>/^pg:reset$/.test(v(e)[0]??""),action:"claude.bash.db.destructive",why:"heroku pg:reset wipes the database"}],kubectl:[{match:e=>v(e)[0]==="delete"&&!Dt(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"kubectl deletes from a cluster"},{match:e=>(["apply","create","delete","replace","patch","scale","set","edit","label","annotate","drain","cordon","uncordon","taint","expose","autoscale"].includes(v(e)[0]??"")||v(e)[0]==="run"&&!Rc(e)||v(e)[0]==="rollout"&&["restart","undo","pause","resume"].includes(v(e)[1]??""))&&!Dt(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"kubectl changes a cluster"}],helm:[{match:e=>["uninstall","delete"].includes(v(e)[0]??"")&&!Dt(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"helm removes a release from a cluster"},{match:e=>["install","upgrade","rollback"].includes(v(e)[0]??"")&&!Dt(e,["--dry-run"],["true","client","server"]),action:"claude.bash.deploy",why:"helm changes a cluster"}],terraform:[{match:e=>v(e)[0]==="import"||v(e)[0]==="state"&&["rm","mv","push","replace-provider"].includes(v(e)[1]??"")||["taint","untaint","force-unlock"].includes(v(e)[0]??""),action:"claude.bash.deploy",why:"terraform changes the shared state that every later apply works from"},{match:e=>v(e)[0]==="destroy"||v(e)[0]==="apply"&&T(e,"-destroy","--destroy"),action:"claude.bash.deploy",why:"terraform destroy deletes real infrastructure"},{match:e=>v(e)[0]==="apply",action:"claude.bash.deploy",why:"terraform changes real infrastructure"}],tofu:[{match:e=>v(e)[0]==="destroy"||v(e)[0]==="apply"&&T(e,"-destroy","--destroy"),action:"claude.bash.deploy",why:"tofu destroy deletes real infrastructure"},{match:e=>["apply","import","taint"].includes(v(e)[0]??""),action:"claude.bash.deploy",why:"tofu changes real infrastructure"}],pulumi:[{match:e=>v(e)[0]==="destroy",action:"claude.bash.deploy",why:"pulumi destroy deletes real infrastructure"},{match:e=>["up","update","cancel"].includes(v(e)[0]??""),action:"claude.bash.deploy",why:"pulumi changes real infrastructure"}],cdk:[{match:e=>v(e)[0]==="destroy",action:"claude.bash.deploy",why:"cdk destroy deletes real infrastructure"},{match:e=>v(e)[0]==="deploy",action:"claude.bash.deploy",why:"cdk changes real infrastructure"}],serverless:[{match:e=>v(e)[0]==="remove",action:"claude.bash.deploy",why:"serverless remove deletes the deployed service"},{match:e=>v(e)[0]==="deploy",action:"claude.bash.deploy",why:"serverless deploys"}],sls:[{match:e=>v(e)[0]==="remove",action:"claude.bash.deploy",why:"serverless remove deletes the deployed service"},{match:e=>v(e)[0]==="deploy",action:"claude.bash.deploy",why:"serverless deploys"}],modal:[{match:e=>v(e)[0]==="deploy"||["app","secret"].includes(v(e)[0]??"")&&["stop","create","delete"].includes(v(e)[1]??""),action:"claude.bash.deploy",why:"modal deploys or changes a live app"},{match:e=>["run","shell","launch"].includes(v(e)[0]??""),action:"claude.bash.spend",why:"modal starts a paid cloud run"},{match:e=>v(e)[0]==="volume"&&["rm","delete"].includes(v(e)[1]??""),action:"claude.bash.db.destructive",why:"modal deletes stored data"}],supabase:[{match:e=>re("db","push")(e)&&!T(e,"--local")&&!Ic(e)&&!Dt(e,["--dry-run"])||re("functions","deploy")(e)||re("secrets","set")(e)||re("functions","delete")(e),action:"claude.bash.deploy",why:"supabase changes a live project"},{match:e=>re("db","reset")(e)&&T(e,"--linked","--db-url"),action:"claude.bash.db.destructive",why:"supabase db reset wipes a linked database"}],prisma:[{match:e=>re("migrate","reset")(e)||re("db","push")(e)&&T(e,"--accept-data-loss","--force-reset"),action:"claude.bash.db.destructive",why:"prisma wipes or drops database data"},{match:e=>re("migrate","deploy")(e),action:"claude.bash.deploy",why:"prisma migrate deploy changes the target database"}],"drizzle-kit":[{match:e=>v(e)[0]==="push"||v(e)[0]==="drop",action:"claude.bash.db.destructive",why:"drizzle-kit push can drop columns and tables to match the schema"}],docker:[{match:e=>(v(e)[0]==="push"||v(e)[0]==="image"&&v(e)[1]==="push"||v(e)[0]==="buildx"&&T(e,"--push"))&&!Cm(e),action:"claude.bash.publish",why:"docker push publishes an image"},{match:e=>["stop","kill","rm","restart"].includes(v(e)[0]??"")&&e.some(t=>S(t)&&/docker\s+ps\b/.test(k(t))),action:"claude.bash.process.kill_by_name",why:"docker stops every container, other sessions' too"},{match:e=>re("system","prune")(e)&&T(e,"--volumes")||v(e)[0]==="volume"&&(v(e)[1]==="prune"||v(e)[1]==="rm"&&!pm(v(e).slice(2)))||re("compose","down")(e)&&T(e,"-v","--volumes"),action:"claude.bash.fs.delete_recursive",why:"docker deletes volumes, and the data in them"},{match:e=>re("system","prune")(e)&&e.some(t=>/^-\w*f/.test(t)||t==="--force"),action:"claude.bash.fs.delete_recursive",why:"docker system prune deletes stopped containers and unused images"}],cargo:[{match:e=>(v(e)[0]==="publish"||v(e)[0]==="yank")&&Ae(e),action:"claude.bash.publish",why:"cargo publishes a crate"}],podman:[{match:e=>v(e)[0]==="push"||v(e)[0]==="image"&&v(e)[1]==="push"||v(e)[0]==="manifest"&&v(e)[1]==="push",action:"claude.bash.publish",why:"podman push publishes an image"}],buildah:[{match:e=>v(e)[0]==="push",action:"claude.bash.publish",why:"buildah push publishes an image"}],nerdctl:[{match:e=>v(e)[0]==="push",action:"claude.bash.publish",why:"nerdctl push publishes an image"}],glab:[{match:e=>v(e)[0]==="mr"&&v(e)[1]==="merge",action:"claude.bash.git.push_main",why:"glab mr merge merges into the default branch (a deploy)"},{match:e=>v(e)[0]==="release"&&v(e)[1]==="create",action:"claude.bash.publish",why:"glab release create publishes a release"}],twilio:[{match:e=>/:(buy|purchase)(:|$)/.test(v(e)[0]??"")||/^api:core:incoming-phone-numbers:create$/.test(v(e)[0]??""),action:"claude.bash.spend",why:"twilio buys a phone number"},{match:e=>/^api:[\w-]+:(messages|calls|conversations|notifications|verify[\w-]*):create$|^api:[\w-]+:[\w-]+:(messages|calls):create$/.test(v(e)[0]??""),action:"claude.bash.external_write",why:"twilio sends a message or places a call"}],twine:[{match:e=>v(e)[0]==="upload",action:"claude.bash.publish",why:"twine uploads a package"}],gem:[{match:e=>["push","yank"].includes(v(e)[0]??""),action:"claude.bash.publish",why:"gem publishes a package"}],poetry:[{match:e=>v(e)[0]==="publish"&&Ae(e),action:"claude.bash.publish",why:"poetry publishes a package"}],vsce:[{match:e=>["publish","unpublish"].includes(v(e)[0]??""),action:"claude.bash.publish",why:"vsce publishes an extension"}],ovsx:[{match:e=>v(e)[0]==="publish",action:"claude.bash.publish",why:"ovsx publishes an extension"}],changeset:[{match:e=>v(e)[0]==="publish",action:"claude.bash.publish",why:"changeset publishes packages"}],lerna:[{match:e=>v(e)[0]==="publish",action:"claude.bash.publish",why:"lerna publishes packages"}],jsr:[{match:e=>v(e)[0]==="publish"&&Ae(e),action:"claude.bash.publish",why:"jsr publishes a package"}],sky:[{match:e=>["launch","exec","jobs"].includes(v(e)[0]??""),action:"claude.bash.spend",why:"sky starts paid cloud machines"}],gcloud:[{match:e=>/\b(instances|clusters|tpus)\b/.test(v(e).join(" "))&&v(e).includes("create"),action:"claude.bash.spend",why:"gcloud starts paid machines"},{match:e=>v(e).includes("deploy")||v(e).includes("delete")&&!v(e).includes("describe"),action:"claude.bash.deploy",why:"gcloud changes cloud resources"},{match:e=>v(e).some(t=>/^(add|remove|set)-iam-policy(-binding)?$/.test(t)),action:"claude.bash.deploy",why:"gcloud changes who can reach cloud resources"},{match:e=>v(e)[0]==="auth"&&/^print-(access|identity)-token$/.test(v(e)[1]??"")||v(e)[0]==="secrets"&&v(e)[1]==="versions"&&v(e)[2]==="access",action:"claude.bash.secrets.print",why:"gcloud prints a credential"}],az:[{match:e=>re("vm","create")(e),action:"claude.bash.spend",why:"az starts a paid machine"},{match:e=>v(e).some(t=>["delete","deploy","create","update","set"].includes(t))&&!re("account","set")(e),action:"claude.bash.deploy",why:"az changes cloud resources"},{match:e=>re("account","get-access-token")(e),action:"claude.bash.secrets.print",why:"az prints an access token"}],doctl:[{match:e=>v(e).includes("create")||v(e).includes("delete"),action:"claude.bash.deploy",why:"doctl changes cloud resources"}],stripe:[{match:e=>["post","delete"].includes(v(e)[0]??"")||v(e).some(t=>["create","update","delete","cancel","refund","capture","pay","void"].includes(t)),action:"claude.bash.external_write",why:"stripe changes live payment data"}],mail:[{match:()=>!0,action:"claude.bash.external_write",why:"sends an email"}],uv:[{match:e=>v(e)[0]==="publish"&&Ae(e),action:"claude.bash.publish",why:"uv publishes a package"}],mvn:[{match:e=>v(e).some(t=>t==="deploy"||t==="release:perform"||t==="deploy:deploy-file"),action:"claude.bash.publish",why:"mvn deploy uploads artifacts to a package repository"}],mvnw:[{match:e=>v(e).some(t=>t==="deploy"||t==="release:perform"),action:"claude.bash.publish",why:"mvn deploy uploads artifacts to a package repository"}],argocd:[{match:e=>v(e)[0]==="app"&&["sync","rollback","delete","set","patch","terminate-op"].includes(v(e)[1]??"")&&Ae(e),action:"claude.bash.deploy",why:"argocd changes what a cluster runs"}],"ansible-playbook":[{match:e=>!T(e,"--check","-C","--syntax-check","--list-hosts","--list-tasks","--list-tags")&&!/^(?:localhost|127\.0\.0\.1),?$/.test(P(e,"-i","--inventory")??""),action:"claude.bash.deploy",why:"ansible-playbook changes the machines in its inventory"}],pm2:[{match:e=>["restart","reload","stop","delete","kill"].includes(v(e)[0]??"")&&(v(e)[0]==="kill"||v(e)[1]==="all"),action:"claude.bash.process.kill_by_name",why:"pm2 stops or restarts every process it manages"}],sendmail:[{match:()=>!0,action:"claude.bash.external_write",why:"sends an email"}],mailx:[{match:()=>!0,action:"claude.bash.external_write",why:"sends an email"}],mutt:[{match:e=>T(e,"-s","-a","-c","-b","-H","-i")||v(e).some(t=>t.includes("@")),action:"claude.bash.external_write",why:"sends an email"}],msmtp:[{match:e=>!T(e,"--help","--version","--serverinfo","-S","-P","--pretend","--rmqs"),action:"claude.bash.external_write",why:"sends an email"}],swaks:[{match:e=>!T(e,"--help","-h","--version"),action:"claude.bash.external_write",why:"sends an email"}]});function Ic(e){let t=e.findIndex(r=>r==="--db-url"||r==="--database-url"),n=t>=0?e[t+1]:e.find(r=>r.startsWith("--db-url=")||r.startsWith("--database-url="))?.split("=").slice(1).join("=");if(!n||S(n))return!1;let s=de(n);return s!==null&&Re(s)}var lm=new Set(["--exclude","--include","--cache-control","--acl","--content-type","--content-encoding","--content-disposition","--content-language","--expires","--sse","--sse-kms-key-id","--sse-c","--sse-c-key","--storage-class","--metadata","--metadata-directive","--grants","--website-redirect","--profile","--region","--endpoint-url","--expected-size","--source-region","--request-payer","--output","--query","--page-size","--color","--ca-bundle","--cli-read-timeout","--cli-connect-timeout"]);function wo(e){let t=e.findIndex((n,s)=>s>0&&["cp","sync","mv"].includes(n)&&e[s-1]==="s3");return t<0?[]:pe(e,t+1,lm)}var cm=/^(run-instances|request-spot-instances|create-training-job|create-cluster|create-db-instance|create-endpoint|purchase-[\w-]+|create-capacity-reservation)$/,um=/^(delete-|terminate-|remove-|deregister-|revoke-|detach-|put-|update-|create-|deploy|attach-|modify-|stop-|reboot-|start-|replace-|disable-|enable-|change-|authorize-|associate-|disassociate-|set-|add-|apply-|import-|restore-|rotate-|schedule-|cancel-|purge-|batch-delete-|batch-write-|reset-|admin-|initiate-|promote-|failover-|reject-|accept-)/,dm=/^(s3|s3api|s3control|kms|dynamodb|rds|backup|secretsmanager|ssm|ecr|ecr-public|sqs|kinesis|firehose|glacier|efs|fsx|elasticache|memorydb|redshift|redshift-serverless|docdb|neptune|opensearch|es|timestream-write|keyspaces|qldb|lightsail|athena|glue|logs|cloudtrail|codecommit|cognito-idp)$/,fm=/^(get-secret-value|get-session-token|assume-role|get-federation-token|get-parameter|get-parameters)$/;function Hs(e){let t=e.argv,n=e.name,s=[],r=_m(e);if(r.length>0)return r;let o=ym(e);if(o.length>0)return o;if(n==="aws"){let[l="",c=""]=v(t),u=c.split("-").some(f=>["delete","deletion","purge","terminate","drop","destroy","wipe","truncate"].includes(f))||/^(disable-key|schedule-key-deletion|remove-objects?)$/.test(c);if(l==="s3"&&["rm","rb"].includes(c))s.push(m("claude.bash.db.destructive",`aws s3 ${c} deletes stored data`,{target:v(t)[2]??null,is_local:!1}));else if(dm.test(l)&&u&&Ae(t))s.push(m("claude.bash.db.destructive",`aws ${l} ${c} deletes stored data`,{target:`${l} ${c}`,is_local:!1}));else if(l==="configure"&&c==="export-credentials")s.push(...ae(e)?[m("claude.bash.secrets.print","aws configure export-credentials prints AWS credentials",{target:"configure export-credentials",is_local:!0})]:[]);else if(/^authorize-security-group-ingress$|^modify-security-group-rules$/.test(c)&&t.some(f=>/(^|[=\s"'])(0\.0\.0\.0\/0|::\/0)\b/.test(f)))s.push(m("claude.bash.net.expose",`aws ${l} ${c} opens a port to the whole internet`,{target:`${l} ${c}`,is_local:!1}));else if(l==="s3"&&["cp","sync","mv"].includes(c)&&(wo(t).slice(-1)[0]??"").startsWith("s3://")&&wo(t).length>=2)s.push(m("claude.bash.deploy",`aws s3 ${c} writes to a bucket`,{target:v(t).slice(-1)[0]??null,is_local:!1}));else if(l==="configure"&&c==="get"&&/secret|key/i.test(v(t)[2]??""))s.push(...ae(e)?[m("claude.bash.secrets.print","prints an AWS credential",{target:v(t)[2]??null,is_local:!0})]:[]);else if(fm.test(c)&&(c!=="get-parameter"&&c!=="get-parameters"||T(t,"--with-decryption")))s.push(...ae(e)?[m("claude.bash.secrets.print",`aws ${l} ${c} prints a secret`,{target:`${l} ${c}`,is_local:!0})]:[]);else if(l==="athena"&&c==="start-query-execution"){let f=ke(P(t,"--query-string")??""),p=be.exec(f)??Hn.exec(f);p&&s.push(m("claude.bash.db.destructive",`aws athena runs destructive SQL (${p[1].replace(/\s+/g," ").toUpperCase()})`,{target:"athena",host:"athena",is_local:!1}))}else if(["redshift-data","rds-data"].includes(l)&&/execute-statement$/.test(c)){let f=ke([P(t,"--sql")??"",...t.filter((p,d)=>t[d-1]==="--sqls")].join(`
|
|
42
|
+
`));be.test(f)&&s.push(m("claude.bash.db.destructive",`aws ${l} runs destructive SQL (${(be.exec(f)?.[1]??"").replace(/\s+/g," ").toUpperCase()})`,{target:`${l} ${c}`,host:l,is_local:!1}))}else cm.test(c)?s.push(m("claude.bash.spend",`aws ${l} ${c} starts paid resources`,{target:`${l} ${c}`,is_local:!1})):["ses","sesv2","sns","sqs"].includes(l)&&/^(send|publish)/.test(c)?s.push(m("claude.bash.external_write",`aws ${l} ${c} sends a message`,{target:`${l} ${c}`,is_local:!1})):um.test(c)&&Ae(t)&&s.push(m("claude.bash.deploy",`aws ${l} ${c} changes cloud resources`,{target:`${l} ${c}`,is_local:!1}));return s}if(["npm","pnpm","yarn","bun"].includes(n))return qc(e);if(["nx","turbo","mise","lerna","run-s","run-p","npm-run-all"].includes(n))return Am(e);if(["make","just","task","mise"].includes(n)){let l=v(t).find(c=>!c.includes("="));return l&&/^(deploy|release|publish|ship)([-:_].*)?$/.test(l)&&!Mc.test(l)&&Ae(t)&&!T(t,"-n","--just-print","--recon")?[m("claude.bash.deploy",`${n} ${l} runs a deploy or release target`,{target:l,is_local:!1})]:[]}let a=Sm(e);if(a.length>0)return a;let i=xm(e);if(i.length>0)return i;if(n==="python"||n==="python3"){let l=t.indexOf("-m");if(l>0&&t[l+1]==="twine"&&t[l+2]==="upload")return[m("claude.bash.publish","twine uploads a package",{is_local:!1})];if(t.includes("manage.py")&&["flush","reset_db","sqlflush"].some(u=>t.includes(u)))return[m("claude.bash.db.destructive","manage.py wipes the database",{is_local:null})];let c=t.indexOf("migrate");if(t.includes("manage.py")&&c>0){let u=t.slice(c+1).filter(f=>!f.startsWith("-"));if(u[1]==="zero")return[m("claude.bash.db.destructive","manage.py migrate APP zero drops the app's tables",{target:u[0]??null,is_local:null})]}return[]}if(n==="alembic"&&v(t).includes("downgrade")&&!T(t,"--sql")||n==="flask"&&re("db","downgrade")(t)&&!T(t,"--sql"))return[m("claude.bash.db.destructive",`${n} downgrades the database schema (drops what the migrations made)`,{target:v(t).slice(-1)[0]??null,is_local:null})];if(n==="rails"||n==="rake"||n==="bin/rails"){let l=(/(?:^|\s)(?:RAILS_ENV|RACK_ENV)=["']?(\w+)/.exec(e.text)?.[1]??P(t,"-e","--environment")??"").toLowerCase();return/^(test|development|dev)$/.test(l)?[]:t.some(c=>/^db:(drop|reset|schema:load|migrate:reset|purge|truncate_all)$/.test(c))?[m("claude.bash.db.destructive","rails wipes or rebuilds the database",{is_local:null})]:/^prod(uction)?$/.test(l)&&t.some(c=>/^db:(migrate|rollback|seed|setup)(:|$)/.test(c))?[m("claude.bash.deploy","rails changes the production database",{target:t.find(c=>c.startsWith("db:"))??null,is_local:!1})]:[]}for(let l of Tc[n==="flyctl"?"fly":n]??[])if(l.match(t)){if(l.action==="claude.bash.secrets.print"&&!ae(e))continue;s.push(m(l.action,l.why,{target:v(t).slice(0,3).join(" ")||n,is_local:!1,host:n}));break}return n==="railway"&&["variables","variable","vars"].includes(v(t)[0]??"")&&s.length===0&&ae(e)&&s.push(m("claude.bash.secrets.print","railway variables prints live production secrets",{target:"railway variables",is_local:!0,host:"railway"})),n==="heroku"&&/^config(:get)?$/.test(v(t)[0]??"")&&s.length===0&&ae(e)&&s.push(m("claude.bash.secrets.print","heroku config prints live secrets",{target:"heroku config",is_local:!0,host:"heroku"})),s.length===0&&s.push(...mm(e),...gm(e)),s.length===0&&s.push(...vm(e),...$m(e)),s}function pm(e){return e.length>0&&e.every(t=>k(t).replace(/[${}"']/g,"").toLowerCase().split(/[-_.:]+/).some(n=>/^(cache|caches|test|tests|testing|tmp|temp|ci|fixture|fixtures|scratch)$/.test(n)))}var Dc=/^(delete|deletion|destroy|drop|purge|wipe|nuke|truncate|erase|rm|rb|remove|terminate|flush|flushall|flushdb|reset)$/i,hm=e=>e.split(/[-:_.]/).some(t=>Dc.test(t)),bl=/^(buckets?|blobs?|objects?|storage|tables?|datasets?|databases?|dbs?|collections?|documents?|docs|indexe?s|indices|topics?|queues?|streams?|keys?|kms|keyrings?|secrets?|backups?|snapshots?|volumes?|disks?|branch(es)?|firestore|datastore|bigtable|spanner|redis|memcache|memorystore|filestore|keyspaces?|schemas?|kv|keyvalue|file-?systems?|repositor(y|ies)|images?|vaults?|caches?|data|records?|rows?|partitions?|shards?|replicas?|buckets?|containers?)$/i,rr=new Set(["gsutil","bq","pscale","turso","neonctl","neon","upstash","xata","atlas","mongocli","snowsql","kafka-topics","kafka-topics.sh","kafka-configs","cqlsh","clickhouse-client","influx","cockroach","surreal","supabase","firebase","fauna","convex","rclone","restic","b2","mc","s3cmd","azcopy","cbq","couchbase-cli","arangosh","typesense","meilisearch","algolia","pinecone","weaviate","qdrant","chroma","elasticdump","curator","litestream","turso-cli","d1","pgbackrest","barman","wal-g"]),yn=new Set(["gcloud","az","doctl","linode-cli","hcloud","oci","ibmcloud","scw","vultr-cli","exo","aliyun","tccli","cf","render","koyeb","northflank","porter","qovery","okteto","nomad","consul","vault","eksctl","kops","flux","databricks","confluent","ccloud","heroku","fly","flyctl","railway","vercel","netlify","wrangler","glab","dokku","caprover","kamal","coolify","sst","amplify","copilot","crane","oras"]),Fc=new Set(["config","configure","auth","login","logout","components","alias","aliases","profile","profiles","context","contexts","completion","init","cache","plugin","plugins","extension","extensions","help","version"]);function gm(e){let t=e.name,n=rr.has(t);if(!n&&!yn.has(t))return[];let s=e.argv;if(!Ae(s)||T(s,"--what-if","--validate-only","--check","--simulate","--no-execute"))return[];let r=v(s).slice(0,6);if(r.length>0&&Fc.has(r[0]))return[];if(t==="rclone"&&pe(s.map(h=>k(h)),1,fc).slice(1).every(h=>!Te(h)))return[];let o=r.findIndex(hm),a=s.find(h=>/^--?(delete|drop|purge|wipe|truncate|destroy|flush|remove)(=|$)/.test(h));if(o<0&&!a)return[];if(o>0&&r.slice(0,o).some(h=>/^(list|ls|describe|get|show|info|logs?|cat|view|inspect|read|search|query)$/i.test(h)))return[];let i=r.slice(0,6),l=n||i.some(h=>bl.test(h)||h.split(/[-:_.]/).some(g=>bl.test(g))),c=o>=0?r[o]:a.split("=")[0],u=`${t} ${o>=0?r.slice(0,o+1).join(" "):c}`.trim(),f=o>=0?r.slice(o+1).find(h=>!h.includes("="))??null:r[0]??null,p=o>=0&&r[o].split(/[-:_.]/).every(h=>!Dc.test(h)||/^reset$/i.test(h));return!l&&o>=0&&r.slice(0,o+1).some(h=>h.split(/[-:_.]/).some(g=>/^(options?|configs?|settings?|labels?|tags?|annotations?|env|vars?|variables?|aliases?|metadata)$/i.test(g)))?[m("claude.bash.deploy",`${u} changes a live service's settings`,{target:f,is_local:!1,host:t})]:[l?m("claude.bash.db.destructive",`${u} ${p?"resets":"deletes"} stored data`,{target:f,is_local:!1,host:t}):m("claude.bash.deploy",`${u} ${p?"resets a cloud resource":"deletes cloud resources"}`,{target:f,is_local:!1,host:t})]}function mm(e){let t=e.argv,n=s=>!!s&&!S(s)&&Ut(s.replace(/:\d+$/,""));if(e.name==="pg_restore"){if(T(t,"-l","--list","-f","--file"))return[];let s=t.some(l=>l==="--clean"||/^-[A-Za-z]+$/.test(l)&&l.includes("c")),r=P(t,"-d","--dbname");if(r===null)return[];let o=P(t,"-h","--host")??(/^postgres(ql)?:\/\//i.test(r)?de(r):null),a=Xc(e,"");if(a===null&&(n(o)||o===null&&!S(r)&&!/^postgres(ql)?:\/\//i.test(r)))return[];let i=a??(o!==null&&!S(o)?fn(o):null);return[m("claude.bash.db.destructive",s?`pg_restore --clean drops the database's objects before it restores${i?` (${i})`:""}`:`pg_restore writes a dump into ${i??"a database the command does not name"}`,{target:i??k(r),is_local:!1,catastrophic:s&&i!==null})]}if(e.name==="mongorestore"||e.name==="mongoimport"){if(!T(t,"--drop"))return[];let s=P(t,"--uri","--host","-h"),r=s?/^mongodb(\+srv)?:\/\//.test(s)?de(s):s:"localhost";return n(r)?[]:[m("claude.bash.db.destructive",`${e.name} --drop drops ${e.name==="mongoimport"?"the collection before it imports":"each collection before it restores"}`,{target:S(r??"")?"a database the command does not name":r,is_local:!1})]}return[]}function ym(e){if(!yn.has(e.name)&&!rr.has(e.name)&&!["aws","kubectl"].includes(e.name))return[];let t=e.argv,n=v(t);if(!Ae(t)||n.some(o=>/^(list|ls|describe|get|show|view|what-if)$/.test(o)))return[];let s=`${e.name} ${n.slice(0,3).join(" ")}`.trim();if(t.some(o=>/(^|[=:,\s"'])all(Authenticated)?Users\b/.test(o))&&!n.some(o=>/^remove-/.test(o))&&!(e.name==="gsutil"&&T(t,"-d")))return[m("claude.bash.net.expose",`${s} makes a cloud resource readable by anyone on the internet`,{target:n.slice(0,4).join(" ")||e.name,host:e.name,is_local:!1})];let r=P(t,"--public-access","--allow-blob-public-access");return r!==null&&/^(blob|container|true)$/i.test(r)?[m("claude.bash.net.expose",`${s} opens a storage container to anonymous reads`,{target:n.slice(0,4).join(" ")||e.name,host:e.name,is_local:!1})]:e.name!=="aws"&&n.some(o=>/^(create|update|add|authorize|allow|set)/.test(o))&&t.some(o=>/(^|[=\s"',])(0\.0\.0\.0\/0|::\/0)\b/.test(o))?[m("claude.bash.net.expose",`${s} admits the whole internet (0.0.0.0/0)`,{target:n.slice(0,4).join(" ")||e.name,host:e.name,is_local:!1})]:[]}var bm=/^(?:default|colima(?:-[\w-]+)?|orbstack|desktop-linux|docker-desktop|rancher-desktop|podman[\w-]*|minikube|lima[\w-]*|(?:unix|npipe):\/\/.*|(?:tcp:\/\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?)$/;function wm(e,t){let n=e.argv,s=v(n),r=R.basename(e.name)==="docker-compose"?s:s[0]==="compose"?s.slice(1):null;if(!(r?r.some(c=>/^(up|deploy|start|restart|run|create)$/.test(c)):/^(run|start|restart|create)$/.test(s[0]??"")||s[0]==="service"&&/^(create|update|scale|rollback)$/.test(s[1]??"")))return[];let a=n.indexOf(s[0]??"\0"),l=[...n.slice(0,a<0?n.length:a).flatMap((c,u,f)=>/^(-H|--host|--context|-c)$/.test(f[u-1]??"")?[c]:/^--(host|context)=/.test(c)?[c.slice(c.indexOf("=")+1)]:[]),...[...t.matchAll(/\bDOCKER_(?:HOST|CONTEXT)=["']?([^\s"';&|)]+)/g)].map(c=>c[1])].find(c=>!bm.test(c));return l?[m("claude.bash.deploy",`${R.basename(e.name)} ${s.slice(0,2).join(" ")} runs on another machine's docker (${l})`,{target:l,is_local:!1,host:"docker"})]:[]}var km=/^(deploy|deploys|deployment|deployments|promote|promotion|release|releases|rollout|rollback)$/i;function vm(e){let t=e.argv,n=v(t).slice(0,6);if(e.name==="docker"||e.name==="podman"){if(n[0]==="stack"&&n[1]==="deploy")return[m("claude.bash.deploy",`${e.name} stack deploy rolls out a swarm stack`,{target:n[2]??null,is_local:!1})];if(n[0]==="compose"&&(n.includes("up")||n.includes("deploy"))){let i=[P(t,"-f","--file")??"",P(t,"-p","--project-name")??"",Kn(e)];if(i.some(l=>Yn.test(R.basename(l).toLowerCase().replace(/\.(ya?ml)$/,""))||/(^|[._-])prod(uction)?([._-]|$)/i.test(R.basename(l))))return[m("claude.bash.deploy",`${e.name} compose starts the production stack (${R.basename(i.find(l=>l)??"")})`,{target:i.find(l=>l)??null,is_local:!1})]}return[]}if(!yn.has(e.name)&&!rr.has(e.name))return[];if(!Ae(t)||T(t,"--what-if","--validate-only","--check","--simulate","--preview"))return[];if(n.length>0&&Fc.has(n[0]))return[];let s=n.findIndex(i=>/^(run|exec|ssh|shell|console|connect|--)$/.test(i)),r=(s<0?n:n.slice(0,s)).filter(i=>!/[/.]/.test(i)||/^[\w-]+:[\w:-]+$/.test(i)),o=r.findIndex(i=>i.split(/[-:_.]/).some(l=>km.test(l)));if(o<0)return[];if(r.slice(0,o+1).some(i=>i.split(/[-:_.]/).some(l=>/^(tokens?|keys?|credentials?)$/i.test(l))))return[];if(n.some(i=>/^(list|ls|describe|get|show|info|logs?|status|history|view|inspect|what-if|validate|diff|plan|wait|cancel|close)$/i.test(i)))return[];if(/^(deploy|release)-(branch|key|keys|hook|hooks|setting|settings|config|target|env)$/i.test(r[o])&&r.slice(0,o).some(i=>/(^|:)(set|unset|config|configure)$/.test(i)))return[m("claude.bash.deploy",`${e.name} ${r.slice(0,o+1).join(" ")} changes a deploy setting`,{target:r.slice(o+1).find(i=>!i.includes("="))??null,host:e.name,is_local:!1})];let a=/(deploys|deployments?|deploy-requests?|releases)$/i.test(r[o])&&r[o+1]!==void 0?o+2:o+1;return[m("claude.bash.deploy",`${e.name} ${r.slice(0,a).join(" ")} starts a deploy`,{target:r.slice(a).find(i=>!i.includes("="))??null,host:e.name,is_local:!1})]}function $m(e){let t=e.argv;return["np","release-it","semantic-release"].includes(e.name)?!Ae(t)||T(t,"--preview","--dry-run","-d","--no-ci","--help","-h")||v(t)[0]==="init"?[]:[m("claude.bash.publish",`${e.name} publishes a release`,{target:v(t)[0]??null,is_local:!1})]:[]}function xm(e){let t=e.argv;return(e.name==="python"||e.name==="python3")&&t.includes("manage.py")&&t.includes("dumpdata")&&Yn.test(Kn(e))?[m("claude.bash.data.export","manage.py dumpdata copies the production database onto this machine",{target:"dumpdata",is_local:!1})]:e.name==="firebase"&&v(t)[0]==="auth:export"?[m("claude.bash.data.export","firebase auth:export copies every user account onto this machine",{target:v(t)[1]??null,host:"firebase",is_local:!1})]:e.name==="prisma"&&v(t)[0]==="db"&&v(t)[1]==="execute"&&(Yn.test(Kn(e))||/(?:^|\s)[A-Z_]*DATABASE_URL=["']?\$\{?[A-Z_]*PROD/i.test(e.text)||/prod/i.test(P(t,"--url")??""))?[m("claude.bash.deploy","prisma db execute runs SQL against the production database",{target:P(t,"--file")??null,is_local:!1})]:[]}function _m(e){let t=e.argv,n=v(t),s=(()=>{switch(e.name){case"gpg":case"gpg2":return t.some(o=>/^--export-secret-(sub)?keys$/.test(o))?"gpg prints a private key":null;case"security":return n[0]==="dump-keychain"?t.some(o=>/^-[a-z]*d/.test(o))?"security dumps the keychain with its secrets":null:/^find-(generic|internet)-password$/.test(n[0]??"")&&t.some(o=>/^-[a-z]*[wg]/.test(o))?"security prints a saved password":null;case"kubectl":case"oc":return n[0]==="config"&&n[1]==="view"&&T(t,"--raw","--flatten")?`${e.name} config view --raw prints the cluster credentials`:null;case"heroku":return n[0]==="auth:token"?"heroku auth:token prints an API token":null;case"stripe":return n[0]==="config"&&T(t,"--list")?"stripe config --list prints the API keys":null;case"az":return n[0]==="ad"&&n[1]==="sp"&&n[2]==="create-for-rbac"?"az ad sp create-for-rbac creates a service principal and prints its password":n[0]==="account"&&n[1]==="get-access-token"?"az account get-access-token prints a token":null;case"aws":return n[0]==="ecr"&&n[1]==="get-login-password"?"aws ecr get-login-password prints a registry password":n[0]==="iam"&&n[1]==="create-access-key"?"aws iam create-access-key creates a key and prints its secret":n[0]==="sts"&&/^(get-session-token|assume-role)$/.test(n[1]??"")?`aws sts ${n[1]} prints temporary credentials`:null;case"claude":return n[0]==="setup-token"?"claude setup-token prints a long-lived Claude token":null;case"glab":return n[0]==="auth"&&n[1]==="status"&&T(t,"-t","--show-token")?"glab auth status --show-token prints the GitLab token":null;case"firebase":return n[0]==="login:ci"?"firebase login:ci prints a CI token":null;case"neonctl":case"neon":return/^(connection-string|cs)$/.test(n[0]??"")?`${e.name} ${n[0]} prints a connection string with its password`:null;case"php":case"artisan":{let o=e.name==="artisan"?0:t.slice(1).findIndex(l=>/(^|\/)artisan$/.test(l))+1;if(e.name==="php"&&o<=0)return null;let[a="",i=""]=t.slice(o+1).filter(l=>!l.startsWith("-"));return a==="config:show"&&/^(app|database|mail|services|cache|queue|broadcasting|filesystems|session|logging)(\.|$)/.test(i)?`artisan config:show ${i} prints settings with their secrets`:null}default:return n.includes("diffsettings")&&(t.some(o=>/(^|\/)manage\.py$/.test(o))||R.basename(e.name)==="django-admin")?"manage.py diffsettings prints SECRET_KEY and the database password":n[0]==="auth"&&/^(token|print-token|show-token)$/.test(n[1]??"")?`${e.name} auth ${n[1]} prints a token`:n.slice(0,4).some(o=>/^print-(access|identity|id)-token$/.test(o))?`${e.name} prints an access token`:n[0]==="token"&&/^(create|new|generate)$/.test(n[1]??"")?`${e.name} token ${n[1]} makes a token and prints it`:null}})(),r=e.pipeTo;return r&&zc(r)?[]:s!==null&&ae(e)?[m("claude.bash.secrets.print",s,{target:n.slice(0,3).join(" ")||e.name,is_local:!0,host:e.name})]:[]}function zc(e){let t=v(e.argv);return["pbcopy","xclip","xsel","wl-copy","clip.exe","clip"].includes(e.name)?!0:["xargs","echo","printf","cat","tee"].includes(R.basename(e.name))||e.argv.some(s=>/^(-o|--output)(=|$)|^--dry-run(=|$)/.test(s))?!1:e.argv.includes("--password-stdin")&&t.includes("login")||["kubectl","oc"].includes(e.name)&&e.argv.some(s=>s==="--from-file=/dev/stdin")||(e.name==="gpg"||e.name==="gpg2")&&T(e.argv,"--import")?!0:["gh","glab"].includes(e.name)?(t[0]==="secret"||t[0]==="variable")&&t[1]==="set":e.name==="wrangler"?t[0]==="secret"&&(t[1]==="put"||t[1]==="bulk"):e.name==="fly"||e.name==="flyctl"?t[0]==="secrets"&&(t[1]==="set"||t[1]==="import"):e.name==="vercel"?t[0]==="env"&&t[1]==="add":!1}function Kn(e){return(/(?:^|\s)(?:NODE_ENV|APP_ENV|RAILS_ENV|RACK_ENV|MIX_ENV|FLASK_ENV|DJANGO_ENV|ENVIRONMENT|STAGE)=["']?([\w.-]+)/.exec(e.text)?.[1]??P(e.argv,"--env","--environment","--settings")??"").toLowerCase()}var Yn=/(^|[._-])(prod|production|live)($|[._-])/;function Sm(e){let t=e.argv,n=v(t),s=Yn.test(Kn(e)),r=a=>[m("claude.bash.db.destructive",a,{target:n.join(" ")||e.name,is_local:!1})],o=a=>s?r(`${a} in production`):[m("claude.bash.db.destructive",`${a}, with no server shown`,{target:n.join(" ")||e.name,is_local:null})];switch(e.name){case"sequelize":case"sequelize-cli":return n[0]==="db:drop"?o("sequelize db:drop drops the database"):s&&/^db:(drop|migrate:undo(:all)?|seed:undo(:all)?)$/.test(n[0]??"")?r(`sequelize ${n[0]} drops data in production`):[];case"knex":return s&&/^migrate:(rollback|down)$/.test(n[0]??"")?r(`knex ${n[0]} runs migrations backwards in production`):[];case"typeorm":case"typeorm-ts-node-commonjs":case"typeorm-ts-node-esm":return n[0]==="schema:drop"?o("typeorm schema:drop drops every table"):n[0]==="schema:sync"?o("typeorm schema:sync drops what the entities no longer name"):s&&/^(schema:drop|migration:revert)$/.test(n[0]??"")?r(`typeorm ${n[0]} drops data in production`):[];case"mix":return/^ecto\.(drop|reset)$/.test(n[0]??"")?o(`mix ${n[0]} drops the database`):s&&/^ecto\.(drop|reset|rollback)$/.test(n[0]??"")?r(`mix ${n[0]} drops data in production`):[];case"flyway":return n.includes("clean")?r("flyway clean drops every object in the schema"):[];case"liquibase":return n.some(a=>/^drop-?all$/i.test(a))?r("liquibase dropAll drops every object in the database"):[];case"php":case"artisan":{let a=e.name==="artisan"?0:t.slice(1).findIndex(l=>/(^|\/)artisan$/.test(l))+1;if(a<0||e.name==="php"&&a===0)return[];let i=t.slice(a+1).find(l=>!l.startsWith("-"))??"";return i==="db:seed"?s||T(t,"--force")?r(`artisan db:seed writes seed data into the database${s?" in production":" (--force: even in production)"}`):[]:/^(db:wipe|migrate:(fresh|reset|refresh|rollback))$/.test(i)?s||T(t,"--force")?r(`artisan ${i} drops the database's tables${s?" in production":" (--force: even in production)"}`):i==="migrate:rollback"?[]:o(`artisan ${i} drops every table`):[]}default:return[]}}function Cm(e){let t=v(e).filter(n=>n.includes("/")||n.includes(":")).filter(n=>!["push","image","buildx","build"].includes(n));return t.length>0&&t.every(n=>/^(localhost|127\.0\.0\.1|\[::1\]|host\.docker\.internal)(:\d+)?\//.test(n))}var Mc=/^(deploy|release|publish|ship)[-:_](notes|changelog|log|check|verify|lint|dry(-?run)?|plan|diff|status|info|list|test|smoke)$|^build[-:_]release$/;function Uc(e){let t=new Set(["--filter","-F","--workspace","-w","--cwd","-C","--dir","--prefix","--scope","--filter-prod"]),n=[];for(let s=1;s<e.length;s++){let r=e[s];if(t.has(r)&&!(r==="-w"&&e[0]!=="npm")){s++;continue}if(r==="--")break;r.startsWith("-")||n.push(r)}return n[0]==="workspace"&&n.length>=3?[n[2],...n.slice(3)]:n[0]==="workspaces"&&n[1]==="foreach"?n.slice(2):n}function qc(e){let t=Uc(e.argv),n=t[0]??"",s=P(e.argv,"--registry");if(["publish","unpublish","deprecate"].includes(n)&&s!==null&&Re(k(s)))return[];if(["publish","unpublish","deprecate"].includes(n)&&Ae(e.argv))return[m("claude.bash.publish",`${e.name} ${n} changes a published package`,{target:t[1]??null,is_local:!1})];if(n==="dist-tag"&&["add","rm"].includes(t[1]??""))return[m("claude.bash.publish",`${e.name} dist-tag moves a published tag`,{target:t.slice(2).join(" "),is_local:!1})];if(n==="owner"&&["add","rm"].includes(t[1]??""))return[m("claude.bash.external_write",`${e.name} owner changes who can publish`,{is_local:!1})];if(R.basename(e.name)==="pnpm"&&n==="deploy")return[];let r=n==="run"||n==="run-script"?t[1]:e.name!=="npm"&&!qo.has(n)?n:void 0;return r?Hc(r,e.argv):[]}function Hc(e,t){let n=!/^(check|verify|test|lint|validate|dry|preview|plan|diff|smoke|generate|prepare)([-:_]|$)/.test(e),s=Mc.test(e),r=t.indexOf("--"),o=r>=0&&!Ae(t.slice(r+1));return s||o?[]:/^(deploy|release|publish|ship)([-:_].*)?$/.test(e)||n&&/[-:_](deploy|release|publish)$/.test(e)?[m(/publish/.test(e)?"claude.bash.publish":"claude.bash.deploy",`the ${e} script deploys or releases`,{target:e,is_local:!1})]:n&&/^(promote|rollout|rollback)([-:_].*)?$|[-:_](promote|rollout|rollback)$/.test(e)?[m("claude.bash.deploy",`the ${e} script changes what is live`,{target:e,is_local:!1})]:/^db[-:_]?(push|reset|drop|wipe|nuke|truncate)\b|^(migrate|migration)[-:_]?(reset|fresh|drop)\b|[-:_](reset|drop|wipe)[-:_]?db$/.test(e)||/(^|[-:_])(db|database|schema|prisma|drizzle|clickhouse|postgres|mysql|mongo)[-:_](reset|drop|wipe|nuke|truncate|rollback|fresh)\b/.test(e)||/(^|[-:_])(migrate|migration|migrations)[-:_](deploy|prod|production|rollback|down|undo)\b/.test(e)?[m("claude.bash.db.destructive",`the ${e} script can drop, reset or change database data`,{target:e,is_local:null})]:[]}function Am(e){let t=R.basename(e.name),n=e.argv.slice(1).map(a=>k(a)),s=n.filter(a=>!a.startsWith("-")),r=(...a)=>n.flatMap((i,l)=>a.includes(i)?[n[l+1]??""]:a.some(c=>i.startsWith(`${c}=`))?[i.slice(i.indexOf("=")+1)]:[]).flatMap(i=>i.split(",")),o=[];if(t==="nx"){if(s[0]==="release"&&!n.includes("--dry-run")&&!n.includes("-d"))return[m("claude.bash.publish","nx release versions and publishes packages",{target:"nx release",is_local:!1})];o=s[0]==="run"?[(s[1]??"").split(":")[1]??""]:["run-many","affected"].includes(s[0]??"")?r("-t","--target","--targets"):s[0]?[s[0].includes(":")?s[0].split(":")[1]:s[0]]:[]}else if(t==="turbo"||t==="mise")o=s[0]==="run"?s.slice(1):t==="turbo"?s:[];else if(t==="lerna"){if(s[0]==="publish"&&!n.includes("--dry-run"))return[m("claude.bash.publish","lerna publish publishes packages",{target:"lerna publish",is_local:!1})];o=s[0]==="run"?s.slice(1,2):[]}else["run-s","run-p","npm-run-all"].includes(t)&&(o=s);for(let a of o.filter(Boolean)){let i=Hc(a,e.argv);if(i.length>0)return i.map(l=>({...l,why:`${l.why} (through ${t})`}))}return[]}var Em=new Set(["anvil","anvil-claude","hardhat","truffle","ape","forge","cast","anchor","prisma","drizzle-kit","supabase","wrangler","eas","expo","firebase","netlify","vercel","serverless","sls","cdk","dbt","ngrok","lt","untun","cloudflared","claude","codex","gemini","smithery","capgo","shorebird","web-ext","chrome-webstore-upload","changeset","lerna","vsce","ovsx","code-push","appcenter"]),qo=new Set(["install","i","add","remove","rm","uninstall","update","up","upgrade","test","t","build","exec","dlx","x","create","init","link","unlink","list","ls","why","outdated","audit","config","cache","info","view","pack","run","start","dev","lint","format","typecheck","version","help","login","logout","whoami","ci","prune","dedupe","store","setup","workspaces","workspace"]),be=/\b(drop\s+(table|database|schema|keyspace|view|materialized\s+view|index|user|role|column|type|function|trigger|sequence|extension|owned|policy)\b|truncate\b|delete\s+from\b|alter\s+table\s+\S+\s+(drop|delete)\b|update\s+\S+\s+set\b(?![\s\S]*\bwhere\b))/i,Rm=/\.(dropDatabase|drop|deleteMany|remove)\s*\(/;function wl(e,t){let n=e.slice(t).search(/[\n\r]/);return n<0?e.length:t+n}function ke(e,t="postgres"){if(/\b(execute|exec|sp_executesql|do)\b/i.test(e))return e;let n=t!=="postgres",s=t==="mysql"||t==="bigquery",r="";for(let o=0;o<e.length;o++){let a=e[o],i=e[o+1];if(a==="-"&&i==="-"&&(t!=="mysql"||o+2>=e.length||/\s/.test(e[o+2])))o=wl(e,o)-1;else if(a==="#"&&(t==="mysql"||t==="bigquery")||a==="/"&&i==="/"&&t==="snowflake")o=wl(e,o)-1;else if(a==="/"&&i==="*"){let l=e.indexOf("*/",o+2);t==="mysql"&&e[o+2]==="!"?r+=` ${e.slice(o+3,l<0?e.length:l)} `:r+=" ",o=l<0?e.length:l+1}else if(a==='"'&&!s||a==="`"&&(t==="mysql"||t==="bigquery")){let l=o+1;for(;l<e.length;l++)if(e[l]===a&&e[l+1]===a)l++;else if(e[l]===a)break;if(l>=e.length)return e;r+=a+a,o=l}else if(a==="$"&&(t==="postgres"||t==="snowflake")&&!/[\w$]/.test(e[o-1]??"")&&/^\$([A-Za-z_]\w*)?\$/.test(e.slice(o,o+64))){let l=/^\$([A-Za-z_]\w*)?\$/.exec(e.slice(o,o+64))[0],c=e.indexOf(l,o+l.length);if(c<0)return e;r+="''",o=c+l.length-1}else if(a==="'"||a==='"'&&s){let l=n||a==="'"&&/(^|[^\w])[eE]$/.test(r),c=o+1;for(;c<e.length;c++)if(l&&e[c]==="\\")c++;else if(e[c]===a&&e[c+1]===a)c++;else if(e[c]===a)break;if(c>=e.length)return e;r+=a+a,o=c}else r+=a}return r}function yt(e){if(/(?<![\w-])ssh(?![\w-])[^\n;&|]{0,200}\s-[A-Za-z]*L\s*\S/.exec(e))return"ssh -L";let n=/\b(DOCKER_(?:HOST|CONTEXT)=\S+|(?:docker|podman)\b[^\n;&|]{0,100}\s(?:-H|--host|--context)[\s=]\S+|cloudflared\s+access\s+(?:tcp|rdp|ssh)|fly(?:ctl)?\s+proxy|(?:kubectl|oc)\b[^\n;&|]{0,200}\bport-forward|cloud[-_]sql[-_]proxy|cloud_sql_proxy|aws\s+ssm\s+start-session\b[^\n;&|]{0,200}PortForward|tsh\s+proxy\s+db|start-iap-tunnel|railway\s+connect)/i.exec(e);return n?n[1].replace(/\s+/g," ").slice(0,40):null}var Om=/\b(create\s+or\s+replace\s+(table|schema|database)|insert\s+overwrite|delete\s+(?!from\b)[\w.`"-]+\s+where)\b/i,Hn={exec(e){let t=Om.exec(e);return t?[t[0],t[1]]:/\bmerge\b/i.test(e)&&/\bthen\s+delete\b/i.test(e)?["MERGE \u2026 THEN DELETE","MERGE \u2026 THEN DELETE"]:null},test(e){return this.exec(e)!==null}};function Ho(e,t){let n=Bc.has(e.name)?Zc(e):null,s=n!==null?{...e,stdin:n}:e;s!==e&&Qs.has(e)&&Qs.add(s);let r=s.argv,o=s.name,a=(...d)=>P(r,...d),i=s.pipeFrom&&["echo","printf","cat"].includes(s.pipeFrom.name)?s.pipeFrom.argv.slice(1).join(" ")+(s.pipeFrom.stdin??""):"",l="",c=null,u=null,f=!0;switch(o){case"psql":case"pgcli":{l=[...r.flatMap((g,y)=>g==="-c"||g==="--command"?[r[y+1]??""]:g.startsWith("--command=")?[g.slice(10)]:[]),s.stdin??"",i].join(`
|
|
43
|
+
`),c=a("-h","--host");let d=a("-d","--dbname")??Gc(r)[0]??null,h=d!==null&&/^\s*[a-z_]+\s*=/i.test(k(d))&&!/\b(host|hostaddr|service)\s*=/i.test(k(d));d!==null&&!h&&(S(d)?f=c!==null&&!S(c)&&Ut(c):(/^postgres(ql)?:\/\//i.test(d)||/\bhost=/.test(d))&&(u=/\bhost=([^\s]+)/.exec(d)?.[1]??de(d)));break}case"sqlite3":case"sqlite":{let d=r.slice(1).find($=>!$.startsWith("-")),h=[r.slice(1).filter($=>!$.startsWith("-"))[1]??"",s.stdin??"",i].join(`
|
|
44
|
+
`);if(!d||!be.test(h)||d===":memory:"||/\/scratchpad(\/|$)|^\/(private\/)?(tmp|var\/folders)\//.test(d))return[];let g=X(d,s.cwd,se(t)),y=g.why===On?"own":ah(g.path,t);return y==="own"?[]:[m("claude.bash.fs.delete_recursive",`destroys data in a real database file (${R.basename(k(d))})`,{target:k(d),is_local:!0,housekeeping:y==="dev"})]}case"mysql":case"mariadb":l=[a("-e","--execute")??"",s.stdin??"",i].join(`
|
|
45
|
+
`),c=a("-h","--host");break;case"clickhouse-client":case"clickhouse":l=[a("-q","--query")??"",s.stdin??"",i].join(`
|
|
46
|
+
`),c=a("-h","--host");break;case"cockroach":{l=a("-e","--execute")??"",c=a("--host");let d=a("--url");d!==null&&(S(d)?f=!1:u=de(d));break}case"cqlsh":l=[a("-e","--execute")??"",s.stdin??"",i].join(`
|
|
47
|
+
`),c=r.slice(1).find((d,h)=>!d.startsWith("-")&&!/^(-e|--execute|-u|--username|-p|--password|-k|--keyspace|-f|--file|--cqlversion|--request-timeout|--connect-timeout|--cqlshrc)$/.test(r[h]??""))??null;break;case"turso":{let d=v(r);if(d[0]!=="db"||d[1]!=="shell")return[];l=[d.slice(3).join(" "),s.stdin??"",i].join(`
|
|
48
|
+
`),c="turso";break}case"prisma":{let d=v(r);if(d[0]!=="db"||d[1]!=="execute"||!T(r,"--stdin"))return[];l=[s.stdin??"",i].join(`
|
|
49
|
+
`);let h=a("--url");h!==null&&!S(h)?u=de(h):f=!1;break}case"pscale":{if(!["shell","sql"].includes(v(r)[0]??""))return[];l=[a("--query","--execute","-e")??"",s.stdin??"",i].join(`
|
|
50
|
+
`),c="planetscale";break}case"trino":case"presto":l=a("--execute")??s.stdin??"",c=a("--server"),c!==null&&(c=de(c)??c);break;case"sqlcmd":l=a("-Q","-q")??s.stdin??"",c=(a("-S")??"").replace(/^tcp:/i,"").split(/[,\\]/)[0]||null,c!==null&&/^(\.|\(local\)|localhost)$/i.test(c)&&(c="localhost"),c===null&&(f=!1);break;case"beeline":l=a("-e")??s.stdin??"",c=/\/\/([^:/;]+)/.exec(a("-u")??"")?.[1]??null,c===null&&(f=!1);break;case"impala-shell":l=a("-q","--query")??"",c=(a("-i","--impalad")??"").replace(/:\d+$/,"")||null,c===null&&(f=!1);break;case"spark-sql":l=a("-e")??"",c="spark";break;case"mongosh":case"mongo":{let d=[a("--eval")??"",s.stdin??""].join(`
|
|
51
|
+
`),h=r.find(y=>/^mongodb(\+srv)?:\/\//i.test(y));h&&(u=de(h)),c=a("--host");let g=r.slice(1).find((y,$)=>!y.startsWith("-")&&!/^--?(eval|file|f|host|port|username|u|password|p|authenticationDatabase)$/.test(r[$]??""));return g!==void 0&&S(g)&&(f=!1),Rm.test(d)?bt(s,c??u,f,`mongo ${/dropDatabase/.test(d)?"drops a database":/\.drop\s*\(/.test(d)?"drops a collection":"deletes documents"}`,yt(t.lineText),d):[]}case"redis-cli":{let d=r.slice(1).map(g=>g.toLowerCase());if(!d.includes("flushall")&&!d.includes("flushdb"))return[];let h=a("-u");return bt(s,a("-h")??(h?de(h):null),f,`redis ${d.includes("flushall")?"FLUSHALL wipes every database":"FLUSHDB wipes a database"}`,yt(t.lineText))}case"dropdb":case"dropuser":return bt(s,a("-h","--host"),f,`${o} deletes a database`,yt(t.lineText));case"mysqladmin":return r.includes("drop")?bt(s,a("-h","--host"),f,"mysqladmin drops a database",yt(t.lineText)):[];case"bq":{let d=v(r),h=E=>[m("claude.bash.db.destructive",E,{target:d.slice(1).join(" ")||"bigquery",host:"bigquery",is_local:!1})];if(d[0]==="rm")return h("bq rm deletes a BigQuery table or dataset");if(d[0]==="load"&&T(r,"--replace"))return h("bq load --replace overwrites a BigQuery table");if(d[0]==="cp"&&T(r,"-f","--force"))return h("bq cp -f overwrites a BigQuery table");let g=a("--expiration","--default_table_expiration","--default_partition_expiration");if(d[0]==="update"&&g!==null&&g!=="0")return h("bq update sets BigQuery data to expire (be deleted)");if(d[0]!=="query"||T(r,"--dry_run"))return[];if(T(r,"--replace"))return h("bq query --replace overwrites its destination table");let y=ke([r.slice(r.indexOf("query")+1).join(`
|
|
52
|
+
`),s.stdin??"",i].join(`
|
|
53
|
+
`),"bigquery"),$=be.exec(y)??Hn.exec(y);return $?h(`bq query runs destructive SQL (${$[1].replace(/\s+/g," ").toUpperCase()})`):[]}case"snowsql":case"snow":{let d=v(r);if(o==="snow"&&(d[0]==="object"&&d[1]==="drop"||d[0]==="stage"&&["remove","rm"].includes(d[1]??"")))return[m("claude.bash.db.destructive",`snow ${d[0]} ${d[1]} deletes Snowflake data`,{target:d.slice(2).join(" ")||"snowflake",host:"snowflake",is_local:!1})];if(o==="snow"&&d[0]!=="sql")return[];let h=ke([a("-q","--query")??"",s.stdin??"",i].join(`
|
|
54
|
+
`),"snowflake"),g=be.exec(h)??Hn.exec(h);return g?[m("claude.bash.db.destructive",`${o} runs destructive SQL (${g[1].replace(/\s+/g," ").toUpperCase()}) on Snowflake`,{target:"snowflake",host:"snowflake",is_local:!1})]:[]}case"databricks":{let d=v(r);if(d[0]==="api"){let h=d[2]??"",g=a("--json")??"",y=(()=>{try{let E=JSON.parse(g);return typeof E=="object"&&E!==null&&typeof E.statement=="string"?E.statement:g}catch{return g}})(),$=ke(y,"bigquery");return d[1]==="post"&&/sql\/statements/.test(h)&&(be.test($)||Hn.test($))||d[1]==="delete"&&/unity-catalog\/(tables|schemas|catalogs|volumes)|\/dbfs\//.test(h)?[m("claude.bash.db.destructive",`databricks api ${d[1]} destroys stored data`,{target:h,host:"databricks",is_local:!1})]:[]}return d[0]==="fs"&&d[1]==="rm"||["tables","schemas","catalogs","volumes","registered-models"].includes(d[0]??"")&&d[1]==="delete"?[m("claude.bash.db.destructive",`databricks ${d[0]} ${d[1]} deletes stored data`,{target:d.slice(2).join(" ")||"databricks",host:"databricks",is_local:!1})]:[]}case"duckdb":{let d=r.slice(1).find(g=>!g.startsWith("-"))??"",h=ke([a("-c")??"",s.stdin??"",i].join(`
|
|
55
|
+
`));return/^(md|motherduck):/i.test(d)&&be.test(h)?[m("claude.bash.db.destructive",`duckdb runs destructive SQL (${be.exec(h)[1].replace(/\s+/g," ").toUpperCase()}) on MotherDuck`,{target:d,host:"motherduck",is_local:!1})]:[]}case"dbt":{let d=v(r);if(!["run","build","seed"].includes(d[0]??"")||!T(r,"--full-refresh"))return[];let h=a("--target","-t");return h===null||!S(h)&&/^(dev|development|local|ci|test|testing|staging|stage|sandbox|qa|preview)([-_][\w-]+)?$/i.test(h)?[]:[m("claude.bash.db.destructive",`dbt ${d[0]} --full-refresh rebuilds tables on ${h?k(h):"the default target"}`,{target:h??"dbt",host:"dbt",is_local:!1})]}case"wrangler":return v(r)[0]==="d1"&&v(r)[1]==="execute"&&T(r,"--remote")&&be.test(a("--command")??"")?[m("claude.bash.db.destructive","wrangler runs destructive SQL on a remote D1 database",{is_local:!1,host:"cloudflare"})]:[];default:return[]}let p=ke(l,["mysql","mariadb","clickhouse-client","clickhouse"].includes(o)?"mysql":["spark-sql","beeline","impala-shell"].includes(o)?"bigquery":"postgres");if(!be.test(p)){let d=s.pipeFrom,h=s.stdinFile??(d&&/^(cat|[bx]?zcat|gunzip|gzip|pv|zstdcat)$/.test(d.name)?d.argv.slice(1).find($=>!$.startsWith("-"))??null:null),g=[...o==="psql"||o==="pgcli"?r.flatMap(($,E)=>$==="-f"||$==="--file"?[r[E+1]??""]:$.startsWith("--file=")?[$.slice(7)]:[]):[],...h!==null&&["psql","mysql","mariadb"].includes(o)?[h]:[]].filter($=>$!=="-"&&$!=="");if(g.length===0)return[];let y=R.basename(k(g[0]));return bt(s,c??u,f,`runs the SQL in ${y}`,yt(t.lineText),p).filter($=>$.target!=="no server shown").map($=>({...$,catastrophic:!1}))}return bt(s,c??u,f,`runs destructive SQL (${(be.exec(p)?.[1]??"").replace(/\s+/g," ").toUpperCase()})`,yt(t.lineText),l)}var Ls='[\\w.$"`[\\]{}-]+',jm=new RegExp(`^(drop\\s+(?:database|table|schema)\\s+(?:if\\s+exists\\s+)?${Ls}(?:\\s*,\\s*${Ls})*(?:\\s+(?:cascade|restrict|purge|sync|on\\s+cluster\\s+\\S+))*$|truncate\\s+(?:table\\s+)?(?:if\\s+exists\\s+)?(?:only\\s+)?${Ls}(?:\\s*,\\s*${Ls})*\\s*(?:(?:restart|continue)\\s+identity\\s*)?(?:cascade|restrict)?(?:\\s+on\\s+cluster\\s+\\S+)?(?:\\s+settings\\s[\\s\\S]*)?$|delete\\s+from\\b(?![\\s\\S]*\\bwhere\\b))`,"i"),Pm=/^(select|insert|update|delete|drop|truncate|create|alter|with|begin|commit|rollback|savepoint|release|set|use|grant|revoke|vacuum|analyze|show|explain|copy|merge|replace|upsert|start|end|pragma|attach|detach|optimize|rename|comment|call|declare|describe|system|kill|lock|unlock|refresh|do|exec|execute|prepare|values|reindex|checkpoint|discard|reset|abort|load)\b/i,Wm=/^\s*(drop\s+(?:database|table|schema)|truncate)(?:\s+table)?(?:\s+if\s+exists)?\s*(?:\$\{|\{|%s|\?|$)/i,kl=/^--?(sql|query|execute|command|statement|stmt|c|e|q|Q)$/,Nm=new Set(["echo","printf","cat","tee","grep","egrep","fgrep","rg","ag","ack","sed","gsed","awk","gawk","mawk","nawk","jq","yq","sort","head","tail","less","more","wc","cut","tr","diff","patch","touch","truncate","git","gh","glab","hg","svn","bash","sh","zsh","dash","ksh","fish","eval","exec","source","ssh","xargs","docker","podman","kubectl","oc","tmux","screen","watch","claude","codex","gemini","aider","llm","sgpt","ollama","amp","cursor-agent","droid","qwen","copilot","crush","opencode","goose","mods","aichat","tgpt","howdoi","fzf","gum","say","logger","osascript","notify-send","vim","nvim","vi","nano","emacs","code","cursor","subl","open","pbcopy","xclip","wl-copy","test","[","export","read","cd","mkdir","umask","cp","mv","dd","install","sponge","split","base64","gzip","gunzip","bzip2","xz","zstd","md5","md5sum","sha1sum","sha256sum","sha512sum","shasum","mail","mailx","sendmail","scp","rsync","tar","zip","sqlfluff","sql-formatter","pg_format","sqlformat","squawk","prettier","mysqldump","pg_dump","pg_dumpall"]),Lm=new Set(["vtctlclient","vtctldclient","vtctl","spanner-cli","bteq"]),Tm=/^(sql|psql|mysql|query|execute|statement|connect)$/,Bc=new Set(["psql","pgcli","sqlite3","sqlite","mysql","mariadb","clickhouse-client","clickhouse","cockroach","cqlsh","turso","prisma","pscale","trino","presto","sqlcmd","beeline","impala-shell","spark-sql","mongosh","mongo","redis-cli","dropdb","dropuser","mysqladmin","bq","snowsql","snow","databricks","duckdb","dbt","wrangler"]),Im=/(?:require\(\s*|from\s+|import\s+(?:[\w.]+\s*,\s*)*)['"]?(?:pg|postgres|mysql2?|mssql|oracledb|psycopg2?|asyncpg|pymysql|MySQLdb|mysql\.connector|sqlalchemy|clickhouse[_-](?:connect|driver)|@clickhouse\/client|snowflake[.-](?:connector|sdk)|@neondatabase\/serverless|@planetscale\/database|@vercel\/postgres|@prisma\/client|knex|sequelize|kysely|pyodbc|pymssql)\b/,vl=/^(?!(?:sqlite\d?|duckdb|file):)[a-z][\w+.-]*:\/\/[^/\s]/i;function $l(e){let t=/^[a-z][\w+.-]*:\/\/(?:[^@/?#]*@)?([^/?#]*)/i.exec(e)?.[1];return t===void 0?de(e):t===""||/^%2f/i.test(t)||/[?&]host=(\/|%2f)/i.test(e)?null:de(e)}var Dm=/^(?:(?:sqlite\d?|duckdb|file):|[^:\s]*\.(?:db|sqlite3?|duckdb)$)/i,Fm=/^(cp|sync|mv|put|upload|add|set|create|write|import|rcat|push)$/;function on(e){if(!e)return null;let t=e.toLowerCase();if(!t.includes("drop")&&!t.includes("truncate")&&!t.includes("delete"))return null;let n=k(e).replace(/^[ \t]*(?:[.\\][^\n]*|go)[ \t]*$/gim,";"),s=ke(n).split(";").map(o=>o.replace(/^(?:\s|--[^\n]*|\/\*[\s\S]*?\*\/)+/,"").trim()).filter(Boolean);if(s.length===0||!Pm.test(s[0]))return null;let r=s.map(o=>jm.exec(o)?.[1]).find(o=>o!==void 0);return r===void 0?null:/^delete/i.test(r)?"DELETE FROM with no WHERE":r.split(/\s+/).slice(0,/^drop/i.test(r)?2:1).join(" ").toUpperCase()}function zm(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n];if(s!=='"'&&s!=="'"&&s!=="`")continue;let r=n+1;for(;r<e.length&&e[r]!==s;)r+=e[r]==="\\"?2:1;if(r>=e.length)break;t.push(e.slice(n+1,r)),n=r}return t}function Mm(e){for(let t of zm(e)){let n=on(t)??Wm.exec(t)?.[1]?.split(/\s+/).slice(0,2).join(" ").toUpperCase();if(n)return n}return null}function Um(e,t){let n=[],s=t?"(?:query|sql|stmt|statement)":"(?:sql|stmt|statement)";for(let r of e.matchAll(new RegExp(`"${s}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`,"gi")))n.push(r[1].replace(/\\n/g,`
|
|
56
|
+
`).replace(/\\(.)/g,"$1"));for(let r of e.matchAll(new RegExp(`(?:^|[?&])${s}=([^&]*)`,"gi")))try{n.push(decodeURIComponent(r[1].replace(/\+/g," ")))}catch{}return n}function qm(e){let t=null,n=!1,s=!1;for(let r=1;r<e.length;r++){let o=e[r];if(o==="-X"||o==="--request"||o==="--method")t=(e[r+1]??"").toUpperCase();else if(o.startsWith("--request=")||o.startsWith("--method="))t=o.slice(o.indexOf("=")+1).toUpperCase();else if(o[0]==="-"&&o[1]!=="-"&&o.includes("X")){let a=/^-[a-zA-Z]*X([A-Za-z]+)$/.exec(o)?.[1];a!==void 0?t=a.toUpperCase():/^-[a-zA-Z]*X$/.test(o)&&(t=(e[r+1]??"").toUpperCase())}(o==="-G"||o==="--get")&&(s=!0),(Mt.includes(o)||/^--(data[\w-]*|json|form[\w-]*|upload-file|post-data|post-file|body-data|body-file)(=|$)/.test(o)||/^-d./.test(o))&&(n=!0)}return t!==null&&t!==""?t!=="GET"&&t!=="HEAD":n&&!s}function Vc(e){if(e.stdin!==null)return e.stdin;let t=e.pipeFrom;return t===null?null:t.name==="echo"?t.argv.slice(1).filter((n,s,r)=>!(/^-[neE]+$/.test(n)&&r.slice(0,s).every(o=>/^-[neE]+$/.test(o)))).join(" "):t.name==="printf"?t.argv.slice(1).join(" ").replace(/\\n/g,`
|
|
57
|
+
`).replace(/\\t/g," "):t.name==="cat"?t.stdin:null}function Zc(e){if(e.stdin!==null||e.pipeFrom!==null)return null;for(let t=e;t.parent!==null&&(t.via==="remote"||t.via==="shell-string");t=t.parent){let n=Vc(t.parent);if(n!==null)return n}return null}var xl=new WeakMap;function _l(e,t){let n=e.lineCommands??[],s=xl.get(n);if(!s){s=new Map;for(let r of n)r.parent!==null&&s.set(r.parent.argv,(s.get(r.parent.argv)??0)+1);xl.set(n,s)}return s.get(t)??0}var Ts=null;function Sl(e){return(Ts===null||Ts.text!==e)&&(Ts={text:e,at:yt(e)}),Ts.at}function Hm(e,t){let n=e.name,s=e.argv;if(Nm.has(n)||Bc.has(n)||e.functionCall)return[];let r=Zc(e),o=e.pipeFrom,a=`${s.join(" ")} ${e.stdin??""} ${r??""} ${o?o.argv.join(" "):""} ${o?.stdin??""}`.toLowerCase();if(!a.includes("drop")&&!a.includes("truncate")&&!a.includes("delete"))return[];if(_l(t,s)>0)return[];if(s.some(x=>/^--?(dry[-_]?run|plan|preview|validate|explain|what-?if|check)(=(true|1|yes))?$/i.test(k(x))))return[];let i=v(s),l=["heroku","fly","flyctl"].includes(n)||yn.has(n)||Qc.has(n),c=i.slice(0,4).flatMap(x=>x.toLowerCase().split(/[-_:]/));if(l&&(c.some(x=>Fm.test(x))||!c.some(x=>Tm.test(x))))return[];let u=l||Lm.has(n),f=n==="curl"||n==="wget";if(f&&!qm(s))return[];let p=f&&s.some(x=>/^(?:[a-z]+:\/\/)?[^/?#\s]*\/(?:[^?#\s]*\/)?(sql|query|queries|statements?|pipeline|execute|_sql)(\/|\?|$)/i.test(k(x))),d=[],h=[],g=[],y=Jo[n]!==void 0?Xn(e):null,$=y!==null,E=(x,b=!1)=>{if(x){if(!$&&on(x)!==null)d.push(x);else if(!b&&Im.test(x))h.push(x);else if(f)for(let j of Um(k(x),p))on(j)!==null&&d.push(j)}};if($)E(y);else{for(let x=1;x<s.length;x++){let b=k(s[x]),j=/^(--?[\w-]+)=([\s\S]+)$/.exec(b),C=A=>n==="curl"&&Mt.includes(A);(kl.test(b)||C(b))&&!/^--?[A-Za-z]/.test(k(s[x+1]??"-x"))?E(s[++x]):j?(kl.test(j[1])||C(j[1])||/^--(post|body)-data$/.test(j[1]))&&E(j[2]):!b.startsWith("-")&&(x===1||!/^-/.test(k(s[x-1]))||s[x-1]==="--"||(n==="curl"||n==="wget")&&!Js.has(s[x-1]))&&(g.push(s[x]),(/\s/.test(b)||(n==="curl"||n==="wget")&&b.includes("="))&&E(s[x],!0))}E(Vc(e)??(r!==null&&e.parent!==null&&_l(t,e.parent.argv)===1?r:null))}if(d.length>0){let x=d.join(`;
|
|
58
|
+
`),j=[.../^(\s*\w+=("[^"]*"|'[^']*'|[^\s;&|]*))*/.exec(e.text)[0].matchAll(/(?:^|\s)(\w+)=("[^"]*"|'[^']*'|\S*)/g)].filter(z=>/(HOST|URL|URI|DSN|ADDR|SERVER|ENDPOINT)/i.test(z[1])||vl.test(z[2].replace(/^["']/,""))).map(z=>z[2].replace(/^["']|["']$/g,"")),C=P(s,"--host","-host","--hostname","--server","-server","--server_address","--vtctld_server","--url","-url","--uri","--dsn","--connection","--connection-string","--conn","--database-url","--db-url","--endpoint","--addr","--address","-h")??(n==="curl"||n==="wget"?s.find((z,B)=>B>0&&!z.startsWith("-")&&!Js.has(s[B-1])&&(un(k(z))||S(z))):s.slice(1).find(z=>vl.test(k(z).replace(/^--?[\w-]+=/,""))))?.replace(/^--?[\w-]+=/,"")??j[0]??null,A=C===null?null:k(C),U=A!==null&&/^[^:[\]]+:\d+$/.test(A),I=A===null?u&&!T(s,"--local")?`${n}'s server`:null:/^[a-z][\w+.-]*:\/\//i.test(A)?$l(A):S(C)?C:U?A.replace(/:\d+$/,""):A,D=I===null?s.slice(1).map(z=>k(z).replace(/^--?[\w-]+=/,"")).find(z=>Dm.test(z)):void 0;return D!==void 0?[m("claude.bash.db.destructive",`${n} runs destructive SQL (${on(x)}) on a database file on this machine (${R.basename(D)})`,{target:D,is_local:!0})]:bt(e,I,!0,`${n} runs destructive SQL (${on(x)})`,Sl(t.lineText),x)}for(let x of h){let b=Mm(x);if(b===null)continue;let j=/\b(?:postgres(?:ql)?|mysql|mariadb|clickhouse|mssql|sqlserver|cockroachdb|redshift|snowflake)(?:\+\w+)?:\/\/[^\s'"`]+/i.exec(x)?.[0],C=j!==void 0?$l(j):/\bhost(?:name)?['"]?\s*[:=]\s*(['"`])([^'"`\s]+)\1/i.exec(x)?.[2]??null,A=/(?:process\.env\.|process\.env\[\s*['"]|environ(?:\.get)?\s*[([]\s*['"]|getenv\(\s*['"]|env\.get\(\s*['"])(\w*(?:HOST|URL|URI|DSN|CONN|SERVER)\w*)/i.exec(x)?.[1];if(!(C===null&&A===void 0&&(j===void 0&&/sqlite|duckdb|:memory:/i.test(x))))return bt(e,C??(A!==void 0?`$${A}`:null),!0,`${n} runs destructive SQL (${b}) through a database driver`,Sl(t.lineText),x)}return[]}function Bm(e){let t=ue(e[0]??"");if(t!=="heroku"&&t!=="netlify"&&t!=="vercel")return null;let n=/^(local|dev):(run|exec)$/.test(e[1]??"")?2:e[1]==="env"&&e[2]==="run"?3:-1;if(n<0)return null;let s=e.slice(e[n]==="--"?n+1:n);return s.length>0&&!s[0].startsWith("-")?s:null}function Gc(e){let t=new Set(["-c","--command","-f","--file","-h","--host","-p","--port","-U","--username","-d","--dbname","-v","--set","--variable","-o","--output","-L","--log-file","-P","--pset","-T","-F","-R"]),n=[];for(let s=1;s<e.length;s++){let r=e[s];t.has(r)?s++:r.startsWith("-")||n.push(r)}return n}function Ut(e){return e.startsWith("/")||Re(e)}function bt(e,t,n,s,r=null,o=""){let a=Yc(e),i=(e.remote===null||e.remote.startsWith("container:"))&&a===null,l=n&&!e.productionEnv&&i&&r===null&&(t===null||Ut(t))&&!(t!==null&&S(t)),c=Xc(e,o),u=t?fn(t):a??e.remote;if(c!==null)return[m("claude.bash.db.destructive",`${s}: ${c} is named for production`,{target:c,host:u,is_local:!1,catastrophic:!0})];if(l)return t!==null||e.remote!==null||Zm.has(e.name)||Qs.has(e)?[]:[m("claude.bash.db.destructive",`${s}, with no server shown`,{target:"no server shown",is_local:null,catastrophic:!1})];let f=r!==null&&(t===null||Ut(t))?`a database forwarded here (${r})`:t?fn(t):e.productionEnv?"production (railway run)":a!==null?`${a} (${e.remote?.replace(/^container:/,"container ")??"a container"})`:e.remote??"a database the command does not name";return[m("claude.bash.db.destructive",`${s} on ${f}`,{target:f,host:u,is_local:!1,catastrophic:!0})]}function Kc(e){return e.remote===null?null:e.remote.startsWith("container:")?Yc(e):e.remote==="kubernetes"?"a cluster's pod":e.remote}var Cl=/^(reload|restart|stop|start|enable|disable|daemon-reload|mask|kill|try-restart|reload-or-restart|graceful|delete|down|up|rm|update)$/;function Vm(e){let t=Kc(e);if(t===null)return[];let n=v(e.argv).map(i=>k(i)),s=R.basename(e.name),r=i=>[m("claude.bash.deploy",`${i} on ${t}`,{target:t,host:t,is_local:!1})];if(["rm","unlink","rmdir","shred","truncate"].includes(s)&&n.length>0)return r(`${s} deletes files`);if((s==="systemctl"||s==="service")&&n.some(i=>Cl.test(i)))return r(`${s} ${n.find(i=>Cl.test(i))} changes a service`);if(["docker","podman","docker-compose"].includes(s)){let i=n[0]==="compose"?1:0,l=n[i]==="exec"?void 0:n.slice(i,4).find(c=>/^(down|up|stop|rm|restart|kill|start|run|rmi|prune)$/.test(c));if(l)return r(`${s}${n[0]==="compose"?" compose":""} ${l} changes containers`)}let o=/^(\.{0,2}\/|~\/)|\.(sh|bash|py|rb)$/.test(e.argv[0]??"")||["bash","sh","zsh"].includes(s)&&/\.(sh|bash)$/.test(n[0]??""),a=n.find(i=>/^(remove|delete|destroy|uninstall|purge|drop|teardown|down)$/i.test(i));return o&&a?r(`runs ${R.basename(k(e.argv[0]??s))} ${a}`):[]}var Qs=new WeakSet,Zm=new Set(["redis-cli","mongosh","mongo"]);function Yc(e){if(e.remote===null||!e.remote.startsWith("container:"))return null;for(let t=e.parent;t;t=t.parent)if(t.remote!==null&&!t.remote.startsWith("container:"))return t.remote;return null}function or(e){let t=e.split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])/);return t.some((n,s)=>/^(prod|prd|production|live)\d*$/i.test(n)&&!/^(non|pre|not|no|un)$/i.test(t[s-1]??""))}function Gm(e){let t=[];for(let n=e;n;n=n.parent){let s=P(["",...n.wrapperArgs],"--config","--env","--environment","--stage","--profile");s!==null&&t.push(s)}return t}function Jc(e){return[.../^(\s*\w+=("[^"]*"|'[^']*'|[^\s;&|]*))*/.exec(e.text)[0].matchAll(/(?:^|\s)(\w+)=("[^"]*"|'[^']*'|\S*)/g)].filter(n=>!/pass|pwd|secret|token|key|auth/i.test(n[1])).flatMap(n=>[n[1],n[2]])}function Xc(e,t){let n=e.argv.map(r=>k(r));return[...Gm(e),...n.filter((r,o)=>o>0&&!/\s/.test(r)&&!/^-([UupPfoceqWaL]|-(user(name)?|pass(word)?|port|file|output|command|execute|eval|query|sql|log-file))$/.test(n[o-1])&&!/^(--?(user|pass|port|file|output)|-[UupP].)/.test(r)).map(r=>r.replace(/^--?[\w-]+=/,"")),...n.flatMap(r=>[...r.matchAll(/\b(?:dbname|host)=([^\s'"]+)/g)].map(o=>o[1])),...[...k(t).matchAll(/(?:\\c(?:onnect)?\s+|\b(?:drop\s+(?:database|schema|keyspace)\s+(?:if\s+exists\s+)?|use\s+|(?:table|from|into|update)\s+(?:if\s+exists\s+)?(?=[`"']?[\w$]+[`"']?\.)))[`"']?([\w$-]+)/gi)].map(r=>r[1]),...Jc(e)].map(r=>r.replace(/(:\/\/)[^@/\s]+@/,"$1").replace(/\?.*$/,"")).find(r=>r.length<=200&&or(r))?.slice(0,80)??null}var Qc=new Set(["firebase","xata","fauna","aws","gsutil","azd","upctl","yc","openstack","terraform","tofu","terragrunt","pulumi","cdk","cdktf","serverless","sls","ticloud","neon","neonctl","upstash","supabase","pscale","turso","atlas","mongocli","modal","bq","snow","snowsql","juju","rclone","s3cmd","mc","b2","argocd","velero","rancher","zeet","scaleway","civo"]),Km=/^(delete|deletion|destroy|remove|rm|rb|uninstall|terminate|purge|teardown|deprovision|decommission|drop|wipe|nuke|erase|tombstone|truncate|flushall|flushdb)$/,Ym=/^(env|envs|vars?|variables?|configs?|settings?|labels?|tags?|annotations?|alias(es)?|metadata|options?|domains?)$/,Jm=/^(clusters?|serverless|instances?|buckets?|regions?|stores?|replicas?|shards?|partitions?|brokers?|namespaces?|volumes?|stacks?|deployments?|tombstone|vpcs?)$/,eu=/^(kind-|k3d-|minikube$|docker-desktop$|rancher-desktop$|orbstack$|colima)/,Xm=/\.aws\/credentials|\.azure\/|gcloud\/.*(credential|token)|application_default_credentials|service[-_]?account[^/]*\.json|-sa(-key)?\.json$|\.kube\/config|kubeconfig|\.oci\/|oci_api_key|doctl\/|credentials\.tfrc|\.s3cfg|\.boto$|\.vault-token/i,Qm=/^\/(var\/lib\/(mysql|postgresql|pgsql|mongodb|redis|cassandra|clickhouse|elasticsearch|influxdb|etcd|mariadb)|(usr\/local|opt\/homebrew)\/var\/(postgres|mysql|mongodb))/;function ey(e){if(eu.test(k(P(e.argv,"--context","--kube-context")??"")))return!1;let t=v(e.argv);if(e.name==="helm"||t[0]!=="delete"||T(e.argv,"-f","--filename","-k","--kustomize"))return!0;let n=t[1]??"";return!(n.includes("/")?t.slice(1).map(s=>s.split("/")[0]):n.split(",")).every(s=>/^(po|pods?|jobs?|events?|ev|rs|replicasets?|leases?)$/i.test(s))}function ty(e,t){if(e.catastrophic!==void 0||e.housekeeping)return e;let n=e.action,s=t.name,r=t.argv.map(d=>k(d)),o=v(r).slice(0,6).flatMap(d=>d.toLowerCase().split(/[-_:]/)),a=d=>o.some(h=>d.test(h)),i=(a(Km)||r.includes("-destroy")||r.includes("--destroy"))&&!a(Ym),l=["kubectl","oc","helm"].includes(s),c=l||Qc.has(s)||yn.has(s),u=n==="claude.bash.db.destructive",f=u||n==="claude.bash.deploy"?(l?i&&ey(t):c?(i||u&&!/\bresets\b/.test(e.why))&&!T(t.argv,"--local"):i&&e.is_local===!1&&/read by its words/.test(e.why)&&a(Jm)&&!r.some(d=>eu.test(d)))||u&&(t.productionEnv||Yn.test(Kn(t))||Jc(t).some(or))||s==="heroku"&&r[1]==="run"&&/\b(db:(drop|reset|purge|schema:load)|flush|migrate:(fresh|reset|refresh)|ecto\.(drop|reset)|dropdb)\b/.test(r.join(" ")):n==="claude.bash.fs.delete_recursive"?r.some(d=>Qm.test(d)):n==="claude.bash.secrets.print"&&(c||[e.target??"",...r,t.stdinFile??""].some(d=>Xm.test(k(d)))),p=c&&n!=="claude.bash.fs.delete_recursive"&&a(/^(credentials?|keys?|passwords?|tokens?|rbac)$/)&&a(/^(reset|create|rotate|new|regenerate|renew|for)$/)&&ae(t);return f||p?{...e,catastrophic:!0}:e}var ny=/(^|\/)(\.env(\.(?![\w.-]*\b(example|sample|template|tpl|tmpl|dist|defaults|schema)\b)[\w.-]+)?|\.envrc|[^/]*\.pem|[^/]*\.key|[^/]*\.p12|[^/]*\.pfx|[^/]*\.keystore|[^/]*\.jks|id_(rsa|dsa|ecdsa|ed25519)|\.npmrc|\.pypirc|\.netrc|\.git-credentials|credentials(\.json)?|[^/]*[-_.]credentials\.json|[^/]*service[-_]account[^/]*\.json|(key|keystore)\.properties|[\w-]*deploy[-_]key(\.pem)?|[^/]*serviceaccountkey[^/]*\.json|[^/]*\.p8|[^/]*keypair[^/]*\.json|\.config\/solana\/id\.json|\.dockercfg|kubeconfig(-[\w.-]+)?(\.(ya?ml|json|conf))?|[\w-]+[-_]kubeconfig(\.(ya?ml|json))?|\.pgpass|\.my\.cnf|credentials\.tfrc\.json|rclone\.conf|\.s3cfg|\.vault-token|\.dev\.vars|[^/]*firebase-admin[^/]*\.json|secrets?\.(ya?ml|json|toml)|terraform\.tfvars|authorized_keys|\.anvil\/workspace-keys\.json)$/i,sy=/(^|\/)\.(aws|kube|docker|ssh|gnupg|config\/gh)\/(credentials|config(\.json)?|hosts\.yml|id_[a-z0-9_]+|[^/]*\.pem)$/i,ry=/(^|\/)\.ssh\/config$/;function ko(e){return ye(e)&&!ry.test(k(e))}var oy=/(^|\/)\.ssh\/(?!known_hosts|authorized_keys|config$|environment$|rc$)[^/]+(?<!\.pub)$/;function ye(e){let t=k(e);return ny.test(t)||sy.test(t)||oy.test(t)||iy.test(t)&&!/\/memory(\/|$)/.test(t)}var iy=/(^|\/)\.claude\/projects(\/[^/]+)?\/?$|(^|\/)\.claude\/projects\/[^/]+\/[^/]+\.jsonl$|(^|\/)\.claude\/projects\/[^/]+\/[^/]+\/subagents\/[^/]+\.jsonl$/,dn=/(SECRET|TOKEN|PASSW(OR)?D|PASSPHRASE|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY|CREDENTIAL|AUTH|DSN|DATABASE_UR[IL]|DB_URL|REDIS_UR[IL]|POSTGRES(QL)?_UR[IL]|PG_?URL|MONGO(DB)?_UR[IL]|AMQP_URL|RABBITMQ_URL|CONNECTION_STRING|WEBHOOK_URL|CLIENT_SECRET|SIGNING|_PAT$|^PAT_|COOKIE|SESSION_KEY)/i,tu=/^(PWD|OLDPWD|PATH|HOME|USER|SHELL|TERM|LANG|TMPDIR|LOGNAME|EDITOR|PAGER|HOSTNAME)$/;function ae(e){if(e.captured||e.redirects.some(r=>(r.op===">"||r.op===">>"||r.op==="&>"||r.op===">|"||r.op==="1>")&&(r.fd===null||r.fd===1)&&r.target&&!["/dev/stdout","/dev/tty","/dev/stderr"].includes(r.target)))return!1;let t=!1,n=e.pipeTo,s=!1;for(let r=e.pipeTo;r;r=r.pipeTo)if(n=r,r.name==="tee"&&(s=!0),r.name==="tee"&&r.argv.slice(1).some(o=>/^\/dev\/(stderr|tty|fd\/[12])$/.test(k(o))))return!0;if(n&&!s&&zc(n))return!1;for(let r=e.pipeTo;r;r=r.pipeTo)if(["grep","rg","egrep"].includes(r.name)&&ly(r.argv.slice(1))&&(t=!0),ay(r)&&t||nu(r)||r.redirects.some(o=>(o.op===">"||o.op===">>")&&(o.fd===null||o.fd===1)&&o.target&&o.target!=="/dev/stdout"))return!1;return e.parent?ae(e.parent):!0}function ay(e){return e.name==="sed"&&/\[\^[^\]]*@[^\]]*\][*+]@/.test(e.argv.slice(1).join(" "))}function ly(e){let t=e.find(s=>!s.startsWith("-"));if(!t)return!1;let n=t.replace(/[\^$()\\]/g,"").split("|").map(s=>s.trim().replace(/=$/,"")).filter(Boolean);return n.length>0&&n.every(s=>/^[A-Za-z0-9_]+$/.test(s)&&(/(URL|URI|DSN|POSTGRES|PG_?URL|REDIS|MONGO|DATABASE)/i.test(s)||/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/.test(s)&&!dn.test(s)))}function nu(e){let t=e.argv.slice(1),n=t.join(" ");switch(e.name){case"wc":case"sha256sum":case"shasum":case"md5":case"diff":case"cmp":return t.some(s=>s==="-q"||s==="--brief"||s==="--quiet");case"md5sum":case"pbcopy":case"xclip":case"true":return!0;case"grep":case"rg":case"egrep":return t.some(s=>/^-[a-zA-Z]*[clLq]/.test(s)||s==="--count"||s==="--quiet"||s==="--files-with-matches")||cy(t)||uy(t);case"cut":return/-d\s*=?\s*'?=/.test(n.replace(/\s+/g," "))&&/-f\s*1\b|-f1\b/.test(n);case"awk":return/\{\s*print\s+\$1\s*\}/.test(n)&&/-F\s*'?=|-F=/.test(n);case"sed":return/\bs([/|#,])=\.[*+]\$?\1[^\\&]*\1/.test(n);case"jq":return/\bkeys\b|\blength\b|\bhas\(/.test(n);case"node":case"python":case"python3":case"ruby":return/\bkeys\b|Object\.keys|\.keys\(\)|length/.test(n+(e.stdin??""));case"head":return t.includes("-c")&&t[t.indexOf("-c")+1]==="0";default:return!1}}function cy(e){let t=e.find(s=>!s.startsWith("-"));if(!t)return!1;let n=t.replace(/[\^$()\\]/g,"").split("|").map(s=>s.trim().replace(/=$/,"")).filter(Boolean);return n.length>0&&n.every(s=>/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/.test(s)&&!dn.test(s))}function uy(e){if(!e.some(s=>/^-[a-zA-Z]*o[a-zA-Z]*$/.test(s)||s==="--only-matching"))return!1;let t=e.find(s=>!s.startsWith("-")),n=t?.endsWith("=")?t.slice(0,-1):t;return n!==void 0&&!/\.|\\S|\[\^|=|\\w\*/.test(n)}var er=new Set(["cat","head","tail","less","more","bat","nl","tac","strings","grep","rg","egrep","sed","awk","cut","sort","uniq","xxd","od","base64","jq","yq","column","pr","paste","fold","rev","fmt","expand","unexpand","iconv","tr","tee","diff","hexdump","hd","comm"]);function dy(e,t){let n=t.secretCopies,s=e.argv,r=e.name,o=s.slice(1);if(r==="printenv"||(r==="env"||r==="set"||r==="export"||r==="declare")&&o.every(f=>f.startsWith("-")&&f!=="-c"))return r==="printenv"&&o.filter(f=>!f.startsWith("-")).length>0&&!o.some(f=>!f.startsWith("-")&&dn.test(f))?[]:(r==="export"||r==="declare")&&!o.some(f=>f==="-p"||f==="-x"||o.length===0)?[]:r==="set"&&o.length>0?[]:!ae(e)||yy(e)==="no-secret"?[]:[m("claude.bash.secrets.print",`${r} prints the environment, secrets included`,{target:r,is_local:!0})];let a=f=>ko(f)||n.has(X(f,e.cwd,se(t)).path),l=(r==="xargs"?s.find((f,p)=>s[p-1]==="-a"||s[p-1]==="--arg-file")??s.find(f=>f.startsWith("--arg-file="))?.slice(11)??s.find(f=>/^-a./.test(f))?.slice(2):void 0)??e.stdinFile;if((r==="exec"||r==="xargs")&&l&&a(l))return[m("claude.bash.secrets.print",`${r==="exec"?"feeds a secrets file to the commands after it":"passes a secrets file to a command"} (${R.basename(k(l))})`,{target:k(l),is_local:!0})];if(r==="git"&&s.includes("--no-index")&&s.slice(1).some(f=>!f.startsWith("-")&&a(f))&&ae(e)){let f=s.slice(1).find(p=>!p.startsWith("-")&&a(p));return[m("claude.bash.secrets.print",`prints a secrets file (${R.basename(k(f))})`,{target:k(f),is_local:!0})]}let c=r==="dd"?s.find(f=>f.startsWith("if="))?.slice(3):void 0,u=s.find(f=>f.startsWith("of="))?.slice(3);if(c&&a(c)&&(u===void 0?ae(e):["/dev/stdout","/dev/stderr","/dev/tty","/dev/fd/1","/dev/fd/2"].includes(u)))return[m("claude.bash.secrets.print",`prints a secrets file (${R.basename(k(c))})`,{target:k(c),is_local:!0})];if(er.has(r)){let f=["-","/dev/stdin","/dev/fd/0"],p=r==="tr"||r==="tee"?[]:qt(e).filter(j=>!f.includes(j)),d=r==="tr"||r==="tee"||e.argv.slice(1).some(j=>f.includes(j))||qt(e).length===0,h=e.stdinFile!==null&&d?[...p,e.stdinFile]:p,g=["sed","gsed"].includes(r)&&e.argv.slice(1).some(j=>/^(-i\S*|--in-place(=.*)?|-[A-Za-z]*i)$/.test(k(j)))||/^g?awk$/.test(r)&&/(^| )(-i ?|--include[= ])inplace\b/.test(e.argv.map(k).join(" ")),y=h.filter(j=>(g?ye(j):ko(j))||n.has(X(j,e.cwd,se(t)).path)),$=r==="tee"&&qt(e).some(j=>["/dev/stderr","/dev/tty","/dev/fd/2","/dev/stdout"].includes(j)),E=["sed","gsed"].includes(r)&&e.argv.slice(1).some(j=>/^(-i\S*|--in-place(=.*)?|-[A-Za-z]*i)$/.test(k(j))),x=j=>X(j,e.cwd,se(t)).path||k(j);if(y.length&&E)return y.slice(0,8).map(j=>m("claude.file.write_secret",`edits a secrets file in place (${R.basename(k(j))})`,{target:x(j),is_local:!0}));if(y.length&&(ae(e)||$)&&!nu({...e,pipeTo:null}))return y.slice(0,8).map(j=>m("claude.bash.secrets.print",`prints a secrets file (${R.basename(k(j))})`,{target:x(j),is_local:!0}));let b=e.stdinExpands&&ae(e)?Al(e.stdin??"",e,t):null;return b?[m("claude.bash.secrets.print",`prints a secret through $(\u2026) (${R.basename(b)})`,{target:b,is_local:!0})]:[]}if(r==="security"&&/^find-(generic|internet)-password$/.test(o[0]??"")&&o.some(f=>f==="-w"||f==="-g"||/^-[a-z]*[wg]$/.test(f)))return ae(e)?[m("claude.bash.secrets.print","prints a keychain password",{target:"keychain",is_local:!0})]:[];if(r==="kubectl"&&["get","describe"].includes(v(s)[0]??"")&&/^secrets?$/.test(v(s)[1]??"")&&s.some((f,p)=>/^-o(yaml|json|jsonpath|go-template)|^--output/.test(f)||["yaml","json"].includes(f)||/^(jsonpath|go-template|custom-columns)=/.test(f)||s[p-1]==="-o"&&/^(yaml|json|jsonpath|go-template)/.test(f)))return ae(e)?[m("claude.bash.secrets.print","kubectl prints a secret",{target:"kubectl secret",is_local:!1})]:[];if(r==="op"&&(o[0]==="read"||o[0]==="item"&&o.includes("--reveal"))||r==="vault"&&(o[0]==="read"||o[0]==="kv"&&o[1]==="get")||r==="doppler"&&o[0]==="secrets"&&(o.length===1||["get","download"].includes(o[1]??"")||(o[1]??"").startsWith("-"))||r==="infisical"&&(o[0]==="secrets"&&(o.length===1||o[1]==="get"||o[1].startsWith("-"))||o[0]==="export"&&!s.some(f=>f.startsWith("--output-file")))||r==="az"&&v(s)[0]==="keyvault"&&v(s)[1]==="secret"&&v(s)[2]==="show"||r==="dotenv"&&["list","get"].includes(pe(s,1,new Set(["-f","--file","-e","-c","-v","-p"]))[0]??""))return ae(e)?[m("claude.bash.secrets.print",`${r} prints a secret`,{target:r,is_local:!0})]:[];if((r==="echo"||r==="printf"||r==="print"||e.stdinKind==="here-string"&&er.has(r))&&ae(e)){let f=[...s.slice(1),e.stdinKind==="here-string"?e.stdin??"":""].map(p=>Al(p,e,t)).find(p=>p!==null);if(f)return[m("claude.bash.secrets.print",`prints a secret through $(\u2026) (${R.basename(f)})`,{target:f,is_local:!0})]}if(r==="echo"||r==="printf"||r==="print"){let f=su(e.text);for(let p of f.matchAll(/\$(?:\{(#?)([A-Za-z_][A-Za-z0-9_]*)([^}]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g)){let d=p[2]??p[4],h=p[3]??"";if(!(p[1]==="#"||/^:?\+/.test(h)||/^:\s*0?\s*:\s*[1-8]$/.test(h))&&dn.test(d.replace(/AUTHOR(?!IZ)/gi,""))&&!tu.test(d)&&ae(e))return[m("claude.bash.secrets.print",`echoes a secret variable (${d})`,{target:d,is_local:!0})]}}return[]}function fy(e){let t=[];for(let n=0;n<e.length;n++)if(e[n]==="`"){let s=e.indexOf("`",n+1);if(s<0)break;t.push(e.slice(n+1,s)),n=s}else if(e[n]==="$"&&e[n+1]==="("){let s=0,r=n+1;for(;r<e.length;r++)if(e[r]==="(")s++;else if(e[r]===")"&&--s===0)break;t.push(e.slice(n+2,r)),n=r}return t}function Al(e,t,n){if(!e.includes("$(")&&!e.includes("`"))return null;for(let s of fy(e)){let r=s.trim(),o=/^<\s*["']?([^"'\s]+)["']?$/.exec(r);if(o){if(ye(o[1]))return o[1];continue}for(let a of Jn(r,t.cwd,n).commands){let i=Gn(a,n).find(l=>l.action==="claude.bash.secrets.print"&&!l.why.startsWith("echoes a secret variable"));if(i)return i.target??a.name}}return null}function qt(e){let t=e.argv.slice(1),n=t.filter((o,a)=>!o.startsWith("-")&&!["-e","-f","--regexp","--file","-m","-A","-B","-C","--max-count"].includes(t[a-1]??"")),s=t.some(o=>o==="-e"||o==="--regexp"||o.startsWith("--regexp=")||o==="-f"||o==="--file");return["grep","rg","egrep","sed","awk","jq","yq"].includes(e.name)&&!(e.name!=="sed"&&e.name!=="awk"&&e.name!=="jq"&&e.name!=="yq"&&s)&&!(e.name==="sed"&&s)?n.slice(1):n}var py=/(^|\/)(public|static|www|htdocs|wwwroot|public_html)(\/|$)/;function hy(e,t){if(["cp","mv","install","rsync","ditto"].includes(e.name)){let n=e.argv.slice(1).filter(o=>!o.startsWith("-")),s=n.at(-1),r=n.slice(0,-1).find(o=>ye(o));if(s!==void 0&&r!==void 0&&!S(s)&&py.test(M(s,e.cwd,t.ctx))&&He(s,e,t).kind!=="disposable")return[m("claude.bash.secrets.expose",`copies a secrets file (${R.basename(k(r))}) into a folder a web server serves (${k(s)})`,{target:k(s),is_local:!0})]}if(["echo","printf","print"].includes(e.name)){let n=e.redirects.find(s=>[">",">>",">|","1>","&>"].includes(s.op)&&(s.fd===null||s.fd===1)&&s.target)?.target;if(n&&!n.startsWith("/dev/")&&!S(n)&&!ye(n)&&!ot.test(n)){let s=[...su(e.text).matchAll(/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g)].map(r=>r[1]??r[2]).find(r=>dn.test(r)&&!tu.test(r));if(s!==void 0&&He(n,e,t).kind!=="disposable")return[m("claude.bash.secrets.expose",`writes the value of ${s} into ${R.basename(k(n))}`,{target:k(n),is_local:!0})]}}return[]}var gy=/\.(pem|key|crt|cer|der|p12|pfx|jks|keystore|p8)$/i;function my(e,t){let n=t.replace(/(?<!\/)\/+$/,""),s=e.startsWith(`${n}/`)?e.slice(n.length+1):null;return s!==null?/^\.(ssh|aws|kube|gnupg|docker|azure|oci|helm|minikube|config\/(gcloud|gh|helm|doctl))(\/|$)/.test(s):/^\/(etc|usr|System|Library|private\/etc|opt\/homebrew\/etc|var\/lib)(\/|$)/.test(e)||!e.startsWith("/")}function su(e){let t="",n=!1;for(let s=0;s<e.length;s++){let r=e[s];if(r==="\\"&&!n)t+=e.slice(s,s+2),s++;else if(r==='"')n=!n,t+=r;else if(r==="'"&&!n){let o=e.indexOf("'",s+1),a=o===-1?e.length:o;t+=" ".repeat(a-s+1),s=a}else t+=r}return t}function yy(e){let t=e.pipeTo;if(!t||!["grep","rg","egrep"].includes(t.name))return"none";let n=t.argv.slice(1).find(s=>!s.startsWith("-"))??"";return dn.test(n)||n===""?"secret":"no-secret"}function El(e,t){let n=[];for(let u of e.redirects)[">",">>","&>",">|","1>"].includes(u.op)&&u.target&&n.push(u.target);e.name==="tee"&&n.push(...e.argv.slice(1).filter(u=>!u.startsWith("-")));let s=e.argv.slice(1).flatMap(u=>u==="--no-clobber"||/^--update=none(-fail)?$/.test(u)?["n"]:u==="--force"?["f"]:u==="--interactive"?["i"]:/^-[A-Za-z]+$/.test(u)?[...u.slice(1)].filter(f=>"nfi".includes(f)):[]).pop(),r=(e.name==="cp"||e.name==="mv")&&s==="n";(e.name==="cp"||e.name==="mv"||e.name==="install")&&e.argv.length>=3&&!r&&n.push(e.argv[e.argv.length-1]);let o=u=>{let f=R.basename(k(u)).toLowerCase();return/\.(pem|crt|cer)$/.test(f)&&/(^|[-_.])(ca|cacert|cert|certs|certificate|certificates|chain|fullchain|bundle|root|intermediate|public|pub)([-_.]|$)/.test(f)&&!/key|priv|secret|p12|pfx|keystore|jks|id_/.test(f)},a=u=>{let f=X(u,e.cwd,se(t)).path,p=t.projectRoot&&!S(t.projectRoot)?t.projectRoot.replace(/(?<!\/)\/+$/,""):null,d=t.ctx.home.replace(/(?<!\/)\/+$/,"");return p!==null&&p!==""&&p!=="/"&&p!==d&&!d.startsWith(`${p}/`)&&f.startsWith(`${p}/`)},i=n.find(u=>ye(u)&&!u.startsWith("/dev/")&&!(o(u)&&a(u)));if(!i)return[];if(He(i,e,t).kind==="disposable")return[];let c=R.basename(k(i));return gy.test(c)&&e.remote===null&&!my(X(i,e.cwd,se(t)).path,t.ctx.home)?[]:[m("claude.file.write_secret",`writes ${/\.(pem|crt|cer|der|p12|pfx|key)$/i.test(c)?"a key or certificate file":"a secrets file"} (${c})`,{target:k(i),is_local:!0})]}function Bs(e,t){let n=e.findIndex((s,r)=>r>0&&new RegExp(`^-[A-Za-z]*${t}$`).test(s));return n>0?e[n+1]??null:null}function fn(e){let t=k(e).replace(/^["']|["']$/g,"");return/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||/^[\w.-]+\.[a-z]{2,}\//i.test(t)?de(t)??t.replace(/\/.*/,""):t.replace(/(:\/\/)[^@/\s]+@/g,"$1***@")}function P(e,...t){for(let n=1;n<e.length;n++){let s=e[n];for(let r of t){if(s===r&&e[n+1]!==void 0)return e[n+1];if(r.startsWith("--")&&s.startsWith(`${r}=`))return s.slice(r.length+1);if(!r.startsWith("--")&&r.length===2&&s.startsWith(r)&&s.length>2)return s.slice(2)}}return null}function Le(e,t=!1){let n=k(e).replace(/(?<!\/)\/+$/,""),s=R.basename(n);return/\.(enc|sops|encrypted|gpg|age|asc)(\.[\w-]+)?$|\.enc\.|\.sops\./i.test(s)||/^(package(-lock)?\.json|tsconfig[\w.-]*\.json|readme[\w.-]*|license[\w.-]*|changelog[\w.-]*|\.gitkeep|\.keep|\.gitignore)$/i.test(s)||t&&/^\.(npmrc|envrc)$/.test(s)||/(^|\/)templates\//.test(n)&&/^secrets?\.ya?ml$/.test(s)||s==="debug.keystore"||/\.(pem|crt)$/i.test(s)&&/(bundle|chain|cacert|ca-cert|^ca[-_.]|root|intermediate|cert|public|pub)/i.test(s)&&!/key|priv/i.test(s)?!1:/^[^/]+\.env$/.test(s)&&!/^(example|sample|template|tpl)\.env$/i.test(s)?!0:ye(n)||ye(n.replace(/\*+$/,""))||/(^|\/)\.(ssh|aws|gnupg|kube|docker|config\/gh)$|(^|\/)(secrets?|credentials)$/i.test(n)||/(^|\/)(secrets?|credentials)\//i.test(n)&&(!/\./.test(s)||/\.(json|ya?ml|env|toml|ini|txt|pem|key|p12|pfx|crt|cer|properties|conf|cfg|xml|plist|csv|jks|keystore)$/i.test(s))}var by=/^\/\.claude(\/settings(\.local)?\.json|\/hooks(\/.*)?|\/plugins(\/.*)?)?$|^\/\.claude\.json$|^\/\.mcp\.json$|^\/\.anvil(\/claude(\/.*)?|\/rules\.(?:json|md)|\/workspace-keys\.json|\/telemetry-notice)?$/i,wy=/(^|\/)managed-(settings|mcp)\.json$/i,ky=/(^|\/)library\/launch(agents|daemons)(\/|$)|^\/etc\/systemd\/|(^|\/)\.config\/systemd\/user(\/|$)|^\/(usr\/)?lib\/systemd\/system(\/|$)|^\/etc\/cron(\.(d|hourly|daily|weekly|monthly)(\/|$)|tab$)|^\/(private\/)?(var\/spool\/cron|usr\/lib\/cron\/tabs)(\/|$)/;function Bo(e,t,n=[],s=!0){return Vo(e,t,n,s).place}function Vo(e,t,n=[],s=!0){let r=so(e,t,n,s);if(r==="agent")return{place:r,at:e};let o=u=>{for(let[f,p]of Object.entries(t.controlLinks??{})){if(S(u)||!(u===f||u.startsWith(`${f}/`)))continue;let d=p+u.slice(f.length);if(so(d,t,n,s)==="agent")return d}return null},a=o(e);if(a!==null)return{place:"agent",at:a};if(!t.onDisk)return{place:r,at:e};let i=ks(e,t.onDisk,!0),l=i!==null?o(i):null;if(l!==null)return{place:"agent",at:l};let c=i===null?null:so(i,t,n,s);return i!==null&&(c==="agent"||r===null)?{place:c,at:i}:{place:r,at:e}}var vy=/^\/projects\/[^/]+\/(?:[^/]+\.jsonl|[^/]+\/subagents\/.+\.jsonl)$/i,$y=/^\/projects(?:\/[^/]+(?:\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:\/subagents)?)?)?\/?$/i,Zo=e=>[`${e.home.replace(/(?<!\/)\/+$/,"")}/.claude`,...e.claudeConfigDir&&!S(e.claudeConfigDir)?[e.claudeConfigDir.replace(/(?<!\/)\/+$/,"")]:[]];function St(e,t,n=!0){let s=e.toLowerCase();return!s.includes("/projects")||S(e)||/\/memory(\/|$)/i.test(e)?!1:Zo(t).some(r=>(s===`${r.toLowerCase()}/projects`||s.startsWith(`${r.toLowerCase()}/projects/`))&&(vy.test(e.slice(r.length))||n&&$y.test(e.slice(r.length))))}function ir(e,t,n){if(!/[*?[]/.test(e)||S(e)||!e.toLowerCase().includes("/projects"))return!1;let s="3f2a9c1e-5d4b-4a7e-9b1c-2e8f6a0d7c35",r=(i,l)=>{if(!/[*?[]/.test(i))return i.toLowerCase()===l.toLowerCase()||l!=="projects"&&l!=="subagents"&&(l.endsWith(".jsonl")?/\.jsonl$/i.test(i):l===s?/^[0-9a-f]{8}-/i.test(i):i.toLowerCase()!=="memory");let c=/^[^*?[]*/.exec(i)[0];return[l,c+l.slice(c.length)].some(u=>Go(i).test(u))},o=[["projects","-Users-dev-app",`${s}.jsonl`],["projects","-Users-dev-app",s,"subagents","agent-a1b2c3.jsonl"],["projects","-Users-dev-app",s,"subagents","workflows","w","journal.jsonl"]],a=n?[...o,["projects","-Users-dev-app"],["projects","-Users-dev-app",s],["projects","-Users-dev-app",s,"subagents"]]:o;return Zo(t).some(i=>{if(!e.toLowerCase().startsWith(`${i.toLowerCase()}/`))return!1;let l=e.slice(i.length+1).replace(/(?<!\/)\/+$/,"").split("/");return a.some(c=>c.length===l.length&&l.every((u,f)=>r(u,c[f])))})}function ar(e,t,n=null){if(!S(e))return!1;let s=e.indexOf(ie),r=s>0?e.slice(0,s).replace(/(?<!\/)\/+$/,"").toLowerCase():"";if(r&&!Zo(t).some(u=>`${u.toLowerCase()}/projects`.startsWith(r)||r.startsWith(`${u.toLowerCase()}/projects`)))return!1;let o=k(e);if(n!==null&&!S(n)&&/\.jsonl|\b(ls|find)\b|\*/.test(o)&&St(n.replace(/(?<!\/)\/+$/,""),t))return!/\/memory(\/|$)/i.test(o);if(!o.toLowerCase().includes("/projects"))return!1;let a=t.home.replace(/(?<!\/)\/+$/,""),i=t.claudeConfigDir&&!S(t.claudeConfigDir)?t.claudeConfigDir.replace(/(?<!\/)\/+$/,""):null,l=u=>u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(?:(?:~|\\$\\{?HOME\\}?|${l(a)})["']?/\\.claude${i?`|${l(i)}["']?`:""})/projects(?:/[^\\s'"|;&)<>]*)?`,"gi");for(let u of o.matchAll(c)){let f=o.slice(u.index);if(!(/\/memory\//i.test(f)&&!/(^|\/)\.\.(\/|$)/.test(f)))return!0}return!1}function xy(e,t){return e.name==="find"||e.name==="gfind"?iu(e,t)!==null:e.argv.slice(1).some(n=>{if(n.startsWith("-"))return!1;let s=k(M(n,e.cwd,t.ctx));return ar(n,t.ctx,e.cwd)||St(s,t.ctx)||ir(s,t.ctx,!0)})}function _y(e){return`writes Claude Code's record of a session (${R.basename(e)||e})`}var Sy=["3f2a9c1e-5d4b-4a7e-9b1c-2e8f6a0d7c35.jsonl","3f2a9c1e-5d4b-4a7e-9b1c-2e8f6a0d7c35","agent-a1b2c3.jsonl","journal.jsonl","subagents","workflows","-Users-dev-app","projects"];function Cy(e,t){let n=e.argv.slice(1),s=n.findIndex(l=>/^-(exec|execdir|ok|okdir)$/.test(l)),r=n.findIndex((l,c)=>c>s&&(l===";"||l==="+")),o=s<0?[]:n.slice(s+1,r<0?void 0:r),a=n.find((l,c)=>/^-(fprint0?|fprintf|fls)$/.test(n[c-1]??"")&&St(k(M(l,e.cwd,t.ctx)),t.ctx,!1));if(a!==void 0)return k(M(a,e.cwd,t.ctx));let i=n.includes("-delete");return!i&&!(o.length>0&&ou(o,o.at(-1)==="{}"))||(i||/^(rm|unlink)$/.test(ue(o[0]??"")))&&ru(n,i?n.indexOf("-delete"):s)?null:iu(e,t)}function ru(e,t){let n=e.findIndex((s,r)=>e[r-1]==="-mtime"&&/^\+([7-9]|[1-9]\d+)$/.test(s)||e[r-1]==="-mmin"&&/^\+\d+$/.test(s)&&Number(s.slice(1))>=10080);return n>0&&n<t&&!["!","-not"].includes(e[n-2]??"")&&!e.some(s=>["-o","-or","(",")",","].includes(s))}function ou(e,t){let n=ue(e[0]??""),s=e.slice(1);if(/^(rm|unlink|shred|srm|trash|truncate|tee|dd|touch|chmod|chown|chflags|xattr|setfacl|g?mv|ed|ex|sponge)$/.test(n))return!0;if(/^(g?sed|perl)$/.test(n))return s.some(o=>/^-[a-zA-Z]*i/.test(o)||o.startsWith("--in-place"));if(/^g?awk$/.test(n))return s.some((o,a)=>o==="inplace"&&s[a-1]==="-i");if(/^(g?cp|install|rsync|ln|ditto)$/.test(n))return t&&!s.some(o=>o==="-t"||o.startsWith("--target-directory"));let r=/^(ba|z|da|k)?sh$/.test(n)?s.indexOf("-c"):-1;return r>=0&&/[>]|\b(rm|truncate|tee|g?mv|dd|touch|sed\s+-[a-zA-Z]*i|perl\s+-[a-zA-Z]*i)\b/.test(s[r+1]??"")}function iu(e,t){let n=e.argv.slice(1),s=[],r=0;for(;r<n.length&&/^-[HLPEXdsx]$/.test(n[r]);)r++;for(;r<n.length&&!/^[-(!]/.test(n[r]);r++)s.push(n[r]);s.length===0&&s.push(".");let o=n.flatMap((f,p)=>p>0&&["-name","-iname"].includes(n[p-1])?[{f,i:n[p-1]==="-iname"}]:[]),a=o.length===0||o.some(({f,i:p})=>Sy.some(d=>Go(p?f.toLowerCase():f).test(p?d.toLowerCase():d))),i=n.flatMap((f,p)=>p>0&&["-path","-ipath","-wholename","-iwholename"].includes(n[p-1])?[f]:[]);if(!a||i.length>0&&i.every(f=>/memory/i.test(f)))return null;let l=t.ctx.home.replace(/(?<!\/)\/+$/,"").toLowerCase(),c=t.ctx.claudeConfigDir&&!S(t.ctx.claudeConfigDir)?t.ctx.claudeConfigDir.replace(/(?<!\/)\/+$/,"").toLowerCase():null,u=[`${l}/.claude/projects`,...c?[`${c}/projects`]:[]];for(let f of s){if(S(f)&&!f.startsWith("/"))continue;let p=M(f,e.cwd,t.ctx).replace(/(?<!\/)\/+$/,"");if(S(p))continue;let d=p.toLowerCase();if(u.some(h=>d===h||h.startsWith(`${d}/`)||d==="/"||d.startsWith(`${h}/`)&&!/\/memory(\/|$)/.test(d)))return k(p)}return null}function so(e,t,n,s=!0){let r=k(e);if(s&&(St(r,t,s===!0)||ir(r,t,s===!0)))return"agent";let o=n.filter(f=>f!==null&&f!==""&&!S(f)),a=r.toLowerCase();if((o.length>1?[...new Set(o)].map(f=>a.startsWith(`${f.toLowerCase()}/`)?r.slice(f.length):null).filter(f=>f!==null):[r.replace(/^.*(?=\/\.claude(\/|\.json$|$)|\/\.mcp\.json$|\/\.anvil(\/|$))/,"")]).some(f=>by.test(f))||wy.test(r))return"agent";let l=t.claudeConfigDir?.replace(/(?<!\/)\/+$/,"").toLowerCase();if(l&&(a===l||a===`${l}/settings.json`||a===`${l}/settings.local.json`||a===`${l}/.claude.json`||a===`${l}/hooks`||a.startsWith(`${l}/hooks/`)||a===`${l}/plugins`||a.startsWith(`${l}/plugins/`)))return"agent";let c=R.dirname(r);if(Do(c)||X(c,null,{home:t.home,tmpdir:t.tmpdir,projectRoot:null}).kind==="disposable")return null;if(ky.test(r.toLowerCase()))return"jobs";let u=t.home;return[`${u}/.gitconfig`,`${u}/.config/git/config`,"/etc/gitconfig"].some(f=>f.toLowerCase()===a)?"gitconfig":null}function Ay(e,t){let n=[],s=a=>{a&&a!=="-"&&!a.startsWith("/dev/")&&n.push(M(Ie(a,e,t),e.cwd,t.ctx))};for(let a of e.redirects)a.target&&a.op.includes(">")&&!(a.op.endsWith("&")&&/^(\d+|-)$/.test(a.target))&&s(a.target);let r=e.argv.slice(1),o=r.filter(a=>!a.startsWith("-"));switch(e.name){case"tee":case"sponge":case"truncate":case"rm":case"unlink":case"trash":case"srm":case"shred":case"mkfifo":o.forEach(s);break;case"mknod":o[0]&&s(o[0]);break;case"touch":for(let a=0;a<r.length;a++)/^(-[tdrA]|--(date|reference|time))$/.test(r[a])?a++:r[a].startsWith("-")||s(r[a]);break;case"cp":case"mv":case"install":case"ln":case"ditto":case"gcp":case"gmv":{let a=P(e.argv,"-t","--target-directory"),i=a!==null?o.filter(c=>c!==a):o.slice(0,-1),l=a??(o.length>=2?o[o.length-1]:e.name==="ln"&&o.length===1?".":null);if(l!==null){s(l);for(let c of i)s(R.join(l,R.basename(k(c))))}e.name==="ln"&&i.forEach(s),(e.name==="mv"||e.name==="gmv")&&i.forEach(s);break}case"sed":case"gsed":case"perl":case"ruby":case"yq":{if(!r.some(c=>c==="--in-place"||c.startsWith("--in-place=")||c==="--inplace"||/^-[A-Za-z]*i/.test(c)&&!c.startsWith("--")))break;let i=[],l=!1;for(let c=0;c<r.length;c++){let u=r[c];["-e","--expression","-f","--file"].includes(u)||(e.name==="perl"||e.name==="ruby")&&/^-[A-Za-z]*e$/.test(u)?(l=!0,c++):u.startsWith("-")||i.push(u)}(l?i:i.slice(1)).forEach(s);break}case"dd":s(r.find(a=>a.startsWith("of="))?.slice(3));break;case"chmod":case"chown":case"chgrp":case"chflags":if(e.name==="chmod"){let a=r.filter(i=>!/^-[RHLPfhvcECNiI]+$/.test(i)&&!i.startsWith("--"));(r.some(i=>i.startsWith("--reference"))?a:a.slice(1)).forEach(s)}else(r.some(a=>a.startsWith("--reference"))?o:o.slice(1)).forEach(s);break;case"curl":s(P(e.argv,"-o","--output")??Bs(e.argv,"o"));break;case"scp":{let a=new Set(["-P","-i","-F","-o","-c","-l","-S","-J","-D","-X"]),i=r.filter((c,u)=>!c.startsWith("-")&&!a.has(r[u-1]??"")),l=i.length>=2?i[i.length-1]:null;l!==null&&!/^[^/]*:/.test(l)&&s(l);break}case"wget":s(P(e.argv,"-O","--output-document")??Bs(e.argv,"O")??P(e.argv,"-P","--directory-prefix"));break;case"rsync":{let a=pe(e.argv,1,Ko),i=a.length>=2?a[a.length-1]:null;if(i!==null&&!Te(i)){s(i);for(let l of a.slice(0,-1))s(R.join(i,R.basename(k(l).replace(/(?<!\/)\/+$/,""))))}break}case"tar":case"gtar":case"bsdtar":case"unzip":{let a=e.name==="unzip"?P(e.argv,"-d"):P(e.argv,"-C","--directory");(e.name==="unzip"?!r.some(l=>/^-[A-Za-z]*[ltpZ]/.test(l)):r.some(l=>/^-?[A-Za-z]*x/.test(l)||l==="--extract"||l==="--get"))&&s(a??".");break}case"7z":case"7za":case"7zr":case"7zz":["x","e"].includes(o[0]??"")&&s(r.find(a=>a.startsWith("-o"))?.slice(2)||".");break;case"sort":s(P(e.argv,"-o","--output")??Bs(e.argv,"o"));break;case"base64":s(P(e.argv,"-o","--output"));break;case"openssl":s(P(e.argv,"-out"));break;case"awk":case"gawk":case"mawk":case"nawk":{let a=Mr(e.argv)??"";if(r.some((i,l)=>i==="-i"&&r[l+1]==="inplace"||i==="-iinplace"||i==="--include=inplace")){let i=pe(e.argv,1,new Set(["-i","--include","-F","-v","-f","-e","-l"]));(a&&i[0]===a?i.slice(1):i).forEach(s)}for(let i of a.matchAll(/\b(?:print|printf)\b(?:"(?:\\.|[^"\\])*"|[^;}|"])*?>{1,2}\s*"((?:\\.|[^"\\])+)"/g))s(i[1]);break}case"ed":case"red":case"ex":case"vi":case"vim":case"nvim":case"emacs":{if(r.some(i=>i==="-R"||i==="-M"||i==="--read-only")||e.name==="emacs"&&!r.some(i=>i==="--batch"||i==="-batch"||i==="--script"))break;let a=e.name==="ed"||e.name==="red"?new Set(["-p"]):new Set(["-c","--cmd","-S","-u","-U","-i","-T","-w","-W","-t","-q","--eval","-l","--load","-f","--funcall","--script"]);pe(e.argv,1,a).filter(i=>!i.startsWith("+")).forEach(s);break}case"patch":s(pe(e.argv,1,new Set(["-i","--input","-p","-d","-o","--output","-r","-B","-z","-V","-F"]))[0]);break;case"plutil":r.some(a=>/^-(replace|insert|remove|convert)$/.test(a))&&s(o[o.length-1]);break;case"git":{let a=_t(e);if(a&&a.sub==="clone"&&s(pe(["git",...a.args],1,new Set(["-b","--branch","-o","--origin","--depth","-c","--config","--reference","--template","-j","--jobs","--filter"]))[1]),a&&["checkout","restore"].includes(a.sub)){let i=a.args.indexOf("--");(a.sub==="restore"&&a.args.some(u=>u==="--staged"||u==="-S")&&!a.args.some(u=>u==="--worktree"||u==="-W")?[]:i>=0?a.args.slice(i+1):a.sub==="restore"?a.args.filter(u=>!u.startsWith("-")):[]).forEach(s)}break}default:break}return n}var au=/permissionMode:\s*['"]?bypassPermissions\b|allowed-tools:[^\n]*\bBash(\(\*\))?(?![\w(])|allowed-tools:[ \t]*\n(?:[ \t]*-[^\n]*\n)*?[ \t]*-[ \t]*['"]?Bash(\(\*\))?['"]?[ \t]*(?:\n|$)/;function Rl(e){if(!e||typeof e!="object")return"";let t=e,n=Array.isArray(t.edits)?t.edits.map(s=>s&&typeof s=="object"&&typeof s.new_string=="string"?s.new_string:""):[];return[t.content,t.new_string,...n].filter(s=>typeof s=="string").join(`
|
|
59
|
+
`)}function Ey(e,t){for(let[n,s]of Object.entries(t.controlLinks??{}))if(e===n||e.startsWith(`${n}/`))return s+e.slice(n.length);return e}function lu(e,t){if(/(^|\/)\.claude\/(agents|commands|skills)\//i.test(e))return!0;let n=t.claudeConfigDir?.replace(/(?<!\/)\/+$/,"");return!!n&&e.startsWith(`${n}/`)&&/^(agents|commands|skills)\//i.test(e.slice(n.length+1))}function Ol(e,t){if(S(e))return!1;let n=e.replace(/(?<!\/)\/+$/,""),s=t.home.replace(/(?<!\/)\/+$/,""),r=t.claudeConfigDir?.replace(/(?<!\/)\/+$/,"");return[`${s}/.claude`,`${s}/.anvil`,...r?[r]:[],...Object.keys(t.controlLinks??{})].some(a=>n===""||a.startsWith(`${n}/`))}var Ry=/(^|\/)\.(zshrc|zshenv|zprofile|zlogin|bashrc|bash_profile|bash_login|bash_aliases|bash_functions|zsh_aliases|aliases|profile|envrc|zshrc\.local|bashrc\.local)$|(^|\/)\.(bashrc|zshrc)\.d\/.+$|(^|\/)\.oh-my-zsh\/custom\/.+\.zsh$|(^|\/)\.zsh\/.+\.zsh$|(^|\/)\.config\/fish\/(config\.fish|conf\.d\/.+\.fish|functions\/.+\.fish)$/,Oy=/(^|\/)[Dd]ocuments\/(?:[Ww]indows)?[Pp]ower[Ss]hell\/[^/]*[Pp]rofile\.ps1$/,ot={test:e=>Ry.test(e)||V()&&Oy.test(e)};function jy(e,t){let n=k(e),s=t.ctx.home.replace(/(?<!\/)\/+$/,"");if(S(e)||!n.startsWith(`${s}/`)||!ot.test(n)||/(^|\/)\.envrc$/.test(n))return!1;let r=t.projectRoot;return r&&!S(r)&&r!==s&&n.startsWith(`${r}/`)?!1:X(R.dirname(n),null,{home:t.ctx.home,tmpdir:t.ctx.tmpdir,projectRoot:null}).kind!=="disposable"}function Py(e,t,n){let s=k(e);if(t.remote!==null||S(e)||$t(t)||!/^\/usr\/local\/./.test(s))return!1;let r=it(n,{kind:"owner",arg:s});return typeof r=="string"&&/^\d+$/.test(r)&&r!=="0"}var Wy=/^\/(etc|usr|bin|sbin|lib|lib32|lib64|libexec|boot|System|Library|root|private\/etc)(\/|$)/;function Ny(e){let t=k(e);return!S(e)&&Wy.test(t)&&!/^\/(etc|private\/etc)$|^\/usr$/.test(t)}function Ly(e,t){let n=k(e);if(S(e))return!1;let s=t.ctx.home.replace(/(?<!\/)\/+$/,"");return/^\/(private\/)?etc\/(profile|bashrc|bash\.bashrc|zshrc|zshenv|zprofile|zlogin|environment)$|^\/(private\/)?etc\/profile\.d\//.test(n)?!0:ot.test(n)&&/^\/(root|home\/[^/]+|Users\/[^/]+)\//.test(n)&&!n.startsWith(`${s}/`)&&!/(^|\/)\.envrc$/.test(n)}function pn(e){return Ty.test(e.replace(/\\[ntr]/g,`
|
|
60
|
+
`))}var Ty=/\b(CLAUDE_CONFIG_DIR|ANVIL_CLAUDE_SYNC|CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE|ANVIL_WORKSPACE_KEYS_PATH)\b|\balias\s+['"]?claude=|\bclaude\s*\(\s*\)|\bfunction\s+claude\b/;function vo(e){let t=e.pipeFrom,n=e.stdin??(["echo","printf","sed"].includes(e.name)?e.argv.slice(1).join(`
|
|
61
|
+
`):t&&["echo","printf","cat"].includes(t.name)?t.stdin??t.argv.slice(1).join(`
|
|
62
|
+
`):null),s=(e.groupWriters??[]).map(r=>vo(r)??"").filter(Boolean).join(`
|
|
63
|
+
`);return n??(s!==""?s:null)}function Iy(e){let t=e.argv.slice(1),n=t.filter(r=>!r.startsWith("-")),s=r=>S(r)||r==="."||/\/\.?$/.test(r)||/[*?[]/.test(r);switch(e.name){case"cp":case"gcp":{if(!t.some(i=>i==="--recursive"||i==="--archive"||/^-[A-Za-z]*[rRa]/.test(i)&&!i.startsWith("--")))return[];let r=P(e.argv,"-t","--target-directory"),o=r!==null?n.filter(i=>i!==r):n.slice(0,-1),a=r??(n.length>=2?n[n.length-1]:null);return a!==null&&o.some(s)?[a]:[]}case"ditto":return n.length>=2?[n[n.length-1]]:[];case"rsync":{let r=pe(e.argv,1,Ko),o=r.length>=2?r[r.length-1]:null;return o!==null&&!Te(o)&&r.slice(0,-1).some(s)?[o]:[]}case"7z":case"7za":case"7zr":case"7zz":return["x","e"].includes(n[0]??"")?[t.find(r=>r.startsWith("-o"))?.slice(2)||"."]:[];default:{if(e.name==="unar")return[P(e.argv,"-o","-output-directory")??"."];if(e.name==="jar")return/^-?[a-z]*x/.test(t[0]??"")||t.includes("--extract")?[P(e.argv,"-C","--dir")??"."]:[];if(e.name==="cpio"||e.name==="bsdcpio")return t.some(i=>i==="--extract"||/^-[A-Za-z]*i/.test(i))?[P(e.argv,"-D","--directory")??"."]:[];if(e.name==="pax")return t.some(i=>/^-[A-Za-z]*r/.test(i))?["."]:[];if(!/^python(\d+(\.\d+)?)?$/.test(e.name))return[];let r=t.indexOf("-m");if(r<0||!["zipfile","tarfile"].includes(t[r+1]??""))return[];let o=t.slice(r+2),a=o.findIndex(i=>i==="-e"||i==="--extract");return a<0?[]:[o.slice(a+1).filter(i=>!i.startsWith("-"))[1]??"."]}}}function tr(e,t){let n=[],s=Vy(e,t).find(d=>hu(d,t));if(s!==void 0){let d=k(s),h=t.ctx.home.replace(/(?<!\/)\/+$/,""),g=d===h?"~":d.startsWith(`${h}/`)?`~${d.slice(h.length)}`:d;return[m("claude.agent.controls",`links to a folder that holds Anvil's or Claude Code's settings (${g})`,{target:d,is_local:!0})]}for(let d of Iy(e)){if(S(d)&&!d.startsWith("/"))continue;let h=M(d,e.cwd,t.ctx),g=St(k(h),t.ctx);if(!Ol(h,t.ctx)&&!g)continue;let y=t.ctx.home.replace(/(?<!\/)\/+$/,""),$=k(h).length;for(;$>1&&k(h)[$-1]==="/";)$--;let E=k(h).slice(0,$),x=E===y?"~":E.startsWith(`${y}/`)?`~${E.slice(y.length)}`:E;return[m("claude.agent.controls",`${e.name} writes what it copies or unpacks into a folder that holds ${g?"Claude Code's records of sessions":"Anvil's or Claude Code's settings"} (${x})`,{target:E,is_local:!0})]}let r=Hy(e);e.via==="xargs"&&!Bn.has(e.name)&&cn(t,`${ie}(paths ${e.name} reads from xargs)${le}`,e.cwd),(e.name==="git"?_t(e)?.sub==="apply"&&!e.argv.some(d=>/^--(?:check|stat|numstat|summary)$/.test(d)):e.name==="patch"&&!e.argv.some(d=>d==="--dry-run"||d==="-C"||d==="--check"))&&cn(t,`${ie}(paths the patch names)${le}`,e.cwd);let a=["rm","trash","srm","shred","mv","gmv"].includes(e.name),i=a||/^((g|bsd)?tar|unzip|7z[arz]?|unar|jar|(bsd)?cpio|pax)$/.test(e.name)||"files",l=e.via==="xargs"?e.parent?.pipeFrom??e.pipeFrom:null,c=l!==null&&/^(rm|unlink)$/.test(e.name)&&/^g?find$/.test(l.name)&&ru(l.argv.slice(1),l.argv.length);l&&!c&&ou(e.argv,!e.argv.includes("{}")||e.argv.at(-1)==="{}")&&xy(l,t)&&n.push(m("claude.agent.controls",`${e.name} changes Claude Code's records of sessions (a listing of its projects folder, through xargs)`,{target:k(l.argv.slice(1).join(" ")).slice(0,200),is_local:!0}));let u=r.argv.slice(1),f=["mv","gmv"].includes(e.name)?P(r.argv,"-t","--target-directory")??u.filter(d=>!d.startsWith("-")).at(-1)??null:null,p=new Set(f!==null&&!S(f)?[M(f,e.cwd,t.ctx),M(f,e.cwd,t.ctx).replace(/(?<!\/)\/+$/,"")]:[]);for(let d of Ay(r,t)){if(cn(t,d,e.cwd),ar(d,t.ctx,e.cwd)){n.push(m("claude.agent.controls","writes Claude Code's record of a session (a file a listing of its projects folder names)",{target:k(d).slice(0,200),is_local:!0}));continue}if(a&&!p.has(d)&&Ol(d,t.ctx)){n.push(m("claude.agent.controls",`${e.name} takes a folder that holds the agent's controls (${k(d)})`,{target:k(d),is_local:!0}));continue}let h=pu(d,t.ctx,[t.ctx.home,t.projectRoot,t.base],i).find(E=>E!==d);if(h!==void 0){n.push(m("claude.agent.controls",Vs(k(h),t.ctx),{target:k(h),is_local:!0}));continue}if(ot.test(d)&&pn(vo(e)??"")){n.push(m("claude.agent.controls",`changes how every later Claude Code session starts (${R.basename(k(d))})`,{target:k(d),is_local:!0}));continue}if(Jp.test(d)&&!kt(d,t)){n.push(m("claude.bash.git.discard",`rewrites git's own records (${k(d).split("/.git/").pop()})`,{target:k(d),is_local:!0}));continue}if(lu(d,t.ctx)){let E=vo(e);if(E!==null&&au.test(E)){n.push(m("claude.agent.controls",`gives a subagent, command or skill its own bypass or unrestricted shell (${R.basename(k(d))})`,{target:k(d),is_local:!0}));continue}}let{place:g,at:y}=Vo(d,t.ctx,[t.ctx.home,t.projectRoot,t.base],i),$=k(y);if(g===null&&jy(d,t)){n.push(m("claude.bash.persistence",`changes a shell startup file (${R.basename(k(d))}), which runs in every new shell`,{target:k(d),is_local:e.remote===null,host:e.remote}));continue}if(g===null&&Ly(d,t)){n.push(m("claude.bash.persistence",`changes a shell startup file outside your own home (${k(d)}), which runs in other users' shells`,{target:k(d),is_local:e.remote===null,host:e.remote}));continue}if(g===null&&Ny(d)&&!Py(d,e,t)){let E=["rm","trash","srm","shred","unlink"].includes(e.name);n.push(m(E?"claude.bash.fs.delete_recursive":"claude.bash.privilege",`${E?"deletes":"changes"} a system file (${k(d)})`,{target:k(d),is_local:e.remote===null,host:e.remote}));continue}g==="agent"?n.push(m("claude.agent.controls",Vs($,t.ctx),{target:$,is_local:!0})):g==="jobs"?n.push(m("claude.bash.persistence",`installs or changes a background job (${$})`,{target:$,is_local:e.remote===null,host:e.remote})):g==="gitconfig"&&n.push(m("claude.bash.persistence",`rewrites the global git config (${$})`,{target:$,is_local:!0}))}if(!n.some(d=>d.action==="claude.agent.controls")&&!Bn.has(e.name)&&pn(`${e.argv.join(`
|
|
64
64
|
`)}
|
|
65
|
-
${e.stdin??""}`)){let
|
|
66
|
-
`);if(
|
|
67
|
-
`)}return null}function Yc(e){return e===null?[]:[...e.slice(0,262144).matchAll(/^(?:---|\+\+\+)\s+(\S+)/gm)].map(n=>n[1]).filter(n=>n!=="/dev/null").flatMap(n=>/^[ab]\//.test(n)?[n,n.slice(2)]:[n])}function vy(e,n){let t=[],s=0;for(;s<n.length&&n[s].startsWith("-");s++){let a=n[s];if(a==="-C"||a==="--work-tree"||a==="--git-dir")t.push(n[++s]??"");else if(a==="-c"){let l=n[++s]??"";/^core\.worktree=/i.test(l)&&t.push(l.slice(l.indexOf("=")+1))}else(a.startsWith("--work-tree=")||a.startsWith("--git-dir="))&&t.push(a.slice(a.indexOf("=")+1))}for(let a of e.text.matchAll(/\bGIT_(?:WORK_TREE|DIR)=("[^"]*"|'[^']*'|[^\s;&|]+)/g))t.push(a[1].replace(/^["']|["']$/g,""));let r=n[s]??"",o=n.slice(s+1);if(r==="stash"&&["list","show"].includes(o[0]??"")||r==="worktree"&&(o[0]??"")==="list"||r==="apply"&&o.some(a=>["--check","--stat","--numstat","--summary"].includes(a)))return null;if(r==="apply"||r==="am")return{names:[...t,...o,...Yc(Kc(e))],cwd:!0};let i=r==="restore"&&o.some(a=>a==="--staged"||a==="-S")&&!o.some(a=>a==="--worktree"||a==="-W")||r==="reset"&&!o.some(a=>a==="--hard"||a==="--merge"||a==="--keep")||r==="rm"&&o.includes("--cached");return by.has(r)||i?null:{names:[...t,...t.length===0&&e.cwd!==null?[e.cwd]:[],...o],cwd:!0}}function $y(e){let n=t=>{if(/[\s"']/.test(t))return!1;let s=t.indexOf("{"),r=s<0?-1:t.indexOf(",",s+1);return r>s&&t.lastIndexOf("}")>r};return e.argv.slice(1).some(n)?{...e,argv:[e.argv[0],...e.argv.slice(1).flatMap(t=>n(t)?Jc(t):[t])].slice(0,256)}:e}function Jc(e){if(!e.includes("{"))return[e];let n=[],t=[e];for(let s=0;t.length>0&&n.length<64&&s<256;s++){let r=t.shift(),o=r.indexOf("{"),i=-1,a=[];for(let c=o,u=0;o>=0&&c<r.length;c++)if(r[c]==="{")u++;else if(r[c]==="}"&&--u===0){i=c;break}else r[c]===","&&u===1&&a.push(c);if(o<0||i<0||a.length===0){n.push(r);continue}let l=[o,...a,i];for(let c=0;c+1<l.length;c++)t.push(r.slice(0,o)+r.slice(l[c]+1,l[c+1])+r.slice(i+1))}return n.length>0?n:[e]}function _y(e){let n=/^[*?[]/.test(e)?"(?!\\.)":"";for(let t=0;t<e.length;t++){let s=e[t];if(s==="*")n+="[^/]*";else if(s==="?")n+="[^/]";else if(s==="["){let r=e.indexOf("]",t+2);r<0?n+="\\[":(n+=`[${e.slice(t+1,r).replace(/^!/,"^").replace(/\\/g,"\\\\")}]`,t=r)}else n+=s.replace(/[.+^${}()|\\]/g,"\\$&")}try{return new RegExp(`^${n}$`)}catch{return new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`)}}function Xc(e,n){let t=[...new Set(n.filter(o=>typeof o=="string"&&o.startsWith("/")&&!C(o)).map(o=>o.replace(/(?<!\/)\/+$/,"")))],s=e.claudeConfigDir&&!C(e.claudeConfigDir)?e.claudeConfigDir.replace(/(?<!\/)\/+$/,""):null,r=e.home.replace(/(?<!\/)\/+$/,"");return{files:[...t.flatMap(o=>[`${o}/.claude/settings.json`,`${o}/.claude/settings.local.json`,`${o}/.claude.json`,`${o}/.mcp.json`,`${o}/.claude`]),`${r}/.anvil`,`${r}/.anvil/rules.json`,`${r}/.anvil/rules.md`,`${r}/.anvil/workspace-keys.json`,`${r}/.anvil/telemetry-notice`,...s?[s,`${s}/settings.json`,`${s}/settings.local.json`,`${s}/.claude.json`]:[]],folders:[...t.flatMap(o=>[`${o}/.claude/hooks`,`${o}/.claude/plugins`]),`${r}/.anvil/claude`,...s?[`${s}/hooks`,`${s}/plugins`]:[]]}}function Qc(e,n,t){let s=[];for(let r of Jc(e)){if(!/[*?[]/.test(r)){Io(r,n,t)==="agent"&&s.push(r);continue}let o=r.split("/"),i=o.map(_y),a=(u,d)=>{let p=u.split("/");return(d?o.length>p.length:o.length===p.length)&&p.every((f,h)=>i[h].test(f))},l=Xc(n,t),c=l.files.find(u=>a(u,!1))??l.folders.find(u=>a(u,!1)||a(u,!0));c!==void 0&&s.push(c)}return s}function xy(e,n){let t=[n.ctx.home,n.projectRoot,n.base],s=e.cwd!==null&&!C(e.cwd)?e.cwd.replace(/(?<!\/)\/+$/,""):null,r=s!==null&&Xc(n.ctx,t).folders.some(c=>s===c||s.startsWith(`${c}/`)),o=c=>{if(c.startsWith("-")&&!c.includes("=")&&!/[~/]/.test(c))return null;let u=c.startsWith("-")?c.includes("=")?c.slice(c.indexOf("=")+1):c.slice(Math.max(0,c.search(/[~/]/))):c,d=/^(\/|~|\.\.?\/)/.test(u)||!/\s/.test(u)&&(/^\.[\w-]/.test(u)||u.includes("/")||/^[\w.-]+$/.test(u));return!u||C(u)&&!u.startsWith("/")||!d?null:Qc(U(u,e.cwd,n.ctx),n.ctx,t)[0]??null};for(let c of e.wrapperArgs){let u=o(c);if(u!==null)return u}let i=ky(e,n.ctx.claudeConfigDir&&!C(n.ctx.claudeConfigDir)?n.ctx.claudeConfigDir.replace(/(?<!\/)\/+$/,""):null);if(i===null)return null;let a=n.ctx.home.replace(/(?<!\/)\/+$/,"");if(e.name==="git"&&yy.has(xt(e)?.sub??""))for(let c of i.names){if(C(c))continue;let u=U(c,e.cwd,n.ctx).replace(/(?<!\/)\/+$/,"");if(u===a)return`${a}/.claude`;let d=Object.entries(n.ctx.controlLinks??{}).find(([p])=>p.startsWith(`${u}/`));if(d)return d[1]}let l=dg(e);for(let c of i.names){let u=l.has(c)?Dt(n,()=>o(c)):o(c);if(u!==null)return u}return i.cwd&&r?s:null}function Sy(e,n){let t=e.argv.slice(1),s=t.some(d=>d==="--symbolic"||/^-[a-zA-Z]*s/.test(d));if(e.name==="ln"?!s:!(["cp","gcp"].includes(e.name)&&t.some(d=>d==="--symbolic-link"||d==="--link"||/^-[a-zA-Z]*[sl]/.test(d))))return[];let r=new Set(["-t","--target-directory","-S","--suffix"]),o=t.filter((d,p)=>!d.startsWith("-")&&!r.has(t[p-1]??"")),i=j(e.argv,"-t","--target-directory"),a=i!==null||o.length===1?o:o.slice(0,-1),l=i??(o.length>=2?o[o.length-1]:"."),c=e.name==="ln"&&!C(l)?U(l,e.cwd,n.ctx):null,u=c===null?[e.cwd]:i!==null||o.length<2?[c]:[R.dirname(c),c];return a.filter(d=>!C(d)).flatMap(d=>(d.startsWith("/")||d.startsWith("~")?[e.cwd]:u).map(p=>U(d,p,n.ctx)))}var Cy=["/Library/Application Support/ClaudeCode","/etc/claude-code","/c/program files/claudecode"];function eu(e,n){if(Io(e,n.ctx,[n.ctx.home,n.projectRoot,n.base])==="agent")return!0;let t=v(e).replace(/(?<!\/)\/+$/,"").toLowerCase();return[n.ctx.home,n.ctx.claudeConfigDir??null,...Cy].filter(r=>typeof r=="string"&&r.startsWith("/")&&!C(r)).map(r=>r.replace(/(?<!\/)\/+$/,"").toLowerCase()).some(r=>r===t||r.startsWith(`${t}/`)||t==="")}function qs(e){return/(^|\/)\.anvil(\/|$)/.test(e)?`changes Anvil's checks on this agent (${R.basename(e)})`:`changes Claude Code's own permissions, hooks or MCP servers (${R.basename(e)})`}function Bn(e,n,t=[]){let s=[...t].reverse().find(a=>typeof a=="string"&&a.startsWith("/")&&!C(a))??null,r=e.startsWith("/")||e.startsWith("~")?U(e,null,n):s!==null?U(e,s,n):e,{place:o,at:i}=Do(r,n,[n.home,...t]);return o==="agent"?{action:"claude.agent.controls",service:null,target:i,branch:null,host:null,is_local:!0,why:qs(i)}:o==="jobs"?{action:"claude.bash.persistence",service:null,target:i,branch:null,host:null,is_local:!0,why:`installs or changes a background job (${i})`}:o==="gitconfig"?{action:"claude.bash.persistence",service:null,target:i,branch:null,host:null,is_local:!0,why:`rewrites the global git config (${i})`}:null}var Ay=new Set(["-m","--message","-F","--file","-C","--reuse-message","-c","--reedit-message","--author","--date","--fixup","--squash","--cleanup","-t","--template","--trailer","--pathspec-from-file"]);function Ey(e,n){if(e.name!=="git")return[];let t=xt(e);if(!t||!["add","stage","commit"].includes(t.sub))return[];let s=t.sub==="commit";if(t.args.includes("--dry-run")||!s&&t.args.some(c=>/^-[A-Za-z]*n[A-Za-z]*$/.test(c)))return[];let r=e.via==="find-exec"&&e.parent?.name==="find"?bo(e.parent)[0]??null:null,o=[],i=!1;for(let c=0;c<t.args.length;c++){let u=t.args[c];!i&&u==="--"?i=!0:!i&&u.startsWith("-")?(s&&(Ay.has(u)||/^-[A-Za-z]*[mFCct]$/.test(u))||!s&&(u==="--chmod"||u==="--pathspec-from-file"))&&c++:o.push(u==="{}"&&r!==null?r:u)}e.via==="xargs"&&o.push(...au(e));let a=o.filter(c=>!/^:(!|\^|\([^)]*exclude[^)]*\))/.test(c)).map(c=>c.replace(/^:(\([^)]*\)|\/)?/,"")).flatMap(Un).sort((c,u)=>Number(/key|priv/i.test(u))-Number(/key|priv/i.test(c))).find(c=>Te(c,!0)||n.secretCopies.has(Y(c,e.cwd,te(n)).path));if(!a)return[];let l=Ft(e,t,n);return l!==null&&kt(l,n)?[]:[m("claude.bash.secrets.expose",`git ${t.sub} ${s?"commits":"stages"} a secrets file (${R.basename(v(a))})`,{target:v(a),is_local:!0})]}function Le(e){return/^(scp|sftp|rsync):\/\//.test(e)||/^[^\s/:=]+:/.test(e)&&!/^[A-Za-z]:\\/.test(e)&&!/^[a-z]+:\/\//i.test(e)}function Vn(e){let n=/^(?:[a-z]+:\/\/)?(?:[^@/:]+@)?(\[[^\]]+\]|[^:/]+)/i.exec(e);return n?n[1]:e}function ce(e,n,t){let s=[];for(let r=n;r<e.length;r++){let o=e[r];if(o==="--"){s.push(...e.slice(r+1));break}o.startsWith("-")&&o!=="-"?t.has(o)&&r++:s.push(o)}return s}var Ry=new Set(["-i","-P","-o","-F","-c","-l","-S","-J","-D","-X"]),Fo=new Set(["-e","--rsh","-f","--filter","--exclude","--include","--files-from","--exclude-from","--include-from","--port","--password-file","-B","--block-size","--bwlimit","--log-file","--partial-dir","-T","--temp-dir","--chmod","--chown","--backup-dir","--suffix","--compare-dest","--link-dest","--copy-dest","--max-size","--min-size","--timeout","-M","--remote-option","--rsync-path"]),Oy=new Set(["-o","-h","-u"]),Py=new Set(["-B","-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w"]),jy=new Set(["-B","-b","-c","-D","-F","-i","-J","-l","-o","-P","-R","-S","-s","-X"]),Wy=new Set(["-w","-p","-s","-i","-q","-x","-X","-O","-I","-V","-T","-e","-c","-W","-M","-m","-g","-G"]);function Ny(e){let n=e.pipeFrom;if(!n)return null;if(Js.has(n.name)||["tar","gtar","zip","gzip"].includes(n.name)){let t=(["tar","gtar","zip","gzip"].includes(n.name)?n.argv.slice(1).filter(s=>!s.startsWith("-")):Ut(n)).find(s=>Te(s));if(t)return t}return n.stdinFile!==null&&Te(n.stdinFile)?n.stdinFile:null}function Ty(e,n){let t=e.argv,s=e.name,r=(c,u)=>[m("claude.bash.secrets.expose",`${s} sends a secrets file (${R.basename(v(c))}) to ${u}`,{target:v(c),host:u,is_local:!1})],o=au(e),i=(c,u)=>{let d=c.flatMap(h=>h==="{}"&&o.length>0?o:Un(h));if(d.length<2)return[];let p=d[d.length-1],f=d.slice(0,-1).find(h=>Te(h)||n.secretCopies.has(Y(h,e.cwd,te(n)).path));return f&&u(p)&&!Re(Vn(p))?r(f,Vn(v(p))):[]},a=e.redirects.find(c=>c.target!==null&&/^\/dev\/(tcp|udp)\/[^/]+\/\d+/.test(c.target)&&[">",">>",">|"].includes(c.op)),l=a?a.target.split("/")[3]:null;if(l!==null&&!Re(l)&&Js.has(s)){let c=Ut(e).find(u=>Te(u))??(e.stdinFile!==null&&Te(e.stdinFile)?e.stdinFile:null);if(c)return r(c,l)}switch(s){case"scp":return i(ce(t,1,Ry),Le);case"rsync":return i(ce(t,1,Fo),Le);case"rclone":{let c=ce(t,1,new Set(["--config","--exclude","--include","--filter","--transfers","--checkers","--log-file","--bwlimit","--max-age","--min-age","--max-size","--min-size"]));return["copy","copyto","sync","move","moveto","bisync"].includes(c[0]??"")?i(c.slice(1,3),Le):[]}case"gsutil":{let c=ce(t,1,Oy);return["cp","mv","rsync"].includes(c[0]??"")?i(c.slice(1),u=>u.startsWith("gs://")):[]}case"gcloud":{let c=w(t);return c[0]==="compute"&&c[1]==="scp"?i(ce(t,t.indexOf("scp")+1,new Set(["--zone","--project","--ssh-key-file","--scp-flag","--tunnel-through-iap"])),Le):c[0]==="compute"&&c[1]==="ssh"&&e.stdinFile!==null&&Te(e.stdinFile)?r(e.stdinFile,c[2]??"a VM"):c[0]==="storage"&&["cp","mv","rsync"].includes(c[1]??"")?i(c.slice(2),u=>u.startsWith("gs://")):[]}case"az":{let c=w(t);if(c[0]!=="storage")return[];let u=j(t,"-f","--file","-s","--source");return u&&Te(u)&&["blob","file","copy","fs"].includes(c[1]??"")?r(u,"Azure storage"):[]}case"aws":{let c=w(t);return c[0]==="s3"&&["cp","mv","sync"].includes(c[1]??"")?i(fo(t),u=>u.startsWith("s3://")):[]}case"s3cmd":return["put","sync","cp","mv"].includes(w(t)[0]??"")?i(w(t).slice(1),c=>c.startsWith("s3://")):[];case"azcopy":return["copy","cp","sync"].includes(w(t)[0]??"")?i(w(t).slice(1,3),c=>/^https:\/\/[^/]+\.(blob|dfs|file)\.core\.windows\.net\//.test(c)):[];case"mc":return["cp","mv","mirror"].includes(w(t)[0]??"")?i(w(t).slice(1),c=>!/^[./~]/.test(c)&&c.includes("/")):[];case"croc":case"wormhole":case"ffsend":{let c=w(t),u=["send","upload","u"].includes(c[0]??"")?c.slice(1).find(d=>Te(d)):void 0;return u?r(u,`a ${s} relay`):[]}case"kubectl":{let c=w(t);return c[0]==="cp"?i(c.slice(1),u=>/^([^\s/:]+\/)?[^\s/:]+:/.test(u)):[]}case"nc":case"ncat":case"netcat":case"socat":case"telnet":case"ssh":case"sftp":{let c=e.stdinFile!==null&&Te(e.stdinFile)?e.stdinFile:Ny(e);s==="socat"&&(c??=t.slice(1).map(h=>/^(FILE|OPEN|GOPEN|READ):([^,]+)/i.exec(h)?.[2]).find(h=>h!==void 0&&Te(h))??null);let u=(e.stdin??"")+(e.pipeFrom&&["echo","printf"].includes(e.pipeFrom.name)?`
|
|
65
|
+
${e.stdin??""}`)){let d=e.argv.slice(1).filter(h=>!/\s/.test(h)&&!h.startsWith("-")).map(h=>M(h,e.cwd,t.ctx)).find(h=>!S(h)&&ot.test(h));d!==void 0&&n.push(m("claude.agent.controls",`changes how every later Claude Code session starts (${R.basename(d)})`,{target:k(d),is_local:!0}))}if(n.length===0&&(e.name==="find"||e.name==="gfind")){let d=Cy(r,t);d!==null&&n.push(m("claude.agent.controls",`${e.name} deletes or changes Claude Code's records of sessions (${d})`,{target:d,is_local:!0}))}if(n.length===0){let d=By(r,t);d!==null&&n.push(m("claude.agent.controls",Vs(k(d),t.ctx),{target:k(d),is_local:!0}))}return n.filter((d,h)=>n.findIndex(g=>g.action===d.action)===h)}var Bn=new Set(["mkdir","cat","bat","less","more","head","tail","ls","stat","file","wc","grep","egrep","fgrep","rg","ag","diff","cmp","md5","md5sum","shasum","sha1sum","sha256sum","cksum","jq","du","readlink","realpath","test","[","echo","printf","basename","dirname","od","hexdump","strings","nl","cut","column","cd","pushd","popd","type","which","command","pwd","view","tree","fd","fdfind","shellcheck","open","xdg-open","code","code-insiders","cursor","subl","ccusage"]),Dy=new Set(["tee","sponge","truncate","rm","unlink","trash","srm","shred","mkfifo","mknod","touch","cp","gcp","mv","gmv","install","ln","ditto","perl","ruby","yq","dd","awk","gawk","mawk","nawk","base64","openssl","plutil","rsync","scp","sort","chflags","chgrp","chmod","chown"]),Fy=new Set(["checkout","switch","restore","reset","stash","pull","merge","rebase","cherry-pick","revert","am","apply","read-tree","checkout-index","clean"]),zy=new Set(["push","reflog","config","ls-remote","add","commit","status","diff","log","show","blame","ls-files","grep","rev-parse","describe","shortlog","cat-file","ls-tree","check-ignore","fetch","remote","branch","tag","update-index"]),My=new Set(["node","python","python3","bash","sh","zsh","dash","ksh","ruby","perl","deno","bun","php","tsx","ts-node","source","."]),jl=/\bfileinput\.(input|FileInput)\s*\([^)]*inplace\s*=\s*(True|1)|\bunlink\s*\(?\s*['"$]|\bopen\s*\([^)]{0,300}(,\s*|mode\s*=\s*)['"]([wax]|rb?\+)|\.open\s*\(\s*(mode\s*=\s*)?['"]([wax]|rb?\+)|\.write_(text|bytes)\s*\(|\bshutil\.(copy\w*|move|rmtree)\s*\(|\bos\.(rename|replace|remove|unlink|truncate)\s*\(|\.(unlink|rename|touch|rm|rmdir)\s*\(|\b(writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|copyFileSync|copyFile|cpSync|renameSync|unlinkSync|rmSync|truncateSync)\s*\(|\bFile\.(write|delete|rename)\b|\bFile\.open\s*\([^)]*['"][wa]|\bIO\.write\b|\bFileUtils\.|\bopen\s*\(?\s*(my\s+)?[$\w]+\s*,\s*['"]?\s*(>|\+<)|\bDeno\.(writeTextFile|writeFile|remove|rename)|\bBun\.write\b/;function Uy(e,t=null){let n=e.argv.slice(1),s=(...a)=>n.some(i=>a.includes(i)),r=n.filter(a=>!a.startsWith("-"));if(e.name==="fd"||e.name==="fdfind"){let a=n.findIndex(u=>["-x","--exec","-X","--exec-batch"].includes(u));if(a<0)return null;let i=ue(n[a+1]??""),l=n[a+2]??"";return i==="node"&&(l==="--check"||l==="-c")||["bash","sh","zsh"].includes(i)&&l==="-n"||Bn.has(i)?null:{names:n.slice(0,a),cwd:!0}}if(e.name==="tree"&&n.some(a=>a.startsWith("-o")))return{names:[P(e.argv,"-o")??""].filter(Boolean),cwd:!1};if(Bn.has(e.name)||e.name==="rmdir"||e.name==="inspector"&&/@modelcontextprotocol\/inspector/.test(e.argv[0]??"")||["bash","sh","zsh","dash","ksh"].includes(e.name)&&n[0]==="-n"||e.name==="node"&&s("--check","-c")||e.name==="tsc"&&s("--noEmit")||e.name==="eslint"&&!n.some(a=>a.startsWith("--fix"))||e.name==="ruff"&&n[0]==="check"&&!s("--fix")||["mypy","flake8","pylint","pyright","pytest","vitest","jest","mocha"].includes(e.name)||e.name==="black"&&s("--check")||/^python(3(\.\d+)?)?$/.test(e.name)&&n[0]==="-m"&&["py_compile","compileall","pytest","mypy","unittest"].includes(n[1]??"")||e.name==="prettier"&&s("--check","-c","--list-different","-l")&&!s("--write","-w")||e.name==="xxd"&&!n.some(a=>/^-(r|revert)$/.test(a))||e.name==="xattr"&&!n.some(a=>/^-[a-z]*[wdcr]/.test(a)))return null;if(/^python(3(\.\d+)?)?$/.test(e.name)&&n[0]==="-m"&&n[1]==="json.tool")return{names:n.slice(2).filter((i,l,c)=>!i.startsWith("-")&&c[l-1]!=="--indent").slice(1),cwd:!1};if(e.name==="git")return qy(e,n);if(e.name==="find"){let a=n.findIndex(p=>/^-(exec|execdir|ok|okdir)$/.test(p)),i=ue(n[a+1]??""),l=n[a+2]??"",c=i==="node"&&(l==="--check"||l==="-c")||["bash","sh","zsh"].includes(i)&&l==="-n",u=n.some(p=>/^-(delete|fprint0?|fprintf|fls)$/.test(p))||a>=0&&!c&&!Bn.has(ue(n[a+1]??"")),f=n.filter((p,d)=>d>0&&["-name","-iname"].includes(n[d-1]));return u&&f.length>0&&f.every(p=>/\.(jsonl|log|tmp)$/i.test(p))?null:u?{names:n,cwd:!0}:null}let o=Xn(e);if(o!==null){let a=n.filter(g=>g!==o),i=e.cwd!==null&&(/\/\.anvil(\/|$)|\/\.claude(\/|$)/.test(e.cwd)||t!==null&&e.cwd.startsWith(t)),l=Yo(o.slice(0,65536)),c=/homedir\(|expanduser|Path\.home\(|process\.env\.HOME|environ[^\n]{0,12}HOME|ENV\[['"]HOME/.test(l),u=[...l.matchAll(/(?:[(,=[]|\b(?:unlink|rmtree|rename|truncate|open)\s)\s*(['"`])([^'"`\n]*(?:\.anvil|\.claude|\.mcp\.json)[^'"`\n]*)\1/g)].flatMap(g=>{let y=g.index+g[0].length,$=/^(?:\s*[,/]\s*(['"])([^'"\n]+)\1)+/.exec(l.slice(y,y+512))?.[0]??"",E=[g[2],...[...$.matchAll(/(['"])([^'"\n]+)\1/g)].map(b=>b[2])].join("/").replace(/\/{2,}/g,"/");if(/^(\/|~\/)/.test(E))return[E];if(/^\$\{?HOME\}?\//.test(E))return[E.replace(/^\$\{?HOME\}?/,"~")];if(/^\$ENV\{['"]?HOME['"]?\}\//.test(E))return[E.replace(/^\$ENV\{['"]?HOME['"]?\}/,"~")];let x=E.replace(/^\$\{[^}]*\}\/?/,"");return c&&/^\.(anvil|claude|mcp\.json)(\/|\.json|$)/.test(x)?[`~/${x}`]:[]}),f={n:0},p=wu(l,{hit:!1},f),h=p.length>0&&f.n===0&&p.every(g=>!S(g.path)&&!/\.anvil|\.claude|\.mcp\.json|LaunchAgents|LaunchDaemons|\.gitconfig/.test(g.path))?[]:u;return(i||h.length>0||a.some(g=>/\.claude|\.anvil|\.mcp\.json|managed-/.test(g)))&&jl.test(l)?{names:[...a,...h],cwd:!0}:null}if(My.has(e.name)){let a=n.indexOf("-");if(a>=0)return e.stdin!==null&&!jl.test(e.stdin.slice(0,65536))?null:{names:n.slice(a+1),cwd:!1};let i=n.indexOf("-m");if(i>=0)return{names:n.slice(i+2),cwd:!1};let l=n.findIndex(c=>!c.startsWith("-"));return l<0?null:{names:n.slice(l+1).filter(c=>!/(^|\/)\.(claude|anvil)\/?$/.test(c)),cwd:!1}}if(e.name==="uniq")return{names:r.slice(1,2),cwd:!1};if(e.name==="zip")return{names:r.slice(0,1),cwd:!1};if(["tar","bsdtar","gtar"].includes(e.name)){let a=n[0]&&!n[0].startsWith("--")?n[0].replace(/^-/,""):"";if(/t/.test(a)||s("--list"))return null;if(/x/.test(a)||s("--extract","--get"))return{names:n,cwd:!0};let i=P(e.argv,"-f","--file")??(/f/.test(a)?n[1]??null:null);return{names:i?[i]:[],cwd:!1}}if(/^7z[arz]?$/.test(e.name)){if(["l","t","i","h"].includes(n[0]??""))return null;if(["x","e"].includes(n[0]??"")){let a=n.filter(i=>i.startsWith("-o")).map(i=>i.slice(2));return{names:a,cwd:a.length===0}}return{names:r.slice(1,2),cwd:!1}}if(e.name==="unzip"){if(n.some(i=>/^-[a-zA-Z]*[ltvZp]/.test(i)))return null;let a=P(e.argv,"-d");return{names:a?[a]:[],cwd:a===null}}if(e.name==="patch"){let a=P(e.argv,"-d","--directory"),i=uu(cu(e));return{names:[P(e.argv,"-o","--output")??"",...i,...a?i.map(l=>`${a.replace(/(?<!\/)\/+$/,"")}/${l}`):[]].filter(Boolean),cwd:!0}}return["sed","gsed","vim","vi","nvim","ex","ed","red","emacs"].includes(e.name)?["vim","vi","nvim"].includes(e.name)&&s("-R")?null:{names:n.flatMap(a=>[...a.matchAll(/(?:^|[\s;:|{}\/!%,$\d])(?:w|W|wq|x|write|sav|saveas)!?\s*(?:>>\s*)?([~\/.][^\s;|}]*)/g)].map(i=>i[1])),cwd:!1}:e.name==="curl"?{names:n,cwd:n.some(a=>/^-[a-zA-Z]*[OJ]|^--(remote-name|remote-header-name|output-dir)/.test(a))}:e.name==="wget"?{names:n,cwd:!n.some((a,i)=>(a==="-O"||a==="--output-document")&&n[i+1]==="-"||/^-[a-zA-Z]*O-$/.test(a))}:Dy.has(e.name)?{names:[],cwd:!1}:{names:n,cwd:!0}}function cu(e){if(e.stdin!==null)return e.stdin;let t=e.pipeFrom;if(!t)return null;if(["cat","echo","printf"].includes(t.name))return t.stdin??t.argv.slice(1).join(`
|
|
66
|
+
`);if(t.name==="git"&&t.argv[1]==="diff"){let n=t.argv.indexOf("--");return n<0?null:t.argv.slice(n+1).map(s=>`+++ ${s}`).join(`
|
|
67
|
+
`)}return null}function uu(e){return e===null?[]:[...e.slice(0,262144).matchAll(/^(?:---|\+\+\+)\s+(\S+)/gm)].map(t=>t[1]).filter(t=>t!=="/dev/null").flatMap(t=>/^[ab]\//.test(t)?[t,t.slice(2)]:[t])}function qy(e,t){let n=[],s=0;for(;s<t.length&&t[s].startsWith("-");s++){let i=t[s];if(i==="-C"||i==="--work-tree"||i==="--git-dir")n.push(t[++s]??"");else if(i==="-c"){let l=t[++s]??"";/^core\.worktree=/i.test(l)&&n.push(l.slice(l.indexOf("=")+1))}else(i.startsWith("--work-tree=")||i.startsWith("--git-dir="))&&n.push(i.slice(i.indexOf("=")+1))}for(let i of e.text.matchAll(/\bGIT_(?:WORK_TREE|DIR)=("[^"]*"|'[^']*'|[^\s;&|]+)/g))n.push(i[1].replace(/^["']|["']$/g,""));let r=t[s]??"",o=t.slice(s+1);if(r==="stash"&&["list","show"].includes(o[0]??"")||r==="worktree"&&(o[0]??"")==="list"||r==="apply"&&o.some(i=>["--check","--stat","--numstat","--summary"].includes(i)))return null;if(r==="apply"||r==="am")return{names:[...n,...o,...uu(cu(e))],cwd:!0};let a=r==="restore"&&o.some(i=>i==="--staged"||i==="-S")&&!o.some(i=>i==="--worktree"||i==="-W")||r==="reset"&&!o.some(i=>i==="--hard"||i==="--merge"||i==="--keep")||r==="rm"&&o.includes("--cached");return zy.has(r)||a?null:{names:[...n,...n.length===0&&e.cwd!==null?[e.cwd]:[],...o],cwd:!0}}function Hy(e){let t=n=>{if(/[\s"']/.test(n))return!1;let s=n.indexOf("{"),r=s<0?-1:n.indexOf(",",s+1);return r>s&&n.lastIndexOf("}")>r};return e.argv.slice(1).some(t)?{...e,argv:[e.argv[0],...e.argv.slice(1).flatMap(n=>t(n)?du(n):[n])].slice(0,256)}:e}function du(e){if(!e.includes("{"))return[e];let t=[],n=[e];for(let s=0;n.length>0&&t.length<64&&s<256;s++){let r=n.shift(),o=r.indexOf("{"),a=-1,i=[];for(let c=o,u=0;o>=0&&c<r.length;c++)if(r[c]==="{")u++;else if(r[c]==="}"&&--u===0){a=c;break}else r[c]===","&&u===1&&i.push(c);if(o<0||a<0||i.length===0){t.push(r);continue}let l=[o,...i,a];for(let c=0;c+1<l.length;c++)n.push(r.slice(0,o)+r.slice(l[c]+1,l[c+1])+r.slice(a+1))}return t.length>0?t:[e]}function Go(e){let t=/^[*?[]/.test(e)?"(?!\\.)":"";for(let n=0;n<e.length;n++){let s=e[n];if(s==="*")t+="[^/]*";else if(s==="?")t+="[^/]";else if(s==="["){let r=e.indexOf("]",n+2);r<0?t+="\\[":(t+=`[${e.slice(n+1,r).replace(/^!/,"^").replace(/\\/g,"\\\\")}]`,n=r)}else t+=s.replace(/[.+^${}()|\\]/g,"\\$&")}try{return new RegExp(`^${t}$`)}catch{return new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`)}}function fu(e,t){let n=[...new Set(t.filter(o=>typeof o=="string"&&o.startsWith("/")&&!S(o)).map(o=>o.replace(/(?<!\/)\/+$/,"")))],s=e.claudeConfigDir&&!S(e.claudeConfigDir)?e.claudeConfigDir.replace(/(?<!\/)\/+$/,""):null,r=e.home.replace(/(?<!\/)\/+$/,"");return{files:[...n.flatMap(o=>[`${o}/.claude/settings.json`,`${o}/.claude/settings.local.json`,`${o}/.claude.json`,`${o}/.mcp.json`,`${o}/.claude`]),`${r}/.anvil`,`${r}/.anvil/rules.json`,`${r}/.anvil/rules.md`,`${r}/.anvil/workspace-keys.json`,`${r}/.anvil/telemetry-notice`,...s?[s,`${s}/settings.json`,`${s}/settings.local.json`,`${s}/.claude.json`]:[]],folders:[...n.flatMap(o=>[`${o}/.claude/hooks`,`${o}/.claude/plugins`]),`${r}/.anvil/claude`,...s?[`${s}/hooks`,`${s}/plugins`]:[]]}}function pu(e,t,n,s=!0){let r=[];for(let o of du(e)){if(!/[*?[]/.test(o)||s&&St(k(o),t,s===!0)){Bo(o,t,n,s)==="agent"&&r.push(o);continue}if(s&&ir(k(o),t,s===!0)){r.push(o);continue}let a=o.split("/"),i=a.map(Go),l=(f,p)=>{let d=f.split("/");return(p?a.length>d.length:a.length===d.length)&&d.every((h,g)=>i[g].test(h))},c=fu(t,n),u=c.files.find(f=>l(f,!1))??c.folders.find(f=>l(f,!1)||l(f,!0));u!==void 0&&r.push(u)}return r}function By(e,t){let n=[t.ctx.home,t.projectRoot,t.base],s=e.cwd!==null&&!S(e.cwd)?e.cwd.replace(/(?<!\/)\/+$/,""):null,r=s!==null&&fu(t.ctx,n).folders.some(c=>s===c||s.startsWith(`${c}/`)),o=c=>{if(c.startsWith("-")&&!c.includes("=")&&!/[~/]/.test(c))return null;let u=c.startsWith("-")?c.includes("=")?c.slice(c.indexOf("=")+1):c.slice(Math.max(0,c.search(/[~/]/))):c,f=/^(\/|~|\.\.?\/)/.test(u)||!/\s/.test(u)&&(/^\.[\w-]/.test(u)||u.includes("/")||/^[\w.-]+$/.test(u));return!u||S(u)&&!u.startsWith("/")||!f?null:pu(M(u,e.cwd,t.ctx),t.ctx,n,!1)[0]??null};for(let c of e.wrapperArgs){let u=o(c);if(u!==null)return u}let a=Uy(e,t.ctx.claudeConfigDir&&!S(t.ctx.claudeConfigDir)?t.ctx.claudeConfigDir.replace(/(?<!\/)\/+$/,""):null);if(a===null)return null;let i=t.ctx.home.replace(/(?<!\/)\/+$/,"");if(e.name==="git"&&Fy.has(_t(e)?.sub??""))for(let c of a.names){if(S(c))continue;let u=M(c,e.cwd,t.ctx).replace(/(?<!\/)\/+$/,"");if(u===i)return`${i}/.claude`;let f=Object.entries(t.ctx.controlLinks??{}).find(([p])=>p.startsWith(`${u}/`));if(f)return f[1]}let l=Ag(e);for(let c of a.names){let u=l.has(c)?Ft(t,()=>o(c)):o(c);if(u!==null)return u}return a.cwd&&r?s:null}function Vy(e,t){let n=e.argv.slice(1),s=n.some(f=>f==="--symbolic"||/^-[a-zA-Z]*s/.test(f));if(e.name==="ln"?!s:!(["cp","gcp"].includes(e.name)&&n.some(f=>f==="--symbolic-link"||f==="--link"||/^-[a-zA-Z]*[sl]/.test(f))))return[];let r=new Set(["-t","--target-directory","-S","--suffix"]),o=n.filter((f,p)=>!f.startsWith("-")&&!r.has(n[p-1]??"")),a=P(e.argv,"-t","--target-directory"),i=a!==null||o.length===1?o:o.slice(0,-1),l=a??(o.length>=2?o[o.length-1]:"."),c=e.name==="ln"&&!S(l)?M(l,e.cwd,t.ctx):null,u=c===null?[e.cwd]:a!==null||o.length<2?[c]:[R.dirname(c),c];return i.filter(f=>!S(f)).flatMap(f=>(f.startsWith("/")||f.startsWith("~")?[e.cwd]:u).map(p=>M(f,p,t.ctx)))}var Zy=["/Library/Application Support/ClaudeCode","/etc/claude-code","/c/program files/claudecode"];function hu(e,t){if(Bo(e,t.ctx,[t.ctx.home,t.projectRoot,t.base])==="agent")return!0;let n=k(e).replace(/(?<!\/)\/+$/,"").toLowerCase();return[t.ctx.home,t.ctx.claudeConfigDir??null,...Zy].filter(r=>typeof r=="string"&&r.startsWith("/")&&!S(r)).map(r=>r.replace(/(?<!\/)\/+$/,"").toLowerCase()).some(r=>r===n||r.startsWith(`${n}/`)||n==="")}function Vs(e,t=null){return t&&(St(k(e),t)||ir(k(e),t,!0))?_y(e):/(^|\/)\.anvil(\/|$)/.test(e)?`changes Anvil's checks on this agent (${R.basename(e)})`:`changes Claude Code's own permissions, hooks or MCP servers (${R.basename(e)})`}function Vn(e,t,n=[]){let s=[...n].reverse().find(i=>typeof i=="string"&&i.startsWith("/")&&!S(i))??null,r=e.startsWith("/")||e.startsWith("~")?M(e,null,t):s!==null?M(e,s,t):e,{place:o,at:a}=Vo(r,t,[t.home,...n]);return o==="agent"?{action:"claude.agent.controls",service:null,target:a,branch:null,host:null,is_local:!0,why:Vs(a,t)}:o==="jobs"?{action:"claude.bash.persistence",service:null,target:a,branch:null,host:null,is_local:!0,why:`installs or changes a background job (${a})`}:o==="gitconfig"?{action:"claude.bash.persistence",service:null,target:a,branch:null,host:null,is_local:!0,why:`rewrites the global git config (${a})`}:null}var Gy=new Set(["-m","--message","-F","--file","-C","--reuse-message","-c","--reedit-message","--author","--date","--fixup","--squash","--cleanup","-t","--template","--trailer","--pathspec-from-file"]);function Ky(e,t){if(e.name!=="git")return[];let n=_t(e);if(!n||!["add","stage","commit"].includes(n.sub))return[];let s=n.sub==="commit";if(n.args.includes("--dry-run")||!s&&n.args.some(c=>/^-[A-Za-z]*n[A-Za-z]*$/.test(c)))return[];let r=e.via==="find-exec"&&e.parent?.name==="find"?So(e.parent)[0]??null:null,o=[],a=!1;for(let c=0;c<n.args.length;c++){let u=n.args[c];!a&&u==="--"?a=!0:!a&&u.startsWith("-")?(s&&(Gy.has(u)||/^-[A-Za-z]*[mFCct]$/.test(u))||!s&&(u==="--chmod"||u==="--pathspec-from-file"))&&c++:o.push(u==="{}"&&r!==null?r:u)}e.via==="xargs"&&o.push(...vu(e));let i=o.filter(c=>!/^:(!|\^|\([^)]*exclude[^)]*\))/.test(c)).map(c=>c.replace(/^:(\([^)]*\)|\/)?/,"")).flatMap(qn).sort((c,u)=>Number(/key|priv/i.test(u))-Number(/key|priv/i.test(c))).find(c=>Le(c,!0)||t.secretCopies.has(X(c,e.cwd,se(t)).path));if(!i)return[];let l=zt(e,n,t);return l!==null&&kt(l,t)?[]:[m("claude.bash.secrets.expose",`git ${n.sub} ${s?"commits":"stages"} a secrets file (${R.basename(k(i))})`,{target:k(i),is_local:!0})]}function Te(e){return/^(scp|sftp|rsync):\/\//.test(e)||/^[^\s/:=]+:/.test(e)&&!/^[A-Za-z]:\\/.test(e)&&!/^[a-z]+:\/\//i.test(e)}function Zn(e){let t=/^(?:[a-z]+:\/\/)?(?:[^@/:]+@)?(\[[^\]]+\]|[^:/]+)/i.exec(e);return t?t[1]:e}function pe(e,t,n){let s=[];for(let r=t;r<e.length;r++){let o=e[r];if(o==="--"){s.push(...e.slice(r+1));break}o.startsWith("-")&&o!=="-"?n.has(o)&&r++:s.push(o)}return s}var Yy=new Set(["-i","-P","-o","-F","-c","-l","-S","-J","-D","-X"]),Ko=new Set(["-e","--rsh","-f","--filter","--exclude","--include","--files-from","--exclude-from","--include-from","--port","--password-file","-B","--block-size","--bwlimit","--log-file","--partial-dir","-T","--temp-dir","--chmod","--chown","--backup-dir","--suffix","--compare-dest","--link-dest","--copy-dest","--max-size","--min-size","--timeout","-M","--remote-option","--rsync-path"]),Jy=new Set(["-o","-h","-u"]),Xy=new Set(["-B","-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w"]),Qy=new Set(["-B","-b","-c","-D","-F","-i","-J","-l","-o","-P","-R","-S","-s","-X"]),eb=new Set(["-w","-p","-s","-i","-q","-x","-X","-O","-I","-V","-T","-e","-c","-W","-M","-m","-g","-G"]);function tb(e){let t=e.pipeFrom;if(!t)return null;if(er.has(t.name)||["tar","gtar","zip","gzip"].includes(t.name)){let n=(["tar","gtar","zip","gzip"].includes(t.name)?t.argv.slice(1).filter(s=>!s.startsWith("-")):qt(t)).find(s=>Le(s));if(n)return n}return t.stdinFile!==null&&Le(t.stdinFile)?t.stdinFile:null}function nb(e,t){let n=e.argv,s=e.name,r=(c,u)=>[m("claude.bash.secrets.expose",`${s} sends a secrets file (${R.basename(k(c))}) to ${u}`,{target:k(c),host:u,is_local:!1})],o=vu(e),a=(c,u)=>{let f=c.flatMap(h=>h==="{}"&&o.length>0?o:qn(h));if(f.length<2)return[];let p=f[f.length-1],d=f.slice(0,-1).find(h=>Le(h)||t.secretCopies.has(X(h,e.cwd,se(t)).path));return d&&u(p)&&!Re(Zn(p))?r(d,Zn(k(p))):[]},i=e.redirects.find(c=>c.target!==null&&/^\/dev\/(tcp|udp)\/[^/]+\/\d+/.test(c.target)&&[">",">>",">|"].includes(c.op)),l=i?i.target.split("/")[3]:null;if(l!==null&&!Re(l)&&er.has(s)){let c=qt(e).find(u=>Le(u))??(e.stdinFile!==null&&Le(e.stdinFile)?e.stdinFile:null);if(c)return r(c,l)}switch(s){case"scp":return a(pe(n,1,Yy),Te);case"rsync":return a(pe(n,1,Ko),Te);case"rclone":{let c=pe(n,1,new Set(["--config","--exclude","--include","--filter","--transfers","--checkers","--log-file","--bwlimit","--max-age","--min-age","--max-size","--min-size"]));return["copy","copyto","sync","move","moveto","bisync"].includes(c[0]??"")?a(c.slice(1,3),Te):[]}case"gsutil":{let c=pe(n,1,Jy);return["cp","mv","rsync"].includes(c[0]??"")?a(c.slice(1),u=>u.startsWith("gs://")):[]}case"gcloud":{let c=v(n);return c[0]==="compute"&&c[1]==="scp"?a(pe(n,n.indexOf("scp")+1,new Set(["--zone","--project","--ssh-key-file","--scp-flag","--tunnel-through-iap"])),Te):c[0]==="compute"&&c[1]==="ssh"&&e.stdinFile!==null&&Le(e.stdinFile)?r(e.stdinFile,c[2]??"a VM"):c[0]==="storage"&&["cp","mv","rsync"].includes(c[1]??"")?a(c.slice(2),u=>u.startsWith("gs://")):[]}case"az":{let c=v(n);if(c[0]!=="storage")return[];let u=P(n,"-f","--file","-s","--source");return u&&Le(u)&&["blob","file","copy","fs"].includes(c[1]??"")?r(u,"Azure storage"):[]}case"aws":{let c=v(n);return c[0]==="s3"&&["cp","mv","sync"].includes(c[1]??"")?a(wo(n),u=>u.startsWith("s3://")):[]}case"s3cmd":return["put","sync","cp","mv"].includes(v(n)[0]??"")?a(v(n).slice(1),c=>c.startsWith("s3://")):[];case"azcopy":return["copy","cp","sync"].includes(v(n)[0]??"")?a(v(n).slice(1,3),c=>/^https:\/\/[^/]+\.(blob|dfs|file)\.core\.windows\.net\//.test(c)):[];case"mc":return["cp","mv","mirror"].includes(v(n)[0]??"")?a(v(n).slice(1),c=>!/^[./~]/.test(c)&&c.includes("/")):[];case"croc":case"wormhole":case"ffsend":{let c=v(n),u=["send","upload","u"].includes(c[0]??"")?c.slice(1).find(f=>Le(f)):void 0;return u?r(u,`a ${s} relay`):[]}case"kubectl":{let c=v(n);return c[0]==="cp"?a(c.slice(1),u=>/^([^\s/:]+\/)?[^\s/:]+:/.test(u)):[]}case"nc":case"ncat":case"netcat":case"socat":case"telnet":case"ssh":case"sftp":{let c=e.stdinFile!==null&&Le(e.stdinFile)?e.stdinFile:tb(e);s==="socat"&&(c??=n.slice(1).map(h=>/^(FILE|OPEN|GOPEN|READ):([^,]+)/i.exec(h)?.[2]).find(h=>h!==void 0&&Le(h))??null);let u=(e.stdin??"")+(e.pipeFrom&&["echo","printf"].includes(e.pipeFrom.name)?`
|
|
68
68
|
${e.pipeFrom.argv.slice(1).join(" ").replace(/\\n/g,`
|
|
69
|
-
`)}`:"");if(s==="sftp"&&(c??=[...u.matchAll(/(?:^|\n|;)\s*put\s+(?:-\w+\s+)*(\S+)/g)].map(h=>h[1]).find(h=>
|
|
70
|
-
`),p=
|
|
71
|
-
`):"";return u[0]==="query"&&Dn(ke(d,"bigquery"))&&pt(e)?[m("claude.bash.data.export","bq query copies table rows onto this machine",{target:"bigquery",host:"bigquery",is_local:!1})]:[]}case"gsutil":case"gcloud":{if(re("compute","ssh")(t)&&/\b(pg_dump|pg_dumpall|mysqldump|mongodump|mongoexport)\b/.test(j(t,"--command")??"")&&pt(e))return[m("claude.bash.data.export","dumps a database on a VM and streams it onto this machine",{target:"gcloud compute ssh",host:"gcloud",is_local:!1})];let u=w(t),d=s==="gsutil"?u.slice(1):u[0]==="storage"?u.slice(2):[],p=s==="gsutil"?u[0]:u[1];return["cp","rsync"].includes(p??"")&&d.length>=2&&d[0].startsWith("gs://")&&!d[d.length-1].startsWith("gs://")&&/\bbq\s+extract\b/.test(n.lineText)?[m("claude.bash.data.export","downloads a table the line exported from BigQuery",{target:d[0],host:"bigquery",is_local:!1})]:[]}case"wrangler":return w(t)[0]==="d1"&&w(t)[1]==="export"&&L(t,"--remote")&&!L(t,"--no-data")?[m("claude.bash.data.export","wrangler d1 export copies a remote D1 database onto this machine",{target:"d1",host:"cloudflare",is_local:!1})]:[];case"pscale":return re("database","dump")(t)?[m("claude.bash.data.export","pscale database dump copies a PlanetScale database onto this machine",{target:"planetscale",host:"planetscale",is_local:!1})]:[];case"turso":return re("db","shell")(t)&&t.some(u=>u===".dump")?[m("claude.bash.data.export","turso db shell .dump copies a Turso database onto this machine",{target:"turso",host:"turso",is_local:!1})]:[];case"aws":return re("dynamodb","scan")(t)&&pt(e)?[m("claude.bash.data.export","aws dynamodb scan copies a table onto this machine",{target:"dynamodb",host:"dynamodb",is_local:!1})]:[];case"curl":case"wget":return/\bheroku\s+pg:backups:url\b/.test(n.lineText)?[m("claude.bash.data.export","downloads a Heroku production backup onto this machine",{target:"heroku",host:"heroku",is_local:!1})]:[];case"fly":case"flyctl":{let u=j(t,"-C","--command")??"";return re("ssh","console")(t)&&/\b(pg_dump|pg_dumpall|mysqldump|mongodump|mongoexport)\b/.test(u)?[m("claude.bash.data.export","dumps a Fly database and streams it onto this machine",{target:"fly",host:"fly",is_local:!1})]:[]}case"heroku":return/^pg:(pull|backups:download)$/.test(w(t)[0]??"")?[m("claude.bash.data.export",`heroku ${w(t)[0]} copies a production database onto this machine`,{target:"heroku",host:"heroku",is_local:!1})]:[];case"supabase":return re("db","dump")(t)&&L(t,"--data-only")&&!L(t,"--local")&&!Cc(t)?[m("claude.bash.data.export","supabase db dump copies a linked database's data onto this machine",{target:"supabase",host:"supabase",is_local:!1})]:[];default:return[]}let i=e.remote===null||e.remote.startsWith("container:"),a=yt(n.lineText),l=r===null||!C(r)&&Mt(r);if(o&&!e.productionEnv&&i&&l&&a===null)return[];let c=a!==null&&l?`a database forwarded here (${a})`:r?dn(r):e.productionEnv?"production (railway run)":e.remote??"a database the command does not name";return[m("claude.bash.data.export",`${s} copies the data of ${c} onto this machine`,{target:c,host:r?dn(r):e.remote,is_local:!1})]}var Fy=/^((https?|wss?):\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|anvil|hardhat|ganache)\b|^(localhost|hardhat|anvil|ganache|localnet|local|development|l)$/i,$l=/sepolia|holesky|hoodi|goerli|rinkeby|ropsten|kovan|testnet|devnet|localnet|amoy|mumbai|fuji|chapel|alfajores|chiado|moonbase|baobab|calibration|shasta|nile|bepolia|hekla|garnet|cardona|fork|^d$|^t$/i,_l=/0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80|0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d/i;function Ue(e){if(e===null)return!1;let n=v(e).replace(/^["']|["']$/g,""),t=/^([a-z][a-z0-9+.-]*:\/\/)?([^/?#\s]+)([^?#\s]*)/i.exec(n);if(t&&(t[1]||t[3])){let s=t[2].replace(/:\d+$/,"").replace(/^[^@]*@/,"").toLowerCase();return/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|anvil|hardhat|ganache|host\.docker\.internal)$/.test(s)?!0:$l.test(`${s}${t[3]}`)}return Fy.test(n)||$l.test(n)}function xl(e,n){let t=e.argv,s=w(t),r=a=>a===null?null:dn(a),o=(a,l)=>[m("claude.bash.crypto.transaction",`${a} on ${r(l)??"a network the command does not name"}`,{target:`${e.name} ${s[0]??""}`.trim(),host:r(l),is_local:!1})],i=()=>j(t,"--rpc-url","-r","--fork-url",...e.name==="forge"?["-f"]:[])??/(?:^|[\s;&|(])(?:export\s+)?ETH_RPC_URL=["']?([^\s"';&|)]+)/.exec(n.lineText)?.[1]??null;switch(e.name){case"cast":{if(!(["send","s","publish"].includes(s[0]??"")||s[0]==="rpc"&&/^(eth_sendRawTransaction|eth_sendTransaction|personal_sendTransaction)$/.test(s[1]??"")))return[];let l=i();return Ue(l)||l===null&&_l.test(t.join(" "))?[]:o(`cast ${s[0]} sends a transaction`,l)}case"forge":{if(!(s[0]==="script"&&L(t,"--broadcast","--resume")||s[0]==="create"))return[];let l=i();return Ue(l)||l===null&&_l.test(t.join(" "))?[]:o(`forge ${s[0]} ${s[0]==="create"?"deploys a contract":"broadcasts transactions"}`,l)}case"solana":case"spl-token":{if(!(e.name==="solana"?["transfer","deploy","pay","delegate-stake","deactivate-stake","withdraw-stake","create-stake-account","split-stake","merge-stake","withdraw-from-vote-account","close-vote-account"].includes(s[0]??"")||s[0]==="program"&&["deploy","close","set-upgrade-authority","extend","write-buffer","upgrade"].includes(s[1]??""):["transfer","mint","burn","close","authorize","approve","create-token","create-account","wrap","unwrap","freeze","thaw"].includes(s[0]??"")))return[];let l=j(t,"--url","-u")??/\bsolana\s+config\s+set\s+(?:--url|-u)\s+(\S+)/.exec(n.lineText)?.[1]??null,c={m:"mainnet-beta",d:"devnet",t:"testnet",l:"localhost"};return Ue(l)?[]:o(`${e.name} ${s[0]} sends a transaction`,l===null?null:c[l]??l)}case"anchor":{if(!["deploy","upgrade","migrate"].includes(s[0]??""))return[];let a=j(t,"--provider.cluster");return Ue(a)?[]:o(`anchor ${s[0]} deploys a program`,a)}case"bitcoin-cli":case"lncli":{let a=ce(t,1,new Set(["--network","--rpcserver","--macaroonpath","--tlscertpath","--lnddir","--chain","--profile"]))[0]??"";if(!(e.name==="bitcoin-cli"?["sendtoaddress","sendmany","send","sendall","sendrawtransaction","bumpfee"].includes(a):["sendpayment","payinvoice","sendcoins","sendmany","openchannel","closechannel","closeallchannels","sendtoroute"].includes(a)))return[];let c=t.find(d=>/^-(regtest|testnet|testnet4|signet)$|^--?(chain|network)=/.test(d))??(j(t,"--network","--chain")!==null?`--network=${j(t,"--network","--chain")}`:null);return c!==null&&/regtest|testnet|signet|(chain|network)=(test|regtest|signet|simnet)/i.test(c)?[]:o(`${e.name} ${a} sends a payment`,c===null?"mainnet":c)}case"near":{let a=["deploy","send","send-near","call","delete","delete-account","stake","contract","tokens","transaction"].includes(s[0]??""),l=t.some(c=>/mainnet/i.test(c)||/\.near$/.test(c))||/\bNEAR_ENV=mainnet\b/.test(n.lineText);return a&&l?o(`near ${s[0]} sends a transaction`,"mainnet"):[]}case"starkli":{if(!["invoke","deploy","declare","transfer"].includes(s[0]??"")&&!(s[0]==="account"&&s[1]==="deploy"))return[];let a=j(t,"--network","--rpc");return Ue(a)?[]:o(`starkli ${s[0]} sends a transaction`,a)}case"stellar":case"soroban":{if(!(s[0]==="contract"&&["invoke","deploy","install","upload","extend","restore"].includes(s[1]??"")||s[0]==="tx"&&["send","new"].includes(s[1]??"")))return[];let l=j(t,"--network","--rpc-url");return l!==null&&/^(testnet|futurenet|local|standalone)$/i.test(l)?[]:Ue(l)?[]:o(`${e.name} ${s[0]} ${s[1]} sends a transaction`,l)}case"cardano-cli":return t.includes("submit")?t.some(a=>a==="--testnet-magic"||a.startsWith("--testnet-magic="))?[]:o("cardano-cli submits a transaction",t.includes("--mainnet")?"mainnet":null):[];case"sui":{if(!(s[0]==="client"&&["publish","upgrade","transfer","transfer-sui","pay","pay-sui","pay-all-sui","call","split-coin","merge-coin","ptb"].includes(s[1]??"")))return[];let l=j(t,"--client.env")??/\bsui\s+client\s+switch\s+--env\s+(\S+)/.exec(n.lineText)?.[1]??null;return Ue(l)?[]:o(`sui client ${s[1]} sends a transaction`,l)}case"aptos":{if(!(s[0]==="move"&&["publish","run","deploy-object","upgrade-object","create-object-and-publish-package","run-script"].includes(s[1]??"")||s[0]==="account"&&["transfer"].includes(s[1]??"")))return[];let l=j(t,"--profile","--url")??null;return Ue(l)?[]:o(`aptos ${s[0]} ${s[1]} sends a transaction`,l)}case"ape":{if(s[0]!=="run")return[];let a=j(t,"--network");return a===null||Ue(a)?[]:o(`ape run ${s[1]??""} sends transactions`,a)}case"hardhat":case"truffle":case"brownie":{let a=s[0]==="ignition"?s[1]??"":s[0]??"";if(!(["run","deploy","migrate"].includes(a)||/deploy|mint|transfer|send|upgrade|migrat|withdraw|airdrop|burn|propose|execute/i.test(a)))return[];let c=j(t,"--network")??(e.name==="hardhat"?/(?:^|[\s;&|(])(?:export\s+)?HARDHAT_NETWORK=["']?([^\s"';&|)]+)/.exec(n.lineText)?.[1]??null:null);return c===null||Ue(c)?[]:o(`${e.name} ${a} sends transactions`,c)}default:{if(/^[a-z]+d$/.test(e.name)&&s[0]==="tx"&&!L(t,"--generate-only","--dry-run")){let a=j(t,"--chain-id"),l=j(t,"--node");return a!==null&&/test|devnet|local/i.test(a)||l!==null&&Ue(l)?[]:o(`${e.name} tx ${s[1]??""} broadcasts a transaction`,a??l)}return[]}}}var ht=(e,...n)=>e.some(t=>n.some(s=>new RegExp(`^(?:/{1,2}|-)${s}(?::.*)?$`,"i").test(t))),Xr=(e,...n)=>{for(let t=0;t<e.length;t++)for(let s of n){let r=new RegExp(`^(?:/{1,2}|-)${s}(?::(.*))?$`,"i").exec(e[t]);if(r)return r[1]??e[t+1]??null}return null},Sl=/[\\/](?:Run|RunOnce|RunServices|RunServicesOnce)\b|[\\/]Winlogon\b|[\\/]Services[\\/]|[\\/]Image File Execution Options[\\/]|[\\/]Explorer[\\/]Shell Folders|[\\/]Policies[\\/]Explorer[\\/]Run|^(?:Registry::)?HK(?:CU|EY_CURRENT_USER):?[\\/]Environment\b|[\\/]Session Manager[\\/]Environment\b|[\\/]Command Processor\b/i,zy=new Set(["format","format-volume","clear-disk","initialize-disk","remove-partition","clear-recyclebin","diskpart","vssadmin","wmic","wbadmin","wsl","bcdedit","reg","set-itemproperty","new-itemproperty","remove-itemproperty","remove-item","sc","new-service","remove-service","set-service","stop-service","register-scheduledtask","set-scheduledtask","unregister-scheduledtask","new-scheduledtask","set-executionpolicy","set-mppreference","add-mppreference","netsh","set-netfirewallprofile","new-netfirewallrule","disable-netfirewallrule","remove-netfirewallrule","takeown","icacls","taskkill","runas","gsudo","mountvol","robocopy","setx","forfiles"]);function My(e,n){let t=e.argv.slice(1),s=t.join(" "),r={is_local:e.remote===null,host:e.remote},o=(i,a,l={})=>[m(i,a,{target:e.argv.slice(0,4).join(" "),...r,...l})];switch(e.name){case"format":case"format-volume":case"clear-disk":case"initialize-disk":case"remove-partition":return t.length>0||e.name!=="format"?o("claude.bash.fs.delete_recursive",`formats or wipes a drive (${e.name})`,{service:"fs.device"}):[];case"diskpart":return o("claude.bash.fs.delete_recursive","changes disks and partitions (diskpart)",{service:"fs.device"});case"clear-recyclebin":return o("claude.bash.fs.delete_recursive","empties the Recycle Bin, deleting what is in it for good",{target:"the Recycle Bin"});case"vssadmin":return/\b(delete|resize)\s+shadow/i.test(s)?o("claude.bash.fs.delete_recursive","deletes Windows' restore points (shadow copies)",{service:"fs.system"}):[];case"wmic":return/\bshadowcopy\b.*\bdelete\b/i.test(s)?o("claude.bash.fs.delete_recursive","deletes Windows' restore points (shadow copies)",{service:"fs.system"}):[];case"wbadmin":return/\bdelete\b/i.test(s)?o("claude.bash.fs.delete_recursive","deletes Windows' backups (wbadmin)",{service:"fs.system"}):[];case"wsl":return ht(t,"unregister")||t.includes("--unregister")?o("claude.bash.fs.delete_recursive","unregisters a Linux distribution, deleting its whole disk (wsl --unregister)",{service:"fs.root"}):[];case"bcdedit":return t.length===0||ht(t,"enum","v")?[]:o("claude.bash.privilege","changes how Windows starts (bcdedit)");case"reg":{let i=(t[0]??"").toLowerCase();if(["query","compare","export"].includes(i))return[];let a=t[1]??"";return Sl.test(a)?o("claude.bash.persistence",`changes what Windows starts at sign-in or boot (reg ${i} ${a})`):/^HK(LM|EY_LOCAL_MACHINE)/i.test(a)?o("claude.bash.privilege",`changes Windows' machine-wide settings (reg ${i})`):[]}case"set-itemproperty":case"new-itemproperty":case"remove-itemproperty":case"remove-item":{let i=Xr(t,"path","literalpath")??t.find(a=>!a.startsWith("-"))??"";return/^(HK(CU|LM|CR|U|CC)|HKEY_|Registry::)/i.test(i)?Sl.test(i)?o("claude.bash.persistence",`changes what Windows starts at sign-in or boot (${i})`):/^(HKLM|HKEY_LOCAL_MACHINE)/i.test(i)?o("claude.bash.privilege","changes Windows' machine-wide settings (the registry)"):[]:[]}case"sc":{let i=(t[0]??"").toLowerCase();return["create","config","delete","failure","sidtype","privs"].includes(i)?o("claude.bash.persistence",`changes a Windows service (sc ${i})`):i==="stop"?o("claude.bash.process.kill_by_name",`stops a Windows service (sc stop ${t[1]??""})`):[]}case"new-service":case"remove-service":return o("claude.bash.persistence",`changes a Windows service (${e.name})`);case"set-service":return ht(t,"startuptype")?o("claude.bash.persistence","changes when a Windows service starts"):[];case"stop-service":return o("claude.bash.process.kill_by_name",`stops a Windows service (${t.find(i=>!i.startsWith("-"))??""})`);case"register-scheduledtask":case"set-scheduledtask":case"unregister-scheduledtask":case"new-scheduledtask":return o("claude.bash.persistence",`changes Windows scheduled tasks (${e.name})`);case"set-executionpolicy":return o("claude.bash.privilege","changes which PowerShell scripts may run (Set-ExecutionPolicy)");case"set-mppreference":case"add-mppreference":return/-(Disable\w+|Exclusion\w+)/i.test(s)?o("claude.bash.privilege","turns off or narrows Microsoft Defender's checks"):[];case"netsh":return/firewall\b.*\b(state\s+off|disable|delete|add\s+rule|set\s+rule)/i.test(s)||/\bportproxy\b.*\badd\b/i.test(s)?o("claude.bash.net.expose","changes the Windows firewall or forwards a port (netsh)"):[];case"set-netfirewallprofile":case"new-netfirewallrule":case"disable-netfirewallrule":case"remove-netfirewallrule":return o("claude.bash.net.expose",`changes the Windows firewall (${e.name})`);case"takeown":return o("claude.bash.privilege",`takes ownership of files (takeown${ht(t,"r")?" /r":""})`);case"icacls":return ht(t,"grant","reset","setowner","inheritance","remove","deny")?o("claude.bash.privilege","changes who may read or change files (icacls)"):[];case"taskkill":{let i=Xr(t,"im");if(i)return o("claude.bash.process.kill_by_name",`kills every ${i} process (taskkill /im)`,{target:i});let a=Xr(t,"fi");return a?/^\s*imagename\s+eq\s+\S+\s*$/i.test(a)?o("claude.bash.process.kill_by_name",`kills every process its filter names (taskkill /fi "${a}")`,{target:a}):o("claude.bash.process.kill_by_name",`kills every process its filter matches (taskkill /fi "${a}")`,{target:a,service:"proc.all"}):[]}case"robocopy":{if(!ht(t,"mir","purge"))return[];let i=`robocopy ${ht(t,"mir")?"/mir":"/purge"}`,a=t.filter(l=>!/^\/{1,2}[A-Za-z]+(?::.*)?$/.test(l));return a.length<2?o("claude.bash.fs.delete_recursive",`${i} deletes from a folder the line does not show`):/^[A-Za-z]:(?![\\/])/.test(a[1])?o("claude.bash.fs.delete_recursive",`${i} deletes from ${a[1]}, a folder under a drive's current folder`):dc({...e,name:"rsync",argv:["rsync","-a","--delete",a[0],a[1]]},n).map(l=>({...l,why:l.why.replace(/^rsync --delete/,i)}))}case"setx":return t.length>0?o("claude.bash.persistence",`sets an environment variable every later program starts with (setx ${t.find(i=>!i.startsWith("/"))??""})`):[];case"runas":case"gsudo":return o("claude.bash.privilege",`runs a command as another user or as an administrator (${e.name})`);case"mountvol":return ht(t,"d","p")?o("claude.bash.fs.delete_recursive","removes a drive from Windows (mountvol)",{service:"fs.device"}):[];default:return[]}}function Uy(e){let n=e.argv,t=s=>[m("claude.bash.persistence",s,{target:n.slice(0,3).join(" "),is_local:e.remote===null,host:e.remote})];switch(e.name){case"crontab":{let s=n.slice(1).filter(r=>/^-[A-Za-z]+$/.test(r));return s.some(r=>r.includes("r"))?t("crontab -r deletes every scheduled job"):s.some(r=>/[lTV]/.test(r))?[]:s.some(r=>r.includes("e"))?t("crontab -e changes scheduled jobs"):t("crontab replaces every scheduled job")}case"launchctl":{let s=n.slice(1).find(r=>!r.startsWith("-"))??"";return["load","bootstrap","enable","submit"].includes(s)?t(`launchctl ${s} installs a background job`):[]}case"systemctl":{let s=n.slice(1).find(r=>!r.startsWith("-"))??"";return["enable","link","mask","preset","preset-all","set-default","edit","add-wants","add-requires"].includes(s)?t(`systemctl ${s} changes what starts at boot`):[]}case"pm2":return w(n)[0]==="startup"?t("pm2 startup makes processes start at boot"):[];case"brew":return w(n)[0]==="services"&&["start","restart"].includes(w(n)[1]??"")?t(`brew services ${w(n)[1]} registers a job that starts at login`):[];case"osascript":return/\bmake\s+(new\s+)?login\s+item\b/i.test(n.join(" "))?t("osascript adds a login item"):[];case"powershell":case"powershell.exe":case"pwsh":case"pwsh.exe":{let s=j(n,"-Command","-c","-command")??"",r=o=>new RegExp(`(^|[;|{(\\n&]\\s*)(${o})`,"i").test(s.trim());return r("Register-ScheduledTask|Set-ScheduledTask|Unregister-ScheduledTask|New-Service|schtasks(\\.exe)?\\s+\\/(create|change|delete)")||r("Set-Service\\b[^;|\\n]*-StartupType\\s+Automatic")?t("PowerShell changes scheduled tasks or services"):[]}case"schtasks":case"schtasks.exe":return n.some(s=>(H()?/^\/{1,2}(create|change|delete)$/i:/^\/(create|change|delete)$/i).test(s))?t("schtasks changes Windows scheduled tasks"):[];case"at":case"batch":return L(n,"-l","-r","-d","-c")?[]:e.name==="batch"||n.slice(1).some(s=>!s.startsWith("-"))?t(`${e.name} schedules a command to run later`):[];default:return[]}}var qy=/^(core\.(hookspath|sshcommand|fsmonitor|askpass|gitproxy)|credential\..+|url\..+\.(insteadof|pushinsteadof)|https?\..*\.?(sslcainfo|sslcapath|proxy|extraheader|sslcert|sslkey)|include\.path|includeif\..+\.path|init\.templatedir|filter\..+\.(clean|smudge|process)|diff\..+\.textconv|merge\..+\.driver|gpg\.(program|ssh\.program|x509\.program|openpgp\.program))$/i;function Hy(e,n){if(e.name!=="git")return[];let t=xt(e);if(!t||t.sub!=="config")return[];let s=[...t.args],r="set",o=s[0]??"";["set","unset","get","list","edit","rename-section","remove-section"].includes(o)&&(s.shift(),r=o==="get"||o==="list"?"read":o==="edit"?"edit":o==="set"?"set":"unset");let i=!1,a=[];for(let f=0;f<s.length;f++){let h=s[f];if(h==="--global"||h==="--system")i=!0;else if(h==="-f"||h==="--file"||h.startsWith("--file=")){let g=h.startsWith("--file=")?h.slice(7):s[++f]??"";Io(U(g,e.cwd,n.ctx),n.ctx,[n.ctx.home])==="gitconfig"&&(i=!0)}else h==="--unset"||h==="--unset-all"||h==="--remove-section"||h==="--rename-section"?r="unset":/^(--get|--get-all|--get-regexp|--get-urlmatch|--get-color|--get-colorbool|-l|--list)$/.test(h)?r="read":h==="-e"||h==="--edit"?r="edit":["--type","--default","--comment","--value","-t"].includes(h)?f++:h.startsWith("-")||a.push(h)}if(!i||r==="read")return[];let l=/^\s*(?:\w+=\S*\s+)*(?:HOME|GIT_CONFIG_GLOBAL|XDG_CONFIG_HOME)=["']?([^\s"']+)/.exec(e.text)?.[1]??/(?:^|[;&|\n(]\s*)(?:export\s+)?(?:HOME|GIT_CONFIG_GLOBAL|XDG_CONFIG_HOME)=["']?([^\s"';&|)]+)["']?\s*(?=$|[;&\n|])/.exec(n.lineText.slice(0,Math.max(0,n.lineText.indexOf(e.text))))?.[1];if(l!==void 0&&kt(U(l,e.cwd,n.ctx),n))return[];let c=(a[0]??"").replace(/(:\/\/)[^@/\s]+@/g,"$1***@"),u=f=>[m("claude.bash.persistence",f,{target:c||"git config --global",is_local:!0})];if(r==="edit")return u("git config --global --edit rewrites the global git config");let d=(a[0]??"").toLowerCase(),p=a[1]??"";return r==="unset"?d==="core.hookspath"?u("turns off the git hooks every repository on this machine runs"):[]:a.length<2?[]:/^https?\..*sslverify$/.test(d)?/^(false|0|no|off)$/i.test(p)?u("turns off TLS certificate checks for every repository on this machine"):[]:/^alias\./.test(d)?p.startsWith("!")?u(`adds a git alias that runs a shell command (${a[0]})`):[]:d==="core.fsmonitor"?/^(true|false|0|1|yes|no|on|off)$/i.test(p)?[]:u(`sets ${c} to run a program for every repository`):/^protocol\..*allow$/.test(d)?/^always$/i.test(p)?u(`allows a git transport that can run commands (${c})`):[]:d==="diff.external"?/^(difft|difftastic|delta|diff-so-fancy|icdiff|meld|opendiff|kdiff3|code|ksdiff)(\s|$)/.test(R.basename(p))?[]:u(`sets ${c} to run a program on every diff`):/^(core\.(pager|editor)|sequence\.editor|interactive\.difffilter|pager\.\w+)$/.test(d)?/[;&`>]|\$\(|\b(curl|wget|nc|ncat|base64)\b|\b(sh|bash|zsh|python3?|node|perl|ruby)\s+-[ce]\b/.test(p)?u(`sets ${c} to run a shell command for every repository`):[]:qy.test(d)?u(`sets ${c} for every repository on this machine`):[]}function By(e){let n=Jn(e);if(n===null)return[];let t=zo(n.slice(0,65536));if(!jo(t)||!Po.test(t))return[];let s=/\.delete\s*\(|method\s*[:=]\s*['"]DELETE|request\s*\(\s*['"]DELETE/i.test(t)?"DELETE":/\.(post|put|patch)\s*\(|method\s*[:=]\s*['"](POST|PUT|PATCH)|request\s*\(\s*['"](POST|PUT|PATCH)|Request\([^)]*data\s*=|-X\s*POST/i.test(t)?"POST":null,r=s!==null?wc(t,s,t):null;return r!==null?[m("claude.agent.controls",`changes your Anvil workspace's modes through its API (${r})`,{target:r,is_local:!1})]:[]}function nu(e,n,t){let s=n.lineText.slice(0,Math.max(0,n.lineText.indexOf(e.text))),r=t.join("|"),o=new RegExp(`^\\s*(?:\\w+=\\S*\\s+)*(?:${r})=["']?([^\\s"']+)`).exec(e.text)?.[1],i=[...s.matchAll(new RegExp(`(?:^|[;&|\\n(]\\s*)(?:export\\s+)?(?:${r})=["']?([^\\s"';&|)]+)`,"g"))].map(u=>u[1]),a=o??i[i.length-1];if(!a)return null;let l=a.replace(/^\$\{?([A-Za-z_]\w*)\}?/,(u,d)=>{let p=new RegExp(`(?:^|[;&|\\n(]\\s*)(?:export\\s+)?${d}=(?:"?\\$\\(mktemp\\b[^)]*\\)"?|["']?([^\\s"';&|)]+))`).exec(s);return p?p[1]??`${n.ctx.tmpdir.replace(/(?<!\/)\/+$/,"")}/mktemp`:u});if(C(l)||l.includes("$"))return null;let c=Y(l,e.cwd,te(n));return c.kind==="disposable"&&c.why!==Rn?c.path:null}var Vy=new Set(["node","nodejs","bun","deno","tsx","ts-node","sh","bash","zsh","dash","ksh","source",".","python","python3","perl","ruby"]),Zy=/(?:\.anvil\/claude\/bin\/|useanvil\S*\/|\/anvil\/bin\/)claude-(?:hook|hook-core|sync|meter)\.(?:[cm]?js|sh)\b/;function Gy(e,n){let t=e.argv,s=w(t),r=a=>[m("claude.agent.controls",a,{target:`${e.name} ${s[0]??""}`.trim(),is_local:!0})],o=t.findIndex((a,l)=>t[l+1]==="claude"&&/\$\(|`/.test(v(a))&&/(^|[^\w.-])anvil($|[^\w.-])/.test(v(a)));if(o>=0){let a=Nn(w(["anvil",...t.slice(o+1)]));if(a)return r(a)}let i=t.findIndex(a=>/\$\(|`/.test(v(a))&&/(^|[^\w.-])anvil-claude($|[^\w.-])/.test(v(a)));if(i>=0){let a=_s(w(["anvil-claude",...t.slice(i+1)]),t.slice(i+1));if(a)return r(a)}if(Vy.has(e.name)){let a=t.findIndex((l,c)=>c>0&&Zy.test(/^[/~$]/.test(v(l))?v(l):`${e.cwd??""}/${v(l)}`));if(a>0&&!(/claude-sync\.js$/.test(v(t[a]))&&t.length===a+2&&t[a+1]==="--status"))return r("runs Anvil's own hook by hand: what it records would be made up")}switch(e.name){case"claude":{if((s[0]==="plugin"||s[0]==="plugins")&&["list","ls","validate"].includes(s[1]??"")&&!(s[1]==="list"&&s[2]==="marketplace")||s[0]==="mcp"&&["list","get"].includes(s[1]??"")||s[0]==="config"&&["get","list"].includes(s[1]??"")||s.length===0&&L(t,"--version","-v"))return[];let a=(s[0]==="plugin"||s[0]==="plugins")&&["install","i","enable","disable","uninstall","remove","rm","marketplace"].includes(s[1]??"")||s[0]==="mcp"&&["add","add-json","add-from-claude-desktop","remove"].includes(s[1]??"")||s[0]==="config"&&["set","add","remove"].includes(s[1]??""),l=t.some(($,E)=>["-s","--scope"].includes(t[E-1]??"")&&/^(project|local)$/.test($)||/^(--scope=|-s)(project|local)$/.test($));if(a&&!l&&nu(e,n,["HOME","CLAUDE_CONFIG_DIR"]))return[];if(s[0]==="mcp"&&["add","add-json","add-from-claude-desktop"].includes(s[1]??""))return r(`claude mcp ${s[1]} gives Claude Code a new MCP server`);if(s[0]==="config"&&["set","add"].includes(s[1]??""))return r("claude config changes Claude Code's settings");if(s[0]==="import")return r("claude import brings another agent's MCP servers and settings into Claude Code");if((s[0]==="plugin"||s[0]==="plugins")&&(["install","i","enable"].includes(s[1]??"")||s[1]==="marketplace"&&s[2]==="add"))return r(`claude plugin ${s.slice(1,3).join(" ")} gives Claude Code new hooks, tools or MCP servers`);if((s[0]==="plugin"||s[0]==="plugins")&&(["disable","uninstall","remove","rm"].includes(s[1]??"")||s[1]==="marketplace"&&["remove","rm"].includes(s[2]??"")))return r(`claude plugin ${s.slice(1,3).join(" ")} turns off hooks Claude Code was running`);if(L(t,"--dangerously-skip-permissions","--allow-dangerously-skip-permissions")||j(t,"--permission-mode")==="bypassPermissions")return r("runs Claude Code with its permission checks off");let c=j(t,"--setting-sources"),u=c?.split(",").map($=>$.trim())??[];if(c!==null&&!(u.includes("user")&&u.includes("local")))return r("runs Claude Code without your user or local settings, where Anvil's hook is");let p=`${/^\s*((?:(?:env\s+(?:-\S+\s+)*)?[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+)/.exec(e.text)?.[1]??""} ${e.text.slice(0,Math.max(0,e.text.search(/(^|[\s/])claude(\s|$)/)))}`,f=n.lineText.slice(0,65536);if(/(^|\s)(CLAUDE_CONFIG_DIR|HOME)=/.test(p)||/(^|[\s;&|(])(export|declare\s+-x)\s+(CLAUDE_CONFIG_DIR|HOME)=/.test(f)||/(^|[\s;&|(])CLAUDE_CONFIG_DIR=/.test(f))return r("runs Claude Code with its settings folder moved, away from Anvil's hook");if(/(^|\s)(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(p)||/(^|[\s;&|(])export\s+(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(f))return r("runs Claude Code under another account's key, whose modes its sync would take");if(/(^|[\s;&|(])unset\s+(-v\s+)?CLAUDE_CONFIG_DIR\b|\benv\s+(?:-\S+\s+)*-u\s*CLAUDE_CONFIG_DIR\b/.test(f))return r("runs Claude Code without the settings folder this session uses, where Anvil's hook is");if(L(t,"--bare","--safe-mode")||/(^|\s)(CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE)=/.test(p)||/(^|[\s;&|(])(export\s+|declare\s+-x\s+)?(CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE)=/.test(f))return r("runs Claude Code with hooks and plugins skipped, Anvil's among them");let h=j(t,"--settings");if(h!==null&&/bypassPermissions|dangerously|"Bash(\(\*\))?"|disableAllHooks|"hooks"\s*:/.test(h))return r("runs Claude Code with settings that turn its permission checks off");let g=[];for(let $=1;$<t.length;$++)if(t[$]==="--allowedTools"||t[$]==="--allowed-tools"||/^--allowed-?[tT]ools=/.test(t[$])){t[$].includes("=")&&g.push(t[$].slice(t[$].indexOf("=")+1));for(let E=$+1;E<t.length&&!t[E].startsWith("-");E++)g.push(t[E])}if(g.some($=>/(^|[\s,'"])Bash(\(\*\))?($|[\s,'"])/.test($)))return r("runs Claude Code with every shell command allowed");let y=j(t,"--mcp-config");return y!==null&&!/^\s*\{\s*("mcpServers"\s*:\s*\{\s*\}\s*)?\}\s*$/.test(y)?r("runs Claude Code with MCP servers from a config file"):h!==null&&!h.trim().startsWith("{")?r("runs Claude Code with settings from a file the command does not show"):[]}case"fish":case"set":return/\bset\s+-[a-zA-Z]*U[a-zA-Z]*\s+(CLAUDE_CONFIG_DIR|CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE|ANVIL_CLAUDE_SYNC|ANVIL_WORKSPACE_KEYS_PATH)\b/.test(e.name==="set"?`set ${t.slice(1).join(" ")}`:t.slice(1).join(" "))?r("a fish universal variable changes how every later Claude Code session starts"):[];case"launchctl":{let a=["CLAUDE_CONFIG_DIR","CLAUDE_CODE_SIMPLE","CLAUDE_CODE_SAFE_MODE","ANVIL_CLAUDE_SYNC","ANVIL_WORKSPACE_KEYS_PATH"];return s[0]==="setenv"&&a.includes(s[1]??"")?r(`launchctl setenv ${s[1]} changes how every later Claude Code session starts`):[]}case"anvil":{let a=Nn(s);if(a)return r(a);let l=/^\s*((?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+)/.exec(e.text)?.[1]??"";return s[0]==="claude"&&(/(^|\s)(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(l)||/(^|[\s;&|(])export\s+(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(n.lineText.slice(0,65536)))?r("runs anvil claude under another account's key, whose modes it would take"):e.via==="xargs"&&s[0]==="claude"&&s.length===1?r("anvil claude with its subcommand read from input"):[]}case"anvil-claude":{if(e.via==="xargs"&&s.length===0)return r("anvil-claude with its subcommand read from input");let a=_s(s,t.slice(1));return a?r(a):[]}case"node":case"bun":case"deno":case"tsx":case"ts-node":{let a=t.findIndex((d,p)=>p>0&&!d.startsWith("-")),l=a>0?v(t[a]):"",c=/@useanvil\/claude-code\/|(?:^|\/)anvil-claude$/i.test(l),u=a>0&&(c||/(?:^|\/)(?:@useanvil\/sdk|anvil)(?:\/|\.[cm]?[jt]s$|$)|useanvil/i.test(l))?c?_s(w([e.name,...t.slice(a+1)]),t.slice(a+1)):Nn(w([e.name,...t.slice(a+1)])):null;return u?r(u):[]}case"code":case"code-insiders":return L(t,"--add-mcp")?r(`${e.name} --add-mcp gives an AI agent a new MCP server`):[];case"codex":return s[0]==="mcp"&&s[1]==="add"?r("codex mcp add gives Codex a new MCP server"):L(t,"--dangerously-bypass-approvals-and-sandbox","--yolo")||j(t,"-s","--sandbox")==="danger-full-access"||t.some((a,l)=>(t[l-1]==="-c"||t[l-1]==="--config")&&/^sandbox_mode\s*=\s*["']?danger-full-access/.test(a))?r("runs Codex with its sandbox and approvals off"):[];case"gemini":return s[0]==="mcp"&&s[1]==="add"?r("gemini mcp add gives Gemini CLI a new MCP server"):L(t,"--yolo","-y")||j(t,"--approval-mode")==="yolo"?r("runs Gemini CLI approving every action"):[];case"cursor-agent":return L(t,"--force","-f")?r("runs Cursor Agent without asking before commands"):[];case"aider":return L(t,"--yes-always")?r("runs aider confirming every action"):[];case"amp":return L(t,"--dangerously-allow-all")?r("runs Amp with every action allowed"):[];case"droid":return L(t,"--skip-permissions-unsafe")?r("runs Droid with its permission checks off"):[];case"q":return s[0]==="chat"&&L(t,"--trust-all-tools")?r("runs Amazon Q trusting every tool"):[];case"qwen":case"crush":return L(t,"--yolo","-y")?r(`runs ${e.name} approving every action`):[];case"fastmcp":return s[0]==="install"?r("fastmcp install adds an MCP server to an AI agent"):[];case"copilot":return L(t,"--yolo","--allow-all-tools")?r("runs Copilot CLI approving every tool"):[];case"smithery":return s[0]==="install"||s[0]==="mcp"&&s[1]==="add"?r("installs an MCP server into an AI agent"):[];case"install-mcp":return s.length>0?r("installs an MCP server into an AI agent"):[];case"mcp-get":return s[0]==="install"?r("installs an MCP server into an AI agent"):[];default:return[]}}var Ky=new Set(["deliver","pilot","supply","upload_to_app_store","upload_to_testflight","upload_to_play_store","appstore","testflight","app_store_connect","upload_to_play_store_internal_app_sharing"]),Yy=new Set(["init","download_metadata","download_screenshots","list","builds","export","help"]),Jy=/(^|_)(release|beta|deploy|production|prod|store|publish|submit|upload|ship|distribute|promote|appstore|testflight|playstore|alpha|internal|rollout)(_|$)/i,Xy=/(^|_)(build|test|tests|lint|screenshots?|certs|certificates|match|setup|bump|version|changelog|notes|metadata|precheck|dry_?run|check|verify|dsyms?|symbols|crashlytics|sentry|bugsnag)(_|$)/i;function Qy(e){if(e.some((s,r)=>/^(--)?(validate|verify)_only(:|=)?(true)?$/i.test(s)&&(/true$/i.test(s)||/^true$/i.test(e[r+1]??""))))return!1;let n=w(e);["ios","android","mac"].includes(n[0]??"")&&(n=n.slice(1)),n[0]==="run"&&(n=n.slice(1));let t=n[0]??"";return t==="match"&&n[1]==="nuke"||t==="match_nuke"?!0:Ky.has(t)?!Yy.has(n[1]??""):/(^|_)(dsyms?|symbols|crashlytics|sentry|bugsnag|metadata|screenshots?)(_|$)/i.test(t)?!1:/(^|_)(upload|deploy|submit|distribute|publish|ship|promote|testflight|appstore|playstore|rollout)(_|$)/i.test(t)||/(^|_)and_(release|beta|production|prod|store)(_|$)/i.test(t)?!0:Jy.test(t)&&!Xy.test(t)}function Qr(e){return e.slice(1).some(n=>/^prod(uction)?$/i.test(v(n))||/^--(deployment-?name|deploymentName|destDeploymentName|target-deployment)=prod/i.test(n))}function su(e){return L(e,"-m","--dry-run")?[]:e.slice(1).filter(n=>!n.startsWith("-")&&!n.includes("=")).map(n=>n.slice(n.lastIndexOf(":")+1))}function Cl(e){return su(e).some(n=>/^publish\w*(Bundles?|Apks?|Listing)$|^promote\w*Artifact$/.test(n))}function Al(e){return su(e).some(n=>/^publish(AllPublicationsTo\w+Repository|\w+PublicationTo\w+Repository|ToSonatype|ToMavenCentral|AndReleaseToMavenCentral)?$/.test(n))}var ru=/^(preview|previews|staging|stage|dev|develop|development|test|testing|qa|internal|canary|pr-[\w.-]+|feat(ure)?[/-][\w./-]+)$/i;function eb(e){let n=w(e),[t="",s=""]=(n[0]??"").split(":");if(t==="submit"||t==="build"&&s==="submit")return!0;if(t==="build"&&!s)return L(e,"--auto-submit","--auto-submit-with-profile");if(t==="update"&&!s){let r=j(e,"--branch","--channel");return!(r!==null&&!C(r)&&ru.test(r))}return t==="update"?["republish","rollback","roll-back-to-embedded","edit","revert-update-rollout"].includes(s):t==="channel"?["edit","rollout"].includes(s||(n[1]??"")):t==="deploy"?L(e,"--prod","--production"):!1}function mo(e,n){let t=e.trim();if(/^[A-Za-z_$][\w$.]*$/.test(t)){let s=new RegExp(`(?:^|[^\\w$.])${t.replace(/[.$]/g,r=>`\\${r}`)}\\s*(?::\\s*[\\w.]+\\s*)?=(?!=)\\s*([^\\n;]+)`).exec(n);s&&(t=s[1])}return t=t.replace(/\b(require|__import__|import)\s*\(\s*(['"`])[^'"`]*\2\s*\)/g,"$1()"),[...t.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)].map(s=>s[2]).join("/").replace(/\/{2,}/g,"/")}function yo(e,n,t){let s=e.indexOf("(",n);if(s<0)return[];let r=e.slice(s,s+4e3),o=sr(r,0);return o<0&&s+4e3<e.length&&(t.hit=!0),o>0?hn(r.slice(1,o)):[]}function El(e,n){let t=n,s=Math.max(0,n-400);for(;;){for(;t>s&&/\s/.test(e[t-1]);)t--;if(e[t-1]===")"){let i=0,a=null,l=t-1;for(;l>=s;l--){let c=e[l];if(a){c===a&&e[l-1]!=="\\"&&(a=null);continue}if(c==='"'||c==="'"||c==="`")a=c;else if(c===")")i++;else if(c==="("&&--i===0)break}if(l<s)return null;t=l}let o=t;for(;o>s&&/[\w$]/.test(e[o-1]);)o--;if(o===t&&e[t]!=="(")return null;if(t=o,e[t-1]==="."&&t-1>s){t--;continue}break}let r=e.slice(t,n).trim();return r===""?null:r}var tb=/^\s*[rRbB]?['"][rwxabt+U]{1,4}['"]\s*$/,Rl=/['"][^'"]*[wax+]|\bO_(?:WRONLY|RDWR|CREAT|TRUNC|APPEND)\b/,nb=/\b(exec|eval|compile|execfile|run_path|run_module|system|popen|spawn|spawnSync|execSync|execFileSync|Function|vm\.run\w*|subprocess\.\w+|os\.exec\w*)\s*\(/;function zo(e){return!/'''|"""|`[^`]*\n/.test(e)||nb.test(e)?e:e.replace(/('''|""")([\s\S]*?)\1|`((?:\\.|[^`\\])*\n(?:\\.|[^`\\])*)`/g,n=>{let t=n.startsWith("'''")||n.startsWith('"""')?3:1;return n.slice(0,t)+n.slice(t,n.length-t).replace(/[^\n]/g," ")+n.slice(n.length-t)})}function ou(e,n,t){let s=[],r=zo(e),o=(a,l=!0)=>{let c=mo(a,e);c!==""?s.push({path:c,content:l,expr:a}):t&&t.n++},i=a=>yo(e,a,n);for(let a of Ze([...r.matchAll(/\b(?:f?open|openSync|File\.new)\s*\(/g)],n)){let l=i(a.index),c=(l.find(u=>/^\s*mode\s*=/.test(u))??"").replace(/^\s*mode\s*=/,"");if(e[a.index-1]==="."&&(tb.test(l[0]??"")||/^\s*mode\s*=/.test(l[0]??""))){let u=Rl.test(c||l[0])?El(e,a.index-1):null;u&&o(u);continue}Rl.test(l[1]??c)&&o(l[0]??"")}for(let a of Ze([...r.matchAll(/\.(write_text|write_bytes|unlink|chmod|rename|replace|touch)\s*\(/g)],n)){let l=El(e,a.index);l&&o(l,a[1]==="write_text"||a[1]==="write_bytes"),a[1]==="rename"?o(i(a.index)[0]??""):a[1]==="replace"&&l&&sb(l,e)&&o(yo(e,a.index,{hit:!1})[0]??"")}for(let a of Ze([...r.matchAll(/\b(writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|truncateSync|truncate|outputFileSync|outputFile|outputJsonSync|outputJson|writeJsonSync|writeJson|file_put_contents|Deno\.writeTextFileSync|Deno\.writeTextFile|Deno\.writeFileSync|Deno\.writeFile|Bun\.write|(?:File|IO)\.(?:write|binwrite))\s*\(/g)],n))o(i(a.index)[0]??"");for(let a of Ze([...r.matchAll(/\b(rmSync|unlinkSync|unlink|chmodSync|chmod|Deno\.remove|os\.remove|os\.unlink|os\.chmod|shutil\.rmtree|rmtree|rimraf(?:\.sync)?|fse?\.removeSync|fse?\.remove|(?:File|IO)\.(?:delete|unlink)|FileUtils\.(?:rm|rm_f|rm_rf|remove_dir|touch))\s*\(/g)],n))o(i(a.index)[0]??"",!1);for(let a of Ze([...r.matchAll(/\bfileinput\.(?:input|FileInput)\s*\(/g)],n)){let l=i(a.index);if(!l.some(d=>/^\s*inplace\s*=\s*(?:True|1)\s*$/.test(d)))continue;let c=(l.find(d=>/^\s*files\s*=/.test(d))??l.find(d=>!/^\s*\w+\s*=/.test(d))??"").replace(/^\s*files\s*=\s*/,"").trim(),u=/^[[(]([\s\S]*)[\])]$/.exec(c);for(let d of u?hn(u[1]):[c])o(d.trim())}for(let a of Ze([...r.matchAll(/\bopen\s*\(?\s*(?:my\s+)?(?:\$\w+|[A-Z]\w*)\s*,\s*['"](?:\+?>{1,2}|\+<)['"]\s*,\s*([^;)]+)/g)],n))o(a[1].trim());for(let a of Ze([...r.matchAll(/\bopen\s*\(?\s*(?:my\s+)?(?:\$\w+|[A-Z]\w*)\s*,\s*(['"])\s*(?:\+?>{1,2}|\+<)\s*([^'"]+)\1/g)],n))o(`"${a[2].trim()}"`);for(let a of Ze([...r.matchAll(/\b(copyFileSync|copyFile|renameSync|rename|cpSync|(?<=\.)cp|(?:fse?|fsExtra)\.(?:copySync|copy|moveSync|move)|shutil\.copy\w*|shutil\.move|os\.replace|os\.rename|FileUtils\.(?:cp|mv|ln_s|ln_sf|cp_r)|File\.rename)\s*\(/g)],n)){let l=i(a.index);o(l[1]??""),/rename|move|replace/.test(a[1])&&o(l[0]??"",!1)}return s}function sb(e,n){if(/\b(?:pathlib\.)?Path\s*\(|\.with_(?:name|suffix|stem)\s*\(/.test(e))return!0;let t=/^[A-Za-z_]\w*$/.exec(e.trim())?.[0];return t!==void 0&&new RegExp(`(?:^|[^\\w.])${t}\\s*=\\s*(?:pathlib\\.)?Path\\s*\\(`).test(n)}var rb=/(?:\b(?:os\.symlink|os\.link|fs\.symlinkSync|fs\.symlink|fs\.linkSync|fs\.link|symlinkSync|linkSync|File\.symlink|File\.link|FileUtils\.ln_sf|FileUtils\.ln_s|FileUtils\.ln|Deno\.symlinkSync|Deno\.symlink|symlink)|\.(?:symlink_to|hardlink_to))\s*\(/g,Ol=/\.claude(\/settings(\.local)?\.json|\/hooks(\/.*)?)?\/?$|\.claude\.json$|\.mcp\.json$|\.anvil\/(claude(\/.*)?|rules\.json)$|Library\/Launch(Agents|Daemons)\/|\.gitconfig$/,ob=/(?:^|[;\n])[ \t]*(?:from\s+google\.cloud\s+import\s+bigquery\b|import\s+google\.cloud\.bigquery\b|import\s+snowflake\b|from\s+snowflake\b|import\s+redshift_connector\b|from\s+databricks\b[\w.]*\s+import\b|(?:const|let|var|import)\b[^\n;]{0,80}(?:require\(\s*|from\s+)['"](?:@google-cloud\/bigquery|snowflake-sdk|@databricks\/sql)['"])/;function ib(e,n){let t=Jn(e);if(t===null)return[];let s=[],r=ou(t,n.cut);for(let o of r){if(!o.content||!ye(o.path))continue;let i=qt(o.expr,t,e,0,n.ctx.home,n.cut);if(!(i===null||i.startsWith("/dev/")||!ye(i))&&qe(i,e,n).kind!=="disposable"){s.push(m("claude.file.write_secret",`writes a secrets file (${R.basename(v(i))}) (from ${e.name})`,{target:v(i),is_local:!0}));break}}for(let{path:o}of r){let i=v(o);if(!Ol.test(i)){let h=i.startsWith("/")?i:U(i,e.cwd,n.ctx);if(ln(n,C(o)?U(o,e.cwd,n.ctx):h),rt.test(h)&&fn(t)){s.push(m("claude.agent.controls",`changes how every later Claude Code session starts (${R.basename(h)}) (from ${e.name})`,{target:v(h),is_local:!0}));continue}let g=C(h)?null:Bn(h,n.ctx,[n.projectRoot,n.base]);if(g){s.push({...g,why:`${g.why} (from ${e.name})`});continue}let y=Ie(h,e,n),$=y!==h?y:bs(h,n.ctx.onDisk,!0);if($===null||!Ol.test($))continue;let E=Bn($,n.ctx,[n.projectRoot,n.base]);if(E){s.push({...E,why:`${E.why} (from ${e.name})`});continue}continue}let a=i.replace(/^(\$ENV\{['"]?HOME['"]?\}|ENV\[['"]HOME['"]\]|\$?\{[^}]*\}|HOME|~|USERPROFILE|homedir\(\))\/?/,""),l=/\b(HOME|homedir|expanduser|USERPROFILE)\b|Path\.home\b/.test(t),c=/^\/(\.claude|\.mcp\.json|\.gitconfig|\.anvil\/|Library\/)/.test(i),u=i!==a||/^(\.claude\.json|\.gitconfig|Library\/)/.test(a)||c&&l,d=u?nu(e,n,["HOME"])??n.ctx.home:n.ctx.home,p=i.startsWith("/")&&!(c&&l)?i:u?`${d}/${a.replace(/^\/+/,"")}`:U(a,e.cwd,n.ctx);ln(n,p);let f=Bn(Ie(p,e,n),n.ctx,[n.projectRoot,n.base]);if(f){s.push({...f,why:`${f.why} (from ${e.name})`});continue}}for(let o of Ze([...t.matchAll(rb)],n.cut)){let i=yo(t,o.index,n.cut)[0];if(i===void 0)continue;let a=qt(i,t,e,0,n.ctx.home,n.cut)??mo(i,t);if(!a||C(a)||a.startsWith(pn))continue;let l=U(a,e.cwd,n.ctx);if(!eu(l,n))continue;let c=n.ctx.home.replace(/(?<!\/)\/+$/,""),u=l===c?"~":l.startsWith(`${c}/`)?`~${l.slice(c.length)}`:l;s.push(m("claude.agent.controls",`links to a folder that holds Anvil's or Claude Code's settings (${u}) (from ${e.name})`,{target:l,is_local:!0}));break}if(/\bread_sql(_query|_table)?\s*\(/.test(t)&&/\.to_(csv|parquet|json|excel|feather|pickle|orc|hdf)\s*\(/.test(t)&&!/localhost|127\.0\.0\.1|sqlite/i.test(t)&&s.push(m("claude.bash.data.export",`copies query rows from a database into a file (from ${e.name})`,{target:e.name,host:null,is_local:!1})),/\.to_gbq\s*\([^)]{0,500}if_exists\s*=\s*['"]replace/.test(t)&&s.push(m("claude.bash.db.destructive",`replaces a BigQuery table (from ${e.name})`,{target:e.name,host:"bigquery",is_local:!1})),(/\bfrom\s+pyngrok\s+import\b|\bimport\s+pyngrok\b/.test(t)&&/\bngrok\.connect\s*\(/.test(t)||/require\(\s*['"](localtunnel|ngrok|@ngrok\/ngrok)['"]\s*\)|\bngrok\.(forward|connect)\s*\(/.test(t))&&s.push(m("claude.bash.net.expose",`opens a local port to the internet (from ${e.name})`,{target:e.name,host:null,is_local:!1})),ob.test(t)){let o=(()=>{if(/\.(delete_table|delete_dataset|delete_model|delete_routine)\s*\(|\.(table|dataset)\([^)]*\)\.delete\s*\(/.test(t))return"deletes warehouse data";for(let i of Ze([...t.matchAll(/\.(query|execute|execute_string|executemany|sql|run_query)\s*\(/g)],n.cut)){let a=t.indexOf("(",i.index),l=t.slice(a,a+4e3),c=sr(l,0);c<0&&a+4e3<t.length&&(n.cut.hit=!0);let u=c>0?hn(l.slice(1,c))[0]??"":"",d=/^\s*[A-Za-z_$][\w$]*\s*$/.test(u)&&mo(u,t)||u,p=be.exec(d)??qn.exec(d);if(p)return`runs destructive SQL (${p[1].replace(/\s+/g," ").toUpperCase()})`}return null})();o&&s.push(m("claude.bash.db.destructive",`${o} through a warehouse client (from ${e.name})`,{target:e.name,host:/bigquery/i.test(t)?"bigquery":/snowflake/i.test(t)?"snowflake":/databricks/i.test(t)?"databricks":"redshift",is_local:!1}))}return s}function ab(e,n){let t=e.argv,s=[],r=null;if(e.name==="tmux"&&["new","new-session","new-window","neww","split-window","splitw","respawn-pane"].includes(t[1]??""))s=[ce(t,2,new Set(["-s","-n","-t","-c","-x","-y","-F","-e","-l","-f"])).join(" ")],r="tmux";else if(e.name==="tmux"&&["send-keys","send"].includes(t[1]??""))s=[ce(t,2,new Set(["-t","-N"])).filter(i=>!/^(Enter|C-m|KPEnter)$/.test(i)).join(" ")];else if(e.name==="screen"){let i=1;for(;i<t.length&&t[i].startsWith("-");)i+=/^-[A-Za-z]*[ScpTXh]$/.test(t[i])||t[i]==="-Logfile"?2:1;s=[t.slice(i).join(" ")],r="screen"}else if(e.name==="concurrently")s=ce(t,1,new Set(["-n","--names","-c","--prefix-colors","-p","--prefix","-s","--success","--restart-tries"]));else if(e.name==="kitty"&&t[1]==="@"&&t[2]==="launch"||e.name==="wezterm"&&t[1]==="cli"&&t[2]==="spawn"||e.name==="zellij"&&(t[1]==="run"||t[1]==="r")||e.name==="systemd-run"){let i=t.indexOf("--"),a=e.name==="systemd-run"?1:e.name==="zellij"?2:3,l=i>=0?t.slice(i+1):ce(t,a,new Set(["--type","--title","--cwd","-u","--unit","-p","--property","--uid","--gid","--name","-n","--pane-id","--domain","--workspace"]));if(l.length===0)return[];s=[l.join(" ")],r=e.name}else if(e.name==="launchctl"){let i=t.slice(1).find(a=>!a.startsWith("-"))??"";if(i==="submit"){let a=t.indexOf("--");if(a<0)return gt("launchctl submit");s=[t.slice(a+1).join(" ")],r="launchctl submit"}else if(i==="load"||i==="bootstrap")return gt(`launchctl ${i}`)}else if(e.name==="crontab"||e.name==="at"||e.name==="batch"){let i=t.slice(1).filter(c=>/^-[A-Za-z]+$/.test(c));if(e.name==="crontab"&&i.some(c=>/[lTVre]/.test(c)))return[];if(e.name!=="crontab"&&i.some(c=>/[lrdcq]/.test(c)))return[];let a=e.name==="crontab"?t.slice(1).filter(c=>!c.startsWith("-")||c==="-").filter(c=>c!=="-"):[],l=a.length===1?pb(a[0],e,n):a.length===0&&!t.includes("-f")?Pl(e)??(e.name==="crontab"?hb(e,n):null):null;if(l===null)return gt(e.name);s=e.name==="crontab"?gb(l):l.split(`
|
|
72
|
-
`),r=e.name}else if(e.name==="osascript"){let
|
|
73
|
-
`):
|
|
74
|
-
`).replace(/\\t/g," "):null:
|
|
75
|
-
`)}function
|
|
69
|
+
`)}`:"");if(s==="sftp"&&(c??=[...u.matchAll(/(?:^|\n|;)\s*put\s+(?:-\w+\s+)*(\S+)/g)].map(h=>h[1]).find(h=>Le(h))??null),c===null)return[];let f=pe(n,1,s==="ssh"?Xy:s==="sftp"?Qy:eb),p=s==="socat"?n.slice(1).map(h=>/^(?:TCP|TCP4|TCP6|SSL|OPENSSL|UDP)[^:]*:([^:,]+)/i.exec(h)?.[1]).find(h=>h!==void 0)??null:f[0]?Zn(f[0]):null;return["nc","ncat","netcat"].includes(s)&&n.slice(1).some(h=>/^-[A-Za-z]*l/.test(h))?p!==null&&Re(p)?[]:r(c,"anyone who connects"):p===null||Re(p)?[]:r(c,k(p))}default:return[]}}var sb="BbcDEeFIiJLlmOoPpQRSWw";function Pl(e){let t=!1;for(let n=1;n<e.length;n++){let s=e[n];if(s==="--")return!1;if(!s.startsWith("-")){if(t)return!1;t=!0;continue}if(!s.startsWith("--"))for(let r=1;r<s.length;r++){let o=s[r];if(o==="R")return!0;if(o==="o"){let a=r+1<s.length?s.slice(r+1):e[n+1]??"";if(/^RemoteForward\b/i.test(a))return!0}if(sb.includes(o)){r===s.length-1&&n++;break}}}return!1}function $o(e){let t=e.argv,n=v(t),s=r=>[m("claude.bash.net.expose",r,{target:`${e.name} ${n[0]??""}`.trim(),is_local:!1})];switch(e.name){case"ngrok":return["http","tcp","tls","start","tunnel"].includes(n[0]??"")||n[0]==="service"&&["install","start"].includes(n[1]??"")?s(`ngrok ${n[0]} opens a local port to the internet`):[];case"cloudflared":return n[0]==="access"?[]:T(t,"--url","--hello-world")||n[0]==="tunnel"&&(n.includes("run")||n.includes("route"))||n[0]==="service"&&n[1]==="install"?s("cloudflared opens a tunnel from the internet to this machine"):[];case"lt":return T(t,"--port","-p")?s("localtunnel opens a local port to the internet"):[];case"tailscale":return n[0]==="funnel"&&!["status","reset"].includes(n[1]??"")&&!n.includes("off")?s("tailscale funnel opens a local port to the internet"):[];case"ssh":case"autossh":return e.name==="ssh"&&t.slice(1).some(r=>/^-[a-zA-Z]*G[a-zA-Z]*$/.test(r))?[]:Pl(e.name==="autossh"?t.filter((r,o)=>!(r==="-M"||t[o-1]==="-M"||/^-M\d/.test(r))):t)?s(`${e.name} -R opens a port on another machine that reaches this one`):[];case"gcloud":{let r=t.indexOf("--");return n[0]==="compute"&&n[1]==="ssh"&&r>0&&Pl(["ssh",...t.slice(r+1),"host"])?s("gcloud compute ssh -R opens a port on a VM that reaches this machine"):[]}case"frpc":return["verify","status","reload","stop"].includes(n[0]??"")||T(t,"-v","--version")?[]:s("frpc exposes local services through an frp server");case"bore":return n[0]==="local"?s("bore opens a local port to the internet"):[];case"zrok":return n[0]==="share"&&n[1]==="public"?s("zrok shares a local port publicly"):[];case"loclx":case"localxpose":return n[0]==="tunnel"?s("localxpose opens a local port to the internet"):[];case"devtunnel":return n[0]==="host"&&T(t,"--allow-anonymous","-a")?s("devtunnel host lets anyone reach a local port"):[];case"ddev":case"valet":case"herd":return n[0]==="share"?s(`${e.name} share serves this project at a public URL`):[];case"tmole":case"tunnelmole":return n.length>0?s(`${e.name} opens a local port to the internet`):[];case"untun":return n[0]==="tunnel"?s("untun opens a local port to the internet"):[];case"expo":return n[0]==="start"&&T(t,"--tunnel")?s("expo start --tunnel serves the dev server at a public URL"):[];case"code":case"code-insiders":return n[0]==="tunnel"&&!["status","kill","unregister","prune","rename","user","help"].includes(n[1]??"")?s(`${e.name} tunnel opens this machine to remote access over the internet`):[];case"docker":case"podman":{let r=gu(t);if(!r)return[];let o=/(^|\/)(cloudflared|ngrok)(:[^/]*)?$/.exec(r.image)?.[2];return o?$o({...e,name:o,argv:[o,...r.args]}):[]}default:return[]}}var rb=new Set(["-e","--env","--env-file","-v","--volume","-p","--publish","--name","--network","--net","-w","--workdir","-u","--user","--entrypoint","--mount","-l","--label","--label-file","--restart","-m","--memory","--memory-swap","--cpus","--cpu-shares","-c","--platform","--pull","--add-host","--dns","-h","--hostname","--device","--cap-add","--cap-drop","--gpus","--log-driver","--log-opt","--ulimit","--shm-size","--tmpfs","--ipc","--pid","--security-opt","--stop-signal","-a","--attach","--cidfile","--expose","--link","--runtime","--userns","--volumes-from","--group-add","--health-cmd"]);function gu(e){let t=1;if((e[t]==="container"||e[t]==="compose")&&t++,e[t]!=="run")return null;let n=null;for(t++;t<e.length;t++){let s=e[t];if(s.startsWith("--entrypoint")&&(n=s.includes("=")?s.slice(s.indexOf("=")+1):e[t+1]??null),!s.startsWith("-"))return{image:k(s),args:n?[n,...e.slice(t+1)]:e.slice(t+1)};(rb.has(s)||s==="--entrypoint")&&t++}return null}function Fn(e){if(/^\s*(explain|describe|desc|show)\b/i.test(e)||/\bfrom\s+(information_schema|pg_catalog|sys|mysql)\./i.test(e))return!1;let t=e.search(/\bfrom\b/i);if(!/\bselect\b/i.test(e)||t<0)return!1;let n=e.slice(0,t);if(/\bselect\s+(count|sum|avg|min|max)\s*\(/i.test(n)&&!n.includes(","))return!1;let s=/\blimit\s+(\d+)/i.exec(e);return!(s&&Number(s[1])<=1e3)}function ht(e){for(let t=e;t;t=t.pipeTo)if(t.redirects.some(n=>[">",">>",">|","&>","&>>"].includes(n.op)&&(n.fd===null||n.fd===1)&&n.target!==null&&!n.target.startsWith("/dev/"))||t!==e&&t.name==="tee"&&t.argv.slice(1).some(n=>!n.startsWith("-")))return!0;return!1}var ob=new Set(["-f","--file","-F","--format","-j","--jobs","-n","--schema","-N","--exclude-schema","-t","--table","-T","--exclude-table","-Z","--compress","-E","--encoding","-h","--host","-p","--port","-U","--username","-d","--dbname","--role","-S","--superuser","--exclude-table-data","--lock-wait-timeout","--section","--snapshot","-l","--database"]);function Wl(e,t){let n=e.argv,s=e.name,r=null,o=!0;switch(s){case"pg_dump":case"pg_dumpall":case"pg_basebackup":{if(T(n,"--schema-only")||n.some(f=>/^-[A-Za-z]+$/.test(f)&&/^[^fFjnNtTZEhpUdSlD]*s/.test(f.slice(1))))return[];r=P(n,"-h","--host")??/(?:^|[\s;&|(])(?:export\s+)?PGHOST=["']?([^\s"';&|)]+)/.exec(t.lineText)?.[1]??null;let u=P(n,"-d","--dbname")??pe(n,1,ob)[0]??null;u!==null&&(S(u)?o=r!==null&&!S(r)&&Ut(r):/^postgres(ql)?:\/\//i.test(u)?r=/^postgres(?:ql)?:\/\/(?:[^@/]*@)?([^/:?#]*)/i.exec(u)?.[1]||/[?&]host=([^&]+)/.exec(u)?.[1]||r:/\bhost=/.test(u)&&(r=/\bhost=([^\s]+)/.exec(u)?.[1]??r));break}case"psql":case"pgcli":{let u=e.pipeFrom&&["echo","printf","cat"].includes(e.pipeFrom.name)?e.pipeFrom.argv.slice(1).join(" ")+(e.pipeFrom.stdin??""):"",f=[P(n,"-c","--command")??"",e.stdin??"",u].join(`
|
|
70
|
+
`),p=Fn(ke(f))&&(ht(e)||P(n,"-o","--output")!==null);if(!/\\copy\s+(\([\s\S]{0,4000}?\)|\S+)\s+to\b/i.test(f)&&!/\bcopy\s+(\([\s\S]{0,4000}?\)|\S+)\s+to\s+stdout\b/i.test(f)&&!p)return[];r=P(n,"-h","--host");let d=P(n,"-d","--dbname")??Gc(n)[0]??null;d!==null&&(S(d)?o=r!==null&&!S(r)&&Ut(r):(/^postgres(ql)?:\/\//i.test(d)||/\bhost=/.test(d))&&(r=/\bhost=([^\s]+)/.exec(d)?.[1]??de(d)??r));break}case"mysqldump":case"mariadb-dump":case"mysqlpump":case"mydumper":if(T(n,"--no-data","-d"))return[];r=P(n,"-h","--host");break;case"mysql":case"mariadb":case"clickhouse-client":case"clickhouse":{let u=P(n,"-e","--execute","-q","--query")??e.stdin??"";if(!Fn(ke(u,"mysql"))||!(ht(e)||/\binto\s+outfile\b/i.test(u)))return[];r=P(n,"-h","--host");break}case"mongosh":case"mongo":{let u=P(n,"--eval")??e.stdin??"";if(!/\.(find|aggregate)\s*\(/.test(u)||!ht(e))return[];let f=n.slice(1).find(p=>/^mongodb(\+srv)?:\/\//i.test(k(p))||S(p)&&!p.startsWith("-"))??null;r=P(n,"--host")??(f&&!S(f)?de(f):null),f!==null&&S(f)&&(o=!1);break}case"sqlcmd":{let u=P(n,"-Q","-q")??e.stdin??"";if(!Fn(ke(u))||!(P(n,"-o")!==null||ht(e)))return[];r=(P(n,"-S")??"").replace(/^tcp:/i,"").split(/[,\\]/)[0]||null,r!==null&&/^(\.|\(local\)|localhost)$/i.test(r)&&(r="localhost"),r===null&&(o=!1);break}case"bcp":{if(!["out","queryout"].includes(n[2]??""))return[];r=P(n,"-S"),r!==null&&/^(\.|\(local\)|localhost)(\\|,|$)/i.test(r)&&(r="localhost"),r===null&&(o=!1);break}case"mongodump":case"mongoexport":{let u=P(n,"--uri")??n.find(f=>/^mongodb(\+srv)?:\/\//i.test(k(f)))??null;r=P(n,"--host","-h")??(u&&!S(u)?de(u):null),u!==null&&S(u)&&(o=!1);break}case"redis-cli":{if(!T(n,"--rdb"))return[];let u=P(n,"-u");r=P(n,"-h")??(u?S(u)?u:de(u):null),u!==null&&S(u)&&(o=!1);break}case"snowsql":case"snow":{let u=v(n);if(s==="snow"&&u[0]!=="sql")return[];let f=P(n,"-q","--query")??e.stdin??"";return Fn(ke(f,"snowflake"))&&(ht(e)||n.some(p=>/^output_file=/i.test(p)))?[m("claude.bash.data.export",`${s} copies query rows from Snowflake onto this machine`,{target:"snowflake",host:"snowflake",is_local:!1})]:[]}case"bq":{let u=v(n),f=u[0]==="query"?[u.slice(1).join(" "),e.stdin??""].join(`
|
|
71
|
+
`):"";return u[0]==="query"&&Fn(ke(f,"bigquery"))&&ht(e)?[m("claude.bash.data.export","bq query copies table rows onto this machine",{target:"bigquery",host:"bigquery",is_local:!1})]:[]}case"gsutil":case"gcloud":{if(re("compute","ssh")(n)&&/\b(pg_dump|pg_dumpall|mysqldump|mongodump|mongoexport)\b/.test(P(n,"--command")??"")&&ht(e))return[m("claude.bash.data.export","dumps a database on a VM and streams it onto this machine",{target:"gcloud compute ssh",host:"gcloud",is_local:!1})];let u=v(n),f=s==="gsutil"?u.slice(1):u[0]==="storage"?u.slice(2):[],p=s==="gsutil"?u[0]:u[1];return["cp","rsync"].includes(p??"")&&f.length>=2&&f[0].startsWith("gs://")&&!f[f.length-1].startsWith("gs://")&&/\bbq\s+extract\b/.test(t.lineText)?[m("claude.bash.data.export","downloads a table the line exported from BigQuery",{target:f[0],host:"bigquery",is_local:!1})]:[]}case"wrangler":return v(n)[0]==="d1"&&v(n)[1]==="export"&&T(n,"--remote")&&!T(n,"--no-data")?[m("claude.bash.data.export","wrangler d1 export copies a remote D1 database onto this machine",{target:"d1",host:"cloudflare",is_local:!1})]:[];case"pscale":return re("database","dump")(n)?[m("claude.bash.data.export","pscale database dump copies a PlanetScale database onto this machine",{target:"planetscale",host:"planetscale",is_local:!1})]:[];case"turso":return re("db","shell")(n)&&n.some(u=>u===".dump")?[m("claude.bash.data.export","turso db shell .dump copies a Turso database onto this machine",{target:"turso",host:"turso",is_local:!1})]:[];case"aws":return re("dynamodb","scan")(n)&&ht(e)?[m("claude.bash.data.export","aws dynamodb scan copies a table onto this machine",{target:"dynamodb",host:"dynamodb",is_local:!1})]:[];case"curl":case"wget":return/\bheroku\s+pg:backups:url\b/.test(t.lineText)?[m("claude.bash.data.export","downloads a Heroku production backup onto this machine",{target:"heroku",host:"heroku",is_local:!1})]:[];case"fly":case"flyctl":{let u=P(n,"-C","--command")??"";return re("ssh","console")(n)&&/\b(pg_dump|pg_dumpall|mysqldump|mongodump|mongoexport)\b/.test(u)?[m("claude.bash.data.export","dumps a Fly database and streams it onto this machine",{target:"fly",host:"fly",is_local:!1})]:[]}case"heroku":return/^pg:(pull|backups:download)$/.test(v(n)[0]??"")?[m("claude.bash.data.export",`heroku ${v(n)[0]} copies a production database onto this machine`,{target:"heroku",host:"heroku",is_local:!1})]:[];case"supabase":return re("db","dump")(n)&&T(n,"--data-only")&&!T(n,"--local")&&!Ic(n)?[m("claude.bash.data.export","supabase db dump copies a linked database's data onto this machine",{target:"supabase",host:"supabase",is_local:!1})]:[];default:return[]}let a=e.remote===null||e.remote.startsWith("container:"),i=yt(t.lineText),l=r===null||!S(r)&&Ut(r);if(o&&!e.productionEnv&&a&&l&&i===null)return[];let c=i!==null&&l?`a database forwarded here (${i})`:r?fn(r):e.productionEnv?"production (railway run)":e.remote??"a database the command does not name";return[m("claude.bash.data.export",`${s} copies the data of ${c} onto this machine`,{target:c,host:r?fn(r):e.remote,is_local:!1})]}var ib=/^((https?|wss?):\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|anvil|hardhat|ganache)\b|^(localhost|hardhat|anvil|ganache|localnet|local|development|l)$/i,Nl=/sepolia|holesky|hoodi|goerli|rinkeby|ropsten|kovan|testnet|devnet|localnet|amoy|mumbai|fuji|chapel|alfajores|chiado|moonbase|baobab|calibration|shasta|nile|bepolia|hekla|garnet|cardona|fork|^d$|^t$/i,Ll=/0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80|0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d/i;function Ue(e){if(e===null)return!1;let t=k(e).replace(/^["']|["']$/g,""),n=/^([a-z][a-z0-9+.-]*:\/\/)?([^/?#\s]+)([^?#\s]*)/i.exec(t);if(n&&(n[1]||n[3])){let s=n[2].replace(/:\d+$/,"").replace(/^[^@]*@/,"").toLowerCase();return/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|anvil|hardhat|ganache|host\.docker\.internal)$/.test(s)?!0:Nl.test(`${s}${n[3]}`)}return ib.test(t)||Nl.test(t)}function Tl(e,t){let n=e.argv,s=v(n),r=i=>i===null?null:fn(i),o=(i,l)=>[m("claude.bash.crypto.transaction",`${i} on ${r(l)??"a network the command does not name"}`,{target:`${e.name} ${s[0]??""}`.trim(),host:r(l),is_local:!1})],a=()=>P(n,"--rpc-url","-r","--fork-url",...e.name==="forge"?["-f"]:[])??/(?:^|[\s;&|(])(?:export\s+)?ETH_RPC_URL=["']?([^\s"';&|)]+)/.exec(t.lineText)?.[1]??null;switch(e.name){case"cast":{if(!(["send","s","publish"].includes(s[0]??"")||s[0]==="rpc"&&/^(eth_sendRawTransaction|eth_sendTransaction|personal_sendTransaction)$/.test(s[1]??"")))return[];let l=a();return Ue(l)||l===null&&Ll.test(n.join(" "))?[]:o(`cast ${s[0]} sends a transaction`,l)}case"forge":{if(!(s[0]==="script"&&T(n,"--broadcast","--resume")||s[0]==="create"))return[];let l=a();return Ue(l)||l===null&&Ll.test(n.join(" "))?[]:o(`forge ${s[0]} ${s[0]==="create"?"deploys a contract":"broadcasts transactions"}`,l)}case"solana":case"spl-token":{if(!(e.name==="solana"?["transfer","deploy","pay","delegate-stake","deactivate-stake","withdraw-stake","create-stake-account","split-stake","merge-stake","withdraw-from-vote-account","close-vote-account"].includes(s[0]??"")||s[0]==="program"&&["deploy","close","set-upgrade-authority","extend","write-buffer","upgrade"].includes(s[1]??""):["transfer","mint","burn","close","authorize","approve","create-token","create-account","wrap","unwrap","freeze","thaw"].includes(s[0]??"")))return[];let l=P(n,"--url","-u")??/\bsolana\s+config\s+set\s+(?:--url|-u)\s+(\S+)/.exec(t.lineText)?.[1]??null,c={m:"mainnet-beta",d:"devnet",t:"testnet",l:"localhost"};return Ue(l)?[]:o(`${e.name} ${s[0]} sends a transaction`,l===null?null:c[l]??l)}case"anchor":{if(!["deploy","upgrade","migrate"].includes(s[0]??""))return[];let i=P(n,"--provider.cluster");return Ue(i)?[]:o(`anchor ${s[0]} deploys a program`,i)}case"bitcoin-cli":case"lncli":{let i=pe(n,1,new Set(["--network","--rpcserver","--macaroonpath","--tlscertpath","--lnddir","--chain","--profile"]))[0]??"";if(!(e.name==="bitcoin-cli"?["sendtoaddress","sendmany","send","sendall","sendrawtransaction","bumpfee"].includes(i):["sendpayment","payinvoice","sendcoins","sendmany","openchannel","closechannel","closeallchannels","sendtoroute"].includes(i)))return[];let c=n.find(f=>/^-(regtest|testnet|testnet4|signet)$|^--?(chain|network)=/.test(f))??(P(n,"--network","--chain")!==null?`--network=${P(n,"--network","--chain")}`:null);return c!==null&&/regtest|testnet|signet|(chain|network)=(test|regtest|signet|simnet)/i.test(c)?[]:o(`${e.name} ${i} sends a payment`,c===null?"mainnet":c)}case"near":{let i=["deploy","send","send-near","call","delete","delete-account","stake","contract","tokens","transaction"].includes(s[0]??""),l=n.some(c=>/mainnet/i.test(c)||/\.near$/.test(c))||/\bNEAR_ENV=mainnet\b/.test(t.lineText);return i&&l?o(`near ${s[0]} sends a transaction`,"mainnet"):[]}case"starkli":{if(!["invoke","deploy","declare","transfer"].includes(s[0]??"")&&!(s[0]==="account"&&s[1]==="deploy"))return[];let i=P(n,"--network","--rpc");return Ue(i)?[]:o(`starkli ${s[0]} sends a transaction`,i)}case"stellar":case"soroban":{if(!(s[0]==="contract"&&["invoke","deploy","install","upload","extend","restore"].includes(s[1]??"")||s[0]==="tx"&&["send","new"].includes(s[1]??"")))return[];let l=P(n,"--network","--rpc-url");return l!==null&&/^(testnet|futurenet|local|standalone)$/i.test(l)?[]:Ue(l)?[]:o(`${e.name} ${s[0]} ${s[1]} sends a transaction`,l)}case"cardano-cli":return n.includes("submit")?n.some(i=>i==="--testnet-magic"||i.startsWith("--testnet-magic="))?[]:o("cardano-cli submits a transaction",n.includes("--mainnet")?"mainnet":null):[];case"sui":{if(!(s[0]==="client"&&["publish","upgrade","transfer","transfer-sui","pay","pay-sui","pay-all-sui","call","split-coin","merge-coin","ptb"].includes(s[1]??"")))return[];let l=P(n,"--client.env")??/\bsui\s+client\s+switch\s+--env\s+(\S+)/.exec(t.lineText)?.[1]??null;return Ue(l)?[]:o(`sui client ${s[1]} sends a transaction`,l)}case"aptos":{if(!(s[0]==="move"&&["publish","run","deploy-object","upgrade-object","create-object-and-publish-package","run-script"].includes(s[1]??"")||s[0]==="account"&&["transfer"].includes(s[1]??"")))return[];let l=P(n,"--profile","--url")??null;return Ue(l)?[]:o(`aptos ${s[0]} ${s[1]} sends a transaction`,l)}case"ape":{if(s[0]!=="run")return[];let i=P(n,"--network");return i===null||Ue(i)?[]:o(`ape run ${s[1]??""} sends transactions`,i)}case"hardhat":case"truffle":case"brownie":{let i=s[0]==="ignition"?s[1]??"":s[0]??"";if(!(["run","deploy","migrate"].includes(i)||/deploy|mint|transfer|send|upgrade|migrat|withdraw|airdrop|burn|propose|execute/i.test(i)))return[];let c=P(n,"--network")??(e.name==="hardhat"?/(?:^|[\s;&|(])(?:export\s+)?HARDHAT_NETWORK=["']?([^\s"';&|)]+)/.exec(t.lineText)?.[1]??null:null);return c===null||Ue(c)?[]:o(`${e.name} ${i} sends transactions`,c)}default:{if(/^[a-z]+d$/.test(e.name)&&s[0]==="tx"&&!T(n,"--generate-only","--dry-run")){let i=P(n,"--chain-id"),l=P(n,"--node");return i!==null&&/test|devnet|local/i.test(i)||l!==null&&Ue(l)?[]:o(`${e.name} tx ${s[1]??""} broadcasts a transaction`,i??l)}return[]}}}var gt=(e,...t)=>e.some(n=>t.some(s=>new RegExp(`^(?:/{1,2}|-)${s}(?::.*)?$`,"i").test(n))),ro=(e,...t)=>{for(let n=0;n<e.length;n++)for(let s of t){let r=new RegExp(`^(?:/{1,2}|-)${s}(?::(.*))?$`,"i").exec(e[n]);if(r)return r[1]??e[n+1]??null}return null},Il=/[\\/](?:Run|RunOnce|RunServices|RunServicesOnce)\b|[\\/]Winlogon\b|[\\/]Services[\\/]|[\\/]Image File Execution Options[\\/]|[\\/]Explorer[\\/]Shell Folders|[\\/]Policies[\\/]Explorer[\\/]Run|^(?:Registry::)?HK(?:CU|EY_CURRENT_USER):?[\\/]Environment\b|[\\/]Session Manager[\\/]Environment\b|[\\/]Command Processor\b/i,ab=new Set(["format","format-volume","clear-disk","initialize-disk","remove-partition","clear-recyclebin","diskpart","vssadmin","wmic","wbadmin","wsl","bcdedit","reg","set-itemproperty","new-itemproperty","remove-itemproperty","remove-item","sc","new-service","remove-service","set-service","stop-service","register-scheduledtask","set-scheduledtask","unregister-scheduledtask","new-scheduledtask","set-executionpolicy","set-mppreference","add-mppreference","netsh","set-netfirewallprofile","new-netfirewallrule","disable-netfirewallrule","remove-netfirewallrule","takeown","icacls","taskkill","runas","gsudo","mountvol","robocopy","setx","forfiles"]);function lb(e,t){let n=e.argv.slice(1),s=n.join(" "),r={is_local:e.remote===null,host:e.remote},o=(a,i,l={})=>[m(a,i,{target:e.argv.slice(0,4).join(" "),...r,...l})];switch(e.name){case"format":case"format-volume":case"clear-disk":case"initialize-disk":case"remove-partition":return n.length>0||e.name!=="format"?o("claude.bash.fs.delete_recursive",`formats or wipes a drive (${e.name})`,{service:"fs.device"}):[];case"diskpart":return o("claude.bash.fs.delete_recursive","changes disks and partitions (diskpart)",{service:"fs.device"});case"clear-recyclebin":return o("claude.bash.fs.delete_recursive","empties the Recycle Bin, deleting what is in it for good",{target:"the Recycle Bin"});case"vssadmin":return/\b(delete|resize)\s+shadow/i.test(s)?o("claude.bash.fs.delete_recursive","deletes Windows' restore points (shadow copies)",{service:"fs.system"}):[];case"wmic":return/\bshadowcopy\b.*\bdelete\b/i.test(s)?o("claude.bash.fs.delete_recursive","deletes Windows' restore points (shadow copies)",{service:"fs.system"}):[];case"wbadmin":return/\bdelete\b/i.test(s)?o("claude.bash.fs.delete_recursive","deletes Windows' backups (wbadmin)",{service:"fs.system"}):[];case"wsl":return gt(n,"unregister")||n.includes("--unregister")?o("claude.bash.fs.delete_recursive","unregisters a Linux distribution, deleting its whole disk (wsl --unregister)",{service:"fs.root"}):[];case"bcdedit":return n.length===0||gt(n,"enum","v")?[]:o("claude.bash.privilege","changes how Windows starts (bcdedit)");case"reg":{let a=(n[0]??"").toLowerCase();if(["query","compare","export"].includes(a))return[];let i=n[1]??"";return Il.test(i)?o("claude.bash.persistence",`changes what Windows starts at sign-in or boot (reg ${a} ${i})`):/^HK(LM|EY_LOCAL_MACHINE)/i.test(i)?o("claude.bash.privilege",`changes Windows' machine-wide settings (reg ${a})`):[]}case"set-itemproperty":case"new-itemproperty":case"remove-itemproperty":case"remove-item":{let a=ro(n,"path","literalpath")??n.find(i=>!i.startsWith("-"))??"";return/^(HK(CU|LM|CR|U|CC)|HKEY_|Registry::)/i.test(a)?Il.test(a)?o("claude.bash.persistence",`changes what Windows starts at sign-in or boot (${a})`):/^(HKLM|HKEY_LOCAL_MACHINE)/i.test(a)?o("claude.bash.privilege","changes Windows' machine-wide settings (the registry)"):[]:[]}case"sc":{let a=(n[0]??"").toLowerCase();return["create","config","delete","failure","sidtype","privs"].includes(a)?o("claude.bash.persistence",`changes a Windows service (sc ${a})`):a==="stop"?o("claude.bash.process.kill_by_name",`stops a Windows service (sc stop ${n[1]??""})`):[]}case"new-service":case"remove-service":return o("claude.bash.persistence",`changes a Windows service (${e.name})`);case"set-service":return gt(n,"startuptype")?o("claude.bash.persistence","changes when a Windows service starts"):[];case"stop-service":return o("claude.bash.process.kill_by_name",`stops a Windows service (${n.find(a=>!a.startsWith("-"))??""})`);case"register-scheduledtask":case"set-scheduledtask":case"unregister-scheduledtask":case"new-scheduledtask":return o("claude.bash.persistence",`changes Windows scheduled tasks (${e.name})`);case"set-executionpolicy":return o("claude.bash.privilege","changes which PowerShell scripts may run (Set-ExecutionPolicy)");case"set-mppreference":case"add-mppreference":return/-(Disable\w+|Exclusion\w+)/i.test(s)?o("claude.bash.privilege","turns off or narrows Microsoft Defender's checks"):[];case"netsh":return/firewall\b.*\b(state\s+off|disable|delete|add\s+rule|set\s+rule)/i.test(s)||/\bportproxy\b.*\badd\b/i.test(s)?o("claude.bash.net.expose","changes the Windows firewall or forwards a port (netsh)"):[];case"set-netfirewallprofile":case"new-netfirewallrule":case"disable-netfirewallrule":case"remove-netfirewallrule":return o("claude.bash.net.expose",`changes the Windows firewall (${e.name})`);case"takeown":return o("claude.bash.privilege",`takes ownership of files (takeown${gt(n,"r")?" /r":""})`);case"icacls":return gt(n,"grant","reset","setowner","inheritance","remove","deny")?o("claude.bash.privilege","changes who may read or change files (icacls)"):[];case"taskkill":{let a=ro(n,"im");if(a)return o("claude.bash.process.kill_by_name",`kills every ${a} process (taskkill /im)`,{target:a});let i=ro(n,"fi");return i?/^\s*imagename\s+eq\s+\S+\s*$/i.test(i)?o("claude.bash.process.kill_by_name",`kills every process its filter names (taskkill /fi "${i}")`,{target:i}):o("claude.bash.process.kill_by_name",`kills every process its filter matches (taskkill /fi "${i}")`,{target:i,service:"proc.all"}):[]}case"robocopy":{if(!gt(n,"mir","purge"))return[];let a=`robocopy ${gt(n,"mir")?"/mir":"/purge"}`,i=n.filter(l=>!/^\/{1,2}[A-Za-z]+(?::.*)?$/.test(l));return i.length<2?o("claude.bash.fs.delete_recursive",`${a} deletes from a folder the line does not show`):/^[A-Za-z]:(?![\\/])/.test(i[1])?o("claude.bash.fs.delete_recursive",`${a} deletes from ${i[1]}, a folder under a drive's current folder`):$c({...e,name:"rsync",argv:["rsync","-a","--delete",i[0],i[1]]},t).map(l=>({...l,why:l.why.replace(/^rsync --delete/,a)}))}case"setx":return n.length>0?o("claude.bash.persistence",`sets an environment variable every later program starts with (setx ${n.find(a=>!a.startsWith("/"))??""})`):[];case"runas":case"gsudo":return o("claude.bash.privilege",`runs a command as another user or as an administrator (${e.name})`);case"mountvol":return gt(n,"d","p")?o("claude.bash.fs.delete_recursive","removes a drive from Windows (mountvol)",{service:"fs.device"}):[];default:return[]}}function cb(e){let t=e.argv,n=s=>[m("claude.bash.persistence",s,{target:t.slice(0,3).join(" "),is_local:e.remote===null,host:e.remote})];switch(e.name){case"crontab":{let s=t.slice(1).filter(r=>/^-[A-Za-z]+$/.test(r));return s.some(r=>r.includes("r"))?n("crontab -r deletes every scheduled job"):s.some(r=>/[lTV]/.test(r))?[]:s.some(r=>r.includes("e"))?n("crontab -e changes scheduled jobs"):n("crontab replaces every scheduled job")}case"launchctl":{let s=t.slice(1).find(r=>!r.startsWith("-"))??"";return["load","bootstrap","enable","submit"].includes(s)?n(`launchctl ${s} installs a background job`):[]}case"systemctl":{let s=t.slice(1).find(r=>!r.startsWith("-"))??"";return["enable","link","mask","preset","preset-all","set-default","edit","add-wants","add-requires"].includes(s)?n(`systemctl ${s} changes what starts at boot`):[]}case"pm2":return v(t)[0]==="startup"?n("pm2 startup makes processes start at boot"):[];case"brew":return v(t)[0]==="services"&&["start","restart"].includes(v(t)[1]??"")?n(`brew services ${v(t)[1]} registers a job that starts at login`):[];case"osascript":return/\bmake\s+(new\s+)?login\s+item\b/i.test(t.join(" "))?n("osascript adds a login item"):[];case"powershell":case"powershell.exe":case"pwsh":case"pwsh.exe":{let s=P(t,"-Command","-c","-command")??"",r=o=>new RegExp(`(^|[;|{(\\n&]\\s*)(${o})`,"i").test(s.trim());return r("Register-ScheduledTask|Set-ScheduledTask|Unregister-ScheduledTask|New-Service|schtasks(\\.exe)?\\s+\\/(create|change|delete)")||r("Set-Service\\b[^;|\\n]*-StartupType\\s+Automatic")?n("PowerShell changes scheduled tasks or services"):[]}case"schtasks":case"schtasks.exe":return t.some(s=>(V()?/^\/{1,2}(create|change|delete)$/i:/^\/(create|change|delete)$/i).test(s))?n("schtasks changes Windows scheduled tasks"):[];case"at":case"batch":return T(t,"-l","-r","-d","-c")?[]:e.name==="batch"||t.slice(1).some(s=>!s.startsWith("-"))?n(`${e.name} schedules a command to run later`):[];default:return[]}}var ub=/^(core\.(hookspath|sshcommand|fsmonitor|askpass|gitproxy)|credential\..+|url\..+\.(insteadof|pushinsteadof)|https?\..*\.?(sslcainfo|sslcapath|proxy|extraheader|sslcert|sslkey)|include\.path|includeif\..+\.path|init\.templatedir|filter\..+\.(clean|smudge|process)|diff\..+\.textconv|merge\..+\.driver|gpg\.(program|ssh\.program|x509\.program|openpgp\.program))$/i;function db(e,t){if(e.name!=="git")return[];let n=_t(e);if(!n||n.sub!=="config")return[];let s=[...n.args],r="set",o=s[0]??"";["set","unset","get","list","edit","rename-section","remove-section"].includes(o)&&(s.shift(),r=o==="get"||o==="list"?"read":o==="edit"?"edit":o==="set"?"set":"unset");let a=!1,i=[];for(let d=0;d<s.length;d++){let h=s[d];if(h==="--global"||h==="--system")a=!0;else if(h==="-f"||h==="--file"||h.startsWith("--file=")){let g=h.startsWith("--file=")?h.slice(7):s[++d]??"";Bo(M(g,e.cwd,t.ctx),t.ctx,[t.ctx.home])==="gitconfig"&&(a=!0)}else h==="--unset"||h==="--unset-all"||h==="--remove-section"||h==="--rename-section"?r="unset":/^(--get|--get-all|--get-regexp|--get-urlmatch|--get-color|--get-colorbool|-l|--list)$/.test(h)?r="read":h==="-e"||h==="--edit"?r="edit":["--type","--default","--comment","--value","-t"].includes(h)?d++:h.startsWith("-")||i.push(h)}if(!a||r==="read")return[];let l=/^\s*(?:\w+=\S*\s+)*(?:HOME|GIT_CONFIG_GLOBAL|XDG_CONFIG_HOME)=["']?([^\s"']+)/.exec(e.text)?.[1]??/(?:^|[;&|\n(]\s*)(?:export\s+)?(?:HOME|GIT_CONFIG_GLOBAL|XDG_CONFIG_HOME)=["']?([^\s"';&|)]+)["']?\s*(?=$|[;&\n|])/.exec(t.lineText.slice(0,Math.max(0,t.lineText.indexOf(e.text))))?.[1];if(l!==void 0&&kt(M(l,e.cwd,t.ctx),t))return[];let c=(i[0]??"").replace(/(:\/\/)[^@/\s]+@/g,"$1***@"),u=d=>[m("claude.bash.persistence",d,{target:c||"git config --global",is_local:!0})];if(r==="edit")return u("git config --global --edit rewrites the global git config");let f=(i[0]??"").toLowerCase(),p=i[1]??"";return r==="unset"?f==="core.hookspath"?u("turns off the git hooks every repository on this machine runs"):[]:i.length<2?[]:/^https?\..*sslverify$/.test(f)?/^(false|0|no|off)$/i.test(p)?u("turns off TLS certificate checks for every repository on this machine"):[]:/^alias\./.test(f)?p.startsWith("!")?u(`adds a git alias that runs a shell command (${i[0]})`):[]:f==="core.fsmonitor"?/^(true|false|0|1|yes|no|on|off)$/i.test(p)?[]:u(`sets ${c} to run a program for every repository`):/^protocol\..*allow$/.test(f)?/^always$/i.test(p)?u(`allows a git transport that can run commands (${c})`):[]:f==="diff.external"?/^(difft|difftastic|delta|diff-so-fancy|icdiff|meld|opendiff|kdiff3|code|ksdiff)(\s|$)/.test(R.basename(p))?[]:u(`sets ${c} to run a program on every diff`):/^(core\.(pager|editor)|sequence\.editor|interactive\.difffilter|pager\.\w+)$/.test(f)?/[;&`>]|\$\(|\b(curl|wget|nc|ncat|base64)\b|\b(sh|bash|zsh|python3?|node|perl|ruby)\s+-[ce]\b/.test(p)?u(`sets ${c} to run a shell command for every repository`):[]:ub.test(f)?u(`sets ${c} for every repository on this machine`):[]}function fb(e){let t=Xn(e);if(t===null)return[];let n=Yo(t.slice(0,65536));if(!zo(n)||!Fo.test(n))return[];let s=/\.delete\s*\(|method\s*[:=]\s*['"]DELETE|request\s*\(\s*['"]DELETE/i.test(n)?"DELETE":/\.(post|put|patch)\s*\(|method\s*[:=]\s*['"](POST|PUT|PATCH)|request\s*\(\s*['"](POST|PUT|PATCH)|Request\([^)]*data\s*=|-X\s*POST/i.test(n)?"POST":null,r=s!==null?Oc(n,s,n):null;return r!==null?[m("claude.agent.controls",`changes your Anvil workspace's modes through its API (${r})`,{target:r,is_local:!1})]:[]}function mu(e,t,n){let s=t.lineText.slice(0,Math.max(0,t.lineText.indexOf(e.text))),r=n.join("|"),o=new RegExp(`^\\s*(?:\\w+=\\S*\\s+)*(?:${r})=["']?([^\\s"']+)`).exec(e.text)?.[1],a=[...s.matchAll(new RegExp(`(?:^|[;&|\\n(]\\s*)(?:export\\s+)?(?:${r})=["']?([^\\s"';&|)]+)`,"g"))].map(u=>u[1]),i=o??a[a.length-1];if(!i)return null;let l=i.replace(/^\$\{?([A-Za-z_]\w*)\}?/,(u,f)=>{let p=new RegExp(`(?:^|[;&|\\n(]\\s*)(?:export\\s+)?${f}=(?:"?\\$\\(mktemp\\b[^)]*\\)"?|["']?([^\\s"';&|)]+))`).exec(s);return p?p[1]??`${t.ctx.tmpdir.replace(/(?<!\/)\/+$/,"")}/mktemp`:u});if(S(l)||l.includes("$"))return null;let c=X(l,e.cwd,se(t));return c.kind==="disposable"&&c.why!==On?c.path:null}var pb=new Set(["node","nodejs","bun","deno","tsx","ts-node","sh","bash","zsh","dash","ksh","source",".","python","python3","perl","ruby"]),hb=/(?:\.anvil\/claude\/bin\/|useanvil\S*\/|\/anvil\/bin\/)claude-(?:hook|hook-core|sync|meter)\.(?:[cm]?js|sh)\b/;function gb(e,t){let n=e.argv,s=v(n),r=i=>[m("claude.agent.controls",i,{target:`${e.name} ${s[0]??""}`.trim(),is_local:!0})],o=n.findIndex((i,l)=>n[l+1]==="claude"&&/\$\(|`/.test(k(i))&&/(^|[^\w.-])anvil($|[^\w.-])/.test(k(i)));if(o>=0){let i=Ln(v(["anvil",...n.slice(o+1)]));if(i)return r(i)}let a=n.findIndex(i=>/\$\(|`/.test(k(i))&&/(^|[^\w.-])anvil-claude($|[^\w.-])/.test(k(i)));if(a>=0){let i=Ss(v(["anvil-claude",...n.slice(a+1)]),n.slice(a+1));if(i)return r(i)}if(pb.has(e.name)){let i=n.findIndex((l,c)=>c>0&&hb.test(/^[/~$]/.test(k(l))?k(l):`${e.cwd??""}/${k(l)}`));if(i>0&&!(/claude-sync\.js$/.test(k(n[i]))&&n.length===i+2&&n[i+1]==="--status"))return r("runs Anvil's own hook by hand: what it records would be made up")}switch(e.name){case"claude":{if((s[0]==="plugin"||s[0]==="plugins")&&["list","ls","validate"].includes(s[1]??"")&&!(s[1]==="list"&&s[2]==="marketplace")||s[0]==="mcp"&&["list","get"].includes(s[1]??"")||s[0]==="config"&&["get","list"].includes(s[1]??"")||s.length===0&&T(n,"--version","-v"))return[];let i=(s[0]==="plugin"||s[0]==="plugins")&&["install","i","enable","disable","uninstall","remove","rm","marketplace"].includes(s[1]??"")||s[0]==="mcp"&&["add","add-json","add-from-claude-desktop","remove"].includes(s[1]??"")||s[0]==="config"&&["set","add","remove"].includes(s[1]??""),l=n.some(($,E)=>["-s","--scope"].includes(n[E-1]??"")&&/^(project|local)$/.test($)||/^(--scope=|-s)(project|local)$/.test($));if(i&&!l&&mu(e,t,["HOME","CLAUDE_CONFIG_DIR"]))return[];if(s[0]==="mcp"&&["add","add-json","add-from-claude-desktop"].includes(s[1]??""))return r(`claude mcp ${s[1]} gives Claude Code a new MCP server`);if(s[0]==="config"&&["set","add"].includes(s[1]??""))return r("claude config changes Claude Code's settings");if(s[0]==="import")return r("claude import brings another agent's MCP servers and settings into Claude Code");if((s[0]==="plugin"||s[0]==="plugins")&&(["install","i","enable"].includes(s[1]??"")||s[1]==="marketplace"&&s[2]==="add"))return r(`claude plugin ${s.slice(1,3).join(" ")} gives Claude Code new hooks, tools or MCP servers`);if((s[0]==="plugin"||s[0]==="plugins")&&(["disable","uninstall","remove","rm"].includes(s[1]??"")||s[1]==="marketplace"&&["remove","rm"].includes(s[2]??"")))return r(`claude plugin ${s.slice(1,3).join(" ")} turns off hooks Claude Code was running`);if(T(n,"--dangerously-skip-permissions","--allow-dangerously-skip-permissions")||P(n,"--permission-mode")==="bypassPermissions")return r("runs Claude Code with its permission checks off");let c=P(n,"--setting-sources"),u=c?.split(",").map($=>$.trim())??[];if(c!==null&&!(u.includes("user")&&u.includes("local")))return r("runs Claude Code without your user or local settings, where Anvil's hook is");let p=`${/^\s*((?:(?:env\s+(?:-\S+\s+)*)?[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+)/.exec(e.text)?.[1]??""} ${e.text.slice(0,Math.max(0,e.text.search(/(^|[\s/])claude(\s|$)/)))}`,d=t.lineText.slice(0,65536);if(/(^|\s)(CLAUDE_CONFIG_DIR|HOME)=/.test(p)||/(^|[\s;&|(])(export|declare\s+-x)\s+(CLAUDE_CONFIG_DIR|HOME)=/.test(d)||/(^|[\s;&|(])CLAUDE_CONFIG_DIR=/.test(d))return r("runs Claude Code with its settings folder moved, away from Anvil's hook");if(/(^|\s)(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(p)||/(^|[\s;&|(])export\s+(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(d))return r("runs Claude Code under another account's key, whose modes its sync would take");if(/(^|[\s;&|(])unset\s+(-v\s+)?CLAUDE_CONFIG_DIR\b|\benv\s+(?:-\S+\s+)*-u\s*CLAUDE_CONFIG_DIR\b/.test(d))return r("runs Claude Code without the settings folder this session uses, where Anvil's hook is");if(T(n,"--bare","--safe-mode")||/(^|\s)(CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE)=/.test(p)||/(^|[\s;&|(])(export\s+|declare\s+-x\s+)?(CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE)=/.test(d))return r("runs Claude Code with hooks and plugins skipped, Anvil's among them");let h=P(n,"--settings");if(h!==null&&/bypassPermissions|dangerously|"Bash(\(\*\))?"|disableAllHooks|"hooks"\s*:/.test(h))return r("runs Claude Code with settings that turn its permission checks off");let g=[];for(let $=1;$<n.length;$++)if(n[$]==="--allowedTools"||n[$]==="--allowed-tools"||/^--allowed-?[tT]ools=/.test(n[$])){n[$].includes("=")&&g.push(n[$].slice(n[$].indexOf("=")+1));for(let E=$+1;E<n.length&&!n[E].startsWith("-");E++)g.push(n[E])}if(g.some($=>/(^|[\s,'"])Bash(\(\*\))?($|[\s,'"])/.test($)))return r("runs Claude Code with every shell command allowed");let y=P(n,"--mcp-config");return y!==null&&!/^\s*\{\s*("mcpServers"\s*:\s*\{\s*\}\s*)?\}\s*$/.test(y)?r("runs Claude Code with MCP servers from a config file"):h!==null&&!h.trim().startsWith("{")?r("runs Claude Code with settings from a file the command does not show"):[]}case"fish":case"set":return/\bset\s+-[a-zA-Z]*U[a-zA-Z]*\s+(CLAUDE_CONFIG_DIR|CLAUDE_CODE_SIMPLE|CLAUDE_CODE_SAFE_MODE|ANVIL_CLAUDE_SYNC|ANVIL_WORKSPACE_KEYS_PATH)\b/.test(e.name==="set"?`set ${n.slice(1).join(" ")}`:n.slice(1).join(" "))?r("a fish universal variable changes how every later Claude Code session starts"):[];case"launchctl":{let i=["CLAUDE_CONFIG_DIR","CLAUDE_CODE_SIMPLE","CLAUDE_CODE_SAFE_MODE","ANVIL_CLAUDE_SYNC","ANVIL_WORKSPACE_KEYS_PATH"];return s[0]==="setenv"&&i.includes(s[1]??"")?r(`launchctl setenv ${s[1]} changes how every later Claude Code session starts`):[]}case"anvil":{let i=Ln(s);if(i)return r(i);let l=/^\s*((?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+)/.exec(e.text)?.[1]??"";return s[0]==="claude"&&(/(^|\s)(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(l)||/(^|[\s;&|(])export\s+(ANVIL_API_KEY|ANVIL_API_BASE_URL|ANVIL_WORKSPACE_KEYS_PATH)=/.test(t.lineText.slice(0,65536)))?r("runs anvil claude under another account's key, whose modes it would take"):e.via==="xargs"&&s[0]==="claude"&&s.length===1?r("anvil claude with its subcommand read from input"):[]}case"anvil-claude":{if(e.via==="xargs"&&s.length===0)return r("anvil-claude with its subcommand read from input");let i=Ss(s,n.slice(1));return i?r(i):[]}case"node":case"bun":case"deno":case"tsx":case"ts-node":{let i=n.findIndex((f,p)=>p>0&&!f.startsWith("-")),l=i>0?k(n[i]):"",c=/@useanvil\/claude-code\/|(?:^|\/)anvil-claude$/i.test(l),u=i>0&&(c||/(?:^|\/)(?:@useanvil\/sdk|anvil)(?:\/|\.[cm]?[jt]s$|$)|useanvil/i.test(l))?c?Ss(v([e.name,...n.slice(i+1)]),n.slice(i+1)):Ln(v([e.name,...n.slice(i+1)])):null;return u?r(u):[]}case"code":case"code-insiders":return T(n,"--add-mcp")?r(`${e.name} --add-mcp gives an AI agent a new MCP server`):[];case"codex":return s[0]==="mcp"&&s[1]==="add"?r("codex mcp add gives Codex a new MCP server"):T(n,"--dangerously-bypass-approvals-and-sandbox","--yolo")||P(n,"-s","--sandbox")==="danger-full-access"||n.some((i,l)=>(n[l-1]==="-c"||n[l-1]==="--config")&&/^sandbox_mode\s*=\s*["']?danger-full-access/.test(i))?r("runs Codex with its sandbox and approvals off"):[];case"gemini":return s[0]==="mcp"&&s[1]==="add"?r("gemini mcp add gives Gemini CLI a new MCP server"):T(n,"--yolo","-y")||P(n,"--approval-mode")==="yolo"?r("runs Gemini CLI approving every action"):[];case"cursor-agent":return T(n,"--force","-f")?r("runs Cursor Agent without asking before commands"):[];case"aider":return T(n,"--yes-always")?r("runs aider confirming every action"):[];case"amp":return T(n,"--dangerously-allow-all")?r("runs Amp with every action allowed"):[];case"droid":return T(n,"--skip-permissions-unsafe")?r("runs Droid with its permission checks off"):[];case"q":return s[0]==="chat"&&T(n,"--trust-all-tools")?r("runs Amazon Q trusting every tool"):[];case"qwen":case"crush":return T(n,"--yolo","-y")?r(`runs ${e.name} approving every action`):[];case"fastmcp":return s[0]==="install"?r("fastmcp install adds an MCP server to an AI agent"):[];case"copilot":return T(n,"--yolo","--allow-all-tools")?r("runs Copilot CLI approving every tool"):[];case"smithery":return s[0]==="install"||s[0]==="mcp"&&s[1]==="add"?r("installs an MCP server into an AI agent"):[];case"install-mcp":return s.length>0?r("installs an MCP server into an AI agent"):[];case"mcp-get":return s[0]==="install"?r("installs an MCP server into an AI agent"):[];default:return[]}}var mb=new Set(["deliver","pilot","supply","upload_to_app_store","upload_to_testflight","upload_to_play_store","appstore","testflight","app_store_connect","upload_to_play_store_internal_app_sharing"]),yb=new Set(["init","download_metadata","download_screenshots","list","builds","export","help"]),bb=/(^|_)(release|beta|deploy|production|prod|store|publish|submit|upload|ship|distribute|promote|appstore|testflight|playstore|alpha|internal|rollout)(_|$)/i,wb=/(^|_)(build|test|tests|lint|screenshots?|certs|certificates|match|setup|bump|version|changelog|notes|metadata|precheck|dry_?run|check|verify|dsyms?|symbols|crashlytics|sentry|bugsnag)(_|$)/i;function kb(e){if(e.some((s,r)=>/^(--)?(validate|verify)_only(:|=)?(true)?$/i.test(s)&&(/true$/i.test(s)||/^true$/i.test(e[r+1]??""))))return!1;let t=v(e);["ios","android","mac"].includes(t[0]??"")&&(t=t.slice(1)),t[0]==="run"&&(t=t.slice(1));let n=t[0]??"";return n==="match"&&t[1]==="nuke"||n==="match_nuke"?!0:mb.has(n)?!yb.has(t[1]??""):/(^|_)(dsyms?|symbols|crashlytics|sentry|bugsnag|metadata|screenshots?)(_|$)/i.test(n)?!1:/(^|_)(upload|deploy|submit|distribute|publish|ship|promote|testflight|appstore|playstore|rollout)(_|$)/i.test(n)||/(^|_)and_(release|beta|production|prod|store)(_|$)/i.test(n)?!0:bb.test(n)&&!wb.test(n)}function oo(e){return e.slice(1).some(t=>/^prod(uction)?$/i.test(k(t))||/^--(deployment-?name|deploymentName|destDeploymentName|target-deployment)=prod/i.test(t))}function yu(e){return T(e,"-m","--dry-run")?[]:e.slice(1).filter(t=>!t.startsWith("-")&&!t.includes("=")).map(t=>t.slice(t.lastIndexOf(":")+1))}function Dl(e){return yu(e).some(t=>/^publish\w*(Bundles?|Apks?|Listing)$|^promote\w*Artifact$/.test(t))}function Fl(e){return yu(e).some(t=>/^publish(AllPublicationsTo\w+Repository|\w+PublicationTo\w+Repository|ToSonatype|ToMavenCentral|AndReleaseToMavenCentral)?$/.test(t))}var bu=/^(preview|previews|staging|stage|dev|develop|development|test|testing|qa|internal|canary|pr-[\w.-]+|feat(ure)?[/-][\w./-]+)$/i;function vb(e){let t=v(e),[n="",s=""]=(t[0]??"").split(":");if(n==="submit"||n==="build"&&s==="submit")return!0;if(n==="build"&&!s)return T(e,"--auto-submit","--auto-submit-with-profile");if(n==="update"&&!s){let r=P(e,"--branch","--channel");return!(r!==null&&!S(r)&&bu.test(r))}return n==="update"?["republish","rollback","roll-back-to-embedded","edit","revert-update-rollout"].includes(s):n==="channel"?["edit","rollout"].includes(s||(t[1]??"")):n==="deploy"?T(e,"--prod","--production"):!1}function xo(e,t){let n=e.trim();if(/^[A-Za-z_$][\w$.]*$/.test(n)){let s=new RegExp(`(?:^|[^\\w$.])${n.replace(/[.$]/g,r=>`\\${r}`)}\\s*(?::\\s*[\\w.]+\\s*)?=(?!=)\\s*([^\\n;]+)`).exec(t);s&&(n=s[1])}return n=n.replace(/\b(require|__import__|import)\s*\(\s*(['"`])[^'"`]*\2\s*\)/g,"$1()"),[...n.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)].map(s=>s[2]).join("/").replace(/\/{2,}/g,"/")}function _o(e,t,n){let s=e.indexOf("(",t);if(s<0)return[];let r=e.slice(s,s+4e3),o=lr(r,0);return o<0&&s+4e3<e.length&&(n.hit=!0),o>0?gn(r.slice(1,o)):[]}function zl(e,t){let n=t,s=Math.max(0,t-400);for(;;){for(;n>s&&/\s/.test(e[n-1]);)n--;if(e[n-1]===")"){let a=0,i=null,l=n-1;for(;l>=s;l--){let c=e[l];if(i){c===i&&e[l-1]!=="\\"&&(i=null);continue}if(c==='"'||c==="'"||c==="`")i=c;else if(c===")")a++;else if(c==="("&&--a===0)break}if(l<s)return null;n=l}let o=n;for(;o>s&&/[\w$]/.test(e[o-1]);)o--;if(o===n&&e[n]!=="(")return null;if(n=o,e[n-1]==="."&&n-1>s){n--;continue}break}let r=e.slice(n,t).trim();return r===""?null:r}var $b=/^\s*[rRbB]?['"][rwxabt+U]{1,4}['"]\s*$/,Ml=/['"][^'"]*[wax+]|\bO_(?:WRONLY|RDWR|CREAT|TRUNC|APPEND)\b/,xb=/\b(exec|eval|compile|execfile|run_path|run_module|system|popen|spawn|spawnSync|execSync|execFileSync|Function|vm\.run\w*|subprocess\.\w+|os\.exec\w*)\s*\(/;function Yo(e){return!/'''|"""|`[^`]*\n/.test(e)||xb.test(e)?e:e.replace(/('''|""")([\s\S]*?)\1|`((?:\\.|[^`\\])*\n(?:\\.|[^`\\])*)`/g,t=>{let n=t.startsWith("'''")||t.startsWith('"""')?3:1;return t.slice(0,n)+t.slice(n,t.length-n).replace(/[^\n]/g," ")+t.slice(t.length-n)})}function wu(e,t,n){let s=[],r=Yo(e),o=(i,l=!0)=>{let c=xo(i,e);c!==""?s.push({path:c,content:l,expr:i}):n&&(n.n++,n.exprs?.push(i))},a=i=>_o(e,i,t);for(let i of Ge([...r.matchAll(/\b(?:f?open|openSync|File\.new)\s*\(/g)],t)){let l=a(i.index),c=(l.find(u=>/^\s*mode\s*=/.test(u))??"").replace(/^\s*mode\s*=/,"");if(e[i.index-1]==="."&&($b.test(l[0]??"")||/^\s*mode\s*=/.test(l[0]??""))){let u=Ml.test(c||l[0])?zl(e,i.index-1):null;u&&o(u);continue}Ml.test(l[1]??c)&&o(l[0]??"")}for(let i of Ge([...r.matchAll(/\.(write_text|write_bytes|unlink|chmod|rename|replace|touch)\s*\(/g)],t)){let l=zl(e,i.index);l&&o(l,i[1]==="write_text"||i[1]==="write_bytes"),i[1]==="rename"?o(a(i.index)[0]??""):i[1]==="replace"&&l&&_b(l,e)&&o(_o(e,i.index,{hit:!1})[0]??"")}for(let i of Ge([...r.matchAll(/\b(writeFileSync|writeFile|appendFileSync|appendFile|createWriteStream|truncateSync|truncate|outputFileSync|outputFile|outputJsonSync|outputJson|writeJsonSync|writeJson|file_put_contents|Deno\.writeTextFileSync|Deno\.writeTextFile|Deno\.writeFileSync|Deno\.writeFile|Bun\.write|(?:File|IO)\.(?:write|binwrite))\s*\(/g)],t))o(a(i.index)[0]??"");for(let i of Ge([...r.matchAll(/\b(rmSync|unlinkSync|unlink|chmodSync|chmod|Deno\.remove|os\.remove|os\.unlink|os\.chmod|shutil\.rmtree|rmtree|rimraf(?:\.sync)?|fse?\.removeSync|fse?\.remove|(?:File|IO)\.(?:delete|unlink)|FileUtils\.(?:rm|rm_f|rm_rf|remove_dir|touch))\s*\(/g)],t))o(a(i.index)[0]??"",!1);for(let i of Ge([...r.matchAll(/\bfileinput\.(?:input|FileInput)\s*\(/g)],t)){let l=a(i.index);if(!l.some(f=>/^\s*inplace\s*=\s*(?:True|1)\s*$/.test(f)))continue;let c=(l.find(f=>/^\s*files\s*=/.test(f))??l.find(f=>!/^\s*\w+\s*=/.test(f))??"").replace(/^\s*files\s*=\s*/,"").trim(),u=/^[[(]([\s\S]*)[\])]$/.exec(c);for(let f of u?gn(u[1]):[c])o(f.trim())}for(let i of Ge([...r.matchAll(/\bopen\s*\(?\s*(?:my\s+)?(?:\$\w+|[A-Z]\w*)\s*,\s*['"](?:\+?>{1,2}|\+<)['"]\s*,\s*([^;)]+)/g)],t))o(i[1].trim());for(let i of Ge([...r.matchAll(/\bopen\s*\(?\s*(?:my\s+)?(?:\$\w+|[A-Z]\w*)\s*,\s*(['"])\s*(?:\+?>{1,2}|\+<)\s*([^'"]+)\1/g)],t))o(`"${i[2].trim()}"`);for(let i of Ge([...r.matchAll(/\b(copyFileSync|copyFile|renameSync|rename|cpSync|(?<=\.)cp|(?:fse?|fsExtra)\.(?:copySync|copy|moveSync|move)|shutil\.copy\w*|shutil\.move|os\.replace|os\.rename|FileUtils\.(?:cp|mv|ln_s|ln_sf|cp_r)|File\.rename)\s*\(/g)],t)){let l=a(i.index);o(l[1]??""),/rename|move|replace/.test(i[1])&&o(l[0]??"",!1)}return s}function _b(e,t){if(/\b(?:pathlib\.)?Path\s*\(|\.with_(?:name|suffix|stem)\s*\(/.test(e))return!0;let n=/^[A-Za-z_]\w*$/.exec(e.trim())?.[0];return n!==void 0&&new RegExp(`(?:^|[^\\w.])${n}\\s*=\\s*(?:pathlib\\.)?Path\\s*\\(`).test(t)}var Sb=/(?:\b(?:os\.symlink|os\.link|fs\.symlinkSync|fs\.symlink|fs\.linkSync|fs\.link|symlinkSync|linkSync|File\.symlink|File\.link|FileUtils\.ln_sf|FileUtils\.ln_s|FileUtils\.ln|Deno\.symlinkSync|Deno\.symlink|symlink)|\.(?:symlink_to|hardlink_to))\s*\(/g,Ul=/\.claude(\/settings(\.local)?\.json|\/hooks(\/.*)?)?\/?$|\.claude\.json$|\.mcp\.json$|\.anvil\/(claude(\/.*)?|rules\.json)$|Library\/Launch(Agents|Daemons)\/|\.gitconfig$|\.claude\/projects(\/[^/]+(\/.+\.jsonl)?)?\/?$/,Cb=/(?:^|[;\n])[ \t]*(?:from\s+google\.cloud\s+import\s+bigquery\b|import\s+google\.cloud\.bigquery\b|import\s+snowflake\b|from\s+snowflake\b|import\s+redshift_connector\b|from\s+databricks\b[\w.]*\s+import\b|(?:const|let|var|import)\b[^\n;]{0,80}(?:require\(\s*|from\s+)['"](?:@google-cloud\/bigquery|snowflake-sdk|@databricks\/sql)['"])/;function Ab(e,t){let n=Xn(e);if(n===null)return[];let s=[],r={n:0,exprs:[]},o=wu(n,t.cut,r),a=Kb(e,n,r.exprs,t);a!==null&&s.push(m("claude.agent.controls",`${e.name} writes the file the line hands it: Claude Code's record of a session (${S(a)?"a file a listing of its projects folder names":R.basename(k(a))})`,{target:k(a).slice(0,200),is_local:!0}));for(let i of o){if(!i.content||!ye(i.path))continue;let l=Ht(i.expr,n,e,0,t.ctx.home,t.cut);if(!(l===null||l.startsWith("/dev/")||!ye(l))&&He(l,e,t).kind!=="disposable"){s.push(m("claude.file.write_secret",`writes a secrets file (${R.basename(k(l))}) (from ${e.name})`,{target:k(l),is_local:!0}));break}}for(let{path:i}of o){let l=k(i);if(S(i)&&ar(i,t.ctx,e.cwd)){s.push(m("claude.agent.controls",`writes Claude Code's record of a session (a file a listing of its projects folder names) (from ${e.name})`,{target:l.slice(0,200),is_local:!0}));continue}if(!Ul.test(l)){let y=l.startsWith("/")?l:M(l,e.cwd,t.ctx);if(cn(t,S(i)?M(i,e.cwd,t.ctx):y),ot.test(y)&&pn(n)){s.push(m("claude.agent.controls",`changes how every later Claude Code session starts (${R.basename(y)}) (from ${e.name})`,{target:k(y),is_local:!0}));continue}let $=S(y)?null:Vn(y,t.ctx,[t.projectRoot,t.base]);if($){s.push({...$,why:`${$.why} (from ${e.name})`});continue}let E=Ie(y,e,t),x=E!==y?E:ks(y,t.ctx.onDisk,!0);if(x===null||!Ul.test(x))continue;let b=Vn(x,t.ctx,[t.projectRoot,t.base]);if(b){s.push({...b,why:`${b.why} (from ${e.name})`});continue}continue}let c=l.replace(/^(\$ENV\{['"]?HOME['"]?\}|ENV\[['"]HOME['"]\]|\$?\{[^}]*\}|HOME|~|USERPROFILE|homedir\(\))\/?/,""),u=/\b(HOME|homedir|expanduser|USERPROFILE)\b|Path\.home\b/.test(n),f=/^\/(\.claude|\.mcp\.json|\.gitconfig|\.anvil\/|Library\/)/.test(l),p=l!==c||/^(\.claude\.json|\.gitconfig|Library\/)/.test(c)||(f||/^\.(claude|anvil)\//.test(c))&&u,d=p?mu(e,t,["HOME"])??t.ctx.home:t.ctx.home,h=l.startsWith("/")&&!(f&&u)?l:p?`${d}/${c.replace(/^\/+/,"")}`:M(c,e.cwd,t.ctx);cn(t,h);let g=Vn(Ie(h,e,t),t.ctx,[t.projectRoot,t.base]);if(g){s.push({...g,why:`${g.why} (from ${e.name})`});continue}}for(let i of Ge([...n.matchAll(Sb)],t.cut)){let l=_o(n,i.index,t.cut)[0];if(l===void 0)continue;let c=Ht(l,n,e,0,t.ctx.home,t.cut)??xo(l,n);if(!c||S(c)||c.startsWith(hn))continue;let u=M(c,e.cwd,t.ctx);if(!hu(u,t))continue;let f=t.ctx.home.replace(/(?<!\/)\/+$/,""),p=u===f?"~":u.startsWith(`${f}/`)?`~${u.slice(f.length)}`:u;s.push(m("claude.agent.controls",`links to a folder that holds Anvil's or Claude Code's settings (${p}) (from ${e.name})`,{target:u,is_local:!0}));break}if(/\bread_sql(_query|_table)?\s*\(/.test(n)&&/\.to_(csv|parquet|json|excel|feather|pickle|orc|hdf)\s*\(/.test(n)&&!/localhost|127\.0\.0\.1|sqlite/i.test(n)&&s.push(m("claude.bash.data.export",`copies query rows from a database into a file (from ${e.name})`,{target:e.name,host:null,is_local:!1})),/\.to_gbq\s*\([^)]{0,500}if_exists\s*=\s*['"]replace/.test(n)&&s.push(m("claude.bash.db.destructive",`replaces a BigQuery table (from ${e.name})`,{target:e.name,host:"bigquery",is_local:!1})),(/\bfrom\s+pyngrok\s+import\b|\bimport\s+pyngrok\b/.test(n)&&/\bngrok\.connect\s*\(/.test(n)||/require\(\s*['"](localtunnel|ngrok|@ngrok\/ngrok)['"]\s*\)|\bngrok\.(forward|connect)\s*\(/.test(n))&&s.push(m("claude.bash.net.expose",`opens a local port to the internet (from ${e.name})`,{target:e.name,host:null,is_local:!1})),Cb.test(n)){let i=(()=>{if(/\.(delete_table|delete_dataset|delete_model|delete_routine)\s*\(|\.(table|dataset)\([^)]*\)\.delete\s*\(/.test(n))return"deletes warehouse data";for(let l of Ge([...n.matchAll(/\.(query|execute|execute_string|executemany|sql|run_query)\s*\(/g)],t.cut)){let c=n.indexOf("(",l.index),u=n.slice(c,c+4e3),f=lr(u,0);f<0&&c+4e3<n.length&&(t.cut.hit=!0);let p=f>0?gn(u.slice(1,f))[0]??"":"",d=/^\s*[A-Za-z_$][\w$]*\s*$/.test(p)&&xo(p,n)||p,h=be.exec(d)??Hn.exec(d);if(h)return`runs destructive SQL (${h[1].replace(/\s+/g," ").toUpperCase()})`}return null})();i&&s.push(m("claude.bash.db.destructive",`${i} through a warehouse client (from ${e.name})`,{target:e.name,host:/bigquery/i.test(n)?"bigquery":/snowflake/i.test(n)?"snowflake":/databricks/i.test(n)?"databricks":"redshift",is_local:!1}))}return s}function Eb(e,t){let n=e.argv,s=[],r=null;if(e.name==="tmux"&&["new","new-session","new-window","neww","split-window","splitw","respawn-pane"].includes(n[1]??"")){let a=ql(n,2,Rb);if(a.length>1&&(a.some(S)||/\s/.test(a[0])))return qe("tmux");s=[a.length>1?Is(a):a.join(" ")],r="tmux"}else if(e.name==="tmux"&&["send-keys","send"].includes(n[1]??""))s=[pe(n,2,new Set(["-t","-N"])).filter(a=>!/^(Enter|C-m|KPEnter)$/.test(a)).join(" ")];else if(e.name==="screen"){let a=1;for(;a<n.length&&n[a].startsWith("-");)a+=/^-[A-Za-z]*[ScpTXh]$/.test(n[a])||n[a]==="-Logfile"?2:1;let i=n.slice(1,a).some(l=>/^-[A-Za-z]*X$/.test(l));if(!i&&n.slice(a).some(S))return qe("screen");s=[i?n.slice(a).join(" "):Is(n.slice(a))],r="screen"}else if(e.name==="concurrently")s=pe(n,1,new Set(["-n","--names","-c","--prefix-colors","-p","--prefix","-s","--success","--restart-tries"]));else if(e.name==="kitty"&&n[1]==="@"&&n[2]==="launch"||e.name==="wezterm"&&n[1]==="cli"&&n[2]==="spawn"||e.name==="zellij"&&(n[1]==="run"||n[1]==="r")||e.name==="systemd-run"){let a=e.name==="systemd-run"?1:e.name==="zellij"?2:3,i=ql(n,a,Ob[e.name]??new Set);if(i.length===0)return[];if(i.some(S)||/\s/.test(i[0]))return qe(e.name);s=[Is(i)],r=e.name}else if(e.name==="launchctl"){let a=n.slice(1).find(i=>!i.startsWith("-"))??"";if(a==="submit"){let i=n.indexOf("--");if(i<0||n.slice(i+1).some(S))return qe("launchctl submit");s=[Is(n.slice(i+1))],r="launchctl submit"}else if(a==="load"||a==="bootstrap")return qe(`launchctl ${a}`)}else if(e.name==="crontab"||e.name==="at"||e.name==="batch"){let a=n.slice(1).filter(c=>/^-[A-Za-z]+$/.test(c));if(e.name==="crontab"&&a.some(c=>/[lTVre]/.test(c)))return[];if(e.name!=="crontab"&&a.some(c=>/[lrdcq]/.test(c)))return[];let i=e.name==="crontab"?n.slice(1).filter(c=>!c.startsWith("-")||c==="-").filter(c=>c!=="-"):[],l=i.length===1?Tb(i[0],e,t):i.length===0&&!n.includes("-f")?Hl(e)??(e.name==="crontab"?Ib(e,t):null):null;if(l===null)return qe(e.name);s=e.name==="crontab"?Db(l):l.split(`
|
|
72
|
+
`),r=e.name}else if(e.name==="osascript"){let a=n.includes("-e")?n.filter((u,f)=>n[f-1]==="-e").join(`
|
|
73
|
+
`):n.length===1||n.length===2&&n[1]==="-"?Hl(e):null;if(a===null)return qe("osascript");let i=P(n,"-l");if(i!==null&&!/^applescript$/i.test(i)&&/terminal|iterm|doShellScript|doScript|\bwrite\s*\(|System\s*Events|keystroke/i.test(a))return qe("osascript");let l=[...a.matchAll(/\b(?:do\s+(?:shell\s+)?script|write\s+text)\b/gi)].length,c=[...a.matchAll(/\b(?:do\s+(?:shell\s+)?script|write\s+text)\s+"((?:\\.|[^"\\])*)"(?!\s*&)/gi)].map(u=>u[1].replace(/\\(.)/g,"$1"));if(l>c.length)return qe("osascript");s=c,r="osascript"}else if(e.name==="open"){let a=P(n,"-a")??P(n,"-b")??"",i=pe(n,1,new Set(["-a","-b","--env","--stdin","--stdout","--stderr","-u"]));if(i.some(l=>/\.(command|tool|terminal|sh|bash|zsh|workflow|scpt|applescript)$/i.test(l))||/terminal|iterm|warp|ghostty|kitty|alacritty|wezterm|hyper/i.test(a)&&i.some(l=>/\.[A-Za-z0-9]+$/.test(R.basename(l))))return qe("open")}let o=[];for(let a of s.filter(i=>i.trim()!=="")){if(r!==null&&!jb(a,e,t,!0)){o.push(...qe(r));continue}let i=Xl({tool:"Bash",command:a,target:null,cwd:e.cwd,git_branch:t.branch,project_dir:t.projectRoot},t);o.push(...lc(i,r!==null&&r!=="tmux"&&r!=="screen"?`(run by ${r}, outside this session)`:`(in ${e.name})`))}return o}function ql(e,t,n){for(let s=t;s<e.length;s++){let r=e[s];if(r==="--")return e.slice(s+1);if(r.startsWith("-")&&r!=="-"){!r.includes("=")&&n.has(r)&&s++;continue}return e.slice(s)}return[]}var Rb=new Set(["-s","-n","-t","-c","-x","-y","-F","-e","-l","-f","-p"]),Ob=oe({"systemd-run":new Set(["-u","--unit","-p","--property","--description","--slice","--uid","--gid","--nice","--working-directory","-E","--setenv","-M","--machine","-H","--host","--on-active","--on-boot","--on-startup","--on-unit-active","--on-unit-inactive","--on-calendar","--timer-property","--path-property","--socket-property","--service-type","-C","--capsule"]),kitty:new Set(["--type","--title","--tab-title","--cwd","--env","--var","--location","--next-to","--os-window-title","--os-window-name","--os-window-class","--os-window-state","--logo","--logo-position","--logo-alpha","--color","--spacing","--marker","--watcher","-w","--source-window","--stdin-source","--match","-m","--bias","--add-to-session","--window-type","--remote-control-password"]),wezterm:new Set(["--pane-id","--domain-name","--window-id","--workspace","--cwd"]),zellij:new Set(["--name","-n","--cwd","--direction","-d","--width","--height","-x","-y"])});function Is(e){return e.map(Co).join(" ")}function qe(e){return[m("claude.agent.controls",`hands a command to ${e}, which runs it outside this session, and Anvil cannot read that command here`,{target:e,is_local:!0})]}function jb(e,t,n,s=!1){return ku(e,t.cwd,n.ctx,n.projectRoot,n.cut,s)}var Pb=new Set(["install","i","ci","add","remove","rm","uninstall","un","ls","list","view","info","outdated","audit","why","config","help","login","whoami","init","link","pack","prune","dedupe","cache","version"]),Wb=new Set(["make","gmake","just","task","rake","invoke","mise","turbo","nx","gulp","grunt","npx","bunx","pnpx","dlx"]),Nb=new Set(["sh","bash","zsh","dash","ksh","fish","node","nodejs","python","python3","ruby","perl","php","deno","tsx","ts-node","bun"]);function Lb(e){let t=R.basename(e.name),n=e.argv.slice(1).filter(s=>!s.startsWith("-"));return["npm","pnpm","yarn","bun"].includes(t)?n.length>0&&!Pb.has(n[0]):Wb.has(t)?!0:Nb.has(t)?!e.argv.slice(1).some(s=>/^(-c|-e|-p|--eval|--print|-m)$/.test(s))&&n.length>0:(e.argv[0]??"").includes("/")&&!/^\/(usr\/)?(s?bin)\/|^\/opt\/homebrew\/bin\/|^\/usr\/local\/bin\//.test(e.argv[0])}function ku(e,t,n,s,r,o=!1){let a=dt(e,{home:n.home,tmpdir:n.tmpdir,cwd:t,projectDir:s,claudeConfigDir:n.claudeConfigDir??null,...Ao(n)});return a.status==="limited"&&(r.hit=!0),a.commands.length>0&&a.commands.every(i=>!S(i.name)&&!S(i.argv[0]??"")&&i.unreadableCode===null&&!["eval","source",".","exec"].includes(i.name)&&!(o&&Lb(i)))}function Hl(e){if(e.stdin!==null)return e.stdinExpands&&/\$|`/.test(e.stdin)?null:e.stdin;let t=e.pipeFrom;if(!t||t.pipeFrom!==null||t.name!=="echo"&&t.name!=="printf")return null;let n=t.argv.slice(1).filter(s=>!/^-[neE]+$/.test(s));return n.length===0||n.some(s=>S(s))?null:t.name==="printf"?n.length===1&&!/%/.test(n[0])?n[0].replace(/\\n/g,`
|
|
74
|
+
`).replace(/\\t/g," "):null:n.join(" ").replace(/\\n/g,`
|
|
75
|
+
`)}function Tb(e,t,n){if(S(e))return null;let s=M(e,t.cwd,{home:n.ctx.home}),r=n.ctx.session?.scripts?.[s];return r!==void 0?r:(n.ctx.wantScripts?.add(s),null)}function Ib(e,t){if(e.pipeFrom!==null||e.stdin!==null)return null;let n=Jn(t.lineText,t.base,t).commands.filter(r=>!(r.name==="crontab"&&r.text===e.text)),s=[];for(let r of n)if(!(r.name==="crontab"&&r.argv.slice(1).every(o=>/^-[A-Za-z]*l[A-Za-z]*$/.test(o)||/^2?>/.test(o)))&&!(["cat","grep","sort","uniq","true","cd"].includes(r.name)&&r.argv.slice(1).every(o=>!S(o)))){if((r.name==="echo"||r.name==="printf")&&r.argv.length>1&&r.argv.slice(1).every(o=>!S(o))){let o=r.argv.slice(1).filter(a=>!/^-[neE]+$/.test(a));if(r.name==="printf"&&(o.length!==1||/%/.test(o[0])))return null;s.push(o.join(" ").replace(/\\n/g,`
|
|
76
76
|
`));continue}return null}return s.length>0?s.join(`
|
|
77
|
-
`):null}function
|
|
78
|
-
`).map(
|
|
79
|
-
`,s),a
|
|
80
|
-
`)break;a++}t.fill(1,s+i.length,Math.max(s+i.length,Math.min(a,e.length)-i.length)),s=Math.max(a,s+1);continue}s++}return r=>t[r]!==1}var lu=ie({python:["-c"],python3:["-c"],node:["-e","--eval","-p","--print"],tsx:["-e","--eval","-p","--print"],"ts-node":["-e","--eval","-p","--print"],perl:["-e","-E"],ruby:["-e"],deno:["eval"],bun:["-e","--eval"],php:["-r"]}),Mo=/^(os\.homedir\(\)|require\(['"](node:)?os['"]\)\.homedir\(\)|process\.env\.HOME\b|process\.env\[['"]HOME['"]\]|Path\.home\(\)|os\.path\.expanduser\(\s*['"]~['"]\s*\)|os\.environ\[['"]HOME['"]\]|os\.environ\.get\(\s*['"]HOME['"]\s*\)|os\.getenv\(\s*['"]HOME['"]\s*\)|Deno\.env\.get\(['"]HOME['"]\)|Dir\.home|ENV\[['"]HOME['"]\]|\$ENV\{['"]?HOME['"]?\}|glob\(\s*['"]~['"]\s*\))/;function vb(e,n,t){let s=[],r=i=>{let a=i.trim(),l=/^(['"`])((?:\\.|(?!\1)[^\\])*)\1$/.exec(a);if(l)return Nl(l[2].replace(/\\(.)/g,"$1"));if(Mo.test(a))return"~";let c=/^(?:process\.env\.(\w+)|process\.env\[['"](\w+)['"]\]|os\.environ\[['"](\w+)['"]\]|os\.environ\.get\(\s*['"](\w+)['"]|os\.getenv\(\s*['"](\w+)['"]|ENV\[['"](\w+)['"]\]|Deno\.env\.get\(['"](\w+)['"]\))/.exec(a);if(c)return`"$${c.slice(1).find(Boolean)}"`;let u=/^[A-Za-z_$][\w$.]*$/.test(a)||/^(?:pathlib\.)?Path\(|^os\.path\.join\(|^path\.join\(/.test(a)?t(a):null;return u!==null?Nl(u):'"$(unknown)"'},o=i=>{let a=[],l=null;for(let d=i.length-1;d>=0;d--){let p=i[d];p===")"||p==="]"||p==="}"?l="close":p==="("||p==="["||p==="{"?l="open":p===","&&l!=="close"&&a.push(d)}let c=[],u=i.length;for(let d of a)c.unshift(i.slice(d+1,u)),u=d;return c.unshift(i.slice(0,u)),c.map(d=>d.trim()).filter(Boolean)};for(let i of e.matchAll(/\b(?:subprocess\.(?:run|call|check_call|check_output|Popen)|Bun\.spawn(?:Sync)?|os\.spawnvp?e?)\s*\(\s*(?:os\.P_\w+\s*,\s*)?(?:\{\s*cmd\s*:\s*)?\[([^\]]*)\]/g)){let a=o(i[1]);n(i.index??0)&&/^(['"`])/.test(a[0]??"")&&s.push(a.map(r).join(" "))}for(let i of e.matchAll(/\b(?:spawn|spawnSync|execFile|execFileSync|execa|execaSync|execaNode)\s*\(\s*((['"`])(?:\\.|(?!\2)[^\\])*\2)\s*,\s*\[([^\]]*)\]/g))n(i.index??0)&&s.push([r(i[1]),...o(i[3]).map(r)].join(" "));for(let i of e.matchAll(/\bDeno\.Command\s*\(\s*((['"`])(?:\\.|(?!\2)[^\\])*\2)\s*,\s*\{\s*args\s*:\s*\[([^\]]*)\]/g))n(i.index??0)&&s.push([r(i[1]),...o(i[3]).map(r)].join(" "));return s}function Nl(e){return/^[\w./=:@%+,~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Jn(e){let n=lu[e.name];if(!n)return null;let t=null;for(let r=1;r<e.argv.length;r++){let o=e.argv[r];if(n.includes(o)||/^-[A-Za-z]{2,}$/.test(o)&&n.some(i=>/^-[A-Za-z]$/.test(i)&&o.endsWith(i.slice(1)))){t=e.argv[r+1]??null;break}}let s=e.argv.length===1||e.argv.slice(1).every(r=>r==="-"||r.startsWith("-"));return t===null&&e.scriptText!==null&&(t=e.scriptText),t===null&&e.stdin!==null&&s&&(t=e.stdin),t===null&&s&&e.pipeFrom&&(e.pipeFrom.name==="echo"||e.pipeFrom.name==="printf")&&(t=e.pipeFrom.argv.slice(1).join(" ")),t}function $b(e,n){let t=Jn(e);if(t===null)return[];let s=kb(t,e.name.startsWith("python")?"python":["node","deno","bun"].includes(e.name)?"js":"other"),r=[],o=[],i=/\b(?:os\.system|os\.popen|subprocess\.(?:run|call|check_call|check_output|Popen)|execSync|execFileSync|spawnSync|exec|system|`)\s*\(\s*(?:\[\s*)?(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;for(let u of t.matchAll(i))s(u.index??0)&&o.push(u[2].replace(/\\(.)/g,"$1"));o.push(...vb(t,s,u=>{let d=qt(u,t,e,0,n.ctx.home,n.cut);return d===null?null:d.startsWith(pn)?R.join(n.ctx.tmpdir,"code-temp"):C(d)?null:d}));for(let u of t.matchAll(/(?:\bBun\.\$|(?<![\w$.])\$)(?:\.\w+\([^)]*\))*\s*`((?:\\.|[^`\\])*)`/g))s(u.index??0)&&o.push(u[1].replace(/\$\{[^}]*\}/g,'"$(unknown)"'));let a=/\b(execSync|execFileSync|spawnSync|check_output|getoutput|getstatusoutput|popen)\b|capture_output\s*=\s*True|stdout\s*=\s*subprocess\.PIPE|stdio\s*:\s*['"]pipe/.test(t);for(let u of o){let d=Ml({tool:"Bash",command:u,target:null,cwd:e.cwd,git_branch:n.branch},n),p=Jl(d,`(run from ${e.name})`).filter(f=>!(f.action==="claude.bash.secrets.print"&&a)&&!(f.action==="claude.bash.privilege"&&/cannot read/.test(d.why)));r.push(...p)}let l=/(?:\b(?:shutil\.rmtree|rmtree|remove_tree|rimraf(?:\.sync)?|fse?\.removeSync|fse?\.remove|Deno\.remove|FileUtils\.rm_rf|FileUtils\.remove_dir)|(?:\bfs|\bpromises|\))\.(?:rmSync|rm|rmdirSync))\s*\(\s*(?:(['"`])((?:\\.|(?!\1)[^\\])*)\1|([A-Za-z_$][\w.{}$]*))/g;for(let u of t.matchAll(l)){if(!s(u.index??0))continue;let d=u[2],p=u[0];if(!(/rmtree|remove_tree|rimraf|remove|rm_rf|remove_dir/.test(p)||/recursive\s*:\s*true/.test(t.slice(u.index??0,(u.index??0)+200))))continue;let h=t.slice((u.index??0)+u[0].length-(u[3]?.length??0),(u.index??0)+u[0].length+40),g=Mo.test(h),y=(u.index??0)+u[0].indexOf("("),$=sr(t,y),E=$>y?hn(t.slice(y+1,$))[0]??u[3]??"?":u[3]??"?",_=d!==void 0&&E.trim().length===d.length+2?Y(Ie(d,e,n),e.cwd,te(n)):g&&E.trim()===(u[3]??"").trim()?Y(n.ctx.home,null,te(n)):_b(t,E,e,n);r.push({..._t([_],e),why:`${_t([_],e).why} (from ${e.name})`})}let c=/\b(?:requests|httpx|axios)\.(post|put|patch|delete)\s*\(\s*(?:(['"`])([^'"`]*)\2|f(['"])([^'"]*)\4|([A-Za-z_$][\w.$]*(?:\[['"]\w+['"]\])?))|\bfetch\s*\(\s*(?:(['"`])([^'"`]*)\7|([A-Za-z_$][\w.$]*))\s*,\s*\{[^}]*method\s*:\s*['"`](POST|PUT|PATCH|DELETE)/gi;for(let u of t.matchAll(c)){if(!s(u.index??0))continue;let d=(u[1]??u[10]??"POST").toUpperCase(),p=u[3]??u[5]??u[8],f=u[6]??u[9],h=p??(f?Sb(t,f):null),g=h===null?null:h.replace(/:\$?\{[^}]*\}/,":1").replace(/\$?\{[^}]*\}/g,"x");g!==null&&/^https?:\/\//i.test(g)?Re(g)||r.push(m("claude.bash.external_write",`${d} to ${de(g)} (from ${e.name})`,{target:g,host:de(g),is_local:!1})):g===null&&f&&!/https?:\/\/(localhost|127\.0\.0\.1|\[::1\])\b/i.test(t)&&r.push(m("claude.bash.external_write",`${d} to a URL held in ${f} (from ${e.name})`,{target:f,host:null,is_local:null}))}return r}function _b(e,n,t,s){let r={kind:"normal",path:n,token:null,why:`a path held in ${n}`},o=qt(n,e,t,0,s.ctx.home,s.cut);if(o===null)return r;if(o.startsWith(pn))return{kind:"disposable",path:n,token:null,why:`a temp folder the code made (${n})`};let i=Y(Ie(o,t,s),t.cwd,te(s));return i.kind==="normal"&&C(o)?r:i}var pn="temp",xb=/^(tempfile\.(mkdtemp|TemporaryDirectory|gettempdir)\b|(?:await\s+)?(?:fs\.|fsp\.|promises\.)?mkdtemp(Sync)?\s*\(|os\.tmpdir\(\)|Dir\.mktmpdir|Deno\.makeTempDir|path\.join\(\s*os\.tmpdir\(\)|tmpdir\(\))/;function qt(e,n,t,s,r,o){if(s>4)return null;let i=e.trim().replace(/\.(resolve|absolute|expanduser)\(\)/g,"").replace(/^await\s+/,"");if(xb.test(i))return pn;let a=Mo.exec(i);if(a)return Ls(r,i.slice(a[0].length).trim()?`/${eo(i.slice(a[0].length).replace(/^\s*[+/]\s*/,""))}`:"");let l=null,c="",u=p=>{let f=p.exec(i);return f&&(c=i.slice(f[0].length)),f},d;if(d=u(/^f?(['"`])((?:\\.|(?!\1)[^\\])*)\1/)){let p=/^\$?\{([A-Za-z_$][\w$.]*)\}(.*)$/s.exec(d[2]);l=p?Ls(qt(p[1],n,t,s+1,r,o),p[2].replace(/\$?\{[^}]*\}/g,"x")):d[2].replace(/\$?\{[^}]*\}/g,"x")}else if(d=u(/^(?:sys\.argv|process\.argv)\[(\d+)\]/)){let p=t.argv.findIndex((h,g)=>g>0&&!h.startsWith("-")),f=Number(d[1]);l=t.argv[p+(i.startsWith("process")?f-1:f)]??null}else if(d=u(/^(?:Path\(\s*__file__\s*\)\.parent|os\.path\.dirname\(\s*(?:os\.path\.abspath\(\s*)?__file__\s*\)?\s*\)|__dirname|path\.dirname\(\s*fileURLToPath\(\s*import\.meta\.url\s*\)\s*\))/))l=t.scriptPath?R.dirname(t.scriptPath):null;else if(d=u(/^(?:pathlib\.)?(?:Path|PurePath|PosixPath|str|String|os\.path\.(?:join|abspath|realpath|normpath)|path\.(?:join|resolve|normalize)|join|resolve)\s*\(/)){let p=sr(i,d[0].length-1);if(p<0)return null;let f=hn(i.slice(d[0].length,p));c=i.slice(p+1),l=qt(f[0]??"",n,t,s+1,r,o);for(let h of f.slice(1))l=Ls(l,`/${eo(h)}`)}else if(d=u(/^(?:self\.|this\.)?([A-Za-z_$][\w$]*)/)){let p=new RegExp(`(?:^|[^\\w$.])${d[1].replace(/\$/g,"\\$")}\\s*(?::\\s*[\\w.\\[\\] ]+\\s*)?=(?!=)\\s*([^\\n;]+)`).exec(n);if(!p||hn(p[1]).length>1)return null;l=qt(p[1],n,t,s+1,r,o)}if(l===null)return null;for(let p=0;c.trim();p++){if(p>=12){o&&(o.hit=!0);break}let f=c.trimStart(),h=/^(\/|\+)\s*(f?(['"`])(?:\\.|(?!\3)[^\\])*\3|[\w.$]+(?:\([^)]*\))?)/.exec(f);if(h){let g=eo(h[2]);if(l=Ls(l,h[1]==="/"?`/${g}`:g),l===null)return null;c=f.slice(h[0].length);continue}if(f.startsWith(".parent")){if(l===null)return null;l=l.startsWith(pn)?l:R.dirname(l),c=f.slice(7);continue}break}return l}function Ls(e,n){return e===null?null:e.startsWith(pn)?e:n.startsWith("/")?`${e.replace(/\/$/,"")}${n}`:`${e}${n}`}function eo(e){let n=/^f?(['"`])((?:\\.|(?!\1)[^\\])*)\1$/.exec(e.trim());return n?n[2].replace(/\$?\{[^}]*\}/g,"x"):"x"}function sr(e,n){let t=0,s=null;for(let r=n;r<e.length;r++){let o=e[r];if(s){o==="\\"?r++:o===s&&(s=null);continue}if(o==='"'||o==="'"||o==="`")s=o;else if(o==="(")t++;else if(o===")"&&--t===0)return r}return-1}function hn(e){let n=[],t=0,s=null,r=0;for(let o=0;o<e.length;o++){let i=e[o];if(s){i==="\\"?o++:i===s&&(s=null);continue}i==='"'||i==="'"||i==="`"?s=i:"([{".includes(i)?t++:")]}".includes(i)?t--:i===","&&t===0&&(n.push(e.slice(r,o).trim()),r=o+1)}return n.push(e.slice(r).trim()),n.filter(o=>o!=="")}function Sb(e,n){let t=n.replace(/^(self|this)\./,"");if(!/^[A-Za-z_$][\w$]*$/.test(t))return null;let s=new RegExp(`(?:^|[^\\w$.])${t.replace(/\$/g,"\\$")}\\s*(?::\\s*\\w+\\s*)?=\\s*f?(['"\`])([^'"\`]*)\\1`).exec(e);return s?s[2]:null}var Uo=new Set(["node","python","python3","ruby","deno","bun","tsx","ts-node","go","php","perl","sh","bash"]),Tl=new Set(["--apply","--write","--commit","--execute","--fix","--force","--yes","--confirm","--no-dry-run","--live","--migrate","--delete","--purge","--reset","--prune"]);function Cb(e){if(!e.productionEnv||e.via==="substitution"||!Uo.has(e.name))return[];let n=e.argv.slice(2).find(s=>Tl.has(s)||Tl.has(s.split("=")[0]??""));if(!n)return[];let t=e.argv.slice(1).find(s=>!s.startsWith("-"))??e.name;return[m("claude.bash.db.destructive",`runs ${R.basename(v(t))} with production credentials and ${n}`,{target:v(t),is_local:!1,host:"production"})]}var cu=/^(deploy|release|publish|ship|rollout|promote)$/i,Ab=/(^|[-_.])(deploy|release|publish|rollout|promote)([-_.]|$)/i,Eb=/(^|[-_.])(tags?[-_.](and[-_.])?push|push[-_.]tags?)([-_.]|$)/i,Rb=/(^|[-_.])(test|tests|spec|check|verify|lint|notes|changelog|build|docs|plan|diff|status|dry|preview|local|mock|fake|stub|prepare)([-_.]|$)/i,Ob=/^(detect|find|get|next|determine|should|is|has|needs|parse|extract|wait|print|show|list|read|info)[-_.]/i,to=e=>Rb.test(e)||Ob.test(e),no=/\.(sh|bash|zsh|py|rb|js|mjs|cjs|ts|mts|cts|pl)$/,Pb=/^(\.{1,2}\/)?[\w.-]+\/[\w./-]*[\w-]$/,so=e=>Pb.test(e)&&!/\.[A-Za-z0-9]{1,5}$/.test(R.basename(e))&&!/(^|\/)node_modules\//.test(e)&&!["gradlew","mvnw","gradle","mvn"].includes(R.basename(e))&&!Hs(R.basename(e))&&!lc.has(R.basename(e))&&!mn.has(R.basename(e))&&!tr.has(R.basename(e)),jb=/(^|[-_.])(drop|purge|nuke|wipe|reset|truncate)[-_.]?(db|dbs|database|databases|data|tables?|schema)([-_.]|$)|(^|[-_.])(db|database)[-_.]?(drop|purge|nuke|wipe|reset|truncate)([-_.]|$)/i,Wb=new Set(["py_compile","compileall","pyflakes","pylint","flake8","mypy","black","ruff"]);function uu(e,n){let t=R.basename(e);if(["sh","bash","zsh","dash","ksh"].includes(t))return n.some(r=>/^-[a-zA-Z]*n[a-zA-Z]*$/.test(r));if(t==="node"||t==="nodejs")return n.some(r=>r==="--check"||r==="-c");let s=/^python[\d.]*$/.test(t)?n.indexOf("-m"):-1;return s>=0&&Wb.has(n[s+1]??"")}function Nb(e,n){if(e.via==="substitution")return[];let t=e.argv.map(f=>v(f)),s=f=>no.test(f)||so(f),r=t[0]?.includes("/")&&s(t[0])?0:(e.name==="source"||e.name===".")&&(no.test(t[1]??"")||(t[1]??"").includes("/")&&so(t[1]))?1:Uo.has(e.name)?t.findIndex((f,h)=>h>0&&!f.startsWith("-")&&(no.test(f)||f.includes("/")&&so(f))):-1;if(r<0||r>0&&uu(e.name,t.slice(1,r)))return[];let o=t[r],i=Y(o,e.cwd,te(n)).path;if(i&&n.lineMade.includes(i)&&ic(o,n,ac(e,o)))return[];let a=R.basename(o).replace(/\.[^.]+$/,""),l=t.slice(r+1),c=l.filter(f=>!f.startsWith("-")),u=["run","exec","task"].includes(c[0]??"")?c[1]:c[0];if(jb.test(a)&&!to(a)&&!l.some(f=>/^--?(dry-?run|plan|help)$/i.test(f)))return[m("claude.bash.db.destructive",`runs ${R.basename(o)}, a script that drops or resets data`,{target:o,is_local:null})];let d=(Ab.test(a)||Eb.test(a))&&!to(a),p=u!==void 0&&cu.test(u)&&!to(a);return!d&&!p||l.some(f=>/^--?(dry-?run|plan|check|preview|diff|help|version|what-?if)$/i.test(f))?[]:[m("claude.bash.deploy",`runs ${R.basename(o)}${p?` ${u}`:""}, a script that deploys or releases`,{target:o,is_local:!1})]}var du=/\.(db|sqlite|sqlite3|db3|log|csv|tsv|parquet|ndjson|jsonl|bak|dump)$/i;function Ll(e){let n=e.name==="printf"&&(e.argv[1]??"")===""&&e.argv.length<=2||e.name==="echo"&&e.argv.slice(1).every(t=>t===""||/^-[neE]+$/.test(t));return e.name===":"||e.name==="true"||n||e.name==="cat"&&e.argv[1]==="/dev/null"&&e.argv.length===2}function Il(e,n){let t=[];e.name==="truncate"&&e.argv.some((o,i)=>(o==="-s"||o==="--size")&&/^0+$/.test(e.argv[i+1]??"")||/^--size=0+$/.test(o)||o==="-s0")&&t.push(...e.argv.slice(1).filter((o,i,a)=>!o.startsWith("-")&&a[i-1]!=="-s"&&a[i-1]!=="--size")),e.name==="cp"&&e.argv[1]==="/dev/null"&&e.argv[2]&&t.push(e.argv[2]);let s=e.groupWriters!==null&&!e.groupWriters.every(Ll);if(Ll(e))for(let o of e.redirects)(o.op===">"||o.op===">|")&&o.target&&!(s&&/\.log$/i.test(v(o.target)))&&t.push(o.target);e.redirects.forEach((o,i)=>{(o.op===">"||o.op===">|")&&(o.fd===null||o.fd===1)&&o.target&&e.redirects.slice(i+1).some(a=>a.fd===1||a.fd===null&&[">",">>",">|",">&"].includes(a.op))&&t.push(o.target)});let r=t.map(o=>({t:o,v:qe(o,e,n)})).find(({t:o,v:i})=>du.test(v(o))&&i.kind!=="disposable");return r?[m("claude.bash.fs.delete_recursive",`empties a data file (${R.basename(v(r.t))})`,{target:r.v.path,is_local:!0})]:[]}import{createHash as kw}from"crypto";import{readFileSync as vw}from"fs";import{join as bn}from"path";import{spawnSync as y_}from"child_process";import{createHash as ow}from"crypto";import{chmodSync as k_,existsSync as v_,lstatSync as iw,mkdirSync as $_,readdirSync as __,readFileSync as x_,readlinkSync as aw,realpathSync as Su,rmdirSync as S_,statSync as Vo,unlinkSync as C_,writeFileSync as A_}from"fs";import{dirname as lw,join as R_,resolve as cw}from"path";var it={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Tb(e){if(!e){let l=c=>c;return{on:!1,bold:l,dim:l,blue:l,grey:l,amber:l,mark:l,field:l}}let n=e==="truecolor",t=l=>c=>`\x1B[${l}m${c}\x1B[0m`,s=t(n?"38;2;76;139;255":"38;5;69"),r=t(n?"38;2;130;134;150":"90"),o=t(n?"38;2;245;165;36":"38;5;214"),i=t(n?"38;2;34;197;94":"32"),a={[it.on]:s,[it.blocked]:s,[it.held]:s,[it.next]:s,[it.watching]:r,[it.problem]:o,[it.ok]:i};return{on:!0,bold:t("1"),dim:t("2"),blue:s,grey:r,amber:o,mark:l=>(a[l]??(c=>c))(l),field:l=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Ib(l)}\x1B[0m`}}var r$=Tb(!1),Lb=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ib(e){return e.replace(Lb,"")}var fu="claude.agent.controls";var pu=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],Db="home and project wipes and force-pushes to main",u$=`always blocking ${Db}`,d$=new Map(pu.map(e=>[e.id,e]));var Fb=new Set(pu.flatMap(e=>Object.keys(e.slugs)));var hu=new Set([fu,"claude.bash.secrets.expose"]);var zb=ie({"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"discard uncommitted work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}});function gu(e){return zb[e]?.text??e}var mu="\u{1F539}",rr=e=>`${mu} ${e} ${mu}`,Mb=ie({"claude.bash.git.push_main":"pushes to main","claude.agent.controls":"its own settings","claude.bash.git.force_push":"force-pushes","claude.bash.fs.delete_recursive":"deletes","claude.bash.git.discard":"thrown-away work","claude.bash.db.destructive":"database wipes","claude.bash.deploy":"deploys","claude.bash.publish":"releases","claude.bash.secrets.print":"printed secrets","claude.bash.spend":"paid compute","claude.bash.external_write":"outside writes","claude.mcp.side_effect":"app changes"}),Ub=e=>Mb[e]??gu(e),qb=Ub;function Hb(e,n){let t=[...[...e].sort((s,r)=>+(s==="claude.agent.controls")-+(r==="claude.agent.controls")).map(qb),...n?[n]:[]];return t.length<=2?t.join(" and "):`${t[0]}, ${t[1]} and ${t.length-2} more`}var yu=e=>`
|
|
81
|
-
${
|
|
82
|
-
${
|
|
83
|
-
`);
|
|
77
|
+
`):null}function Db(e){return e.split(`
|
|
78
|
+
`).map(t=>t.trim()).filter(t=>t!==""&&!t.startsWith("#")&&!/^[A-Za-z_][A-Za-z0-9_]*\s*=/.test(t)).map(t=>t.startsWith("@")?t.replace(/^@\S+\s+/,""):t.split(/\s+/).slice(5).join(" "))}var Bl=new WeakMap;function So(e){let t=Bl.get(e);return t||(t=[P(e.argv,"-name","-iname","-path","-ipath")].filter(n=>n!==null),Bl.set(e,t)),t}function vu(e){let t=e.parent;if(!t)return[];if(e.via==="find-exec"&&t.name==="find")return So(t);if(e.via==="xargs"&&t.pipeFrom){let n=t.pipeFrom;if(n.name==="find")return So(n);if(["echo","printf","ls"].includes(n.name))return n.argv.slice(1).filter(s=>!s.startsWith("-"))}return[]}var $u="reads Anvil's seal key, which signs its rules: with it, a rule changed out of sight would pass as Anvil's own",Fb=/\.anvil\/claude\/seal\.key(?![\w.-])/,zb=new Set(["cat","tac","nl","head","tail","less","more","bat","batcat","grep","egrep","fgrep","rg","ag","ack","base64","base32","xxd","od","hexdump","strings","tar","gtar","bsdtar","zip","7z","7za","gzip","bzip2","xz","zstd","cp","gcp","rsync","scp","sftp","ditto","pax","cpio","openssl","sed","gsed","awk","gawk","diff","cmp","curl","nc","ncat","dd","rclone","aws","gsutil","azcopy"]);function xu(e,t,n){let s=R.join(t,".anvil"),r=R.join(s,"claude"),o=e;for(let a=!0;a;){for(a=!1;o.length>1&&o.endsWith("/");)o=o.slice(0,-1),a=!0;o.endsWith("/.")&&(o=o.slice(0,-2),a=!0)}return o===`${r}/seal.key`||R.dirname(o)===r&&/[*?[]/.test(R.basename(o))&&Mb(R.basename(o),"seal.key")?!0:n?o===s||o===r?!0:R.dirname(o)===s&&/[*?[]/.test(R.basename(o)):!1}function Mb(e,t){let n=(i,l)=>{if(e[i]==="?")return[!0,i+1];if(e[i]==="["){let c=e.indexOf("]",i+2);if(c>i){let u=e.slice(i+1,c),f=u[0]==="!"||u[0]==="^";f&&(u=u.slice(1));let p=!1;for(let d=0;d<u.length;d++)u[d+1]==="-"&&d+2<u.length?(l>=u[d]&&l<=u[d+2]&&(p=!0),d+=2):u[d]===l&&(p=!0);return[p!==f,c+1]}}return[e[i]===l,i+1]},s=0,r=0,o=-1,a=0;for(;r<t.length;){if(e[s]==="*"){o=s++,a=r;continue}if(s<e.length){let[i,l]=n(s,t[r]);if(i){s=l,r++;continue}}if(o<0)return!1;s=o+1,r=++a}for(;e[s]==="*";)s++;return s===e.length}function Ub(e,t){let n=[m("claude.agent.controls",$u,{target:"~/.anvil/claude/seal.key",is_local:!0})];if([e.text,...e.argv.map(k),e.scriptText??"",e.stdin??""].some(a=>Fb.test(a)))return n;let s=t.ctx.home,r=zb.has(e.name)||e.name==="find"&&(e.argv.some(a=>/^-(exec|execdir|ok|okdir)$/.test(a))||e.pipeTo!==null),o=e.cwd??t.base;for(let a=1;a<e.argv.length;a++){let i=e.argv[a];if(S(i))continue;if(["tar","gtar","bsdtar"].includes(e.name)&&(i==="-C"||i==="--directory"||i.startsWith("--directory="))){let c=i.startsWith("--directory=")?i.slice(12):e.argv[++a];c!==void 0&&!S(c)&&(o=M(c,o,t.ctx));continue}if(i.startsWith("-")&&!i.includes("@")&&!i.includes("/"))continue;let l=i.replace(/^(?:-[\w-]*=)?[\w-]*=@?|^@/,"");if(!(l===""||!l.includes("/")&&!l.includes(".")&&!/[*?[]/.test(l))&&!(o===null&&!/^[/~]/.test(l))&&xu(M(l,o,t.ctx),s,r))return n}return[]}function qb(e,t){let n=["docker","podman","docker-compose"].includes(e.name)?gu(e.name==="docker-compose"?["docker","compose",...e.argv.slice(1)]:e.argv):null;if(n&&n.args.length>0&&!/(^|\/)(cloudflared|ngrok)(:[^/]*)?$/.test(n.image)){let s=["sh","bash","ash","zsh","/bin/sh","/bin/bash"].includes(n.args[0])&&n.args[1]==="-c"?n.args[2]??null:n.args.length===1&&/\s/.test(n.args[0])?n.args[0]:null,r=s!==null?Jn(s,null,t,null).commands:[{...e,name:ue(n.args[0]),argv:n.args}];return[...tr(e,t),...r.flatMap(o=>[...Wl(o,t),...Tl(o,t),...Ho(o,t),...$o(o)])]}return[...Eb(e,t),...Ab(e,t),...Ft(t,()=>Ky(e,t)),...Ft(t,()=>nb(e,t)),...$o(e),...Wl(e,t),...Tl(e,t),...cb(e),...db(e,t),...gb(e,t),...fb(e),...tr(e,t),...Ub(e,t)]}var Vl=new Set(["sudo","doas","pkexec","run0"]),Hb=new Set(["-n","-v","-k","-K","-l","--validate","--reset-timestamp","--remove-timestamp","--list","--non-interactive","-nv","-vn","-nl","-ln"]),Ds=new Set(["sh","bash","zsh","dash","ksh","fish","python","python3","node","perl","ruby","php","deno","bun"]),nr=new Set(["curl","wget","fetch","http","https","xh","aria2c"]),Un=new Set(["sh","bash","zsh","dash","ksh","fish","ash","mksh","yash"]);function Bb(e,t){let n=[],s=e.wrappers.find(o=>Vl.has(o));if(s){let o=(e.argv[0]==="true"||e.argv[0]===":")&&e.argv.length===1,a=c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${a(s)}\\b[^;&|\\n]*?\\s-u\\s*([\\w.-]+)[^;&|\\n]*?\\b${a(R.basename(e.name))}\\b`).exec(t.lineText)?.[1],l=i&&!["root","0","#0"].includes(i)?`as the user ${i}`:"as root";!o&&Kc(e)===null&&n.push(m("claude.bash.privilege",`runs ${e.name} ${l} (${s})`,{target:e.argv.slice(0,3).join(" "),is_local:e.remote===null,host:e.remote}))}else Vl.has(e.name)&&e.argv.slice(1).some(o=>!Hb.has(o))&&n.push(m("claude.bash.privilege",`runs ${e.name}`,{target:e.argv.join(" "),is_local:!0}));e.name==="osascript"&&/with\s+administrator\s+privileges/i.test(e.argv.join(" "))&&n.push(m("claude.bash.privilege","osascript runs a shell command as an administrator",{target:"osascript",is_local:!0})),e.name==="su"&&n.push(m("claude.bash.privilege","switches to another user (su)",{target:e.argv.join(" "),is_local:!0})),e.unreadableCode&&n.push(m("claude.bash.privilege",`runs code it cannot read (${e.unreadableCode})`,{target:e.unreadableCode,is_local:null}));let r=Un.has(e.name)?Jt(e.argv).stdin||["/dev/stdin","/dev/fd/0","-"].includes(Jt(e.argv).script??""):!e.argv.slice(1).some(o=>!o.startsWith("-")&&o!=="-"&&o!=="-s");if(Ds.has(e.name)&&e.pipeFrom&&nr.has(e.pipeFrom.name)&&r){let o=e.pipeFrom.argv.find(a=>un(a))??null;(!o||!Re(o))&&n.push(m("claude.bash.privilege",`pipes a download into ${e.name}`,{target:o,host:o?de(o):null,is_local:!1}))}if(Ds.has(e.name)||e.name==="source"||e.name==="."||e.argv[0]?.startsWith("./")||e.argv[0]?.startsWith("/")){let o=e.argv.slice(1).some(i=>["-","-m","--eval","--print"].includes(i)||/^-[a-zA-Z]*[cep]$/.test(i)),a=Un.has(e.name)?Jt(e.argv).script:e.name==="source"||e.name==="."?e.argv[1]:Ds.has(e.name)?o?void 0:e.argv.slice(1).find(i=>!i.startsWith("-")):e.argv[0];a&&!S(a)&&t.downloads.has(X(a,e.cwd,se(t)).path)&&n.push(m("claude.bash.privilege",`runs a script it downloaded (${R.basename(a)})`,{target:a,is_local:!1}))}if(Un.has(e.name)&&e.stdinKind==="here-string"&&/\$\(\s*(curl|wget)\b|`\s*(curl|wget)\b/.test(k(e.stdin??""))&&n.push(m("claude.bash.privilege",`runs a downloaded script with ${e.name}`,{target:k(e.stdin??"").slice(0,120),is_local:!1})),e.name==="xargs"&&e.pipeFrom&&nr.has(e.pipeFrom.name)){let o=e.argv.findIndex((i,l)=>l>0&&Un.has(ue(i))),a=e.pipeFrom.argv.find(i=>un(i))??null;o>0&&Jt(e.argv.slice(o)).command===null&&(!a||!Re(a))&&n.push(m("claude.bash.privilege","pipes a download into a shell through xargs",{target:a,host:a?de(a):null,is_local:!1}))}if(Ds.has(e.name)||e.name==="eval"||e.name==="source"||e.name==="."){let a=Vb(e).find(i=>S(i)&&/\$\(\s*(curl|wget)\b|`\s*(curl|wget)\b|<\(\s*(curl|wget)\b/.test(k(i)));a&&n.push(m("claude.bash.privilege",`runs a downloaded script with ${e.name}`,{target:k(a).slice(0,120),is_local:!1}))}if(e.name==="chmod"){let o=e.argv.slice(1),a=o.some(p=>p==="-R"||p==="--recursive"||/^-[a-zA-Z]*R/.test(p)),i=o.find(p=>!p.startsWith("-"))??"",l=/^0?777$|^a\+rwx$|^ugo\+rwx$|^o\+w|^a\+w|^\+w$/.test(i),c=/^[ugoa]*\+s$|^[2467]\d{3}$/.test(i),u=o.filter((p,d)=>!p.startsWith("-")&&d>o.indexOf(i)),f=u.some(p=>He(p,e,t).kind==="catastrophic");(l&&(a||f)||c)&&n.push(m("claude.bash.privilege",`chmod ${i}${a?" -R":""} opens up permissions`,{target:u.join(" "),is_local:!0}))}return(e.name==="spctl"&&e.argv.includes("--master-disable")||e.name==="csrutil"&&e.argv.includes("disable"))&&n.push(m("claude.bash.privilege",`${e.name} turns off a system protection`,{target:e.argv.join(" "),is_local:!0})),n}function Vb(e){let t=e.argv.slice(1);if(e.name==="eval"||e.name==="source"||e.name===".")return t;let n=new Set(["-c","-e","-E","--eval","-p","--print","-r"]);for(let s=0;s<t.length;s++){let r=t[s];if(n.has(r)||/^-[a-zA-Z]*c$/.test(r))return t[s+1]!==void 0?[t[s+1]]:[];if(!r.startsWith("-"))return[r]}return[]}function Zb(e,t){let n=new Uint8Array(e.length),s=0;for(;s<e.length;){let r=e[s];if(t!=="js"&&r==="#"||t!=="python"&&r==="/"&&e[s+1]==="/"){let a=e.indexOf(`
|
|
79
|
+
`,s),i=a===-1?e.length:a;n.fill(1,s,i),s=i;continue}if(t!=="python"&&r==="/"&&e[s+1]==="*"){let a=e.indexOf("*/",s+2),i=a===-1?e.length:a+2;n.fill(1,s,i),s=i;continue}if(r==='"'||r==="'"||t==="js"&&r==="`"){let a=t==="python"&&e.startsWith(r.repeat(3),s)?r.repeat(3):r,i=s+a.length;for(;i<e.length;){if(e[i]==="\\"){i+=2;continue}if(e.startsWith(a,i)){i+=a.length;break}if(a.length===1&&a!=="`"&&e[i]===`
|
|
80
|
+
`)break;i++}n.fill(1,s+a.length,Math.max(s+a.length,Math.min(i,e.length)-a.length)),s=Math.max(i,s+1);continue}s++}return r=>n[r]!==1}var Jo=oe({python:["-c"],python3:["-c"],node:["-e","--eval","-p","--print"],tsx:["-e","--eval","-p","--print"],"ts-node":["-e","--eval","-p","--print"],perl:["-e","-E"],ruby:["-e"],deno:["eval"],bun:["-e","--eval"],php:["-r"]}),Xo=/^(os\.homedir\(\)|require\(['"](node:)?os['"]\)\.homedir\(\)|process\.env\.HOME\b|process\.env\[['"]HOME['"]\]|Path\.home\(\)|os\.path\.expanduser\(\s*['"]~['"]\s*\)|os\.environ\[['"]HOME['"]\]|os\.environ\.get\(\s*['"]HOME['"]\s*\)|os\.getenv\(\s*['"]HOME['"]\s*\)|Deno\.env\.get\(['"]HOME['"]\)|Dir\.home|ENV\[['"]HOME['"]\]|\$ENV\{['"]?HOME['"]?\}|glob\(\s*['"]~['"]\s*\))/;function Gb(e,t,n){let s=[],r=a=>{let i=a.trim(),l=/^(['"`])((?:\\.|(?!\1)[^\\])*)\1$/.exec(i);if(l)return Co(l[2].replace(/\\(.)/g,"$1"));if(Xo.test(i))return"~";let c=/^(?:process\.env\.(\w+)|process\.env\[['"](\w+)['"]\]|os\.environ\[['"](\w+)['"]\]|os\.environ\.get\(\s*['"](\w+)['"]|os\.getenv\(\s*['"](\w+)['"]|ENV\[['"](\w+)['"]\]|Deno\.env\.get\(['"](\w+)['"]\))/.exec(i);if(c)return`"$${c.slice(1).find(Boolean)}"`;let u=/^[A-Za-z_$][\w$.]*$/.test(i)||/^(?:pathlib\.)?Path\(|^os\.path\.join\(|^path\.join\(/.test(i)?n(i):null;return u!==null?Co(u):'"$(unknown)"'},o=a=>{let i=[],l=null;for(let f=a.length-1;f>=0;f--){let p=a[f];p===")"||p==="]"||p==="}"?l="close":p==="("||p==="["||p==="{"?l="open":p===","&&l!=="close"&&i.push(f)}let c=[],u=a.length;for(let f of i)c.unshift(a.slice(f+1,u)),u=f;return c.unshift(a.slice(0,u)),c.map(f=>f.trim()).filter(Boolean)};for(let a of e.matchAll(/\b(?:subprocess\.(?:run|call|check_call|check_output|Popen)|Bun\.spawn(?:Sync)?|os\.spawnvp?e?)\s*\(\s*(?:os\.P_\w+\s*,\s*)?(?:\{\s*cmd\s*:\s*)?\[([^\]]*)\]/g)){let i=o(a[1]);t(a.index??0)&&/^(['"`])/.test(i[0]??"")&&s.push(i.map(r).join(" "))}for(let a of e.matchAll(/\b(?:spawn|spawnSync|execFile|execFileSync|execa|execaSync|execaNode)\s*\(\s*((['"`])(?:\\.|(?!\2)[^\\])*\2)\s*,\s*\[([^\]]*)\]/g))t(a.index??0)&&s.push([r(a[1]),...o(a[3]).map(r)].join(" "));for(let a of e.matchAll(/\bDeno\.Command\s*\(\s*((['"`])(?:\\.|(?!\2)[^\\])*\2)\s*,\s*\{\s*args\s*:\s*\[([^\]]*)\]/g))t(a.index??0)&&s.push([r(a[1]),...o(a[3]).map(r)].join(" "));return s}function Co(e){return/^[\w./=:@%+,~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Kb(e,t,n,s){let r=Jo[e.name],o=r?e.argv.findIndex((f,p)=>p>0&&r.includes(f)):-1;if(o<0||n.length===0)return null;let a=e.argv.slice(o+2),i=f=>ar(f,s.ctx,e.cwd)||!S(f)&&St(k(M(f,e.cwd,s.ctx)),s.ctx,!1),l=f=>{let p=f.trim(),d=/^[A-Za-z_$][\w$]*$/.test(p)?new RegExp(`(?:^|[^\\w$.])${p.replace(/\$/g,"\\$")}\\s*=(?!=)\\s*([^\\n;]+)`).exec(t)?.[1]??p:p,h=/\b(?:process|sys)\.argv\[(\d+)\]/.exec(d);if(h)return Number(h[1])-1;let g=/(?:\$|\b)ARGV\[(\d+)\]/.exec(d);return g?Number(g[1]):null},c=n.map(l);return(c.every(f=>f!==null)?c.map(f=>a[f]).filter(f=>f!==void 0):a).find(i)??null}function Xn(e){let t=Jo[e.name];if(!t)return null;let n=null;for(let r=1;r<e.argv.length;r++){let o=e.argv[r];if(t.includes(o)||/^-[A-Za-z]{2,}$/.test(o)&&t.some(a=>/^-[A-Za-z]$/.test(a)&&o.endsWith(a.slice(1)))){n=e.argv[r+1]??null;break}}let s=e.argv.length===1||e.argv.slice(1).every(r=>r==="-"||r.startsWith("-"));return n===null&&e.scriptText!==null&&(n=e.scriptText),n===null&&e.stdin!==null&&s&&(n=e.stdin),n===null&&s&&e.pipeFrom&&(e.pipeFrom.name==="echo"||e.pipeFrom.name==="printf")&&(n=e.pipeFrom.argv.slice(1).join(" ")),n}function Yb(e,t){let n=Xn(e);if(n===null)return[];let s=Zb(n,e.name.startsWith("python")?"python":["node","deno","bun"].includes(e.name)?"js":"other"),r=[],o=[],a=/\b(?:os\.system|os\.popen|subprocess\.(?:run|call|check_call|check_output|Popen)|execSync|execFileSync|spawnSync|exec|system|`)\s*\(\s*(?:\[\s*)?(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;for(let u of n.matchAll(a))s(u.index??0)&&o.push(u[2].replace(/\\(.)/g,"$1"));o.push(...Gb(n,s,u=>{let f=Ht(u,n,e,0,t.ctx.home,t.cut);return f===null?null:f.startsWith(hn)?R.join(t.ctx.tmpdir,"code-temp"):S(f)?null:f}));for(let u of n.matchAll(/(?:\bBun\.\$|(?<![\w$.])\$)(?:\.\w+\([^)]*\))*\s*`((?:\\.|[^`\\])*)`/g))s(u.index??0)&&o.push(u[1].replace(/\$\{[^}]*\}/g,'"$(unknown)"'));let i=/\b(execSync|execFileSync|spawnSync|check_output|getoutput|getstatusoutput|popen)\b|capture_output\s*=\s*True|stdout\s*=\s*subprocess\.PIPE|stdio\s*:\s*['"]pipe/.test(n);for(let u of o){let f=Xl({tool:"Bash",command:u,target:null,cwd:e.cwd,git_branch:t.branch},t),p=lc(f,`(run from ${e.name})`).filter(d=>!(d.action==="claude.bash.secrets.print"&&i)&&!(d.action==="claude.bash.privilege"&&/cannot read/.test(f.why)));r.push(...p)}let l=/(?:\b(?:shutil\.rmtree|rmtree|remove_tree|rimraf(?:\.sync)?|fse?\.removeSync|fse?\.remove|Deno\.remove|FileUtils\.rm_rf|FileUtils\.remove_dir)|(?:\bfs|\bpromises|\))\.(?:rmSync|rm|rmdirSync))\s*\(\s*(?:(['"`])((?:\\.|(?!\1)[^\\])*)\1|([A-Za-z_$][\w.{}$]*))/g;for(let u of n.matchAll(l)){if(!s(u.index??0))continue;let f=u[2],p=u[0];if(!(/rmtree|remove_tree|rimraf|remove|rm_rf|remove_dir/.test(p)||/recursive\s*:\s*true/.test(n.slice(u.index??0,(u.index??0)+200))))continue;let h=n.slice((u.index??0)+u[0].length-(u[3]?.length??0),(u.index??0)+u[0].length+40),g=Xo.test(h),y=(u.index??0)+u[0].indexOf("("),$=lr(n,y),E=$>y?gn(n.slice(y+1,$))[0]??u[3]??"?":u[3]??"?",x=f!==void 0&&E.trim().length===f.length+2?X(Ie(f,e,t),e.cwd,se(t)):g&&E.trim()===(u[3]??"").trim()?X(t.ctx.home,null,se(t)):Jb(n,E,e,t);r.push({...xt([x],e),why:`${xt([x],e).why} (from ${e.name})`})}let c=/\b(?:requests|httpx|axios)\.(post|put|patch|delete)\s*\(\s*(?:(['"`])([^'"`]*)\2|f(['"])([^'"]*)\4|([A-Za-z_$][\w.$]*(?:\[['"]\w+['"]\])?))|\bfetch\s*\(\s*(?:(['"`])([^'"`]*)\7|([A-Za-z_$][\w.$]*))\s*,\s*\{[^}]*method\s*:\s*['"`](POST|PUT|PATCH|DELETE)/gi;for(let u of n.matchAll(c)){if(!s(u.index??0))continue;let f=(u[1]??u[10]??"POST").toUpperCase(),p=u[3]??u[5]??u[8],d=u[6]??u[9],h=p??(d?Qb(n,d):null),g=h===null?null:h.replace(/:\$?\{[^}]*\}/,":1").replace(/\$?\{[^}]*\}/g,"x");g!==null&&/^https?:\/\//i.test(g)?Re(g)||r.push(m("claude.bash.external_write",`${f} to ${de(g)} (from ${e.name})`,{target:g,host:de(g),is_local:!1})):g===null&&d&&!/https?:\/\/(localhost|127\.0\.0\.1|\[::1\])\b/i.test(n)&&r.push(m("claude.bash.external_write",`${f} to a URL held in ${d} (from ${e.name})`,{target:d,host:null,is_local:null}))}return r}function Jb(e,t,n,s){let r={kind:"normal",path:t,token:null,why:`a path held in ${t}`},o=Ht(t,e,n,0,s.ctx.home,s.cut);if(o===null)return r;if(o.startsWith(hn))return{kind:"disposable",path:t,token:null,why:`a temp folder the code made (${t})`};let a=X(Ie(o,n,s),n.cwd,se(s));return a.kind==="normal"&&S(o)?r:a}var hn="temp",Xb=/^(tempfile\.(mkdtemp|TemporaryDirectory|gettempdir)\b|(?:await\s+)?(?:fs\.|fsp\.|promises\.)?mkdtemp(Sync)?\s*\(|os\.tmpdir\(\)|Dir\.mktmpdir|Deno\.makeTempDir|path\.join\(\s*os\.tmpdir\(\)|tmpdir\(\))/;function Ht(e,t,n,s,r,o){if(s>4)return null;let a=e.trim().replace(/\.(resolve|absolute|expanduser)\(\)/g,"").replace(/^await\s+/,"");if(Xb.test(a))return hn;let i=Xo.exec(a);if(i)return Fs(r,a.slice(i[0].length).trim()?`/${io(a.slice(i[0].length).replace(/^\s*[+/]\s*/,""))}`:"");let l=null,c="",u=p=>{let d=p.exec(a);return d&&(c=a.slice(d[0].length)),d},f;if(f=u(/^f?(['"`])((?:\\.|(?!\1)[^\\])*)\1/)){let p=/^\$?\{([A-Za-z_$][\w$.]*)\}(.*)$/s.exec(f[2]);l=p?Fs(Ht(p[1],t,n,s+1,r,o),p[2].replace(/\$?\{[^}]*\}/g,"x")):f[2].replace(/\$?\{[^}]*\}/g,"x")}else if(f=u(/^(?:sys\.argv|process\.argv)\[(\d+)\]/)){let p=n.argv.findIndex((h,g)=>g>0&&!h.startsWith("-")),d=Number(f[1]);l=n.argv[p+(a.startsWith("process")?d-1:d)]??null}else if(f=u(/^(?:Path\(\s*__file__\s*\)\.parent|os\.path\.dirname\(\s*(?:os\.path\.abspath\(\s*)?__file__\s*\)?\s*\)|__dirname|path\.dirname\(\s*fileURLToPath\(\s*import\.meta\.url\s*\)\s*\))/))l=n.scriptPath?R.dirname(n.scriptPath):null;else if(f=u(/^(?:pathlib\.)?(?:Path|PurePath|PosixPath|str|String|os\.path\.(?:join|abspath|realpath|normpath)|path\.(?:join|resolve|normalize)|join|resolve)\s*\(/)){let p=lr(a,f[0].length-1);if(p<0)return null;let d=gn(a.slice(f[0].length,p));c=a.slice(p+1),l=Ht(d[0]??"",t,n,s+1,r,o);for(let h of d.slice(1))l=Fs(l,`/${io(h)}`)}else if(f=u(/^(?:self\.|this\.)?([A-Za-z_$][\w$]*)/)){let p=new RegExp(`(?:^|[^\\w$.])${f[1].replace(/\$/g,"\\$")}\\s*(?::\\s*[\\w.\\[\\] ]+\\s*)?=(?!=)\\s*([^\\n;]+)`).exec(t);if(!p||gn(p[1]).length>1)return null;l=Ht(p[1],t,n,s+1,r,o)}if(l===null)return null;for(let p=0;c.trim();p++){if(p>=12){o&&(o.hit=!0);break}let d=c.trimStart(),h=/^(\/|\+)\s*(f?(['"`])(?:\\.|(?!\3)[^\\])*\3|[\w.$]+(?:\([^)]*\))?)/.exec(d);if(h){let g=io(h[2]);if(l=Fs(l,h[1]==="/"?`/${g}`:g),l===null)return null;c=d.slice(h[0].length);continue}if(d.startsWith(".parent")){if(l===null)return null;l=l.startsWith(hn)?l:R.dirname(l),c=d.slice(7);continue}break}return l}function Fs(e,t){return e===null?null:e.startsWith(hn)?e:t.startsWith("/")?`${e.replace(/\/$/,"")}${t}`:`${e}${t}`}function io(e){let t=/^f?(['"`])((?:\\.|(?!\1)[^\\])*)\1$/.exec(e.trim());return t?t[2].replace(/\$?\{[^}]*\}/g,"x"):"x"}function lr(e,t){let n=0,s=null;for(let r=t;r<e.length;r++){let o=e[r];if(s){o==="\\"?r++:o===s&&(s=null);continue}if(o==='"'||o==="'"||o==="`")s=o;else if(o==="(")n++;else if(o===")"&&--n===0)return r}return-1}function gn(e){let t=[],n=0,s=null,r=0;for(let o=0;o<e.length;o++){let a=e[o];if(s){a==="\\"?o++:a===s&&(s=null);continue}a==='"'||a==="'"||a==="`"?s=a:"([{".includes(a)?n++:")]}".includes(a)?n--:a===","&&n===0&&(t.push(e.slice(r,o).trim()),r=o+1)}return t.push(e.slice(r).trim()),t.filter(o=>o!=="")}function Qb(e,t){let n=t.replace(/^(self|this)\./,"");if(!/^[A-Za-z_$][\w$]*$/.test(n))return null;let s=new RegExp(`(?:^|[^\\w$.])${n.replace(/\$/g,"\\$")}\\s*(?::\\s*\\w+\\s*)?=\\s*f?(['"\`])([^'"\`]*)\\1`).exec(e);return s?s[2]:null}var Qo=new Set(["node","python","python3","ruby","deno","bun","tsx","ts-node","go","php","perl","sh","bash"]),Zl=new Set(["--apply","--write","--commit","--execute","--fix","--force","--yes","--confirm","--no-dry-run","--live","--migrate","--delete","--purge","--reset","--prune"]);function ew(e){if(!e.productionEnv||e.via==="substitution"||!Qo.has(e.name))return[];let t=e.argv.slice(2).find(s=>Zl.has(s)||Zl.has(s.split("=")[0]??""));if(!t)return[];let n=e.argv.slice(1).find(s=>!s.startsWith("-"))??e.name;return[m("claude.bash.db.destructive",`runs ${R.basename(k(n))} with production credentials and ${t}`,{target:k(n),is_local:!1,host:"production"})]}var _u=/^(deploy|release|publish|ship|rollout|promote)$/i,tw=/(^|[-_.])(deploy|release|publish|rollout|promote)([-_.]|$)/i,nw=/(^|[-_.])(tags?[-_.](and[-_.])?push|push[-_.]tags?)([-_.]|$)/i,sw=/(^|[-_.])(test|tests|spec|check|verify|lint|notes|changelog|build|docs|plan|diff|status|dry|preview|local|mock|fake|stub|prepare)([-_.]|$)/i,rw=/^(detect|find|get|next|determine|should|is|has|needs|parse|extract|wait|print|show|list|read|info)[-_.]/i,ao=e=>sw.test(e)||rw.test(e),lo=/\.(sh|bash|zsh|py|rb|js|mjs|cjs|ts|mts|cts|pl)$/,ow=/^(\.{1,2}\/)?[\w.-]+\/[\w./-]*[\w-]$/,co=e=>ow.test(e)&&!/\.[A-Za-z0-9]{1,5}$/.test(R.basename(e))&&!/(^|\/)node_modules\//.test(e)&&!["gradlew","mvnw","gradle","mvn"].includes(R.basename(e))&&!Zs(R.basename(e))&&!wc.has(R.basename(e))&&!yn.has(R.basename(e))&&!rr.has(R.basename(e)),iw=/(^|[-_.])(drop|purge|nuke|wipe|reset|truncate)[-_.]?(db|dbs|database|databases|data|tables?|schema)([-_.]|$)|(^|[-_.])(db|database)[-_.]?(drop|purge|nuke|wipe|reset|truncate)([-_.]|$)/i,aw=new Set(["py_compile","compileall","pyflakes","pylint","flake8","mypy","black","ruff"]);function Su(e,t){let n=R.basename(e);if(["sh","bash","zsh","dash","ksh"].includes(n))return t.some(r=>/^-[a-zA-Z]*n[a-zA-Z]*$/.test(r));if(n==="node"||n==="nodejs")return t.some(r=>r==="--check"||r==="-c");let s=/^python[\d.]*$/.test(n)?t.indexOf("-m"):-1;return s>=0&&aw.has(t[s+1]??"")}function lw(e,t){if(e.via==="substitution")return[];let n=e.argv.map(d=>k(d)),s=d=>lo.test(d)||co(d),r=n[0]?.includes("/")&&s(n[0])?0:(e.name==="source"||e.name===".")&&(lo.test(n[1]??"")||(n[1]??"").includes("/")&&co(n[1]))?1:Qo.has(e.name)?n.findIndex((d,h)=>h>0&&!d.startsWith("-")&&(lo.test(d)||d.includes("/")&&co(d))):-1;if(r<0||r>0&&Su(e.name,n.slice(1,r)))return[];let o=n[r],a=X(o,e.cwd,se(t)).path;if(a&&t.lineMade.includes(a)&&yc(o,t,bc(e,o)))return[];let i=R.basename(o).replace(/\.[^.]+$/,""),l=n.slice(r+1),c=l.filter(d=>!d.startsWith("-")),u=["run","exec","task"].includes(c[0]??"")?c[1]:c[0];if(iw.test(i)&&!ao(i)&&!l.some(d=>/^--?(dry-?run|plan|help)$/i.test(d)))return[m("claude.bash.db.destructive",`runs ${R.basename(o)}, a script that drops or resets data`,{target:o,is_local:null})];let f=(tw.test(i)||nw.test(i))&&!ao(i),p=u!==void 0&&_u.test(u)&&!ao(i);return!f&&!p||l.some(d=>/^--?(dry-?run|plan|check|preview|diff|help|version|what-?if)$/i.test(d))?[]:[m("claude.bash.deploy",`runs ${R.basename(o)}${p?` ${u}`:""}, a script that deploys or releases`,{target:o,is_local:!1})]}var Cu=/\.(db|sqlite|sqlite3|db3|log|csv|tsv|parquet|ndjson|jsonl|bak|dump)$/i;function Gl(e){let t=e.name==="printf"&&(e.argv[1]??"")===""&&e.argv.length<=2||e.name==="echo"&&e.argv.slice(1).every(n=>n===""||/^-[neE]+$/.test(n));return e.name===":"||e.name==="true"||t||e.name==="cat"&&e.argv[1]==="/dev/null"&&e.argv.length===2}function Kl(e,t){let n=[];e.name==="truncate"&&e.argv.some((o,a)=>(o==="-s"||o==="--size")&&/^0+$/.test(e.argv[a+1]??"")||/^--size=0+$/.test(o)||o==="-s0")&&n.push(...e.argv.slice(1).filter((o,a,i)=>!o.startsWith("-")&&i[a-1]!=="-s"&&i[a-1]!=="--size")),e.name==="cp"&&e.argv[1]==="/dev/null"&&e.argv[2]&&n.push(e.argv[2]);let s=e.groupWriters!==null&&!e.groupWriters.every(Gl);if(Gl(e))for(let o of e.redirects)(o.op===">"||o.op===">|")&&o.target&&!(s&&/\.log$/i.test(k(o.target)))&&n.push(o.target);e.redirects.forEach((o,a)=>{(o.op===">"||o.op===">|")&&(o.fd===null||o.fd===1)&&o.target&&e.redirects.slice(a+1).some(i=>i.fd===1||i.fd===null&&[">",">>",">|",">&"].includes(i.op))&&n.push(o.target)});let r=n.map(o=>({t:o,v:He(o,e,t)})).find(({t:o,v:a})=>Cu.test(k(o))&&a.kind!=="disposable");return r?[m("claude.bash.fs.delete_recursive",`empties a data file (${R.basename(k(r.t))})`,{target:r.v.path,is_local:!0})]:[]}import{createHash as Gw}from"crypto";import{readFileSync as Kw}from"fs";import{join as wn}from"path";import{spawnSync as t_}from"child_process";import{createHash as Ww}from"crypto";import{chmodSync as r_,existsSync as o_,lstatSync as Nw,mkdirSync as i_,readdirSync as a_,readFileSync as l_,readlinkSync as Lw,realpathSync as Mu,rmdirSync as c_,statSync as si,unlinkSync as u_,writeFileSync as d_}from"fs";import{dirname as Tw,isAbsolute as p_,join as h_,relative as g_,resolve as Iw}from"path";var at={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function cw(e){if(!e){let l=c=>c;return{on:!1,bold:l,dim:l,blue:l,grey:l,amber:l,mark:l,field:l}}let t=e==="truecolor",n=l=>c=>`\x1B[${l}m${c}\x1B[0m`,s=n(t?"38;2;76;139;255":"38;5;69"),r=n(t?"38;2;130;134;150":"90"),o=n(t?"38;2;245;165;36":"38;5;214"),a=n(t?"38;2;34;197;94":"32"),i={[at.on]:s,[at.blocked]:s,[at.held]:s,[at.next]:s,[at.watching]:r,[at.problem]:o,[at.ok]:a};return{on:!0,bold:n("1"),dim:n("2"),blue:s,grey:r,amber:o,mark:l=>(i[l]??(c=>c))(l),field:l=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${dw(l)}\x1B[0m`}}var P$=cw(!1),uw=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function dw(e){return e.replace(uw,"")}var Au="claude.agent.controls";var Eu=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],fw="home and project wipes and force-pushes to main",D$=`always blocking ${fw}`,F$=new Map(Eu.map(e=>[e.id,e]));var pw=new Set(Eu.flatMap(e=>Object.keys(e.slugs)));var Ru=new Set([Au,"claude.bash.secrets.expose"]);var Ou=oe({"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"discard uncommitted work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}});function ju(e){return Ou[e]?.text??e}var Pu="\u{1F539}",cr=e=>`${Pu} ${e} ${Pu}`,hw=oe({"claude.bash.git.push_main":"pushes to main","claude.agent.controls":"its own settings","claude.bash.git.force_push":"force-pushes","claude.bash.fs.delete_recursive":"deletes","claude.bash.git.discard":"thrown-away work","claude.bash.db.destructive":"database wipes","claude.bash.deploy":"deploys","claude.bash.publish":"releases","claude.bash.secrets.print":"printed secrets","claude.bash.spend":"paid compute","claude.bash.external_write":"outside writes","claude.mcp.side_effect":"app changes"}),gw=e=>hw[e]??ju(e),mw=gw;function yw(e,t){let n=[...[...e].sort((s,r)=>+(s==="claude.agent.controls")-+(r==="claude.agent.controls")).map(mw),...t?[t]:[]];return n.length<=2?n.join(" and "):`${n[0]}, ${n[1]} and ${n.length-2} more`}var Wu=e=>`
|
|
81
|
+
${at.next} ${e}`;var bw=72;function ei(e,t){let n=`To ${e}, run in a terminal: ${t}`;return n.length+5<=bw?Wu(n):`${Wu(`To ${e}, run in a terminal:`)}
|
|
82
|
+
${t}`}function ww(e,t,n,s,r=null){if(n.length>0){let l=$w(n[0],s);return`${cr("Anvil on")} but ${l.said}${n.length>1?` (and ${n.length-1} more)`:""}${l.fix??ei("see details",`${Se(s)} report`)}`}let o=ei("add your own rules",`${Se(s)} rules edit`),a=`${cr("Anvil is on")} ${kw}`;if(e.length>=t)return`${a} \xB7 holding every risky action for your OK${o}`;let i=e.filter(l=>!Ru.has(l));return`${i.length>0||r?`${a} \xB7 holding ${yw(i,r)} for your OK`:a}${o}`}var kw="blocking unsafe actions automatically";function vw(e,t,n,s=null){return["Anvil (anvilcontrol.ai) checks every tool call in this session before it runs.",...e.length>0?[`On every install, from the first call, it ${e.join("; it ")}.`]:[],...t.length>0?[`It also stops these when they come up: ${t.join("; ")}.`]:[],...s?[s]:[],...t.length===0?["It watches everything else: it records what it would have stopped, and lets it run."]:[],`When Anvil holds a call, nothing in that command runs until the user allows it, in Claude Code's prompt or with a one-time allow command they are shown. Tell the user what was held; once they allow it, run the same command again. \`${Se(n)} report\` shows what Anvil did; changing Anvil is the user's to do, in their own terminal, so do not run other \`${Se(n)}\` commands, edit ~/.anvil, or look for another way around a hold.`].join(" ")}function $w(e,t){let n=e.lastIndexOf(` run ${Se(t)} on`),s=n>0?e[n-1]:"";if(n<=0||s!==":"&&s!==";")return{said:e,fix:null};let r=e.slice(n+` run ${Se(t)} on`.length);return r!==""&&!/^ to [a-z][a-z ]*$/.test(r)?{said:e,fix:null}:{said:e.slice(0,n-1),fix:ei("fix it",`${Se(t)} on`)}}import{createHash as R0}from"crypto";import{appendFileSync as j0,closeSync as Lu,constants as Nu,fstatSync as Tu,mkdirSync as Aw,openSync as Iu,readdirSync as P0,readFileSync as Ew,readSync as Du,renameSync as Rw,statSync as Ow,unlinkSync as W0,writeFileSync as jw}from"fs";import{homedir as L0}from"os";import{dirname as I0,join as ct}from"path";import{existsSync as ux,readdirSync as dx,statSync as fx}from"fs";import{dirname as hx,isAbsolute as gx,join as mx,posix as yx,resolve as bx}from"path";import{domainToASCII as Ax}from"url";var Lx="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Jx,readdirSync as Xx,realpathSync as Qx}from"fs";import{basename as t0,dirname as n0,join as s0}from"path";function ur(e){return{dir:e,bin:ct(e,"bin"),compiled:ct(e,"compiled.json"),modes:ct(e,"modes.json"),decisions:ct(e,"decisions.jsonl"),install:ct(e,"install.json"),state:ct(e,"state"),approvals:ct(e,"approvals"),counts:ct(e,"counts"),backups:ct(e,"backups")}}function Ke(e,t=8*1024*1024){try{let n=Ow(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function lt(e,t=8*1024*1024){let n;try{n=Iu(e,Nu.O_RDONLY|Nu.O_NONBLOCK)}catch(s){if(s.code==="ENOENT"||s.code==="ENOTDIR")return null;throw s}try{let s=Tu(n);if(!s.isFile())throw new Error(`${e} is not a regular file`);if(s.size>t)throw new Error(`${e} is over ${t} bytes`);let r=Buffer.alloc(s.size),o=0;for(;o<s.size;){let a=Du(n,r,o,s.size-o,o);if(a===0)break;o+=a}return r.subarray(0,o)}finally{Lu(n)}}function ti(e){Aw(e,{recursive:!0,mode:448})}function Fu(e,t){if(Ke(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=Iu(e,"r")}catch{return""}try{let s=Tu(n).size,r=Math.max(0,s-t),o=s-r;if(o<=0)return"";let a=Buffer.alloc(o);Du(n,a,0,o,r);let i=a.toString("utf8");if(r>0){let l=i.indexOf(`
|
|
83
|
+
`);i=l<0?"":i.slice(l+1)}return i}finally{Lu(n)}}function zu(e,t,n=384){let s=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;jw(s,t,{mode:n}),ni(s,e)}function ni(e,t){for(let n=0;;n++)try{Rw(e,t);return}catch(s){let r=s.code;if(process.platform!=="win32"||n>=12||r!=="EPERM"&&r!=="EACCES"&&r!=="EBUSY")throw s;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20+n*10)}}function Qn(e){if(Ke(e)!==!0)return null;try{return JSON.parse(Ew(e,"utf8"))}catch{return null}}var F0=256*1024,z0=1024*1024;var Dw="/.anvil/claude/bin/claude-hook.js",Fw=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var bn=class extends Error{constructor(t){super(t),this.name="SettingsRefused"}};function Uu(e){return`// anvil-claude-hook ${Ww("sha256").update(e).digest("hex").slice(0,16)}`}function ri(e,t){let n=e.startsWith("\uFEFF")?e.slice(1):e;if(n.trim()==="")return{};let s;try{s=JSON.parse(n)}catch(r){throw new bn(`${t} is not valid JSON (${r instanceof Error?r.message:String(r)}). Anvil changed nothing; fix the file and run this again.`)}if(!s||typeof s!="object"||Array.isArray(s))throw new bn(`${t} is not a JSON object. Anvil changed nothing.`);return s}function zw(e){if(!e||typeof e!="object")return null;let{command:t,args:n}=e;return typeof t!="string"?null:Array.isArray(n)?[t,...n.filter(s=>typeof s=="string")].join(" "):t}var Mw=e=>{let t=zw(e);return t!==null&&(t.includes(Dw)||Fw.test(t))};function Uw(e){return lt(e,64*1024*1024)}function qw(e){try{if(!Nw(e).isSymbolicLink())return e}catch{return e}try{return Mu(e)}catch(t){let n=t.code;throw n==="ENOENT"?new bn(`${e} is a link to ${Hw(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new bn(`${e} is a link Anvil cannot follow (${n??String(t)}). Anvil changed nothing.`)}}function Hw(e){let t=Tw(e);try{t=Mu(t)}catch{}return Iw(t,Lw(e))}function qu(e){try{let t=qw(e),n=si(t);if(!n.isFile()||n.size>4*1024*1024)return!1;let s=Uw(t);if(s===null)return!1;let r=ri(s.toString("utf8"),e).hooks?.PreToolUse;return Array.isArray(r)&&r.some(o=>{let a=o&&typeof o=="object"?o:null,i=a?.matcher;return(i===void 0||i===""||i==="*")&&Array.isArray(a?.hooks)&&a.hooks.some(l=>Mw(l)&&Zw(l))})}catch{return!1}}function Bw(e){let t=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),n=o=>o.startsWith("'")?o.slice(1,-1).replace(/'\\''/g,"'"):o,s=t?t.findIndex(o=>o==="/bin/sh"||o==="sh"):-1,r=t&&s>=0&&(t[s+3]==="PreToolUse"||t[s+3]==="SessionStart")?1:0;if(t&&s>=0&&t[s+3+r]==="||"){let o=s>0&&s%5===0;for(let a=0;o&&a<s;a+=5)o=t[a]==="["&&(t[a+1]==="-s"||t[a+1]==="-f")&&t[a+3]==="]"&&t[a+4]==="&&"&&n(t[a+2])===n(t[s+1]);if(s===0||o)return[n(t[s+1]),n(t[s+2])]}return!t||t.length!==2?null:[n(t[0]),n(t[1])]}function Vw(e){if(!e||typeof e!="object")return null;let{command:t,args:n}=e;if(typeof t!="string")return null;if(Array.isArray(n)){let s=n.find(r=>typeof r=="string"&&/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js$/i.test(r));return s?[t,s]:null}return Bw(t)}function Zw(e){let t=Vw(e);if(!t)return!1;try{return si(t[0]).isFile()&&si(t[1]).isFile()}catch{return!1}}var Yw=["claude-hook-core.js","claude-sync.js","claude-hook.js","claude-meter.js","claude-helpers.js","claude-conditions.js"],Jw=process.platform==="darwin"?"/Library/Application Support/ClaudeCode/managed-settings.json":process.platform==="win32"?`${process.env.ProgramFiles||"C:\\Program Files"}\\ClaudeCode\\managed-settings.json`:"/etc/claude-code/managed-settings.json";function Xw(e,t=Jw){let n=[],s=l=>l.startsWith(`${e.home}/`)?`~${l.slice(e.home.length)}`:l;for(let l of[t,...e.files])try{Ke(l,4*1024*1024)===!0&&ri(Kw(l,"utf8"),l).disableAllHooks===!0&&n.push(`hooks are off for new sessions ("disableAllHooks") in
|
|
84
84
|
${(s(l).match(/.{1,63}(?:\/|$)|.{64}/g)??[l]).join(`
|
|
85
|
-
`)}`)}catch{}e.files.some(l=>
|
|
86
|
-
`,1)[0]}catch{}let
|
|
87
|
-
`)}function Mw(e){if(e.kind!=="changes")return null;let n=e.arg??"";try{let t=/^(?:(co|wt|wi|merge|pull|pick|stash|al)\t((?!-)[^\0-\x20:?*[\\\x7f]+)((?:\t(?!-)[^\0-\x1f]+)*)|(zip|tar|p\d\d?)\t(\/[^\0-\x1f]*))$/.exec(n);if(!t)return null;if(t[4]){let c=t[4],u=Zt(t[5]),d=Lw(u,{throwIfNoEntry:!1});if(!d)return Ct;if(!d.isFile())return null;if(c==="zip")return Go("unzip",["-Z1",u],null);if(c==="tar")return Go("tar",["-tf",u],null);let p=Ru(u);return typeof p=="string"&&p!=="missing"?zw(p,Number(c.slice(1))):p==="missing"?Ct:null}let s=t[1],r=t[2],o=(...c)=>Go("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null",...c],e.cwd);if(s==="al")return o("config","--get",`alias.${r}`)?.trim()??Ct;let i=(o("rev-parse","--verify","--quiet",`${r}^0`)||(s==="co"?o("for-each-ref","--count=1","--format=%(objectname)",`refs/remotes/*/${r}`):""))?.trim();if(!i)return s==="pull"?null:s==="co"&&Tw(Dw(Zt(e.cwd??"/"),r))?"":Ct;let a=["--name-only","-z","--no-renames","--no-ext-diff","--no-relative"];if(s==="stash")return o("stash","show","-u",...a,r);if(s==="pick")return o("diff-tree","-r","-m","--root","--no-commit-id",...a,i,...Ou);if(s[0]==="w"){let c=o("rev-parse","--show-toplevel")?.trim()??"";if([".gitattributes",".claude/.gitattributes"].some(u=>{let d=Ru(Iw(c,u));return d===null||d!=="missing"&&/filter\s*=/.test(d)}))return null}let l=t[3]?["--",...t[3].slice(1).split(" ").map(c=>`:(literal)${c}`)]:Ou;return o("diff",...a,...s==="wi"?[]:[s==="wt"?i:`HEAD..${s==="co"?"":"."}${i}`],...l)}catch(t){if(t.signal||t.error?.code==="ETIMEDOUT")return ar}return null}import{spawn as Uw}from"child_process";import{statSync as qw}from"fs";import{join as Pu}from"path";var Hw=6e4;function Bw(e,n){Uw("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",e,n],{detached:!0,stdio:"ignore"}).unref()}function Vw(e,n=Bw){try{let t=e.env;if((e.platform??process.platform)!=="darwin"||!t.CLAUDE_CODE_ENTRYPOINT||t.CI||t.VITEST||t.ANVIL_NO_NOTIFY||!e.transcript||!qw(e.transcript).isFile())return;let s=Pu(e.anvilDir,"state");Ho(s);let r=Pu(s,`notice-${(e.session??"none").replace(/[^\w-]/g,"_").slice(0,80)}`),o=Number(_u(r,64).trim());if(Number.isFinite(o)&&e.now-o<Hw)return;xu(r,String(e.now)),n(rr("Anvil held a call"),`${e.why}. To allow it once, run in a terminal: ${Se(e.cli)} allow`)}catch{}}import{createHash as Lx,randomBytes as Ix}from"crypto";import{readdirSync as Qw,renameSync as Fx,unlinkSync as ek}from"fs";import{join as Lu}from"path";import{createHmac as Zw,randomBytes as fx,timingSafeEqual as Gw}from"crypto";import{closeSync as hx,existsSync as gx,fsyncSync as mx,linkSync as yx,mkdirSync as bx,openSync as wx,readdirSync as kx,readFileSync as ju,unlinkSync as vx,writeSync as $x}from"fs";import{basename as xx,dirname as Sx,join as Kw}from"path";var Qn="_seal";function Yw(e){return Kw(e.dir,"seal.key")}function Wu(e){let n=Yw(e);if(Ge(n,1024)!==!0)return null;try{let t=ju(n,"utf8").trim();return/^[0-9a-f]{64}$/.test(t)?Buffer.from(t,"hex"):null}catch{return null}}function Yo(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>Yo(t===void 0?null:t,n+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(s=>!(n===0&&s===Qn)&&e[s]!==void 0).sort().map(s=>`${JSON.stringify(s)}:${Yo(e[s],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function Jw(e,n){return Zw("sha256",e).update(Yo(n)).digest("hex")}function Ko(e){if(!(Qn in e))return e;let n={...e};return delete n[Qn],n}function Xw(e,n){let t=n[Qn];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let s;try{s=Jw(e,n)}catch{return!1}return Gw(Buffer.from(t,"hex"),Buffer.from(s,"hex"))}function Nu(e,n,t=8*1024*1024){let s=Ge(e,t);if(s===null)return{status:"missing"};if(s===!1)return{status:"unreadable"};let r;try{r=JSON.parse(ju(e,"utf8"))}catch{return{status:"unreadable"}}return!r||typeof r!="object"||Array.isArray(r)?{status:"unreadable"}:n?Qn in r?Xw(n,r)?{status:"ok",value:Ko(r)}:{status:"changed",value:Ko(r)}:{status:"unsealed",value:r}:{status:"unkeyed",value:Ko(r)}}var qx=600*1e3,Hx=1440*60*1e3;function Tu(e){return Lu(e.state,"pending")}function tk(e,n,t,s,r,o,i){let a=0;for(let{hold:l,file:c}of rk(e,n,o))if(!(c===i||(l.session??null)!==(t??null)||(l.project??null)!==(s??null)||l.stops.length===0)&&l.stops.every(u=>r.some(d=>sk(d,u))))try{ek(c),a++}catch{}return a}function nk(e){let n=or(e.anvilDir);tk(n,Wu(n),e.session,e.project,e.stops,e.now)}function sk(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function rk(e,n,t){let s=[];try{s=Qw(Tu(e)).filter(o=>o.endsWith(".json")).slice(0,2e3)}catch{return[]}let r=[];for(let o of s){let i=Lu(Tu(e),o),a=Nu(i,n,64*1024);a.status!=="ok"||a.value.v!==2||!Array.isArray(a.value.stops)||!(Date.parse(a.value.expires_at)>=t)||r.push({hold:a.value,file:i})}return r.sort((o,i)=>Date.parse(i.hold.created_at)-Date.parse(o.hold.created_at))}function Xo(){return{touched:{full:new Set,parent:new Set},read:new Set,written:new Set,unknown:new Set}}function Fu(e){return{full:[...e.touched?.full??[]],parent:[...e.touched?.parent??[]],read:[...e.read??[]],written:[...e.written??[]],unknown:[...e.unknown??[]]}}function ik(e){if(!e||typeof e!="object")return null;let n=e;for(let t of["file_path","notebook_path","path"])if(typeof n[t]=="string")return n[t];return null}var ak=/(?:^|[^\w.-])(?:git|gh|patch|tar|bsdtar|gtar|unzip)(?![\w.-])/,lk=/^(add|annotate|archive|bisect|blame|branch|bundle|cat-file|check-[\w-]+|clean|clone|commit|config|count-objects|describe|diff(-\w+)?|fetch|filter-branch|for-each-ref|format-patch|fsck|gc|grep|hash-object|help|init|log|ls-\w+|maintenance|merge-\w+|mk\w+|mv|name-rev|notes|prune|push|range-diff|reflog|remote|repack|replace|rerere|rev-\w+|rm|shortlog|show(-\w+)?|sparse-checkout|status|submodule|symbolic-ref|tag|update-[\w-]+|var|verify-\w+|version|whatchanged|worktree|\w+-tree)$/,ck=/^(?!-)[^\0-\x20:?*[\\\x7f]+$/,Jo=/^(?:\.\/?|\*|:\/|:\(top\))$/;function Iu(e){let n=e.toLowerCase().split("/");return n[n.length-1]===".mcp.json"||n.some(t=>t===".claude"||t===".anvil")}var kn=e=>typeof e=="string"&&e.startsWith("/")&&!C(e),ve=e=>({what:e,ask:null,base:null,shown:null}),cr=(e,n)=>{let t=e.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g,"");return t.length>n?`${t.slice(0,n-3)}\u2026`:t};function ts(e,n,t){if(e===""||C(e)||!e.startsWith("/")&&!e.startsWith("~")&&!kn(n))return null;let s=U(e,n,{home:t});return kn(s)?s:null}function me(e,n,t,s,r=[]){return!kn(s)||C(t)||!ck.test(t)||r.some(o=>C(o)||!/^(?!-)[^\0-\x1f]+$/.test(o))?ve(e):{what:e,ask:{probe:{kind:"changes",arg:[`${n} ${t}`,...r].join(" "),cwd:s}},base:s,shown:null}}function ei(e,n,t,s,r,o,i,a={}){let l=ts(t,s,i),c=r===null?kn(o)?o:null:ts(r,o,i);return l===null||c===null||/[\u0000-\u001f]/.test(l)?ve(e):{what:e,ask:{probe:{kind:"changes",arg:`${n} ${l}`,cwd:null}},base:c,shown:r===null?null:v(r),...a}}function zu(e){if(e.stdinKind)return;if(e.stdinFile)return e.stdinFile;let n=e.pipeFrom;if(!n)return;let t=n.argv.slice(1).filter(s=>!s.startsWith("-"));return n.name==="cat"&&t.length===1?t[0]:null}function De(e,n,t=[]){let s=[],r=new Map,o=!1;for(let i=0;i<e.length;i++){let a=e[i];if(o)s.push(a);else if(a==="--")o=!0;else if(a.startsWith("--")){let l=a.indexOf("=");r.set(l>0?a.slice(0,l):a,l>0?a.slice(l+1):t.includes(a)?e[++i]??"":"")}else if(a.startsWith("-")&&a.length>1)for(let l=1;l<a.length;l++){let c=a[l];if(n.includes(c)){r.set(`-${c}`,l+1<a.length?a.slice(l+1):e[++i]??"");break}r.set(`-${c}`,"")}else s.push(a)}return{pos:s,opt:r,dashdash:o}}var Fe=(e,n)=>n.some(t=>e.opt.has(t)),es=e=>e==="-"?"@{-1}":e;function Qo(e,n,t,s,r,o,i,a){if(!/^\d{1,2}$/.test(s))return[ve(n)];let l=`p${Number(s)}`,c=(u,d)=>ei(`${n} ${At.basename(v(u))}`,l,u,d,o,i,a);return(t.length>0?t:["-"]).flatMap(u=>{if(u!=="-")return[c(u,r)];let d=zu(e);return d===void 0?[]:d===null?[ve(n)]:[c(d,i)]})}function Mu(e,n,t,s){let r=e.argv,o=n,i=/\bGIT_(?:DIR|WORK_TREE|INDEX_FILE|COMMON_DIR)=/.test(e.text),a=1;for(;a<r.length;a++){let p=r[a];if(p==="-C")o=ts(r[++a]??"",o,t);else if(p==="-c"||p==="--namespace"||p==="--config-env")a++;else if(p==="--git-dir"||p==="--work-tree")i=!0,a++;else if(/^--(git-dir|work-tree)=/.test(p))i=!0;else if(!p.startsWith("-"))break}let l=r[a]??"",c=r.slice(a+1);if(c.includes("--help")||c.includes("-h"))return[];let u=(...p)=>["git",l,...p].map(v).join(" "),d=(()=>{switch(l){case"checkout":{let f=De(c,"bB",["--orphan","--conflict","--pathspec-from-file"]);if(f.pos.some($=>Jo.test($)))return[f.pos.length>1&&!Jo.test(f.pos[0])?me(u(...f.pos),"wt",f.pos[0],o):me(u(...f.pos),"wi","HEAD",o)];if(Fe(f,["-p","--patch","--pathspec-from-file"]))return[];let h=c.indexOf("--"),g=h>=0?c.slice(h+1):f.pos.slice(1);if(g.length>0&&(h<0||f.pos.length>g.length))return[me(u(...f.pos),"wt",f.pos[0],o,g)];if(f.dashdash)return[];let y=Fe(f,["-b","-B","--orphan"])||f.pos.length===1?f.pos[0]:void 0;return Fe(f,["-f","--force"])?[me(u("-f",...f.pos),"wt",y??"HEAD",o)]:y===void 0?[]:[me(u(y),"co",es(y),o)]}case"switch":{let f=De(c,"cC",["--create","--force-create","--orphan","--conflict"]);if(f.opt.has("--orphan"))return[ve(u("--orphan"))];let h=f.pos[0];return Fe(f,["-f","--force","--discard-changes"])?[me(u("-f",...f.pos),"wt",h??"HEAD",o)]:h===void 0?[]:[me(u(h),"co",es(h),o)]}case"restore":{let f=De(c,"s",["--source","--pathspec-from-file","--conflict"]);if(f.pos.length===0||Fe(f,["-S","--staged"])&&!Fe(f,["-W","--worktree"]))return[];let h=f.opt.get("-s")??f.opt.get("--source"),g=f.pos.some(y=>Jo.test(y))?[]:[...f.pos];return[h?me(u(...f.pos),"wt",h,o,g):me(u(...f.pos),"wi","HEAD",o,g)]}case"reset":{let f=De(c,"",["--pathspec-from-file"]),h=["--hard","--keep","--merge"].find(y=>f.opt.has(y)),g=f.pos[0]??"HEAD";return h===void 0||f.dashdash||f.pos.length>1?[]:[me(u(h,...f.pos),"wt",g,o)]}case"merge":{let f=De(c,"mFsX",["--message","--file","--strategy","--strategy-option","--into-name","--cleanup"]);return Fe(f,["--abort","--continue","--quit"])?[]:f.pos.length>0?f.pos.map(h=>me(u(h),"merge",es(h),o)):[me(u(),"merge","@{u}",o)]}case"rebase":{let f=De(c,"sXxC",["--onto","--exec","--strategy","--strategy-option","--empty","--whitespace"]);if(Fe(f,["--continue","--abort","--skip","--quit","--edit-todo","--show-current-patch"]))return[];let h=f.pos[0]??(f.opt.has("--root")?void 0:"@{u}"),g=f.pos[1]!==void 0?[me(u(...f.pos),"co",f.pos[1],o)]:[];for(let y of[f.opt.get("--onto"),h])y&&g.push(me(u(...f.pos),"co",es(y),o));return g}case"pull":{let f=De(c,"sXjo",["--strategy","--strategy-option","--depth","--deepen","--shallow-since","--shallow-exclude","--jobs","--upload-pack","--server-option","--negotiation-tip"]),[h,...g]=f.pos;return(h!==void 0&&g.length>0?g.map($=>`${h}/${$.replace(/^\+/,"").split(":")[0].replace(/^refs\/heads\//,"")}`):["@{u}"]).map($=>me(u(...f.pos),"pull",$,o))}case"cherry-pick":case"revert":{let f=De(c,"mX",["--mainline","--strategy","--strategy-option","--cleanup"]);return Fe(f,["--continue","--abort","--skip","--quit"])?[]:f.opt.has("--stdin")?[ve(u("--stdin"))]:f.pos.map(h=>h.includes("..")||h.startsWith("^")?ve(u(h)):me(u(h),"pick",es(h),o))}case"stash":{let[f="",...h]=c;if(f!=="pop"&&f!=="apply"&&f!=="branch")return[];let g=De(h,""),y=f==="branch"?g.pos[1]:g.pos[0],$=y===void 0?"stash@{0}":/^\d+$/.test(y)?`stash@{${y}}`:y,E=u(f,...g.pos);return f==="branch"?[me(E,"stash",$,o),me(E,"co",`${$}^1`,o)]:[me(E,"stash",$,o)]}case"apply":{let f=De(c,"pC",["--directory","--include","--exclude","--whitespace","--build-fake-ancestor"]);return Fe(f,["--check","--stat","--numstat","--summary"])&&!f.opt.has("--apply")||f.opt.has("--cached")&&!f.opt.has("--index")?[]:Qo(e,"git apply",f.pos,f.opt.get("-p")??"1",o,f.opt.get("--directory")??null,o,t)}case"am":{let f=De(c,"pC",["--directory","--include","--exclude","--whitespace","--patch-format","--resolvemsg","--quoted-cr","--empty"]);return Fe(f,["--continue","--skip","--abort","--quit","--resolved","-r","--show-current-patch","--retry"])?[]:Qo(e,"git am",f.pos,f.opt.get("-p")??"1",o,f.opt.get("--directory")??null,o,t)}}if(!s||!/^[a-z][\w-]*$/.test(l)||lk.test(l))return[];let p=s(l,o);return p===void 0||p===Ct?[]:p===null||/^\s*!|['"\\]/.test(p)?[ve(u())]:Mu({...e,argv:["git",...p.trim().split(/\s+/),...c]},o,t)})();return i?d.map(p=>ve(p.what)):d}function uk(e,n,t){let s=De(e.argv.slice(1),"BDFgiopVxYzdr",["--prefix","--ifdef","--fuzz","--get","--input","--output","--strip","--reject-file","--version-control","--debug","--basename-prefix","--suffix","--directory","--quoting-style","--reject-format","--read-only"]);if(Fe(s,["--dry-run","--check","-C"]))return[];let r=s.opt.get("-d")??s.opt.get("--directory")??null,o=r===null?kn(n)?n:null:ts(r,n,t),[i,a]=s.pos,c=s.opt.get("-o")??s.opt.get("--output")??i;if(c!==void 0){if(c==="-")return[];let d=ts(c,o,t);return[d===null?ve("patch"):{what:`patch ${At.basename(v(c))}`,ask:{files:[d]},base:null,shown:null}]}let u=s.opt.get("-i")??s.opt.get("--input")??a;return Qo(e,"patch",u===void 0?[]:[u],s.opt.get("-p")??s.opt.get("--strip")??"0",o,r,n,t)}function dk(e,n,t){let s=e.argv.slice(1),r,o=null,i="";for(let l=0;l<s.length;l++){let c=s[l];if(!c.startsWith("-")||c.length===1){r??=c;continue}for(let u=1;u<c.length;u++){let d=c[u];if(d==="d"||d==="P"){let p=u+1<c.length?c.slice(u+1):s[++l]??"";d==="d"&&(o=p);break}if(d==="x"){for(;l+1<s.length&&!s[l+1].startsWith("-");)l++;break}i+=d}}if(r===void 0||/[lvtZpcz]/.test(i))return[];if(/[*?[]/.test(v(r)))return[ve(`unzip ${v(r)}`)];let a=`unzip ${At.basename(v(r))}`;return(/\.zip$/i.test(r)?[r]:[r,`${r}.zip`]).map(l=>ei(a,"zip",l,n,o,n,t,{flat:i.includes("j")}))}var fk=["fCTXbgNKVIHFL","fCTXbsI"],pk=new Set(["--file","--directory","--exclude","--files-from","--exclude-from","--transform","--xform","--use-compress-program","--owner","--group","--mode","--mtime","--newer","--newer-mtime","--format","--strip-components","--to-command","--suffix","--occurrence","--sort","--include","--options","--uid","--gid","--passphrase"]);function hk(e,n,t){let s=e.argv.slice(1),r=[];for(let o of fk){let i={extract:!1,toStdout:!1,renames:!1,file:void 0,dest:null},a=(u,d)=>{u==="x"||u==="--extract"||u==="--get"?i.extract=!0:u==="O"||u==="--to-stdout"||u==="--to-command"?i.toStdout=!0:u==="f"||u==="--file"?i.file=d:u==="C"||u==="--directory"?i.dest=d:(u==="s"&&o.includes("s")||u==="--transform"||u==="--xform")&&(i.renames=!0)},l=0;if(s[0]&&/^[A-Za-z]+$/.test(s[0])){l=1;for(let u of s[0])a(u,o.includes(u)?s[l++]??"":"")}for(;l<s.length;l++){let u=s[l];if(u==="--")break;if(u.startsWith("--")){let d=u.indexOf("="),p=d>0?u.slice(0,d):u;a(p,d>0?u.slice(d+1):pk.has(p)?s[++l]??"":"")}else if(u.startsWith("-")&&u.length>1)for(let d=1;d<u.length;d++){let p=u[d];if(o.includes(p)){a(p,d+1<u.length?u.slice(d+1):s[++l]??"");break}a(p,"")}}if(!i.extract||i.toStdout)continue;if(i.renames){r.push(ve("tar -x"));continue}let c=i.file===void 0||i.file==="-"?zu(e):i.file;c!==void 0&&r.push(c===null?ve("tar -x"):ei(`tar -xf ${At.basename(v(c))}`,"tar",c,n,i.dest,n,t))}return r}function gk(e,n,t,s){switch(e.name){case"git":return Mu(e,n,t,s);case"gh":return/^(pr (checkout|co)|co)\b/.test(e.argv.slice(1,3).join(" "))?[ve("gh pr checkout")]:[];case"patch":return uk(e,n,t);case"unzip":return dk(e,n,t);case"tar":case"bsdtar":case"gtar":return hk(e,n,t)}return[]}function mk(e,n){for(let t of n){let s=t.replace(/\\/g,"/");if(s===""||s.endsWith("/"))continue;let r=e.flat?At.basename(s):s,i=[...r.startsWith("/")?[r]:[],e.base?At.join(e.base,r):At.normalize(r)].find(Iu);if(i===void 0)continue;let a=e.shown?At.join(e.shown,r):r,l=cr(Iu(a)?a:i,200);return{why:cr(`${e.what} brings in a change to ${l}`,300),target:l,sure:!0}}return null}function yk(e,n,t){let s=xe(n.home),r=typeof n.cwd=="string"&&n.cwd.startsWith("/")?xe(n.cwd):n.cwd,o=typeof n.project_dir=="string"&&n.project_dir.startsWith("/")?xe(n.project_dir):n.project_dir,i=n.session_facts??null,a=ut(e,{home:s,tmpdir:xe(n.tmpdir),cwd:r,projectDir:o,claudeConfigDir:n.claude_config_dir??null,knownFiles:i?.scripts??null,unreadableFiles:i?.unreadableScripts??null}),l=i?.probed,c=[],u=new Set,d=new Set(a.commands.flatMap(f=>f.name==="git"?f.argv.flatMap(h=>/^alias\.(.+)$/.exec(h)?.[1]??[]):[])),p=(f,h)=>{if(!kn(h))return null;let g={kind:"changes",arg:`al ${f}`,cwd:h},y=jn(g);if(!l||!(y in l))return void t.set(y,g);let $=l[y];return typeof $=="string"&&$!==ar?$:null};return a.commands.forEach((f,h)=>{if(f.via==="remote"||f.functionCall)return;let g=a.commands.slice(0,h).some($=>!["cd","pushd","export","set","true",":"].includes($.name)),y=f.name==="git"&&f.argv[1]==="stash"&&/^(pop|apply)$/.test(f.argv[2]??"")&&f.argv.length===3&&a.commands.slice(0,h).some($=>$.name==="git"&&$.argv[1]==="stash"&&!/^(pop|apply|drop|list|show|clear|branch)$/.test($.argv[2]??""));for(let $ of[...new Set([f.cwd,...f.cwdFallbacks])]){let E=f.name==="git"&&d.has(f.argv[1]??"")?[ve(`git ${v(f.argv[1])}`)]:gk(f,$,s,p);for(let _ of f.via==="xargs"?E.map(k=>ve(k.what)):E){let k,P=!1;if(_.ask===null)k=null;else if("files"in _.ask)k=_.ask.files;else{let A=jn(_.ask.probe);if(!l||!(A in l)){t.set(A,_.ask.probe);continue}let M=l[A];if(M===Ct&&(!g||y))continue;P=M===ar,k=typeof M=="string"&&!P&&M!==Ct?M.split(/[\0\n]/):null}let S=k===null?{why:cr(P?`couldn't check in time which files ${_.what} would change`:`can't tell which files ${_.what} would change`,300),target:cr(_.what,200),sure:!1}:mk(_,k);S&&!u.has(S.why)&&(u.add(S.why),c.push(S))}}}),c.sort((f,h)=>Number(h.sure)-Number(f.sure))}function bk(e,n){let{housekeeping:t,findings:s,...r}=e,o=e.action!=="claude.bash.unclassified"&&e.action!=="claude.tool.other",i=n[0],a=[...new Set([...o?[e.action]:[],...e.also])].filter($=>$!=="claude.agent.controls"),{environment:l,environment_said:c,repo_dir:u,repo_remote:d,repo_via:p,...f}=e.attributes,h={...l!==void 0?{environment:l,environment_said:c??null}:{},...p!==void 0?{repo_dir:u??null,repo_remote:d??null,repo_via:p}:{}},g=e.findings??(o?[{action:e.action,service:e.service,target:e.attributes.target,why:e.why,...h}]:[]),y=[...n.map($=>({action:"claude.agent.controls",service:null,target:$.target,why:$.why})),...g].slice(0,16);return{...r,action:"claude.agent.controls",service:null,attributes:{...f,target:i.target,branch:null,host:null,is_local:!0},why:i.why,also:a,...y.length>1?{findings:y}:{}}}function wk(e){let n=i=>typeof i=="string"&&i!==""?Ne(i):i??null,t=e.control_links?Object.fromEntries(Object.entries(e.control_links).map(([i,a])=>[Ne(i),Ne(a)])):e.control_links,s=e.session_facts?.repoRemotes,r=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:null,o=r?["file_path","notebook_path"].find(i=>typeof r[i]=="string"):void 0;return{...e,...r&&o?{tool_input:{...r,[o]:We(r[o])??r[o]}}:{},cwd:n(e.cwd),project_dir:n(e.project_dir),home:Ne(e.home),tmpdir:Ne(e.tmpdir),...e.claude_config_dir!==void 0?{claude_config_dir:n(e.claude_config_dir)}:{},...e.project_controls?{project_controls:e.project_controls.map(i=>({...i,path:Ne(i.path)}))}:{},...t!==void 0?{control_links:t}:{},...e.session_facts&&s?{session_facts:{...e.session_facts,repoRemotes:Object.fromEntries(Object.entries(s).map(([i,a])=>[Ne(i),a]))}}:{}}}function kk(e){let n=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:null;if(e.tool_name!=="PowerShell"||typeof n?.command!="string")return e;let t=Bt(n.command,{cwd:e.cwd!==null?Ye(e.cwd):null});return t.kind==="shell"?{...e,tool_name:"Bash",tool_input:{...n,command:t.text}}:e}function vk(e){let n=kk(H()?wk(e):e),t=n.tool_input&&typeof n.tool_input=="object"?n.tool_input:{},s=(n.tool_name==="Bash"||n.tool_name==="PowerShell")&&typeof t.command=="string"?t.command:null,r=n.on_disk==="collect"?Xo():n.on_disk?{real:n.on_disk,...Xo()}:null,o=n.tool_name==="Bash"?new Set:null,i=n.tool_name==="Bash"?new Map:null,a=gn({tool:n.tool_name,command:s,target:n.tool_name==="Bash"?null:ik(t),args:n.tool_input,cwd:n.cwd,git_branch:n.git_branch,project_dir:n.project_dir,session_id:n.session_id},{home:n.home,tmpdir:n.tmpdir,claudeConfigDir:n.claude_config_dir??null,onDisk:r,projectControls:n.project_controls??null,controlLinks:n.control_links??null,session:n.session_facts??null,wantScripts:o,wantProbes:i}),l=new Map,c=$=>ak.test($.replace(/['"\\]/g,"")),u=s!==null&&a.action!=="claude.agent.controls"&&(c(s)||Object.values(n.session_facts?.scripts??{}).some(c))?yk(s,n,l):[];u.length>0&&l.clear();let d=u.length>0?bk(a,u):a,p=r?.touched?{...d,touched:Fu(r)}:d,f=o&&o.size>0?{...p,scriptsWanted:[...o].slice(0,8)}:p,h=[...l.values(),...i?.values()??[]],g=h.length>0?{...f,probesWanted:h.slice(0,12)}:f;if(!n.want_makings)return g;let y={paths:[],launched:[]};try{y=la(n.tool_name,n.tool_input,n.cwd,{home:n.home,tmpdir:n.tmpdir,projectDir:n.project_dir})}catch{}return{...g,makings:y}}var $k=1e3,_k=new ok.Script("globalThis.__anvilReplayClassify()");function xk(e,n){let t=globalThis;t.__anvilReplayClassify=e;try{return _k.runInThisContext({timeout:n})}catch(s){if(s.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")return"timeout";throw s}finally{delete t.__anvilReplayClassify}}function Sk(e,n){return e.map(t=>{try{let s=Xo(),r=xk(()=>zl(t.command_judge!==void 0?{...t,command_local:t.command_judge}:t,{...n,...t.session_facts?{session:t.session_facts}:{},onDisk:s}),$k);if(r==="timeout")return{action:"claude.bash.unclassified",also:[],service:null,attributes:{target:null,branch:null,host:null,is_local:null,args_hash:null},parse:"limited",why:"too long to check in time"};let o=r,i=t.command_judge_cut===!0?"limited":o.parse,a=[s.touched?.full,s.touched?.parent,s.read,s.written,s.unknown].some(l=>(l?.size??0)>0);return{action:o.action,also:o.also,service:o.service,attributes:o.attributes,parse:i,why:o.why,...o.findings?{findings:o.findings}:{},...o.catastrophic?{catastrophic:!0}:{},...a?{touched:Fu(s)}:{}}}catch{return{action:"claude.bash.unclassified",also:[],service:null,attributes:{target:null,branch:null,host:null,is_local:null,args_hash:null},parse:"limited",why:"the classifier failed on it"}}})}if(!Du&&lr&&wn&&wn.anvilReplayPool===!0){let e=lr,n=wn.ctx;e.on("message",t=>{try{e.postMessage({id:t.id,ok:!0,results:Sk(t.calls,n)})}catch(s){e.postMessage({id:t.id,ok:!1,error:s instanceof Error?s.message:String(s)})}})}if(!Du&&lr&&wn&&wn.anvilClaudeHook===!0){let e=lr;try{e.postMessage({ok:!0,classification:vk(wn.request)})}catch(n){e.postMessage({ok:!1,error:n instanceof Error?n.message:String(n)})}}export{$k as REPLAY_CALL_LIMIT_MS,Mw as answerChanges,Sk as classifyLogged,vk as classifyRequest,Vw as heldNotice,nk as mootHolds,Rw as sessionChores,Gb as sessionContext,Vb as sessionLine,xw as startProblems};
|
|
85
|
+
`)}`)}catch{}e.files.some(l=>qu(l))||n.push(`no settings file this session reads puts Anvil's check in front of tool calls, so they are not checked: run ${Se(e.cli)} on`);let r=Qn(wn(e.anvilDir,"install.json")),o;try{o=lt(wn(e.anvilDir,"bin","claude-hook.js"),4*1024*1024)?.toString().split(`
|
|
86
|
+
`,1)[0]}catch{}let a=Qn(wn(e.anvilDir,"bin","files.json")),i=a?.v===1&&a.source&&typeof a.source=="object"?a.source:null;for(let l of Array.isArray(r?.package_dirs)?r.package_dirs:[])try{let c=typeof l=="string"?lt(wn(l,"dist","claude-hook.js"),4194304):null,u=Qn(wn(l,"package.json"))?.version,f=typeof u=="string"&&typeof r?.hook_version=="string"&&u.localeCompare(r.hook_version,void 0,{numeric:!0})<0,p=h=>{let g=lt(wn(l,"dist",h),67108864);return g?Gw("sha256").update(g).digest("hex"):void 0},d=i?Yw.some(h=>p(h)!==i[h]):!!o&&Uu(c?.toString()??"")!==o;if(c&&!f&&d){n.push(`its hook is older than the ${typeof u=="string"?`${u} `:""}update: run ${Se(e.cli)} on`);break}}catch{}return n}import{createHash as Qw}from"crypto";import{readdirSync as ek,readFileSync as Hu,renameSync as tk,statSync as dr,unlinkSync as nk}from"fs";import{join as Ct}from"path";function sk(e,t){rk(ur(e),t)}var Bt=1440*60*1e3;function rk(e,t){let n=(s,r)=>{let o=[];try{o=ek(s)}catch{return}for(let a of o.slice(0,5e3))try{let i=dr(Ct(s,a));r(a,i.mtimeMs)||nk(Ct(s,a))}catch{}};n(e.state,(s,r)=>!(s.startsWith("note-")||s.startsWith("problem-")||s.startsWith("helpers-said-"))||t-r<Bt),n(Ct(e.state,"covered"),(s,r)=>t-r<Bt),n(Ct(e.state,"pending"),(s,r)=>t-r<Bt),n(Ct(e.state,"sessions"),(s,r)=>t-r<7*Bt),n(e.approvals,(s,r)=>t-r<Bt),n(e.counts,(s,r)=>t-r<60*Bt);try{if(Ke(e.decisions,Number.MAX_SAFE_INTEGER)===!0){let s=dr(e.decisions).size;s>5*1024*1024&&(s>ok||ak(e,t))&&tk(e.decisions,`${e.decisions}.1`)}}catch{}}var ok=64*1024*1024,ik=14*Bt;function ak(e,t=Date.now()){if(Ke(`${e.decisions}.1`,Number.MAX_SAFE_INTEGER)===null)return!0;let n=null;try{n=JSON.parse(Hu(Ct(e.state,"sync-active.json"),"utf8"))}catch{return!0}if(typeof n?.id!="string")return!0;let s=i=>{try{return t-dr(i).mtimeMs>ik}catch{return!0}},r=Ct(e.state,"sync",`${Qw("sha256").update(n.id).digest("hex").slice(0,16)}.json`),o=null;try{o=JSON.parse(Hu(r,"utf8"))}catch{return s(Ct(e.state,"sync-active.json"))}let a=null;try{a=dr(e.decisions).ino}catch{a=null}return a!==null&&o?.ino===a?!0:s(r)}import{spawnSync as lk}from"child_process";import{existsSync as ck,statSync as uk}from"fs";import{join as dk,resolve as fk}from"path";var pk=4*1024*1024;function Bu(e){try{let t=lt(e,pk);return t===null?"missing":t.toString("utf8")}catch{return null}}function oi(e,t,n){let s=lk(e,t,{cwd:n?Gt(n):void 0,encoding:"utf8",timeout:400,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_OPTIONAL_LOCKS:"0"},windowsHide:!0});if(s.error||s.signal)throw s;return s.status===0&&typeof s.stdout=="string"?s.stdout:null}var fr="not in time",At="not there",Vu=["--",...[".claude",".claude/**",".anvil",".anvil/**",".mcp.json"].map(e=>`:(top,glob,icase)**/${e}`)];function hk(e,t){let n=[];for(let s of e.matchAll(/^(?:\+\+\+|---|\*\*\*|Index:|rename to|copy to) ([^\t\n]+)/gm)){let r=s[1].replace(/^"|"$/g,"").trim();r!=="/dev/null"&&n.push(r.split("/").slice(t).join("/"))}for(let s of e.matchAll(/^diff --git a\/(\S+) b\/(\S+)/gm))n.push(s[1],s[2]);return n.join(`
|
|
87
|
+
`)}function gk(e){if(e.kind!=="changes")return null;let t=e.arg??"";try{let n=/^(?:(co|wt|wi|merge|pull|pick|stash|al)\t((?!-)[^\0-\x20:?*[\\\x7f]+)((?:\t(?!-)[^\0-\x1f]+)*)|(zip|tar|p\d\d?)\t(\/[^\0-\x1f]*))$/.exec(t);if(!n)return null;if(n[4]){let c=n[4],u=Gt(n[5]),f=uk(u,{throwIfNoEntry:!1});if(!f)return At;if(!f.isFile())return null;if(c==="zip")return oi("unzip",["-Z1",u],null);if(c==="tar")return oi("tar",["-tf",u],null);let p=Bu(u);return typeof p=="string"&&p!=="missing"?hk(p,Number(c.slice(1))):p==="missing"?At:null}let s=n[1],r=n[2],o=(...c)=>oi("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null",...c],e.cwd);if(s==="al")return o("config","--get",`alias.${r}`)?.trim()??At;let a=(o("rev-parse","--verify","--quiet",`${r}^0`)||(s==="co"?o("for-each-ref","--count=1","--format=%(objectname)",`refs/remotes/*/${r}`):""))?.trim();if(!a)return s==="pull"?null:s==="co"&&ck(fk(Gt(e.cwd??"/"),r))?"":At;let i=["--name-only","-z","--no-renames","--no-ext-diff","--no-relative"];if(s==="stash")return o("stash","show","-u",...i,r);if(s==="pick")return o("diff-tree","-r","-m","--root","--no-commit-id",...i,a,...Vu);if(s[0]==="w"){let c=o("rev-parse","--show-toplevel")?.trim()??"";if([".gitattributes",".claude/.gitattributes"].some(u=>{let f=Bu(dk(c,u));return f===null||f!=="missing"&&/filter\s*=/.test(f)}))return null}let l=n[3]?["--",...n[3].slice(1).split(" ").map(c=>`:(literal)${c}`)]:Vu;return o("diff",...i,...s==="wi"?[]:[s==="wt"?a:`HEAD..${s==="co"?"":"."}${a}`],...l)}catch(n){if(n.signal||n.error?.code==="ETIMEDOUT")return fr}return null}import{spawn as mk}from"child_process";import{statSync as yk}from"fs";import{join as Zu}from"path";var bk=6e4;function wk(e,t,n){mk("/usr/bin/osascript",["-e",`on run a
|
|
88
|
+
display notification (item 3 of a) with title (item 1 of a) subtitle (item 2 of a)
|
|
89
|
+
end run`,e,t,n],{detached:!0,stdio:"ignore"}).unref()}function kk(e,t=wk){try{let n=e.env;if((e.platform??process.platform)!=="darwin"||!n.CLAUDE_CODE_ENTRYPOINT||n.CI||n.VITEST||n.ANVIL_NO_NOTIFY||!e.transcript||!yk(e.transcript).isFile())return;let s=Zu(e.anvilDir,"state");ti(s);let r=Zu(s,`notice-${(e.session??"none").replace(/[^\w-]/g,"_").slice(0,80)}`),o=Number(Fu(r,64).trim());if(Number.isFinite(o)&&e.now-o<bk)return;zu(r,String(e.now)),t(`${cr("Anvil")} needs your OK`,`Held: ${e.why}`,`Allow once: run ${Se(e.cli)} allow in a terminal.`)}catch{}}import{createHash as _S,randomBytes as SS}from"crypto";import{readdirSync as Ak,renameSync as AS,unlinkSync as Ek}from"fs";import{join as Xu}from"path";import{createHmac as vk,randomBytes as eS,timingSafeEqual as $k}from"crypto";import{closeSync as nS,existsSync as sS,fsyncSync as rS,linkSync as oS,mkdirSync as iS,openSync as aS,readdirSync as lS,readFileSync as Gu,unlinkSync as cS,writeSync as uS}from"fs";import{basename as fS,dirname as pS,join as xk}from"path";var es="_seal";function _k(e){return xk(e.dir,"seal.key")}function Ku(e){let t=_k(e);if(Ke(t,1024)!==!0)return null;try{let n=Gu(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function ai(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>ai(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(s=>!(t===0&&s===es)&&e[s]!==void 0).sort().map(s=>`${JSON.stringify(s)}:${ai(e[s],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function Sk(e,t){return vk("sha256",e).update(ai(t)).digest("hex")}function ii(e){if(!(es in e))return e;let t={...e};return delete t[es],t}function Ck(e,t){let n=t[es];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let s;try{s=Sk(e,t)}catch{return!1}return $k(Buffer.from(n,"hex"),Buffer.from(s,"hex"))}function Yu(e,t,n=8*1024*1024){let s=Ke(e,n);if(s===null)return{status:"missing"};if(s===!1)return{status:"unreadable"};let r;try{r=JSON.parse(Gu(e,"utf8"))}catch{return{status:"unreadable"}}return!r||typeof r!="object"||Array.isArray(r)?{status:"unreadable"}:t?es in r?Ck(t,r)?{status:"ok",value:ii(r)}:{status:"changed",value:ii(r)}:{status:"unsealed",value:r}:{status:"unkeyed",value:ii(r)}}var jS=600*1e3,PS=1440*60*1e3;function Ju(e){return Xu(e.state,"pending")}function Rk(e,t,n,s,r,o,a){let i=0;for(let{hold:l,file:c}of Pk(e,t,o))if(!(c===a||(l.session??null)!==(n??null)||(l.project??null)!==(s??null)||l.stops.length===0)&&l.stops.every(u=>r.some(f=>jk(f,u))))try{Ek(c),i++}catch{}return i}function Ok(e){let t=ur(e.anvilDir);Rk(t,Ku(t),e.session,e.project,e.stops,e.now)}function jk(e,t){return e.kind===t.kind&&(e.target??null)===(t.target??null)}function Pk(e,t,n){let s=[];try{s=Ak(Ju(e)).filter(o=>o.endsWith(".json")).slice(0,2e3)}catch{return[]}let r=[];for(let o of s){let a=Xu(Ju(e),o),i=Yu(a,t,64*1024);i.status!=="ok"||i.value.v!==2||!Array.isArray(i.value.stops)||!(Date.parse(i.value.expires_at)>=n)||r.push({hold:i.value,file:a})}return r.sort((o,a)=>Date.parse(a.hold.created_at)-Date.parse(o.hold.created_at))}function ci(){return{touched:{full:new Set,parent:new Set},read:new Set,written:new Set,unknown:new Set}}function td(e){return{full:[...e.touched?.full??[]],parent:[...e.touched?.parent??[]],read:[...e.read??[]],written:[...e.written??[]],unknown:[...e.unknown??[]]}}function Nk(e){if(!e||typeof e!="object")return null;let t=e;for(let n of["file_path","notebook_path","path"])if(typeof t[n]=="string")return t[n];return null}var Lk=/(?:^|[^\w.-])(?:git|gh|patch|tar|bsdtar|gtar|unzip)(?![\w.-])/,Tk=/^(add|annotate|archive|bisect|blame|branch|bundle|cat-file|check-[\w-]+|clean|clone|commit|config|count-objects|describe|diff(-\w+)?|fetch|filter-branch|for-each-ref|format-patch|fsck|gc|grep|hash-object|help|init|log|ls-\w+|maintenance|merge-\w+|mk\w+|mv|name-rev|notes|prune|push|range-diff|reflog|remote|repack|replace|rerere|rev-\w+|rm|shortlog|show(-\w+)?|sparse-checkout|status|submodule|symbolic-ref|tag|update-[\w-]+|var|verify-\w+|version|whatchanged|worktree|\w+-tree)$/,Ik=/^(?!-)[^\0-\x20:?*[\\\x7f]+$/,li=/^(?:\.\/?|\*|:\/|:\(top\))$/;function Qu(e){let t=e.toLowerCase().split("/");return t[t.length-1]===".mcp.json"||t.some(n=>n===".claude"||n===".anvil")}var vn=e=>typeof e=="string"&&e.startsWith("/")&&!S(e),ve=e=>({what:e,ask:null,base:null,shown:null}),hr=(e,t)=>{let n=e.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g,"");return n.length>t?`${n.slice(0,t-3)}\u2026`:n};function ns(e,t,n){if(e===""||S(e)||!e.startsWith("/")&&!e.startsWith("~")&&!vn(t))return null;let s=M(e,t,{home:n});return vn(s)?s:null}function me(e,t,n,s,r=[]){return!vn(s)||S(n)||!Ik.test(n)||r.some(o=>S(o)||!/^(?!-)[^\0-\x1f]+$/.test(o))?ve(e):{what:e,ask:{probe:{kind:"changes",arg:[`${t} ${n}`,...r].join(" "),cwd:s}},base:s,shown:null}}function di(e,t,n,s,r,o,a,i={}){let l=ns(n,s,a),c=r===null?vn(o)?o:null:ns(r,o,a);return l===null||c===null||/[\u0000-\u001f]/.test(l)?ve(e):{what:e,ask:{probe:{kind:"changes",arg:`${t} ${l}`,cwd:null}},base:c,shown:r===null?null:k(r),...i}}function nd(e){if(e.stdinKind)return;if(e.stdinFile)return e.stdinFile;let t=e.pipeFrom;if(!t)return;let n=t.argv.slice(1).filter(s=>!s.startsWith("-"));return t.name==="cat"&&n.length===1?n[0]:null}function De(e,t,n=[]){let s=[],r=new Map,o=!1;for(let a=0;a<e.length;a++){let i=e[a];if(o)s.push(i);else if(i==="--")o=!0;else if(i.startsWith("--")){let l=i.indexOf("=");r.set(l>0?i.slice(0,l):i,l>0?i.slice(l+1):n.includes(i)?e[++a]??"":"")}else if(i.startsWith("-")&&i.length>1)for(let l=1;l<i.length;l++){let c=i[l];if(t.includes(c)){r.set(`-${c}`,l+1<i.length?i.slice(l+1):e[++a]??"");break}r.set(`-${c}`,"")}else s.push(i)}return{pos:s,opt:r,dashdash:o}}var Fe=(e,t)=>t.some(n=>e.opt.has(n)),ts=e=>e==="-"?"@{-1}":e;function ui(e,t,n,s,r,o,a,i){if(!/^\d{1,2}$/.test(s))return[ve(t)];let l=`p${Number(s)}`,c=(u,f)=>di(`${t} ${Et.basename(k(u))}`,l,u,f,o,a,i);return(n.length>0?n:["-"]).flatMap(u=>{if(u!=="-")return[c(u,r)];let f=nd(e);return f===void 0?[]:f===null?[ve(t)]:[c(f,a)]})}function sd(e,t,n,s){let r=e.argv,o=t,a=/\bGIT_(?:DIR|WORK_TREE|INDEX_FILE|COMMON_DIR)=/.test(e.text),i=1;for(;i<r.length;i++){let p=r[i];if(p==="-C")o=ns(r[++i]??"",o,n);else if(p==="-c"||p==="--namespace"||p==="--config-env")i++;else if(p==="--git-dir"||p==="--work-tree")a=!0,i++;else if(/^--(git-dir|work-tree)=/.test(p))a=!0;else if(!p.startsWith("-"))break}let l=r[i]??"",c=r.slice(i+1);if(c.includes("--help")||c.includes("-h"))return[];let u=(...p)=>["git",l,...p].map(k).join(" "),f=(()=>{switch(l){case"checkout":{let d=De(c,"bB",["--orphan","--conflict","--pathspec-from-file"]);if(d.pos.some($=>li.test($)))return[d.pos.length>1&&!li.test(d.pos[0])?me(u(...d.pos),"wt",d.pos[0],o):me(u(...d.pos),"wi","HEAD",o)];if(Fe(d,["-p","--patch","--pathspec-from-file"]))return[];let h=c.indexOf("--"),g=h>=0?c.slice(h+1):d.pos.slice(1);if(g.length>0&&(h<0||d.pos.length>g.length))return[me(u(...d.pos),"wt",d.pos[0],o,g)];if(d.dashdash)return[];let y=Fe(d,["-b","-B","--orphan"])||d.pos.length===1?d.pos[0]:void 0;return Fe(d,["-f","--force"])?[me(u("-f",...d.pos),"wt",y??"HEAD",o)]:y===void 0?[]:[me(u(y),"co",ts(y),o)]}case"switch":{let d=De(c,"cC",["--create","--force-create","--orphan","--conflict"]);if(d.opt.has("--orphan"))return[ve(u("--orphan"))];let h=d.pos[0];return Fe(d,["-f","--force","--discard-changes"])?[me(u("-f",...d.pos),"wt",h??"HEAD",o)]:h===void 0?[]:[me(u(h),"co",ts(h),o)]}case"restore":{let d=De(c,"s",["--source","--pathspec-from-file","--conflict"]);if(d.pos.length===0||Fe(d,["-S","--staged"])&&!Fe(d,["-W","--worktree"]))return[];let h=d.opt.get("-s")??d.opt.get("--source"),g=d.pos.some(y=>li.test(y))?[]:[...d.pos];return[h?me(u(...d.pos),"wt",h,o,g):me(u(...d.pos),"wi","HEAD",o,g)]}case"reset":{let d=De(c,"",["--pathspec-from-file"]),h=["--hard","--keep","--merge"].find(y=>d.opt.has(y)),g=d.pos[0]??"HEAD";return h===void 0||d.dashdash||d.pos.length>1?[]:[me(u(h,...d.pos),"wt",g,o)]}case"merge":{let d=De(c,"mFsX",["--message","--file","--strategy","--strategy-option","--into-name","--cleanup"]);return Fe(d,["--abort","--continue","--quit"])?[]:d.pos.length>0?d.pos.map(h=>me(u(h),"merge",ts(h),o)):[me(u(),"merge","@{u}",o)]}case"rebase":{let d=De(c,"sXxC",["--onto","--exec","--strategy","--strategy-option","--empty","--whitespace"]);if(Fe(d,["--continue","--abort","--skip","--quit","--edit-todo","--show-current-patch"]))return[];let h=d.pos[0]??(d.opt.has("--root")?void 0:"@{u}"),g=d.pos[1]!==void 0?[me(u(...d.pos),"co",d.pos[1],o)]:[];for(let y of[d.opt.get("--onto"),h])y&&g.push(me(u(...d.pos),"co",ts(y),o));return g}case"pull":{let d=De(c,"sXjo",["--strategy","--strategy-option","--depth","--deepen","--shallow-since","--shallow-exclude","--jobs","--upload-pack","--server-option","--negotiation-tip"]),[h,...g]=d.pos;return(h!==void 0&&g.length>0?g.map($=>`${h}/${$.replace(/^\+/,"").split(":")[0].replace(/^refs\/heads\//,"")}`):["@{u}"]).map($=>me(u(...d.pos),"pull",$,o))}case"cherry-pick":case"revert":{let d=De(c,"mX",["--mainline","--strategy","--strategy-option","--cleanup"]);return Fe(d,["--continue","--abort","--skip","--quit"])?[]:d.opt.has("--stdin")?[ve(u("--stdin"))]:d.pos.map(h=>h.includes("..")||h.startsWith("^")?ve(u(h)):me(u(h),"pick",ts(h),o))}case"stash":{let[d="",...h]=c;if(d!=="pop"&&d!=="apply"&&d!=="branch")return[];let g=De(h,""),y=d==="branch"?g.pos[1]:g.pos[0],$=y===void 0?"stash@{0}":/^\d+$/.test(y)?`stash@{${y}}`:y,E=u(d,...g.pos);return d==="branch"?[me(E,"stash",$,o),me(E,"co",`${$}^1`,o)]:[me(E,"stash",$,o)]}case"apply":{let d=De(c,"pC",["--directory","--include","--exclude","--whitespace","--build-fake-ancestor"]);return Fe(d,["--check","--stat","--numstat","--summary"])&&!d.opt.has("--apply")||d.opt.has("--cached")&&!d.opt.has("--index")?[]:ui(e,"git apply",d.pos,d.opt.get("-p")??"1",o,d.opt.get("--directory")??null,o,n)}case"am":{let d=De(c,"pC",["--directory","--include","--exclude","--whitespace","--patch-format","--resolvemsg","--quoted-cr","--empty"]);return Fe(d,["--continue","--skip","--abort","--quit","--resolved","-r","--show-current-patch","--retry"])?[]:ui(e,"git am",d.pos,d.opt.get("-p")??"1",o,d.opt.get("--directory")??null,o,n)}}if(!s||!/^[a-z][\w-]*$/.test(l)||Tk.test(l))return[];let p=s(l,o);return p===void 0||p===At?[]:p===null||/^\s*!|['"\\]/.test(p)?[ve(u())]:sd({...e,argv:["git",...p.trim().split(/\s+/),...c]},o,n)})();return a?f.map(p=>ve(p.what)):f}function Dk(e,t,n){let s=De(e.argv.slice(1),"BDFgiopVxYzdr",["--prefix","--ifdef","--fuzz","--get","--input","--output","--strip","--reject-file","--version-control","--debug","--basename-prefix","--suffix","--directory","--quoting-style","--reject-format","--read-only"]);if(Fe(s,["--dry-run","--check","-C"]))return[];let r=s.opt.get("-d")??s.opt.get("--directory")??null,o=r===null?vn(t)?t:null:ns(r,t,n),[a,i]=s.pos,c=s.opt.get("-o")??s.opt.get("--output")??a;if(c!==void 0){if(c==="-")return[];let f=ns(c,o,n);return[f===null?ve("patch"):{what:`patch ${Et.basename(k(c))}`,ask:{files:[f]},base:null,shown:null}]}let u=s.opt.get("-i")??s.opt.get("--input")??i;return ui(e,"patch",u===void 0?[]:[u],s.opt.get("-p")??s.opt.get("--strip")??"0",o,r,t,n)}function Fk(e,t,n){let s=e.argv.slice(1),r,o=null,a="";for(let l=0;l<s.length;l++){let c=s[l];if(!c.startsWith("-")||c.length===1){r??=c;continue}for(let u=1;u<c.length;u++){let f=c[u];if(f==="d"||f==="P"){let p=u+1<c.length?c.slice(u+1):s[++l]??"";f==="d"&&(o=p);break}if(f==="x"){for(;l+1<s.length&&!s[l+1].startsWith("-");)l++;break}a+=f}}if(r===void 0||/[lvtZpcz]/.test(a))return[];if(/[*?[]/.test(k(r)))return[ve(`unzip ${k(r)}`)];let i=`unzip ${Et.basename(k(r))}`;return(/\.zip$/i.test(r)?[r]:[r,`${r}.zip`]).map(l=>di(i,"zip",l,t,o,t,n,{flat:a.includes("j")}))}var zk=["fCTXbgNKVIHFL","fCTXbsI"],Mk=new Set(["--file","--directory","--exclude","--files-from","--exclude-from","--transform","--xform","--use-compress-program","--owner","--group","--mode","--mtime","--newer","--newer-mtime","--format","--strip-components","--to-command","--suffix","--occurrence","--sort","--include","--options","--uid","--gid","--passphrase"]);function Uk(e,t,n){let s=e.argv.slice(1),r=[];for(let o of zk){let a={extract:!1,toStdout:!1,renames:!1,file:void 0,dest:null},i=(u,f)=>{u==="x"||u==="--extract"||u==="--get"?a.extract=!0:u==="O"||u==="--to-stdout"||u==="--to-command"?a.toStdout=!0:u==="f"||u==="--file"?a.file=f:u==="C"||u==="--directory"?a.dest=f:(u==="s"&&o.includes("s")||u==="--transform"||u==="--xform")&&(a.renames=!0)},l=0;if(s[0]&&/^[A-Za-z]+$/.test(s[0])){l=1;for(let u of s[0])i(u,o.includes(u)?s[l++]??"":"")}for(;l<s.length;l++){let u=s[l];if(u==="--")break;if(u.startsWith("--")){let f=u.indexOf("="),p=f>0?u.slice(0,f):u;i(p,f>0?u.slice(f+1):Mk.has(p)?s[++l]??"":"")}else if(u.startsWith("-")&&u.length>1)for(let f=1;f<u.length;f++){let p=u[f];if(o.includes(p)){i(p,f+1<u.length?u.slice(f+1):s[++l]??"");break}i(p,"")}}if(!a.extract||a.toStdout)continue;if(a.renames){r.push(ve("tar -x"));continue}let c=a.file===void 0||a.file==="-"?nd(e):a.file;c!==void 0&&r.push(c===null?ve("tar -x"):di(`tar -xf ${Et.basename(k(c))}`,"tar",c,t,a.dest,t,n))}return r}function qk(e,t,n,s){switch(e.name){case"git":return sd(e,t,n,s);case"gh":return/^(pr (checkout|co)|co)\b/.test(e.argv.slice(1,3).join(" "))?[ve("gh pr checkout")]:[];case"patch":return Dk(e,t,n);case"unzip":return Fk(e,t,n);case"tar":case"bsdtar":case"gtar":return Uk(e,t,n)}return[]}function Hk(e,t){for(let n of t){let s=n.replace(/\\/g,"/");if(s===""||s.endsWith("/"))continue;let r=e.flat?Et.basename(s):s,a=[...r.startsWith("/")?[r]:[],e.base?Et.join(e.base,r):Et.normalize(r)].find(Qu);if(a===void 0)continue;let i=e.shown?Et.join(e.shown,r):r,l=hr(Qu(i)?i:a,200);return{why:hr(`${e.what} brings in a change to ${l}`,300),target:l,sure:!0}}return null}function Bk(e,t,n){let s=_e(t.home),r=typeof t.cwd=="string"&&t.cwd.startsWith("/")?_e(t.cwd):t.cwd,o=typeof t.project_dir=="string"&&t.project_dir.startsWith("/")?_e(t.project_dir):t.project_dir,a=t.session_facts??null,i=dt(e,{home:s,tmpdir:_e(t.tmpdir),cwd:r,projectDir:o,claudeConfigDir:t.claude_config_dir??null,knownFiles:a?.scripts??null,unreadableFiles:a?.unreadableScripts??null}),l=a?.probed,c=[],u=new Set,f=new Set(i.commands.flatMap(d=>d.name==="git"?d.argv.flatMap(h=>/^alias\.(.+)$/.exec(h)?.[1]??[]):[])),p=(d,h)=>{if(!vn(h))return null;let g={kind:"changes",arg:`al ${d}`,cwd:h},y=Wn(g);if(!l||!(y in l))return void n.set(y,g);let $=l[y];return typeof $=="string"&&$!==fr?$:null};return i.commands.forEach((d,h)=>{if(d.via==="remote"||d.functionCall)return;let g=i.commands.slice(0,h).some($=>!["cd","pushd","export","set","true",":"].includes($.name)),y=d.name==="git"&&d.argv[1]==="stash"&&/^(pop|apply)$/.test(d.argv[2]??"")&&d.argv.length===3&&i.commands.slice(0,h).some($=>$.name==="git"&&$.argv[1]==="stash"&&!/^(pop|apply|drop|list|show|clear|branch)$/.test($.argv[2]??""));for(let $ of[...new Set([d.cwd,...d.cwdFallbacks])]){let E=d.name==="git"&&f.has(d.argv[1]??"")?[ve(`git ${k(d.argv[1])}`)]:qk(d,$,s,p);for(let x of d.via==="xargs"?E.map(b=>ve(b.what)):E){let b,j=!1;if(x.ask===null)b=null;else if("files"in x.ask)b=x.ask.files;else{let A=Wn(x.ask.probe);if(!l||!(A in l)){n.set(A,x.ask.probe);continue}let U=l[A];if(U===At&&(!g||y))continue;j=U===fr,b=typeof U=="string"&&!j&&U!==At?U.split(/[\0\n]/):null}let C=b===null?{why:hr(j?`couldn't check in time which files ${x.what} would change`:`can't tell which files ${x.what} would change`,300),target:hr(x.what,200),sure:!1}:Hk(x,b);C&&!u.has(C.why)&&(u.add(C.why),c.push(C))}}}),c.sort((d,h)=>Number(h.sure)-Number(d.sure))}function Vk(e,t){let{housekeeping:n,findings:s,...r}=e,o=e.action!=="claude.bash.unclassified"&&e.action!=="claude.tool.other",a=t[0],i=[...new Set([...o?[e.action]:[],...e.also])].filter($=>$!=="claude.agent.controls"),{environment:l,environment_said:c,repo_dir:u,repo_remote:f,repo_via:p,...d}=e.attributes,h={...l!==void 0?{environment:l,environment_said:c??null}:{},...p!==void 0?{repo_dir:u??null,repo_remote:f??null,repo_via:p}:{}},g=e.findings??(o?[{action:e.action,service:e.service,target:e.attributes.target,why:e.why,...h}]:[]),y=[...t.map($=>({action:"claude.agent.controls",service:null,target:$.target,why:$.why})),...g].slice(0,16);return{...r,action:"claude.agent.controls",service:null,attributes:{...d,target:a.target,branch:null,host:null,is_local:!0},why:a.why,also:i,...y.length>1?{findings:y}:{}}}function Zk(e){let t=a=>typeof a=="string"&&a!==""?Ne(a):a??null,n=e.control_links?Object.fromEntries(Object.entries(e.control_links).map(([a,i])=>[Ne(a),Ne(i)])):e.control_links,s=e.session_facts?.repoRemotes,r=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:null,o=r?["file_path","notebook_path"].find(a=>typeof r[a]=="string"):void 0;return{...e,...r&&o?{tool_input:{...r,[o]:We(r[o])??r[o]}}:{},cwd:t(e.cwd),project_dir:t(e.project_dir),home:Ne(e.home),tmpdir:Ne(e.tmpdir),...e.claude_config_dir!==void 0?{claude_config_dir:t(e.claude_config_dir)}:{},...e.project_controls?{project_controls:e.project_controls.map(a=>({...a,path:Ne(a.path)}))}:{},...n!==void 0?{control_links:n}:{},...e.session_facts&&s?{session_facts:{...e.session_facts,repoRemotes:Object.fromEntries(Object.entries(s).map(([a,i])=>[Ne(a),i]))}}:{}}}function Gk(e){let t=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:null;if(e.tool_name!=="PowerShell"||typeof t?.command!="string")return e;let n=Vt(t.command,{cwd:e.cwd!==null?Je(e.cwd):null});return n.kind==="shell"?{...e,tool_name:"Bash",tool_input:{...t,command:n.text}}:e}function Kk(e){let t=Gk(V()?Zk(e):e),n=t.tool_input&&typeof t.tool_input=="object"?t.tool_input:{},s=(t.tool_name==="Bash"||t.tool_name==="PowerShell")&&typeof n.command=="string"?n.command:null,r=t.on_disk==="collect"?ci():t.on_disk?{real:t.on_disk,...ci()}:null,o=t.tool_name==="Bash"?new Set:null,a=t.tool_name==="Bash"?new Map:null,i=mn({tool:t.tool_name,command:s,target:t.tool_name==="Bash"?null:Nk(n),args:t.tool_input,cwd:t.cwd,git_branch:t.git_branch,project_dir:t.project_dir,session_id:t.session_id},{home:t.home,tmpdir:t.tmpdir,claudeConfigDir:t.claude_config_dir??null,onDisk:r,projectControls:t.project_controls??null,controlLinks:t.control_links??null,session:t.session_facts??null,wantScripts:o,wantProbes:a}),l=new Map,c=$=>Lk.test($.replace(/['"\\]/g,"")),u=s!==null&&i.action!=="claude.agent.controls"&&(c(s)||Object.values(t.session_facts?.scripts??{}).some(c))?Bk(s,t,l):[];u.length>0&&l.clear();let f=u.length>0?Vk(i,u):i,p=r?.touched?{...f,touched:td(r)}:f,d=o&&o.size>0?{...p,scriptsWanted:[...o].slice(0,8)}:p,h=[...l.values(),...a?.values()??[]],g=h.length>0?{...d,probesWanted:h.slice(0,12)}:d;if(!t.want_makings)return g;let y={paths:[],launched:[]};try{y=ka(t.tool_name,t.tool_input,t.cwd,{home:t.home,tmpdir:t.tmpdir,projectDir:t.project_dir})}catch{}return{...g,makings:y}}var Yk=1e3,Jk=new Wk.Script("globalThis.__anvilReplayClassify()");function Xk(e,t){let n=globalThis;n.__anvilReplayClassify=e;try{return Jk.runInThisContext({timeout:t})}catch(s){if(s.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")return"timeout";throw s}finally{delete n.__anvilReplayClassify}}function Qk(e,t){return e.map(n=>{try{let s=ci(),r=Xk(()=>Jl(n.command_judge!==void 0?{...n,command_local:n.command_judge}:n,{...t,...n.session_facts?{session:n.session_facts}:{},onDisk:s}),Yk);if(r==="timeout")return{action:"claude.bash.unclassified",also:[],service:null,attributes:{target:null,branch:null,host:null,is_local:null,args_hash:null},parse:"limited",why:"too long to check in time"};let o=r,a=n.command_judge_cut===!0?"limited":o.parse,i=[s.touched?.full,s.touched?.parent,s.read,s.written,s.unknown].some(l=>(l?.size??0)>0);return{action:o.action,also:o.also,service:o.service,attributes:o.attributes,parse:a,why:o.why,...o.findings?{findings:o.findings}:{},...o.catastrophic?{catastrophic:!0}:{},...i?{touched:td(s)}:{}}}catch{return{action:"claude.bash.unclassified",also:[],service:null,attributes:{target:null,branch:null,host:null,is_local:null,args_hash:null},parse:"limited",why:"the classifier failed on it"}}})}if(!ed&&pr&&kn&&kn.anvilReplayPool===!0){let e=pr,t=kn.ctx;e.on("message",n=>{try{e.postMessage({id:n.id,ok:!0,results:Qk(n.calls,t)})}catch(s){e.postMessage({id:n.id,ok:!1,error:s instanceof Error?s.message:String(s)})}})}if(!ed&&pr&&kn&&kn.anvilClaudeHook===!0){let e=pr;try{e.postMessage({ok:!0,classification:Kk(kn.request)})}catch(t){e.postMessage({ok:!1,error:t instanceof Error?t.message:String(t)})}}export{Yk as REPLAY_CALL_LIMIT_MS,gk as answerChanges,Qk as classifyLogged,Kk as classifyRequest,kk as heldNotice,Ok as mootHolds,sk as sessionChores,vw as sessionContext,ww as sessionLine,Xw as startProblems};
|