@useanvil/claude-code 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- var le=[{app:"stripe",name:"Stripe",minor:!0,obj:null,servers:["stripe"],clis:["stripe"],hosts:["api.stripe.com"],at:{create_refund:["amount"],"/v1/refunds":["amount"],"/v1/charges":["amount"],"/v1/charges/*/capture":["amount"],"/v1/payment_intents":["amount"],"/v1/payment_intents/*":["amount"],"/v1/payment_intents/*/capture":["amount_to_capture"],"/v1/payment_intents/*/increment_authorization":["amount"],"/v1/payouts":["amount"],"/v1/transfers":["amount"],"/v1/transfers/*/reversals":["amount"],"/v1/topups":["amount"],"refunds create":["amount"],"charges create":["amount"],"charges capture":["amount"],"payment_intents create":["amount"],"payment_intents update":["amount"],"payment_intents capture":["amount_to_capture"],"payment_intents increment_authorization":["amount"],"payouts create":["amount"],"transfers create":["amount"],"topups create":["amount"]},digits:{isk:2,ugx:2},nameless:["create_refund","/v1/refunds","refunds create"],unread:{invoice:"Stripe adds it up from items added one call at a time, and can bill it on its own"}},{app:"paypal",name:"PayPal",minor:!1,json:!0,obj:["value","currency_code","currency"],servers:["paypal"],clis:[],hosts:["paypal.com"],at:{create_refund:["amount"],record_payment_for_invoice:["amount"],record_refund_for_invoice:["amount"],pay_order:[],"/v2/payments/captures/*/refund":["amount"],"/v2/payments/authorizations/*/capture":["amount"],"/v2/checkout/orders":["purchase_units.*.amount"],"/v2/checkout/orders/*/capture":[],"/v1/payments/payouts":["items.*.amount"],"/v2/invoicing/invoices/*/payments":["amount"],"/v2/invoicing/invoices/*/refunds":["amount"]},invoices:{create_invoice:["items.*.unit_amount \xD7 quantity","$currency_code","!items.*.tax","!items.*.discount","!shipping_cost","!allow_tip"],update_invoicing:["invoice_update.items.*.unit_amount \xD7 quantity","$invoice_update.currency_code","!invoice_update.items.*.tax","!invoice_update.items.*.discount","!invoice_update.shipping_cost","!invoice_update.allow_tip","!recurring_series_update"],"/v2/invoicing/invoices":["items.*.unit_amount \xD7 quantity","$detail.currency_code","!items.*.tax","!items.*.discount","!amount","!configuration.template_id","!configuration.allow_tip"],"/v2/invoicing/invoices/*":["items.*.unit_amount \xD7 quantity","$detail.currency_code","!items.*.tax","!items.*.discount","!amount","!configuration.template_id","!configuration.allow_tip"]}},{app:"square",name:"Square",minor:!0,json:!0,obj:["amount","currency"],servers:["square","squareup"],clis:[],hosts:["squareup.com","squareupsandbox.com"],at:{"make_api_request payments create":["request.amount_money","request.tip_money"],"make_api_request refunds payment":["request.amount_money"],"/v2/payments":["amount_money","tip_money"],"/v2/refunds":["amount_money"]},unread:{invoice:"it bills an order made by a call of its own"}},{app:"shopify",name:"Shopify",minor:!1,json:!0,obj:null,servers:["shopify"],clis:[],hosts:["myshopify.com"],changes:["refund"],at:{"/admin/api/*/graphql.json refundCreate":["input.transactions.*.amount","~input.shipping.amount"],"/admin/api/*/orders/*/refunds.json":["refund.transactions.*.amount","~refund.shipping.amount"]},nameless:["/admin/api/*/graphql.json refundCreate","/admin/api/*/orders/*/refunds.json"]}];var ce=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,Qe=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,et=/(?:^|[^a-z])(?:api|request|requests|execute|exec|run|call|invoke|http|graphql|rpc|raw|batch|bulk|action|actions|command|operation|perform|proxy|custom|query|sql|services|hooks?|webhooks?|triggers?)(?:[^a-z]|$)/,ue=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),de=(e,t)=>e.split("+").every(n=>n[0]==="="?t.split(/[^a-z0-9]+/).includes(n.slice(1)):t.includes(n));function tt(e,t){let n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),o=t.replace(/_/g,"");return e.servers.some(r=>{let s=r.replace(/_/g,"");return`_${t}_`.includes(`_${r}_`)||n.includes(`_${r}_`)||(s.length>4?o.includes(s):s.length>3&&(o.startsWith(s)||o.endsWith(s)))})}function nt(e,t,n){let o=t.normalize("NFKC").toLowerCase().replace(/\.+$/,""),r=/^[a-z0-9.-]+$/.test(o);if(!o.includes("."))return r?(e.clis??[]).includes(o)?"this":"other":"?";let s=o.split("."),a=u=>o===u||o.endsWith(`.${u}`)||u.includes("*")&&u.split(".").every((d,i,l)=>l.length===s.length&&(d==="*"||d===s[i])),c=!1;return e.hosts.some(u=>{let d=u.indexOf("/");return d<0?a(u):(c||=a(u.slice(0,d))&&/^(?:\/batch\/?|\u0000)$/.test(n),a(u.slice(0,d))&&n.includes(u.slice(d)))})?"this":r&&!c?"other":"?"}function rt(e){if(!e||!/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;try{return new URL(e).hostname.replace(/^\[|\]$/g,"")}catch{return"\0"}}function N(e,t,n,o){let r=ue(n);return e.toolWords.length===0||e.toolWords.some(s=>de(s,r))?{hit:"match",part:t,why:e.said}:o===3||/\u0000|%00/.test(r)||et.test(r)||!/[a-z]{3}/.test(r.replace(/[a-z]*\d[a-z0-9]*/g,""))||o===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(r)?{hit:"unknown",part:t,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function ot(e,t,n){let o=l=>({hit:"unknown",part:t,why:`Anvil can't tell ${l}, so it holds it (your rule: ${e.said})`});if(t.action==="claude.mcp.side_effect"){let l=t.host;if(!l)return o("which app this tool belongs to");let f=`mcp.${l}.`,m=ue(n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):t.target?.startsWith(f)?t.target.slice(f.length):"");if(tt(e,l))return N(e,t,m,1);let p=(e.anywhere??[]).some(g=>de(g,m))?{hit:"match",part:t,why:e.said}:null;if(!ce.test(l)&&!Qe.test(l))return p;let h=e.toolPrefixes.find(g=>m.startsWith(g));return h?N(e,t,m.slice(h.length),1):e.servers.some(g=>g.length>2&&`_${m}_`.includes(`_${g}_`))?N(e,t,m,1):p||(e.others??[]).includes(l)?p:o(`which app ${ce.test(l)?`the connector ${l.slice(0,8)}\u2026`:l} acts on`)}let r=t.target??"",s=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(r)?`https://${r}`:r,a=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),c="";try{a&&(c=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{c="\0"}if(!t.host&&!t.service)return o("where this writes");let u=[t.host,t.service,...Array.isArray(t.attributes.hosts)?t.attributes.hosts:[],rt(s)].filter(l=>typeof l=="string"&&l!==""),d=u.map(l=>nt(e,l,c)),i=[r,...u].some(l=>/^smtps?[:.]/i.test(l));if(d.includes("this")||i&&e.hosts.includes("smtp:")){let l=u.find((m,p)=>d[p]==="this"&&!m.includes(".")),f=r.includes("/")?3:2;return l?N(e,t,`cli:${l.toLowerCase()} ${r}`,f):i?N(e,t,"send mail",2):a?N(e,t,c,3):N(e,t,r,f)}return d.includes("?")?o(`where this writes (${u[0].replace(/[\u0000-\u001f]/g,"")})`):n.tool?.startsWith("mcp__")?o("what else this tool's command writes"):null}function B(e,t,n){let o=null;for(let r of t){let s=ot(e,r,n);if(s?.hit==="match")return s;o??=s}return o??(n.parts.length>15&&t[0]?{hit:"unknown",part:t[0],why:`Anvil can't read everything this line does, so it holds it (your rule: ${e.said})`}:null)}var st={over:"over",at_least:"at least",under:"under",at_most:"at most"};var k="Anvil can't read how much this moves",he="Anvil can't read this invoice's total (only drafting or replacing one says it)",it="Anvil can't add up this total (a tax, a discount, shipping, a tip, a template or a series changes it)",fe="Anvil can't tell which currency this moves (it names two)",at="Anvil can't tell how many requests this makes (curl expands {\u2026} and [\u2026] in a URL)",ye="claude.mcp.side_effect",lt=/\$\(|\$'|\$"|`|<<|(?:^|[\s;&|])(?:eval|xargs|source|exec)(?=\s|$)|\b(?:ba|z|k|da)?sh\s+-\w*c\b/,ct=/^(?:[A-Za-z_]\w*=.*|env|sudo|time|nohup|command|builtin|nice)$/,ut="012346#aBfgGiIjJklLMnNOpqRsSvVZ",dt=/^(?:silent|show-error|fail(?:-with-body|-early)?|location(?:-trusted)?|insecure|compressed|include|show-headers|verbose|http1\.[01]|http2(?:-prior-knowledge)?|http3(?:-only)?|globoff|progress-bar|raw|path-as-is|ssl-reqd|tlsv1(?:\.[0-3])?|ipv[46]|tcp-nodelay|remote-name(?:-all)?|remote-header-name|create-dirs|digest|basic|ntlm|negotiate|anyauth|crlf|append|junk-session-cookies|list-only|disable|netrc(?:-optional)?|proxytunnel|parallel|retry-all-errors|retry-connrefused|no-[a-z0-9-]+|get|head)$/,ft=/^(?:data(?:-raw|-binary|-ascii|-urlencode)?|form(?:-string)?|json)$/,pt=/^(?:live|confirm|help|version|dark_style|show_headers|dry_run|reverse_transfer|refund_application_fee|capture|final_capture)$/;function T(e){let t=(e.host??"").toLowerCase(),n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),o=le.filter(r=>e.action===ye?r.servers.some(s=>`_${t}_`.includes(`_${s}_`)||n.includes(`_${s}_`)):r.clis.includes(t)||r.hosts.some(s=>t===s||t.endsWith(`.${s}`)));return o.length===1?o[0]:null}function gt(e){let t=[[]],n="",o=!1,r=!1,s=!1,a=!1,c=!1,u=!1,d=()=>{c&&u?u=!1:c&&t[t.length-1].push({w:n,d:o,x:r,g:s}),n="",o=r=s=a=c=!1};for(let i=0;i<e.length;i++){let l=e[i];if(l==="'"){let f=e.indexOf("'",i+1);if(f<0)return null;n+=e.slice(i+1,f),i=f,a=!0}else if(l==='"'){let f=i+1;for(;f<e.length&&e[f]!=='"';f++){if(e[f]==="\\"&&e[f+1]===`
2
- `){f++;continue}e[f]==="\\"&&/["\\$`]/.test(e[f+1]??"")?f++:e[f]==="$"&&(o=!0),n+=e[f]}if(f>=e.length)return null;i=f,a=!0}else if(l==="\\"){if(i++,e[i]!==`
3
- `)n+=e[i]??"",a=!0;else if(!c)continue}else if(l==="#"&&!c){if(i=e.indexOf(`
4
- `,i)-1,i<0)break;continue}else{if(/[(){}]/.test(l))return null;if(l==="<"||l===">"||l==="&"&&e[i+1]===">"){if((a||!/^\d+$/.test(n))&&d(),n="",o=r=s=a=c=!1,u)return null;l==="&"&&i++,(e[i]===">"?/[>|&]/:/[&>]/).test(e[i+1]??"")&&i++,u=!0;continue}else if(/[;|&\n]/.test(l)){if(d(),u)return null;t[t.length-1].length>0&&t.push([]);continue}else if(l===" "||l===" "){d();continue}else{if(/\s/.test(l))return null;l==="$"&&(o=r=!0),/[*?[]/.test(l)&&(s=!0),n+=l}}c=!0}return d(),u?null:t}function we(e,t){let n=t.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1").split("/");return Object.keys(e).filter(o=>{let r=o.split(" ")[0].split("/");return o[0]==="/"&&r.length===n.length&&r.every((s,a)=>s==="*"?n[a]!=="":s===n[a])})}var Z=e=>e.filter(t=>t[0]!=="!"&&t[0]!=="$").map(t=>t.replace(/^~/,"").split(" ")[0]);function L(e,t){return[...new Set(e.map(n=>n.split(".").pop()))].reduce((n,o)=>n+(t.match(new RegExp(`(?:(?<![a-z0-9_]|[a-z0-9]-)|(?<=(?:^|\\s)-[a-z]+))${o.replace(/_/g,"[-_]")}(?![a-z0-9_]|-[a-z0-9])`,"gi"))?.length??0),0)}function J(e,t,n,o,r){let s=[],a=[],c=0;for(let d of t){let i=/^[!~$]/.test(d)?d[0]:"",[l="",f]=d.slice(i.length).split(" \xD7 "),m=[{v:n,up:null,curs:[]}];for(let p of l.split(".")){let h=[];for(let{v:g,curs:y}of m)if(g!=null){if(p==="*"?!Array.isArray(g):typeof g!="object"||Array.isArray(g))return k;if(p==="*")h.push(...g.map(b=>({v:b,up:null,curs:y})));else if(Object.hasOwn(g,p)){let b=g;h.push({v:b[p],up:b,curs:b.currency===void 0?y:[...y,b.currency]})}}m=h.filter(g=>g.v!==void 0&&g.v!==null)}if(i==="!"&&m.some(p=>p.v!==!1))return it;if(i==="~"&&(c+=m.length),i==="$")for(let{v:p}of m){if(typeof p!="string")return k;a.push(p.toLowerCase())}if(!i)for(let{v:p,up:h,curs:g}of m){let y=f===void 0?void 0:h?.[f];if(f!==void 0&&y==null)return k;if(e.obj){if(typeof p!="object"||Array.isArray(p))return k;{let b=p,w=[...new Set(e.obj.slice(1).map($=>b[$]).filter($=>$!==void 0))];s.push({v:b[e.obj[0]],cur:w.length>1?"?":w[0],q:y})}}else{let b=[...new Set(g)];s.push({v:p,cur:b.length>1?"?":b[0],drop:r,q:y})}}}if(a.length>0){if(new Set(a).size>1)return fe;for(let[d,i]of s.entries())if(i.cur===void 0)s[d]={...i,cur:a[0]};else if(typeof i.cur!="string"||i.cur.toLowerCase()!==a[0])return fe}let u=Z(t);return Math.max(L(u,o),L(u,JSON.stringify(n)))>s.length+c?k:s}var K=/[\s,]+|#[^\n\r]*|("(?:[^"\\\n\r]|\\.)*")|(\.\.\.|[!$&():=@[\]{|}])|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([_A-Za-z]\w*)/y;function mt(e,t,n,o){let r=o,s=r?.variables??{},a=r?.query;if(!r||typeof r!="object"||Array.isArray(r)||typeof a!="string"||a.includes('"""')||typeof s!="object"||Array.isArray(s))return k;let c=[];for(K.lastIndex=0;K.lastIndex<a.length;){let h=K.exec(a);if(!h)return k;let g=h[1]??h[2]??h[3]??h[4];g!==void 0&&c.push(g)}let u=0,d=()=>c[u],i=h=>{let g=c[u++];if(g===void 0||h!==void 0&&g!==h)throw new Error;return g},l=()=>{let h=i();if(!/^[_A-Za-z]/.test(h))throw new Error;return h},f=()=>{let h=i();if(h==="$"){let g=l();if(!Object.hasOwn(s,g))throw new Error;return s[g]}if(h==="["){let g=[];for(;d()!=="]";)g.push(f());return i(),g}if(h==="{"){let g={};for(;d()!=="}";){let y=l();i(":"),g[y]=f()}return i(),g}if(h[0]==='"')return JSON.parse(h);if(/^-?\d/.test(h))return h;if(/^[_A-Za-z]/.test(h))return h==="true"?!0:h==="false"?!1:h==="null"?null:h;throw new Error},m=()=>{let h={};if(d()!=="(")return h;for(i();d()!==")";){let g=l();i(":"),h[g]=f()}return i(),h},p=()=>{for(let h=1;h>0;){let g=i();h+=g==="{"?1:g==="}"?-1:0}};try{let h="query";if(d()!=="{"&&(h=i(),d()!=="("&&d()!=="{"&&l(),d()==="(")){for(i();i()!==")";)if(c[u-1]==="=")throw new Error}i("{");let g=[];if(h==="query")p();else{if(h!=="mutation")throw new Error;for(;d()!=="}";){let y=l();d()===":"&&(i(),y=l());let b=m();for(;d()==="@";){if(i(),l()!=="idempotent")throw new Error;m()}d()==="{"&&(i(),p());let w=n.find($=>$.endsWith(` ${y}`));g.push(w?J(e,t[w],b,JSON.stringify(b),e.nameless?.includes(w)):k)}if(i(),g.length===0)throw new Error}if(u<c.length)throw new Error;return h==="query"?"read":g}catch{return k}}var W=(e,t,n)=>{e.set(t,[...e.get(t)??[],n])};function be(e,t,n,o){let r=Z(e);if([...t.keys()].some(d=>!e.includes(d)&&L(r,d)>0))return k;let s=t.get("currency")??[],a=d=>d.some(i=>i.d)||new Set(d.map(i=>i.w)).size>1?"?":d[0]?.w,c=[],u=0;for(let d of e){let i=t.get(d)??[];if(u+=i.length,i.length===0)continue;let l=a(i);if(l==="?")return k;c.push({v:l,cur:s.length>0?a(s):void 0,drop:o})}return L(Z(e),n)>u?k:c}function Y(e,t,n){let o=t.w.indexOf("=");if(o<=0||t.w.slice(0,o).includes("$"))return!1;let r=t.w.slice(0,o),s=t.w.slice(o+1);try{r=decodeURIComponent(r.replace(/\+/g," ")),n&&(s=decodeURIComponent(s.replace(/\+/g," ")))}catch{return!1}return W(e,r,{w:s,d:t.d&&s.includes("$"),x:!1}),!0}function ht(e,t,n,o,r){let s=[],a=new Map;for(let l=0;l<n.length;l++){let{w:f,d:m}=n[l];if(f.startsWith("--")){let p=f.indexOf("="),h=(p<0?f.slice(2):f.slice(2,p)).replace(/-/g,"_");if(p<0&&pt.test(h))continue;let g=p>=0?{w:f.slice(p+1),d:m,x:!1}:n[++l];if(!g||p<0&&/^-./.test(g.w))return k;if(h==="data"){if(!Y(a,g,!1))return k}else W(a,h,g)}else if(/^-./.test(f)){let p=1;for(;p<f.length&&"chs".includes(f[p]);)p++;if(p===f.length)continue;let h=p+1<f.length?{w:f.slice(p+1),d:m,x:!1}:n[++l];if(!h||p+1===f.length&&/^-./.test(h.w)||f[p]==="d"&&!Y(a,h,!1))return k}else s.push(n[l])}let[c="",u=""]=s.map(l=>l.w);if(c==="get"||u==="list"||u==="retrieve")return"read";let d=`${c} ${u}`,i=Object.hasOwn(t,d)?d:/^(?:post|delete)$/.test(c)&&u[0]==="/"?we(t,u.split("?")[0]).find(l=>!l.includes(" ")):void 0;if(!i)return r;if(i!==d){if(s[1].d)return k;for(let[l,f]of new URLSearchParams(u.includes("?")?u.slice(u.indexOf("?")+1):""))W(a,l,{w:f,d:!1,x:!1})}return be(t[i],a,o,!!e.nameless?.includes(i))}function yt(e){try{return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?new URL(e):/^[\w-]+(?:\.[\w-]+)+(?::\d+)?(?:\/|$)/.test(e)?new URL(`https://${e}`):null}catch{return null}}var wt=(e,t)=>{let n=yt(t);return n&&e.hosts.some(o=>n.hostname===o||n.hostname.endsWith(`.${o}`))?n:null};function bt(e,t,n,o,r){let s=null,a="",c="",u=!1,d=!1,i=[];for(let y=0;y<n.length;y++){let{w:b,d:w}=n[y];if(b.startsWith("--")){let $=b.slice(2);if(/^(?:next|config|variable|expand-.*|upload-file)$|=/.test($))return k;if(/^(?:no-)?(?:get|head)$/.test($)&&(u=$[0]!=="n"),/^(?:no-)?globoff$/.test($)&&(d=$[0]!=="n"),dt.test($))continue;let _=n[++y];if(!_)return k;ft.test($)?i.push({v:_,how:$}):$==="request"&&(c=_.w.toUpperCase())}else if(/^-./.test(b))for(let $=1;$<b.length;$++){let _=b[$];if(_==="K"||_===":"||_==="T")return k;if((_==="G"||_==="I")&&(u=!0),_==="g"&&(d=!0),ut.includes(_))continue;let A=$+1<b.length?{w:b.slice($+1),d:w,x:!1}:n[++y];if(!A)return k;_==="d"||_==="F"?i.push({v:A,how:_==="d"?"data":"form"}):_==="X"&&(c=A.w.toUpperCase());break}else{let $=wt(e,b);if(!$)continue;if(w||s)return k;s=$,a=b}}if(!s)return null;if(/^(?:GET|HEAD|OPTIONS)$/.test(c||(u||i.length===0?"GET":"POST")))return"read";if(!d&&/[{}[\]]/.test(a))return at;if(e.json&&u&&i.length>0)return k;let l;try{l=decodeURIComponent(s.pathname)}catch{return k}let f=we(t,l),m=f.find(y=>!y.includes(" "));if(!m&&f.length===0)return r;let p=new Map;for(let[y,b]of s.searchParams)W(p,y,{w:b,d:!1,x:!1});let h;for(let{v:y,how:b}of i){let w=y.w.trim();if(w[0]==="{"||w[0]==="["){if(y.d||h!==void 0)return k;try{h=JSON.parse(w)}catch{return k}}else for(let $ of w.split("&"))if(!Y(p,{w:$,d:y.d,x:!1},!/urlencode|form/.test(b)))return k}if((h!==void 0||e.json)&&p.size>0)return k;if(!m){let y=h===void 0||p.size>0?k:mt(e,t,f,h);return typeof y=="string"?y:{many:y}}let g=!!e.nameless?.includes(m);return h!==void 0?J(e,t[m],h,o,g):be(t[m],p,o,g)}function $t(e,t,n,o){let r=n.input?.command,s=typeof r=="string"&&!lt.test(r)?gt(r):null;if(!s)return k;let a=[],c=new RegExp([...e.servers,...e.clis].join("|"),"i");for(let u of s){let d=u.map(p=>p.w).join(" "),i=0;for(;i<u.length&&ct.test(u[i].w);)i++;let l=(u[i]?.w??"").replace(/^.*\//,""),f=u.slice(i+1),m=e.clis.includes(l)?ht(e,t,f,d,o):l==="curl"?bt(e,t,f,d,o):null;if(m===null){if(!/^(?:cd|pushd)$/.test(l)&&u.some(p=>c.test(p.w)))return k;continue}if(f.some(p=>p.x||p.g&&!p.w.includes("://")))return"Anvil can't read a word the shell expands (an unquoted $ or *)";m!=="read"&&a.push(...typeof m=="object"&&!Array.isArray(m)?m.many:[m])}return a.length<n.parts.filter(u=>T(u)===e).length?k:a}var V="this call doesn't say how much it moves",pe=e=>typeof e=="number"?Number.isFinite(e)&&e>=0?String(e):"":typeof e=="string"?e.trim():"",ge=/^(\d+)(?:\.(\d+))?$/;function $e(e,t,n){if(e.length===0)return V;let o=0n,r=0;for(let{v:s,cur:a,drop:c,q:u}of e){let d=c&&(a===void 0||typeof a=="string"&&a.toLowerCase()===n.currency)?void 0:a,i=d===void 0?n.bare?n.currency:null:typeof d=="string"&&/^[a-z]{3}$/i.test(d)?d.toLowerCase():"?";if(i===null)return"Anvil can't tell which currency this moves";if(i!==n.currency)return i==="?"?k:`it's in ${i.toUpperCase()}, not ${n.currency.toUpperCase()}`;let l=(t.minor?/^(\d+)()$/:ge).exec(pe(s)),f=u===void 0?null:ge.exec(pe(u));if(!l||u!==void 0&&!f)return k;let m=(t.minor?t.digits?.[i]??n.digits:(l[2]??"").length)+(f?.[2]??"").length,p=Math.max(r,m);o=o*10n**BigInt(p-r)+BigInt(l[1]+(l[2]??""))*BigInt(f?f[1]+(f[2]??""):1)*10n**BigInt(p-m),r=p}return[o,r]}function me(e,t,n){let o=e.toString().padStart(t+1,"0");return`${n}${o.slice(0,o.length-t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}${t>0?`.${o.slice(-t)}`:""}`}function ke(e,t,n){let o=T(t),r=e.invoice?o?.invoices:o?.at,s=n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):"",a=n.input,c=!a||Object.hasOwn(r??{},s)?s:`${s} ${String(a.service).toLowerCase()} ${String(a.method)}`,u=e.invoice?he:k;return!o||!r||!e.apps.includes(o.app)?k:t.action!==ye?$t(o,r,n,u):a&&Object.hasOwn(r,c)?[J(o,r[c],a,JSON.stringify(a),o.nameless?.includes(c))]:u}function kt(e,t,n){let o=ke(e,t,n);if(typeof o=="string")return o;if(o.length===0)return V;let r=0n;for(let s of o){let a=typeof s=="string"?s:$e(s,T(t),e);if(typeof a=="string")return a;let[c,u]=a,d=10n**BigInt(Math.abs(u-e.digits));r+=u<=e.digits?c*d:(c+d-1n)/d}return r<=BigInt(Number.MAX_SAFE_INTEGER)?Number(r):"Anvil can't count an amount that large"}function vt(e,t){let n=e.money;if(!n||!/^[a-z]{3}$/.test(n.currency)||!Number.isInteger(n.digits)||n.digits<0||n.digits>4||!Array.isArray(n.apps))return"Anvil can't use this cap's currency";let o=t?.parts.filter(s=>e.kinds.includes(s.action)&&(!e.match||B(e.match,[s],t)!==null))??[];if(o.length===0)return"Anvil can't tell how much this moves";let r=0;for(let s of o){let a=kt(n,s,t);if(typeof a=="string")return a;r+=a}return Number.isSafeInteger(r)?r:"Anvil can't count an amount that large"}function ve(e,t,n){let o=T(t),r=ke(e,t,n),s=c=>e.invoice&&c===V?he:c;if(typeof r=="string")return{hit:"unknown",why:s(r)};let a=null;for(let c of r){let u=typeof c=="string"?c:$e(c,o,e);if(typeof u=="string"){a??=u;continue}let[d,i]=u,l=Math.max(i,e.digits),f=d*10n**BigInt(l-i),m=BigInt(e.value)*10n**BigInt(l-e.digits),[p,h]=[f,l];for(;h>e.digits&&p%10n===0n;)[p,h]=[p/10n,h-1];if(e.op==="over"?f>m:e.op==="at_least"?f>=m:e.op==="under"?f<m:f<=m)return{hit:"match",detail:`${me(p,h,e.sign)} is ${st[e.op]} ${me(BigInt(e.value),e.digits,e.sign).replace(/\.0+$/,"")}`}}return a===null?null:{hit:"unknown",why:s(a)}}import{existsSync as U,readdirSync as on,statSync as He}from"fs";import{dirname as se,isAbsolute as sn,join as C,posix as an,resolve as I}from"path";import{posix as Sn}from"path";var _t=null;function z(){return _t??process.platform==="win32"}function _e(e){if(!z())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 D(e){return z()?_e(e)??e:e}import{createHash as Pr}from"crypto";import{appendFileSync as Or,closeSync as en,constants as qe,fstatSync as tn,mkdirSync as Mr,openSync as nn,readdirSync as Ir,readFileSync as Lr,readSync as rn,renameSync as Wr,statSync as Tr,unlinkSync as zr,writeFileSync as Dr}from"fs";import{homedir as qr}from"os";import{dirname as Ur,join as Gr}from"path";import{domainToASCII as Ct}from"url";var xt="to cc bcc torecipients ccrecipients bccrecipients toaddresses ccaddresses bccaddresses toaddress ccaddress bccaddress rcptto recipient recipients attendee attendees optionalattendees requiredattendees guests invitees recipientemail extrarecipients toemail toemails ccemails bccemails",At="klaviyo himalaya convertkit api.kit.com activecampaign api-us1.com activehosted constantcontact constant_contact api.cc.email beehiiv helpscout help_scout freshdesk substack",ee=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),Rt=null,te={has:e=>(Rt??=new Set(xt.split(" "))).has(e)},je=/^(?:from|sender|replyto|returnpath|envelopefrom|mailfrom|bounce)|^(?:useremail|usergoogleemail|account|accountemail|organizer|owner|user|mailbox|asm)$/,ne=/(?:contact|member|participant|attendee|guest|invitee|person|people|subscriber|customer|recipient|audience|segment|list|group)(?:id|ids|s)?$|userids$|identifiers$|campaignids?$/,Pe=/^(?:draft|(?:draft|message|msg|email|thread|conversation|originalmessage|replytomessage|parentmessage)ids?|inreplyto|references)$/,Nt=/^(?:instructions?|prompt|task)$/,Ee=/ids?$/,Oe=/^(?:subject|body|text|html|content|contents|textbody|htmlbody|htmlcontent|textcontent|textpart|htmlpart|message|comment|description|summary|title|location|notes?|signature|snippet|preheader|plaintext|markdown|name|displayname)$|body$|html$/,St=/^(?:email|emailaddress|address|mail|addr)$/,jt=null,Pt={exec:e=>(jt??=new RegExp(`(?:^|[^a-z0-9])(${At.replace(/\./g,"\\.").replace(/ /g,"|")})`)).exec(e)},re=/send.{0,20}draft|draft.{0,20}send|(?<!no-?)reply|\/messages\/[^/?\s]+\/[^?\s]{0,200}send/,Me=/\$batch|(?:^|[^a-z])(?:batch|jmap)(?:[^a-z]|$)|multi_?execute|(?:^|[^a-z])execute(?:[^a-z]|$)|graphql|(?:^|[^a-z])(?:api_?)?request(?:[^a-z]|$)/,Et=/^(?:all|everyone|everybody|team|staff|group|list|lists|members|announce(?:ments)?|all-?hands|employees|company)$|^(?:all|team|list|everyone)[._-]|[._-](?:all|team|list|group|members|announce|everyone|staff)$|[%!]/,Ot=/(?:^|\.)(?:googlegroups\.com|groups\.io)$|^(?:lists?|groups?)\./;function oe(e){let t=Ct(e.normalize("NFKC").toLowerCase().replace(/\.$/,""));return/^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$/.test(t)?t:""}function Mt(e){let t=e.trim().replace(/^mailto:/i,""),n=/<([^<>]*)>$/.exec(t);n&&(t=n[1].trim());let o=t.length;for(;o>0&&`"'`.includes(t[o-1]);)o--;t=t.slice(0,o).replace(/^["']+/,"");let r=/^([^\s@<>(),;:"[\]]+)@([^\s@<>(),;:"[\]]+)$/u.exec(t),s=r?oe(r[2]):"";if(!s)return null;let a=r[1].normalize("NFKC").toLowerCase().replace(/(?<=.)\+.*$/,"");return(s==="gmail.com"||s==="googlemail.com")&&(a=a.replace(/\./g,""),s="gmail.com"),{shown:t,local:a,domain:s,alien:/[^\x00-\x7f]/.test(t)||/(?:^|\.)xn--/.test(s),group:Et.test(a)||Ot.test(s)}}function H(e){let t=[],n=!/[<"]/.test(e),o="",r=!1,s=!1;for(let a=0;a<e.length;a++){let c=e[a];if(r&&c==="\\"){o+=c+(e[++a]??"");continue}c==='"'?r=!r:c==="<"?s=!0:c===">"&&(s=!1),!r&&!s&&(c===","||c===";"||n&&/\s/.test(c))?(t.push(o),o=""):o+=c}return t.push(o),r||s?[null]:t.filter(a=>a.trim()).map(a=>(a.replace(/"(?:[^"\\]|\\.)*"/g,"").match(/@/g)??[]).length===1?Mt(a):null)}var v="Anvil can't read who this goes to",j="Anvil can't read who this goes to: it is built when the line runs",Ce="Anvil can't read who this goes to: its body can't be read",O="Anvil can't read who this goes to: a reply, or a draft sent by its id, goes to whoever the thread or the draft names",Ie="Anvil can't read who this goes to: it runs a batch, or any request";function S(e,t){for(let n of H(e))n?(t.list.push(n),t.known=!0):t.why??=`${v} ("${e.trim().slice(0,40)}")`}function Le(e,t){let n=e.includes(`
5
- `)?e:Buffer.from(e,"base64").toString("utf8"),o=/\r?\n\r?\n/.exec(n),r=o?n.slice(0,o.index+o[0].length):n;(!/^[\w-]+:/.test(r)||/\r(?!\n)/.test(r)||n.includes(`\r
6
- `)&&/(?<!\r)\n/.test(r))&&(t.why??=`${v}: its message can't be read`);for(let s of r.replace(/\r?\n[ \t]+/g," ").split(/\r?\n/)){let a=/^(?:resent-)?(?:to|cc|bcc)\s*:/i.exec(s);a&&S(s.slice(a[0].length),t)}}function xe(e){let t=0;for(let n=0;n<e.length;n++){if(e[n]!=='"')continue;for(n++;n<e.length&&e[n]!=='"';n++)e[n]==="\\"&&n++;let o=n+1;for(;/\s/.test(e[o]??"");)o++;e[o]===":"&&t++}return t}function We(e,t){let n;try{n=/^\s*[[{]/.test(e)?JSON.parse(e):void 0}catch{n=void 0}return n!==void 0&&xe(e)!==xe(JSON.stringify(n))&&(t.why??=`${v}: it names a field twice`),n}function R(e,t,n=!1,o=0,r=!1,s=!1){if(o>12)t.why??=v;else if(typeof e=="string"){if(n)S(e,t);else if(!r&&!/[\s@]/.test(e)&&/[/_.]/.test(e)&&re.test(e.toLowerCase()))t.why??=O;else if(!r){let a=We(e,t),c=a===void 0?H(e):[];if(a!==void 0)R(a,t,!1,o+1,!1,s);else if(c.length>0&&c.every(u=>u!==null))for(let u of c)t.list.push(u);else/[^\s@]@[^\s@.]+\.[^\s@]/.test(e)&&(t.why??=`${v} ("${e.trim().slice(0,40)}")`)}}else if(Array.isArray(e))for(let a of e)R(a,t,n,o+1,r,s);else if(e&&typeof e=="object"){let a=!1;for(let[c,u]of Object.entries(e)){let d=ee(c);u==null||u===""||Array.isArray(u)&&u.length===0||(n?St.test(d)&&(a=!0,R(u,t,!0,o+1)):te.has(d)?R(u,t,!0,o+1):d==="raw"&&typeof u=="string"?Le(u,t):(Pe.test(d)||d==="id"&&o===0)&&(typeof u!="object"||Array.isArray(u))?(!s||d.startsWith("draft"))&&(t.why??=O):ne.test(d)?t.why??=`${v}: it names a list ("${c}")`:Nt.test(d)?t.why??=`${v}: another tool picks who it reaches`:d==="calendarid"&&typeof u=="string"&&!/calendar\.google\.com$/i.test(u)?R(u,t,!1,o+1,r,s):!je.test(d)&&!Ee.test(d)&&R(u,t,!1,o+1,r||Oe.test(d),s))}n&&!a&&(t.why??=v)}else n&&e!==null&&e!==void 0&&(t.why??=v)}var X=(e,t)=>e[t]==="`"||e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="(";function It(e){let t=[],n=[],o=!1,r=[],s=[],a="",c=!1,u=!1,d=0,i=[],l=()=>{u&&(d?d===2&&!/^(?:\d+|-)$/.test(a)&&n.push({f:a,dyn:c}):(r.push(a),s.push(c)),d=0),a="",c=u=!1},f=()=>{l(),r.length>0&&t.push({w:r,dyn:s}),r=[],s=[]};for(let m=0;m<e.length;m++){let p=e[m],h=e[m+1];if(p==="\\")h!==void 0&&h!==`
7
- `&&(a+=h,u=!0),m++;else if(p==="'"||p==="$"&&h==="'"){let g=p==="$"?m+2:m+1,y=e.indexOf("'",g);a+=e.slice(g,y<0?void 0:y),c||=p==="$"||y<0,u=!0,m=y<0?e.length:y}else if(p==='"'){let g=m+1;for(;g<e.length&&e[g]!=='"';g++){let y=e[g+1];e[g]==="\\"&&y!==void 0&&'"\\$`\n'.includes(y)?a+=e[++g]===`
8
- `?"":y:(o||=X(e,g),c||=e[g]==="$"||e[g]==="`",a+=e[g])}c||=g>=e.length,u=!0,m=g}else if(p==="$"||p==="`")o||=X(e,m),a+=p,c=u=!0;else if(p==="#"&&!u){let g=e.indexOf(`
9
- `,m);m=(g<0?e.length:g)-1}else if(p==="<"&&h==="<"&&e[m+2]!=="<"){l();let g=/^<<(-?)[ \t]*((?:[^\s;&|<>()'"\\]|'[^']*'|"[^"]*"|\\.)+)/.exec(e.slice(m));g&&i.push([g[2].replace(/'([^']*)'|"([^"]*)"|\\(.)/g,"$1$2$3"),g[1]==="-",/['"\\]/.test(g[2])]),m+=(g?.[0].length??2)-1}else if(p==="<"||p===">"||p==="&"&&h===">"){/^\d+$/.test(a)&&!c&&(u=!1),l();let g=p;for(;/[<>&|]/.test(e[m+1]??"");)g+=e[++m];d=g.includes(">")?2:1}else if(/[;&|()\n]/.test(p)){if(f(),p===`
10
- `)for(let[g,y,b]of i.splice(0)){let w=m+1;for(;;){let $=e.indexOf(`
11
- `,w),_=e.slice(w,$<0?void 0:$);if(w=$<0?e.length:$+1,$<0||(y?_.replace(/^\t+/,""):_)===g)break;for(let A=0;!b&&A<_.length;A++)_[A]==="\\"?A++:o||=X(_,A)}m=w-1}}else/\s/.test(p)?l():(a+=p,u=!0)}return f(),{list:t,sub:o,writes:n}}function Lt(e){let t=0;for(;t<e.w.length&&(/^[A-Za-z_]\w*\+?=/.test(e.w[t])||/^(?:env|sudo|doas|nohup|exec|command|time|nice|stdbuf)$/.test(e.w[t])||t>0&&e.w[t].startsWith("-"));)t++;let n=e.w[t];return n!==void 0&&!e.dyn[t]?{name:(/^(?:\/(?:usr\/(?:local\/)?|opt\/(?:homebrew|local)\/)?s?bin\/)?[^/]+$/.test(n)?n.slice(n.lastIndexOf("/")+1):n).toLowerCase(),at:t+1}:null}var Q=["srAaSqTOuC","cb","tfHE"],Ae=["sifmQd","cb","HeF"],Wt={mail:Q,mailx:Q,"s-nail":Q,sendmail:["fFOpRVNLBXh","","tC"],msmtp:["afCX","","t"],mutt:Ae,neomutt:Ae},Re=/^\s*(?:to|cc|bcc)\s*:/i,F="Anvil can't read who this goes to: it may read them from the message or its settings";function Tt(e,t,n,o,r){let s=Wt[e];if(!s){let i=!1;for(let l=o;l<t.length;l++){let f=/^(?:--(to|cc|bcc|recipients?|attendees?)|-(t))(?:=([^]*))?$/.exec(t[l]);if(!f||f[2]&&e!=="swaks")continue;let m=f[3]??t[++l];i=!0,m===void 0||n[l]?r.why??=j:S(m,r)}i||(r.why??=v);return}let[a,c,u]=s,d=!1;for(let i=o;i<t.length;i++){let l=t[i];if(d||!l.startsWith("-")||l==="-")n[i]?r.why??=j:S(l,r);else if(l==="--")d=!0;else if(l.startsWith("--")){let f=/^--([\w-]+)(=?)/.exec(l),m=f?.[1]??"";if(/^(?:append|subject|return-address|from|attach|content-type|encoding|account|host|port|user)$/.test(m)){let p=f?.[2]?l.slice(l.indexOf("=")+1):t[++i];p!==void 0&&Re.test(p)&&(n[i]?r.why??=j:S(p.slice(p.indexOf(":")+1),r))}else/^(?:norc|nosum|ignore|quit|debug|verbose|auth|tls|read-envelope-from|skip-empty-attachments)$/.test(m)||(r.why??=F)}else if(e==="sendmail"&&/^-b[^m]/.test(l))r.why??=F;else if(/mutt/.test(e)&&l.startsWith("-a"))for(;i+1<t.length&&t[i+1]!=="--";)i++;else for(let f=1;f<l.length;f++){let m=l[f];if(u.includes(m)&&(r.why??=F),!a.includes(m)&&!c.includes(m))continue;let p=f+1<l.length?l.slice(f+1):t[++i];/^\s*(?:sendmail|mta)\s*=/i.test(p??"")&&(r.why??=F),n[i]&&"aTC".includes(m)&&a.includes(m)&&(r.why??=j);let h=p!==void 0&&Re.test(p);if(!c.includes(m)&&!h)break;p===void 0||n[i]?r.why??=j:S(h?p.slice(p.indexOf(":")+1):p,r);break}}}function Ne(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`)}catch{return null}}var zt="AbcCdDeEFHKmoPQrtTuUwxXyYz",Dt=/^(?:data(?:-ascii|-binary|-raw|-urlencode)?|json|form(?:-string)?|url|header)$/,Se=/^(?:config|upload-file|url-query|variable|request-target|mail-rcpt|expand-[\w.-]+)$/,Ft=/^(?:request|user|user-agent|referer|cookie|cookie-jar|output|output-dir|dump-header|max-time|connect-timeout|retry|retry-delay|retry-max-time|max-redirs|write-out|oauth2-bearer|cacert|capath|cert|key|cert-type|key-type|pass|proto|proto-default|proto-redir|limit-rate|max-filesize|aws-sigv4|mail-from|mail-auth|noproxy|keepalive-time|expect100-timeout|tls-max|ciphers|interface|stderr|trace|trace-ascii|libcurl|etag-save|etag-compare|hsts|alt-svc|range|continue-at|time-cond|speed-limit|speed-time|netrc-file)$/,qt=/^(?:silent|show-error|fail|fail-with-body|fail-early|location|location-trusted|verbose|include|insecure|compressed|http1\.0|http1\.1|http2|http2-prior-knowledge|http3|globoff|get|head|progress-bar|progress-meter|ipv4|ipv6|tlsv1\.2|tlsv1\.3|ssl-reqd|retry-all-errors|retry-connrefused|path-as-is|disable|tcp-nodelay|buffer|keepalive|clobber|remote-name|remote-name-all|create-dirs|netrc|netrc-optional|junk-session-cookies|raw|tr-encoding|trace-time|styled-output|parallel|parallel-immediate|anyauth|basic|digest|ntlm|negotiate|post301|post302|post303|ca-native|form-escape|remove-on-error)$/,Ht=/^(?:[oDc]|output|output-dir|dump-header|cookie-jar|stderr|trace|trace-ascii|libcurl|etag-save|hsts|alt-svc)$/,q="Anvil can't read who this goes to: curl takes part of it from elsewhere";function E(e,t,n){(t||/(?:^|\/)(?:\.?(?:curlrc|mailrc|nailrc|muttrc|msmtprc)|mail\.rc|s-nail\.rc|curl|mailx?|s-nail|sendmail|msmtp|(?:neo)?mutt|swaks)$|\/\.?(?:curl|mutt|msmtp|s-nail)\//.test(e))&&(n.why??=`${v}: this line writes a file a send may read or run (${e.slice(0,60)})`)}function Ut(e,t,n,o,r,s){let a=0,c=0,u=[],d=[],i=!1,l=!1,f=e.some((p,h)=>h>=n&&(/^-[^-]*O/.test(p)||p.startsWith("--remote-name"))),m=p=>{if(!r(p))return;let h=Ne(p);if(h?.hostname.toLowerCase().replace(/\.$/,"")!==o)s.why??=`${v}: a URL Anvil reads two ways`;else{c++;let g=h.pathname.toLowerCase();try{g=decodeURIComponent(g)}catch{s.why??=v}re.test(g)?s.why??=O:Me.test(g)&&(s.why??=Ie);for(let[y,b]of h.searchParams)u.push([y,b,!1,!1])}};for(let p=n;p<=e.length;p++){let h=e[p];if(h===void 0||h==="--next"||h==="-:"){if(c>0){a++;for(let w of d)Gt(w,i&&!l,u,s);Bt(u,s)}[c,u,d,i,l]=[0,[],[],!1,!1];continue}let g="",y;if(h.startsWith("--")){let w=/^--([\w.-]+)(=?)/.exec(h);if(g=w?.[1]??"",qt.test(g.replace(/^no-/,"")))continue;if(g==="remote-header-name"||!Dt.test(g)&&!Se.test(g)&&!Ft.test(g)){s.why??=g==="remote-header-name"?q:`${v}: curl takes an option Anvil doesn't know (--${g.slice(0,40)})`;continue}y=w?.[2]?h.slice(h.indexOf("=")+1):e[++p]}else if(h.startsWith("-")&&h.length>1){for(let w=1;w<h.length&&!g;w++)h[w]==="J"&&(s.why??=q),zt.includes(h[w])&&(g=h[w],y=h.slice(w+1)||e[++p]);if(!g)continue}else{if(f){let w=Ne(h)?.pathname.split("/").pop()??"";E(w,!1,s);try{E(decodeURIComponent(w),!1,s)}catch{s.why??=v}}m(h);continue}if(y===void 0){s.why??=v;break}let b=t[p]??!1;if(/^[KT]$/.test(g)||Se.test(g))s.why??=q;else if(g==="url")m(y);else if(g==="H"||g==="header"){let w=/^\s*content-type\s*:/i.exec(y);y.startsWith("@")?s.why??=q:w?/json/i.test(y.slice(w[0].length))&&!b?i=!0:l=!0:b&&!/^\s*[\w-]+\s*:/.test(y)&&(l=!0)}else if(Ht.test(g))E(y,b,s);else if(g==="F"||g.startsWith("form")||g==="data-urlencode"){let w=y.indexOf("="),$=y.indexOf("@"),_=g==="data-urlencode"?$>=0&&(w<0||$<w):g!=="form-string"&&/^[@<]/.test(y.slice(w+1));u.push([w>0?y.slice(0,w):"",y.slice(w+1),b,_])}else(g==="d"||g.startsWith("data")||g==="json")&&(b||g!=="data-raw"&&y.startsWith("@")?s.why??=`${v}: its body is ${b?"built when the line runs":"read from a file"}`:(i||=g==="json",d.push(y)))}return a}function Gt(e,t,n,o){let r=We(e,o);if(r!==void 0?R(r,o):t&&(o.why??=Ce),!t){r===void 0&&/^[\w-]+\s*:/.test(e)&&Le(e,o);for(let s of e.split("&")){let a=s.indexOf("=");try{let c=decodeURIComponent(s.slice(0,Math.max(a,0)).replace(/\+/g," "));/^[\w.[\]-]*$/.test(c)&&(r===void 0||c.split(/[.[\]]+/).map(ee).some(u=>te.has(u)||ne.test(u)))&&n.push([c,decodeURIComponent(s.slice(a+1).replace(/\+/g," ")),!1,!1])}catch{o.why??=Ce}}}}function Bt(e,t){for(let[n,o,r,s]of e){let a=n.split(/[.[\]]+/).map(ee).filter(Boolean),c=a[a.length-1]??"";if(a.some(u=>te.has(u)))s||r?t.why??=`${v}: it is ${s?"read from a file":"built when the line runs"}`:S(o,t);else if(a.some(u=>ne.test(u)))t.why??=`${v}: it names a list ("${n}")`;else if(a.some(u=>Pe.test(u)))t.why??=O;else{if(a.some(u=>je.test(u))||Ee.test(c)||a.some(u=>Oe.test(u)))continue;r?t.why??=j:s||R(o,t)}}}var Kt=/^(?:echo|printf|cat|jq|grep|egrep|fgrep|head|tail|wc|cut|tr|date|sleep|true|false|:|cd|pwd|ls|test|\[|export|unset|column|fold|rev|nl|paste|basename|dirname|realpath|mkdir|touch|tee|curl)$/;function Zt(e,t,n,o){let r=t.includes("."),s=new RegExp(`(?<![\\w.-])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-]|\\.\\w)`),a=l=>s.test(l.replace(/['"\\]/g,"").toLowerCase()),{list:c,sub:u,writes:d}=It(e);u&&(o.why??=`${v}: this line runs a command inside another ($(\u2026) or \`\u2026\`), which Anvil doesn't read`);for(let l of d)E(l.f,l.dyn,o);let i=0;for(let l of c){let f=Lt(l);if(((f?.name==="export"?l.w:l.w.slice(0,f?f.at-1:void 0)).some(m=>/^(?:\w*PATH|path|\w*HOME|\w*RC|LD_\w*|DYLD_\w*|(?:BASH_)?ENV)\+?=/.test(m))||f?.name==="printf"&&l.w.slice(f.at).some(m=>/^-\w*v/.test(m)))&&(o.why??=`${v}: this line sets where a program or its settings come from`),f?.name==="tee")for(let m=f.at;m<l.w.length;m++)l.w[m].startsWith("-")||E(l.w[m],l.dyn[m],o);!f&&l.w.every(m=>/^[A-Za-z_]\w*\+?=/.test(m))||(f&&r&&f.name==="curl"?i+=Ut(l.w,l.dyn,f.at,t,a,o):f&&!r&&f.name===t?(i++,Tt(f.name,l.w,l.dyn,f.at,o)):(!f||!Kt.test(f.name))&&(o.why??=`${v}: this line also runs ${f?f.name:"a command built when it runs"}, which Anvil doesn't read`))}(i===0||i<n)&&(o.why??=`${v}: Anvil reads a plain curl request or mail program, not this`)}function Te(e,t){let n={list:[],why:null},o=(e.host??"").toLowerCase(),r=e.action==="claude.mcp.side_effect",s=`${o} ${r?t.tool??"":/^[a-z][a-z0-9+.-]*:\/\//i.test(e.target??"")?e.target:""}`.toLowerCase(),a=Pt.exec(s)?.[1];return a?n.why=`Anvil can't read who ${a} sends reach: they go to a list or a ticket`:re.test(s)?n.why=O:Me.test(s)?n.why=Ie:r&&t.input?R(t.input,n,!1,0,!1,/forward/.test((t.tool??"").split("__").pop().toLowerCase())):!r&&t.command&&o?Zt(t.command,o,t.parts.filter(c=>c.action===e.action&&(c.host??"").toLowerCase()===o).length,n):n.why=v,n.known||(n.why??=v),n}function Yt(e){let t=a=>Array.isArray(a)&&a.every(c=>typeof c=="string")?a:null,n=t(e.domains??[]),o=t(e.addresses??[]);if(!n||!o)return"a recipient condition's domains and addresses must be lists";if(e.outside!==void 0&&e.outside!==!0)return"a recipient condition's outside must be true";let r=n.map(oe),s=o.map(a=>{let[c,u]=H(a);return c&&!u?`${c.local}@${c.domain}`:""});return r.includes("")||s.includes("")?"a recipient condition names an address or a domain Anvil can't read":r.length+s.length===0?"a recipient condition needs an address or a domain":{type:"recipient",said:String(e.said),...e.outside===!0?{outside:!0}:{},domains:r,addresses:s}}var ze=new WeakMap;function De(e,t,n){let o=ze.get(e);if(o===void 0&&ze.set(e,o=Yt(e)),typeof o=="string")return{hit:"unknown",why:`Anvil can't use this rule's recipients (${o})`};let r;try{r=Te(t,n)}catch{return{hit:"unknown",why:"Anvil can't read who this goes to"}}let s=r.why;for(let a of r.list){let c=o.addresses.includes(`${a.local}@${a.domain}`)||o.domains.some(u=>a.domain===u||a.domain.endsWith(`.${u}`));if(o.outside?!c:c)return{hit:"match",detail:o.outside?`${a.shown} is outside ${[...o.domains,...o.addresses.length>0?["the addresses your rule names"]:[]].join(" and ")}`:`it goes to ${a.shown}`};a.group?s??=`${a.shown} may reach ${o.outside?"people outside":"anyone"} (a list or a relay)`:a.alien&&!o.outside&&(s??=`${a.shown} is in letters from another alphabet`)}return s===null?null:{hit:"unknown",why:s}}var Jt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");function Vt(e,t){if(e&&/^:?[+-]?\d/.test(e))return!0;let n=e?/^:?(?:<[^>]*>|[a-z]{3,})([+-]?)(\d{1,2})(?::(\d\d))?(<|[a-z]{3})?/i.exec(e):null;if(!n)return!1;let o=(n[1]==="-"?1:-1)*(Number(n[2])*60+Number(n[3]??0)),r=-t.getTimezoneOffset();return r!==o&&!(n[4]!==void 0&&r===o+60)}function Fe(e,t,n){let o=new Date(n.now??NaN),r=o.getDay(),s=o.getHours(),a=s*60+o.getMinutes();if(!((n.now??0)>0&&r>=0))return{hit:"unknown",why:"Anvil can't tell when this call was made"};let c=process.env.TZ,u=`:${String(a%60).padStart(2,"0")}`;if(c!==void 0||o.getTimezoneOffset()===0){let d="";try{let i=Intl.DateTimeFormat().resolvedOptions().timeZone;i&&!Vt(c,o)&&(d=o.toLocaleTimeString("en-GB",{timeZone:i,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}))}catch{}if(d!==`${String(s).padStart(2,"0")}${u}`)return{hit:"unknown",why:`Anvil can't read your Mac's time zone${c===void 0?"":` (TZ is "${c}")`}`}}return e.at.some(d=>d.days.includes(r)&&a>=d.from&&a<d.to)?{hit:"match",detail:`it's ${Jt[r]} ${s%12||12}${u}${s<12?"am":"pm"}`}:null}import{existsSync as Qn,readdirSync as er,realpathSync as tr}from"fs";import{basename as rr,dirname as or,join as sr}from"path";function M(e,t=8*1024*1024){let n;try{n=nn(e,qe.O_RDONLY|qe.O_NONBLOCK)}catch(o){if(o.code==="ENOENT"||o.code==="ENOTDIR")return null;throw o}try{let o=tn(n);if(!o.isFile())throw new Error(`${e} is not a regular file`);if(o.size>t)throw new Error(`${e} is over ${t} bytes`);let r=Buffer.alloc(o.size),s=0;for(;s<o.size;){let a=rn(n,r,s,o.size-s,s);if(a===0)break;s+=a}return r.subarray(0,s)}finally{en(n)}}var Kr=256*1024,Zr=1024*1024;function Ge(e,t){try{let n=typeof e.repo_dir=="string"?D(e.repo_dir):e.repo_dir,o=t===null?null:D(t),r=e.repo_via,s=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:r==="gh"&&process.env.GH_REPO||null;if(typeof n!="string"||!sn(n)||!U(n)||r!=="git"&&r!=="gh"||/[$`]/.test(s??""))return null;if(r==="gh"&&s!==null)return Ue([s],n);let a=ln(n,o);if(a===null)return null;let c=new Map;for(let i of a)i.section==="remote"&&i.sub!==null&&(i.key==="url"||(r==="git"?i.key==="pushurl":i.key==="gh-resolved"&&i.value!=="base"))&&c.set(i.sub,[...c.get(i.sub)??[],i.value]);if(s!==null&&!c.has(s)&&!/^[./]|[/:]/.test(s))return null;let u=s!==null?c.get(s)??[s]:[...c.values()].flat();if(s===null)for(let i of a)(i.section==="branch"&&/^(push)?remote$/.test(i.key)||i.section==="remote"&&i.sub===null&&i.key==="pushdefault")&&i.value!=="."&&!c.has(i.value)&&u.push(i.value);let d=new Set(u);for(let i of u)for(let l of a)l.section==="url"&&l.sub!==null&&/^(push)?insteadof$/.test(l.key)&&l.value&&i.startsWith(l.value)&&d.add(l.sub+i.slice(l.value.length));return d.size>0?Ue([...d],n):null}catch{return null}}function Ue(e,t){let n=[];for(let o of e){let r=decodeURIComponent(o.trim()),s=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(r)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(r),c=(s?an.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(r)&&!r.startsWith(".")?r:I(t,r)).replace(/[?#].*$/,"").split(/[\\/]/).filter(f=>f&&f!=="."),u=c.findIndex((f,m)=>m>=2&&/^pulls?$/.test(f));u>=2&&(c=c.slice(0,u));let[d,i]=c.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),l=i??d;if(!l||l==="..")return null;n.push(i!==void 0&&d!==".."?`${d}/${i}`:l)}return n}function ln(e,t){let n=process.env;if(n.GIT_CONFIG_COUNT||n.GIT_CONFIG_PARAMETERS||n.GIT_DIR||n.GIT_COMMON_DIR)return null;let o=cn(e);if(o===null)return null;let r=process.platform==="win32"?[C(n.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),C(n.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(d=>`${d}/gitconfig`),s=n.GIT_CONFIG_NOSYSTEM?[]:n.GIT_CONFIG_SYSTEM?[n.GIT_CONFIG_SYSTEM]:r;n.GIT_CONFIG_GLOBAL?s.push(n.GIT_CONFIG_GLOBAL):t&&s.push(C(n.XDG_CONFIG_HOME||C(t,".config"),"git","config"),C(t,".gitconfig")),s.push(C(o.common,"config"),C(o.gitDir,"config.worktree"));let a=[],c=24,u=(d,i)=>{let l=--c<0||i>5?void 0:M(d,1048576);if(l===void 0)return!1;for(let f of un(l?.toString("utf8")??""))if(a.push(f),f.key==="path"&&/^include(if)?$/.test(f.section)){let m=f.value.startsWith("~/")?t&&C(t,f.value.slice(2)):!/^[~%]/.test(f.value)&&I(se(d),f.value);if(!m||!u(m,i+1))return!1}return!0};return s.every(d=>u(d,0))?a:null}function cn(e){let t=n=>/^(ref: refs\/|[0-9a-f]{40})/.test(M(C(n,"HEAD"),4096)?.toString("utf8")??"");for(let n=I(e),o=0;o<64;o++,n=se(n)){let r=C(n,".git"),s=["objects","refs"].every(a=>U(C(n,a)))&&t(n)?n:null;if(U(r)){let a=He(r);if(a.isDirectory())t(r)&&(s=r);else if(s=a.isFile()?/^gitdir:\s*(.+)$/m.exec(M(r,65536)?.toString("utf8")??"")?.[1]?.trim():null,!s)return null}if(s){let a=I(n,s),c=M(C(a,"commondir"),65536),u=c===null?a:I(a,c.toString("utf8").trim());for(let d of["remotes","branches"]){let i=C(u,d);if(U(i)&&(!He(i).isDirectory()||on(i).length>0))return null}return{gitDir:a,common:u}}if(se(n)===n)return null}return null}function un(e){let t=[],n="",o=null;for(let r of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){r=r.trim();let s=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(r);if(s){let[c,...u]=s[1].toLowerCase().split(".");n=c,o=s[2]?.replace(/\\(.)/g,"$1")??(u.length>0?u.join("."):null),r=r.slice(s[0].length).trim()}let a=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(r);a&&t.push({section:n,sub:o,key:a[1].toLowerCase(),value:a[2]===void 0?"true":a[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(c,u,d)=>u??d??"").trim()})}return t}var dn={slack:"channel",github:"repo",linear:"team",jira:"project"};var fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function x(e,t,n=!1){let o=e==="jira"&&typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?String(t):t;if(typeof o!="string")return null;let r=o.normalize("NFKC").trim().replace(/^(["'])(.*)\1$/,"$2");if(!r||r.length>300||/[$`\u0000-\u001f]/.test(r)||/[^\u0000-\u007f]/.test(r)&&new RegExp("\\p{Script=Latin}","u").test(r)&&new RegExp("(?!\\p{Script=Latin})\\p{L}","u").test(r))return null;if(e==="slack"){if(r=/^<#([A-Z0-9]+)(?:\|[^>]*)?>$/.exec(r)?.[1]??/\/archives\/([A-Z0-9]{6,})(?:[/?#]|$)/.exec(r)?.[1]??r,r.startsWith("@")||/^[DUW][A-Z0-9]{6,}$/.test(r))return"dm";if(/^[A-Z0-9]+$/.test(r))return/^[CG][A-Z0-9]{6,}$/.test(r)?`id:${r}`:null;let c=r.replace(/^#/,"").toLowerCase();return/^[a-z0-9][a-z0-9._-]{0,79}$/.test(c)||/^[\p{L}\p{N}][\p{L}\p{N}._-]{0,79}$/u.test(c)?`name:${c}`:null}if(e==="github"){let c=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s?#]+)/i.exec(r)??/^https?:\/\/(?:api|uploads)\.github\.com\/repos\/([^/\s]+)\/([^/\s?#]+)/i.exec(r)??/^([\w.-]+)\/([\w.-]+)$/.exec(r),u=i=>/^[\w.-]+$/.test(i)&&!/^\.+$/.test(i),d=i=>i.toLowerCase().replace(/\.git$/,"");return c?u(c[1])&&u(c[2])?`repo:${d(c[1])}/${d(c[2])}`:null:u(r)?`repo:?/${d(r)}`:null}let s=e==="linear"?"[A-Za-z][A-Za-z0-9]{0,6}":"[A-Z][A-Z0-9_]{1,9}",a=new RegExp(`^(${s})-\\d+$`).exec(r)??new RegExp(`(?:/issue/|/browse/)(${s})-\\d+`).exec(r);return a?`key:${a[1].toLowerCase()}`:n?null:(e==="linear"?fn.test(r):/^\d+$/.test(r))?`id:${r.toLowerCase()}`:new RegExp(`^${e==="linear"?"[A-Z0-9]{1,7}":"[A-Z][A-Z0-9_]{1,9}"}$`).test(r)?`key:${r.toLowerCase()}`:`name:${r.toLowerCase().replace(/\s+/g," ")}`}function P(e,t){if(!t||e!=="linear"&&e!=="jira"||!t.startsWith("name:"))return[t??"?"];let n=t.slice(5);return(e==="linear"?/^[a-z][a-z0-9]{0,6}$/:/^[a-z][a-z0-9_]{1,9}$/).test(n)?[`key:${n}`,t]:[t]}var ae={slack:/^(?:(?:to|target|dest|destination|source|from|in)_?)?(?:channel|conversation)s?(?:_?(?:ids?|names?|url|link))?$|^(?:target|chat_?id|permalink|message_?(?:url|link))$/i,github:/^(?:(?:parent|item|base|head|target|source)_?)?(?:repo|repository)(?:_?name)?s?$|^(?:repo_?full_?name|full_?name|name_?with_?owner|html_?url|pull_?request_?url|issue_?url)$/i,linear:/^(?:new_?)?team(?:_?(?:id|key|name))?s?$/i,jira:/^projects?(?:_?(?:key|id|id_?or_?key))?s?$/i},Ke={linear:/^(?:id|ids|issues?|issue_?ids?|identifiers?|issue_?identifiers?|parent_?id|url)$/i,jira:/^(?:key|keys|issues?|issue_?keys?|issue_?ids?|issue_?id_?or_?key|parent|parent_?key|url)$/i},pn=/^(?:user|users|user_?ids?|recipient|recipients)$/i,gn=/^(?:arguments|args|params|parameters|input|data|payload|body|request|message|fields|issue|issues|items|options|update)$/i,ie=/^channels?$|^channel_ids?$/,mn=/^(?:text|body|title|description|content|comment|summary|markdown|blocks|attachments)$/i;function hn(e,t){let n=0,o=(r,s)=>++n>2e3||s>6?!1:typeof r=="string"?P(e.app,x(e.app,r)).some(a=>Ve(e,a)):Array.isArray(r)?r.slice(0,200).some(a=>o(a,s+1)):!!(r&&typeof r=="object")&&Object.entries(r).some(([a,c])=>!mn.test(a)&&!ae[e.app].test(a)&&!Ke[e.app]?.test(a)&&o(c,s+1));return o(t,0)}function Ze(e,t,n=!1){if(!t)return null;let o=[],r=0,s=(a,c,u)=>{for(let[d,i]of Object.entries(a)){if(++r>2e3)return void o.push("?");let l=u?"":"~",f=Array.isArray(i)?i:[i];f.length>200&&o.push("?");let m=f.slice(0,200).flatMap(p=>p&&typeof p=="object"&&!Array.isArray(p)?["key","id","name"].map(h=>p[h]).filter(h=>h!==void 0):e==="slack"&&typeof p=="string"?p.split(","):[p]);if(ae[e].test(d)||Ke[e]?.test(d)){let p=!ae[e].test(d),h=e==="github"?/^(.*?)(_?)(?:repo|repository)(?:_?name)?$/i.exec(d):null,g=h?a[`${h[1]}${h[2]}owner`]:void 0;for(let y of m.length>0?m:[void 0])for(let b of P(e,x(e,typeof g=="string"&&typeof y=="string"&&!y.includes("/")?`${g.trim()}/${y.trim()}`:y,p)))o.push(b==="?"?"?":`${l}${b}`)}else if(e==="slack"&&pn.test(d))for(let p of m)o.push(x("slack",p)==="dm"?`${l}dm`:"?");else if(c<6&&i&&typeof i=="object")for(let p of f.slice(0,200))p&&typeof p=="object"&&!Array.isArray(p)&&s(p,c+1,n||u&&c<2&&gn.test(d))}};return s(t,0,!0),o.length>0?o.every(a=>a.startsWith("~"))?[...o,"?"]:o:null}function yn(e){let t=[],n="",o=null;for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"&&o!=="'"){n+=s+(e[++r]??"");continue}if(o)o=s===o?null:o;else if(s==="'"||s==='"')o=s;else if(s===";"||s==="&"||s==="|"||s===`
12
- `){n.trim()&&t.push(n),n="";continue}n+=s}return n.trim()&&t.push(n),t}function Ye(e){let t=[],n="",o=null,r=!1;for(let s=0;s<e.length;s++){let a=e[s];o==="'"?a==="'"?o=null:n+=a:o==='"'?a==='"'?o=null:n+=a==="\\"&&s+1<e.length?e[++s]:a:a==="'"||a==='"'?(o=a,r=!0):a==="\\"?(n+=e[++s]??"",r=!0):/\s/.test(a)?((n||r)&&t.push(n),n="",r=!1):(n+=a,r=!0)}return o?null:((n||r)&&t.push(n),t)}var Be=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`/${e.replace(/^\/+/,"")}`,"https://x").pathname}catch{return"\0"}};function wn(e){let t=Ye(e),n=t?t.findIndex(d=>/(?:^|\/)gh$/.test(d)):-1;if(!t||n<0)return["?"];let o=t.slice(0,n).flatMap(d=>d.startsWith("GH_REPO=")?[d.slice(8)]:[]).pop(),r=t.slice(n+1),s;for(let d=0;d<r.length;d++){let i=r[d];i==="-R"||i==="--repo"?s=r[++d]??"":i.startsWith("--repo=")?s=i.slice(7):/^-R[^-]/.test(i)?s=i.slice(2):/^-[A-Za-z]+R/.test(i)&&(s="?")}let a=r[0]==="repo"&&r[1]!=="rename"&&r[2]!==void 0&&!r[2].startsWith("-")?r[2]:void 0,c=s??o??a,u=r.filter(d=>/^https?:\/\/(?:www\.)?github\.com\/[^/]+\/[^/]+\/(?:pull|issues)\/\d+/i.test(d)).map(d=>`~${x("github",d)??"?"}`);return[c===void 0?"none":x("github",c)??"?",...u]}var bn=(e,t)=>Ge(e.attributes,t.home)?.map(n=>x("github",n)??"?")??["?"];function $n(e,t){let n=Ye(t),o=n?n.findIndex(i=>/(?:^|\/)(?:curl|wget)$/.test(i)):-1;if(!n||o<0)return["?"];let r=[],s=[],a=n.slice(o+1);for(let i=0;i<a.length;i++){let l=a[i],f=/^(--data(?:-ascii|-binary|-raw|-urlencode)?|--json|--form(?:-string)?|--post-data|--body-data)(?:=([\s\S]*))?$/.exec(l);f?r.push(f[2]??a[++i]??""):l==="-d"||l==="-F"?r.push(a[++i]??""):/^-[dF]./.test(l)?r.push(l.slice(2)):/^https?:\/\//i.test(l)&&s.push(l)}let c=[],u=i=>{for(let l of[i].flat().flatMap(f=>typeof f=="string"?f.split(","):[f]))c.push(...P(e,x(e,l)))},d=i=>{let l=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!l)return void c.push("?");if(e==="slack"){let f=Object.keys(l).filter(m=>ie.test(m));f.length===0&&c.push("?");for(let m of f)u(l[m])}else if(e==="jira"){let f=(l.fields&&typeof l.fields=="object"?l.fields:l).project,m=f&&typeof f=="object"?f:null;c.push(...m?[m.key,m.id].filter(p=>p!==void 0).flatMap(p=>P(e,x(e,p))):["?"])}else{let f=Ze("linear",l.variables??{},!0)??[],p=[...(typeof l.query=="string"?l.query:"").matchAll(/\b(teamId|teamKey|team|id|issueId|identifier)\s*:\s*"([^"\\]{1,100})"/g)].flatMap(h=>P(e,x(e,h[2],!/^team/.test(h[1])))).map(h=>`~${h}`);c.push(...f,...p,...f.length===0?["?"]:[])}};for(let i of s)try{for(let[l,f]of new URL(i).searchParams)e==="slack"&&ie.test(l)&&u(f)}catch{c.push("?")}for(let i of r){if(/^@|^[\w-]*@/.test(i)){c.push("?");continue}let l;try{l=JSON.parse(i)}catch{l=void 0}if(l!==void 0)d(l);else if(e==="slack"&&/^[\w-]+=/.test(i)){let f=i.split("&").map(m=>[m.slice(0,m.indexOf("=")<0?m.length:m.indexOf("=")),m.slice(m.indexOf("=")+1)]);for(let[m,p]of f){if(!ie.test(m))continue;let h=p;try{h=decodeURIComponent(p.replace(/\+/g," "))}catch{c.push("?");continue}u(h)}}else c.push("?")}return c.length>0?c:["?"]}var Je=e=>/^[a-z][a-z-]*\s+[a-z][a-z-]*$/.test(e)||!/[/:]/.test(e)&&e!=="graphql"&&e.length>0;function kn(e,t,n){let o=t.target??"";if(e==="slack"&&/hooks\.slack\.com/i.test(`${t.host??""} ${o}`))return["?"];let r=e==="github"&&Je(o);if(e==="github"&&!r){let i=Be(o),l=/^\/repos\/([^/]+)\/([^/]+)/.exec(i)??(/^https?:\/\/(?:www\.)?github\.com\//i.test(o)?/^\/([^/]+)\/([^/]+)/.exec(i):null);return[l?x("github",`${l[1]}/${l[2]}`)??"?":"?"]}let s=e==="jira"?/\/rest\/api\/(?:2|3|latest)\/(issue|project)\/([^/]+)/.exec(Be(o)):null;if(s)return P("jira",x("jira",s[2],s[1]==="issue"));let a=n.command??(typeof n.input?.command=="string"?n.input.command:"");if(a.length>65536)return["?"];let c=yn(a),u=c.filter(i=>r?/(?:^|[\s/])gh\s/.test(i)&&(/\s/.test(o)?i.includes(o.split(/\s+/)[1]):i.includes(o)):o.length>0&&i.includes(o)),d=i=>r?wn(i).flatMap(l=>l==="none"?bn(t,n):[l]):$n(e,i);return u.length>0?u.flatMap(d):[...c.flatMap(d).filter(i=>i!=="?"&&!i.startsWith("~")).map(i=>`~${i}`),"?"]}function vn(e,t){return t==="dm"?e.app==="slack":e.app==="slack"?t.startsWith("name:"):e.app==="github"?t.startsWith("repo:")&&!(t.startsWith("repo:?/")&&e.is.some(n=>n.endsWith(`/${t.slice(7)}`))):e.as!==void 0&&t.startsWith(`${e.as}:`)}function Ve(e,t){return e.is.includes(t)?!0:e.app!=="github"||!t.startsWith("repo:")?!1:e.is.includes(`repo:${t.startsWith("repo:?/")?t.slice(7):t.slice(t.indexOf("/")+1)}`)}var G=e=>e.startsWith("key:")?e.slice(4).toUpperCase():e.replace(/^(?:name|id|repo):(?:\?\/)?/,"");function Xe(e,t,n){let o=dn[e.app],r=e.said.replace(/^in /,""),s=t.action==="claude.mcp.side_effect"?Ze(e.app,n.input):kn(e.app,t,n),a=`Anvil can't tell which ${o} this acts in${e.app==="github"&&t.action!=="claude.mcp.side_effect"&&Je(t.target??"")?" (gh says it with --repo)":""}`;if(!s||s.length===0)return{hit:"unknown",why:a};let c=s.map(i=>i.replace(/^~/,"")).find(i=>Ve(e,i));if(c)return{hit:"match",detail:c.startsWith("id:")?`${G(c)} is ${r}`:e.app==="github"?G(c):r};let u=s.find(i=>i==="?"||i.startsWith("~")||!(e.not??[]).includes(i)&&!vn(e,i));if(u===void 0)return t.action==="claude.mcp.side_effect"&&hn(e,n.input)?{hit:"unknown",why:`Anvil can't tell whether this acts in ${r}: the call names it in a field Anvil doesn't read`}:null;let d=u.replace(/^~/,"");return{hit:"unknown",why:d==="?"?a:`Anvil can't tell whether ${d.startsWith("id:")?`${o} ${G(d)}`:G(d)} is ${r}`}}function ao(e,t,n){switch(e.type){case"amount":return ve(e,t,n);case"recipient":return De(e,t,n);case"part":return Xe(e,t,n);case"when":return Fe(e,t,n)}}async function lo(){}export{vt as capMoved,ao as matchCondition,lo as preloadConditions};
1
+ function E(e){return Object.assign(Object.create(null),e)}var ue=[{app:"stripe",name:"Stripe",minor:!0,obj:null,servers:["stripe"],clis:["stripe"],hosts:["api.stripe.com"],at:{create_refund:["amount"],"/v1/refunds":["amount"],"/v1/charges":["amount"],"/v1/charges/*/capture":["amount"],"/v1/payment_intents":["amount"],"/v1/payment_intents/*":["amount"],"/v1/payment_intents/*/capture":["amount_to_capture"],"/v1/payment_intents/*/increment_authorization":["amount"],"/v1/payouts":["amount"],"/v1/transfers":["amount"],"/v1/transfers/*/reversals":["amount"],"/v1/topups":["amount"],"refunds create":["amount"],"charges create":["amount"],"charges capture":["amount"],"payment_intents create":["amount"],"payment_intents update":["amount"],"payment_intents capture":["amount_to_capture"],"payment_intents increment_authorization":["amount"],"payouts create":["amount"],"transfers create":["amount"],"topups create":["amount"]},digits:{isk:2,ugx:2},nameless:["create_refund","/v1/refunds","refunds create"],unread:{invoice:"Stripe adds it up from items added one call at a time, and can bill it on its own"}},{app:"paypal",name:"PayPal",minor:!1,json:!0,obj:["value","currency_code","currency"],servers:["paypal"],clis:[],hosts:["paypal.com"],at:{create_refund:["amount"],record_payment_for_invoice:["amount"],record_refund_for_invoice:["amount"],pay_order:[],"/v2/payments/captures/*/refund":["amount"],"/v2/payments/authorizations/*/capture":["amount"],"/v2/checkout/orders":["purchase_units.*.amount"],"/v2/checkout/orders/*/capture":[],"/v1/payments/payouts":["items.*.amount"],"/v2/invoicing/invoices/*/payments":["amount"],"/v2/invoicing/invoices/*/refunds":["amount"]},invoices:{create_invoice:["items.*.unit_amount \xD7 quantity","$currency_code","!items.*.tax","!items.*.discount","!shipping_cost","!allow_tip"],update_invoicing:["invoice_update.items.*.unit_amount \xD7 quantity","$invoice_update.currency_code","!invoice_update.items.*.tax","!invoice_update.items.*.discount","!invoice_update.shipping_cost","!invoice_update.allow_tip","!recurring_series_update"],"/v2/invoicing/invoices":["items.*.unit_amount \xD7 quantity","$detail.currency_code","!items.*.tax","!items.*.discount","!amount","!configuration.template_id","!configuration.allow_tip"],"/v2/invoicing/invoices/*":["items.*.unit_amount \xD7 quantity","$detail.currency_code","!items.*.tax","!items.*.discount","!amount","!configuration.template_id","!configuration.allow_tip"]}},{app:"square",name:"Square",minor:!0,json:!0,obj:["amount","currency"],servers:["square","squareup"],clis:[],hosts:["squareup.com","squareupsandbox.com"],at:{"make_api_request payments create":["request.amount_money","request.tip_money"],"make_api_request refunds payment":["request.amount_money"],"/v2/payments":["amount_money","tip_money"],"/v2/refunds":["amount_money"]},unread:{invoice:"it bills an order made by a call of its own"}},{app:"shopify",name:"Shopify",minor:!1,json:!0,obj:null,servers:["shopify"],clis:[],hosts:["myshopify.com"],changes:["refund"],at:{"/admin/api/*/graphql.json refundCreate":["input.transactions.*.amount","~input.shipping.amount"],"/admin/api/*/orders/*/refunds.json":["refund.transactions.*.amount","~refund.shipping.amount"]},nameless:["/admin/api/*/graphql.json refundCreate","/admin/api/*/orders/*/refunds.json"]}];var de=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,et=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,tt=/(?:^|[^a-z])(?:api|request|requests|execute|exec|run|call|invoke|http|graphql|rpc|raw|batch|bulk|action|actions|command|operation|perform|proxy|custom|query|sql|services|hooks?|webhooks?|triggers?)(?:[^a-z]|$)/,fe=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),pe=(e,t)=>e.split("+").every(n=>n[0]==="="?t.split(/[^a-z0-9]+/).includes(n.slice(1)):t.includes(n));function nt(e,t){let n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),s=t.replace(/_/g,"");return e.servers.some(r=>{let o=r.replace(/_/g,"");return`_${t}_`.includes(`_${r}_`)||n.includes(`_${r}_`)||(o.length>4?s.includes(o):o.length>3&&(s.startsWith(o)||s.endsWith(o)))})}function rt(e,t,n){let s=t.normalize("NFKC").toLowerCase().replace(/\.+$/,""),r=/^[a-z0-9.-]+$/.test(s);if(!s.includes("."))return r?(e.clis??[]).includes(s)?"this":"other":"?";let o=s.split("."),i=u=>s===u||s.endsWith(`.${u}`)||u.includes("*")&&u.split(".").every((d,a,l)=>l.length===o.length&&(d==="*"||d===o[a])),c=!1;return e.hosts.some(u=>{let d=u.indexOf("/");return d<0?i(u):(c||=i(u.slice(0,d))&&/^(?:\/batch\/?|\u0000)$/.test(n),i(u.slice(0,d))&&n.includes(u.slice(d)))})?"this":r&&!c?"other":"?"}function ot(e){if(!e||!/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;try{return new URL(e).hostname.replace(/^\[|\]$/g,"")}catch{return"\0"}}function N(e,t,n,s){let r=fe(n);return e.toolWords.length===0||e.toolWords.some(o=>pe(o,r))?{hit:"match",part:t,why:e.said}:s===3||/\u0000|%00/.test(r)||tt.test(r)||!/[a-z]{3}/.test(r.replace(/[a-z]*\d[a-z0-9]*/g,""))||s===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(r)?{hit:"unknown",part:t,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function st(e,t,n){let s=l=>({hit:"unknown",part:t,why:`Anvil can't tell ${l}, so it holds it (your rule: ${e.said})`});if(t.action==="claude.mcp.side_effect"){let l=t.host;if(!l)return s("which app this tool belongs to");let f=`mcp.${l}.`,m=fe(n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):t.target?.startsWith(f)?t.target.slice(f.length):"");if(nt(e,l))return N(e,t,m,1);let p=(e.anywhere??[]).some(g=>pe(g,m))?{hit:"match",part:t,why:e.said}:null;if(!de.test(l)&&!et.test(l))return p;let h=e.toolPrefixes.find(g=>m.startsWith(g));return h?N(e,t,m.slice(h.length),1):e.servers.some(g=>g.length>2&&`_${m}_`.includes(`_${g}_`))?N(e,t,m,1):p||(e.others??[]).includes(l)?p:s(`which app ${de.test(l)?`the connector ${l.slice(0,8)}\u2026`:l} acts on`)}let r=t.target??"",o=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(r)?`https://${r}`:r,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(o),c="";try{i&&(c=decodeURIComponent(new URL(o).pathname).replace(/\/{2,}/g,"/"))}catch{c="\0"}if(!t.host&&!t.service)return s("where this writes");let u=[t.host,t.service,...Array.isArray(t.attributes.hosts)?t.attributes.hosts:[],ot(o)].filter(l=>typeof l=="string"&&l!==""),d=u.map(l=>rt(e,l,c)),a=[r,...u].some(l=>/^smtps?[:.]/i.test(l));if(d.includes("this")||a&&e.hosts.includes("smtp:")){let l=u.find((m,p)=>d[p]==="this"&&!m.includes(".")),f=r.includes("/")?3:2;return l?N(e,t,`cli:${l.toLowerCase()} ${r}`,f):a?N(e,t,"send mail",2):i?N(e,t,c,3):N(e,t,r,f)}return d.includes("?")?s(`where this writes (${u[0].replace(/[\u0000-\u001f]/g,"")})`):n.tool?.startsWith("mcp__")?s("what else this tool's command writes"):null}function K(e,t,n){let s=null;for(let r of t){let o=st(e,r,n);if(o?.hit==="match")return o;s??=o}return s??(n.parts.length>15&&t[0]?{hit:"unknown",part:t[0],why:`Anvil can't read everything this line does, so it holds it (your rule: ${e.said})`}:null)}var it={over:"over",at_least:"at least",under:"under",at_most:"at most"};var $="Anvil can't read how much this moves",we="Anvil can't read this invoice's total (only drafting or replacing one says it)",at="Anvil can't add up this total (a tax, a discount, shipping, a tip, a template or a series changes it)",ge="Anvil can't tell which currency this moves (it names two)",lt="Anvil can't tell how many requests this makes (curl expands {\u2026} and [\u2026] in a URL)",V="claude.mcp.side_effect",ct=/\$\(|\$'|\$"|`|<<|(?:^|[\s;&|])(?:eval|xargs|source|exec)(?=\s|$)|\b(?:ba|z|k|da)?sh\s+-\w*c\b/,ut=/^(?:[A-Za-z_]\w*=.*|env|sudo|time|nohup|command|builtin|nice)$/,dt="012346#aBfgGiIjJklLMnNOpqRsSvVZ",ft=/^(?:silent|show-error|fail(?:-with-body|-early)?|location(?:-trusted)?|insecure|compressed|include|show-headers|verbose|http1\.[01]|http2(?:-prior-knowledge)?|http3(?:-only)?|globoff|progress-bar|raw|path-as-is|ssl-reqd|tlsv1(?:\.[0-3])?|ipv[46]|tcp-nodelay|remote-name(?:-all)?|remote-header-name|create-dirs|digest|basic|ntlm|negotiate|anyauth|crlf|append|junk-session-cookies|list-only|disable|netrc(?:-optional)?|proxytunnel|parallel|retry-all-errors|retry-connrefused|no-[a-z0-9-]+|get|head)$/,pt=/^(?:data(?:-raw|-binary|-ascii|-urlencode)?|form(?:-string)?|json)$/,gt=/^(?:live|confirm|help|version|dark_style|show_headers|dry_run|reverse_transfer|refund_application_fee|capture|final_capture)$/;function O(e){let t=(e.host??"").toLowerCase(),n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),s=ue.filter(r=>e.action===V?r.servers.some(o=>`_${t}_`.includes(`_${o}_`)||n.includes(`_${o}_`)):r.clis.includes(t)||r.hosts.some(o=>t===o||t.endsWith(`.${o}`)));return s.length===1?s[0]:null}function mt(e){let t=[[]],n="",s=!1,r=!1,o=!1,i=!1,c=!1,u=!1,d=()=>{c&&u?u=!1:c&&t[t.length-1].push({w:n,d:s,x:r,g:o}),n="",s=r=o=i=c=!1};for(let a=0;a<e.length;a++){let l=e[a];if(l==="'"){let f=e.indexOf("'",a+1);if(f<0)return null;n+=e.slice(a+1,f),a=f,i=!0}else if(l==='"'){let f=a+1;for(;f<e.length&&e[f]!=='"';f++){if(e[f]==="\\"&&e[f+1]===`
2
+ `){f++;continue}e[f]==="\\"&&/["\\$`]/.test(e[f+1]??"")?f++:e[f]==="$"&&(s=!0),n+=e[f]}if(f>=e.length)return null;a=f,i=!0}else if(l==="\\"){if(a++,e[a]!==`
3
+ `)n+=e[a]??"",i=!0;else if(!c)continue}else if(l==="#"&&!c){if(a=e.indexOf(`
4
+ `,a)-1,a<0)break;continue}else{if(/[(){}]/.test(l))return null;if(l==="<"||l===">"||l==="&"&&e[a+1]===">"){if((i||!/^\d+$/.test(n))&&d(),n="",s=r=o=i=c=!1,u)return null;l==="&"&&a++,(e[a]===">"?/[>|&]/:/[&>]/).test(e[a+1]??"")&&a++,u=!0;continue}else if(/[;|&\n]/.test(l)){if(d(),u)return null;t[t.length-1].length>0&&t.push([]);continue}else if(l===" "||l===" "){d();continue}else{if(/\s/.test(l))return null;l==="$"&&(s=r=!0),/[*?[]/.test(l)&&(o=!0),n+=l}}c=!0}return d(),u?null:t}function be(e,t){let n=t.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1").split("/");return Object.keys(e).filter(s=>{let r=s.split(" ")[0].split("/");return s[0]==="/"&&r.length===n.length&&r.every((o,i)=>o==="*"?n[i]!=="":o===n[i])})}var Y=e=>e.filter(t=>t[0]!=="!"&&t[0]!=="$").map(t=>t.replace(/^~/,"").split(" ")[0]);function T(e,t){return[...new Set(e.map(n=>n.split(".").pop()))].reduce((n,s)=>n+(t.match(new RegExp(`(?:(?<![a-z0-9_]|[a-z0-9]-)|(?<=(?:^|\\s)-[a-z]+))${s.replace(/_/g,"[-_]")}(?![a-z0-9_]|-[a-z0-9])`,"gi"))?.length??0),0)}function X(e,t,n,s,r){let o=[],i=[],c=0;for(let d of t){let a=/^[!~$]/.test(d)?d[0]:"",[l="",f]=d.slice(a.length).split(" \xD7 "),m=[{v:n,up:null,curs:[]}];for(let p of l.split(".")){let h=[];for(let{v:g,curs:y}of m)if(g!=null){if(p==="*"?!Array.isArray(g):typeof g!="object"||Array.isArray(g))return $;if(p==="*")h.push(...g.map(b=>({v:b,up:null,curs:y})));else if(Object.hasOwn(g,p)){let b=g;h.push({v:b[p],up:b,curs:b.currency===void 0?y:[...y,b.currency]})}}m=h.filter(g=>g.v!==void 0&&g.v!==null)}if(a==="!"&&m.some(p=>p.v!==!1))return at;if(a==="~"&&(c+=m.length),a==="$")for(let{v:p}of m){if(typeof p!="string")return $;i.push(p.toLowerCase())}if(!a)for(let{v:p,up:h,curs:g}of m){let y=f===void 0?void 0:h?.[f];if(f!==void 0&&y==null)return $;if(e.obj){if(typeof p!="object"||Array.isArray(p))return $;{let b=p,w=[...new Set(e.obj.slice(1).map(k=>b[k]).filter(k=>k!==void 0))];o.push({v:b[e.obj[0]],cur:w.length>1?"?":w[0],q:y})}}else{let b=[...new Set(g)];o.push({v:p,cur:b.length>1?"?":b[0],drop:r,q:y})}}}if(i.length>0){if(new Set(i).size>1)return ge;for(let[d,a]of o.entries())if(a.cur===void 0)o[d]={...a,cur:i[0]};else if(typeof a.cur!="string"||a.cur.toLowerCase()!==i[0])return ge}let u=Y(t);return Math.max(T(u,s),T(u,JSON.stringify(n)))>o.length+c?$:o}var Z=/[\s,]+|#[^\n\r]*|("(?:[^"\\\n\r]|\\.)*")|(\.\.\.|[!$&():=@[\]{|}])|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([_A-Za-z]\w*)/y;function ht(e,t,n,s){let r=s,o=r?.variables??{},i=r?.query;if(!r||typeof r!="object"||Array.isArray(r)||typeof i!="string"||i.includes('"""')||typeof o!="object"||Array.isArray(o))return $;let c=[];for(Z.lastIndex=0;Z.lastIndex<i.length;){let h=Z.exec(i);if(!h)return $;let g=h[1]??h[2]??h[3]??h[4];g!==void 0&&c.push(g)}let u=0,d=()=>c[u],a=h=>{let g=c[u++];if(g===void 0||h!==void 0&&g!==h)throw new Error;return g},l=()=>{let h=a();if(!/^[_A-Za-z]/.test(h))throw new Error;return h},f=()=>{let h=a();if(h==="$"){let g=l();if(!Object.hasOwn(o,g))throw new Error;return o[g]}if(h==="["){let g=[];for(;d()!=="]";)g.push(f());return a(),g}if(h==="{"){let g={};for(;d()!=="}";){let y=l();a(":"),g[y]=f()}return a(),g}if(h[0]==='"')return JSON.parse(h);if(/^-?\d/.test(h))return h;if(/^[_A-Za-z]/.test(h))return h==="true"?!0:h==="false"?!1:h==="null"?null:h;throw new Error},m=()=>{let h={};if(d()!=="(")return h;for(a();d()!==")";){let g=l();a(":"),h[g]=f()}return a(),h},p=()=>{for(let h=1;h>0;){let g=a();h+=g==="{"?1:g==="}"?-1:0}};try{let h="query";if(d()!=="{"&&(h=a(),d()!=="("&&d()!=="{"&&l(),d()==="(")){for(a();a()!==")";)if(c[u-1]==="=")throw new Error}a("{");let g=[];if(h==="query")p();else{if(h!=="mutation")throw new Error;for(;d()!=="}";){let y=l();d()===":"&&(a(),y=l());let b=m();for(;d()==="@";){if(a(),l()!=="idempotent")throw new Error;m()}d()==="{"&&(a(),p());let w=n.find(k=>k.endsWith(` ${y}`));g.push(w?X(e,t[w],b,JSON.stringify(b),e.nameless?.includes(w)):$)}if(a(),g.length===0)throw new Error}if(u<c.length)throw new Error;return h==="query"?"read":g}catch{return $}}var z=(e,t,n)=>{e.set(t,[...e.get(t)??[],n])};function $e(e,t,n,s){let r=Y(e);if([...t.keys()].some(d=>!e.includes(d)&&T(r,d)>0))return $;let o=t.get("currency")??[],i=d=>d.some(a=>a.d)||new Set(d.map(a=>a.w)).size>1?"?":d[0]?.w,c=[],u=0;for(let d of e){let a=t.get(d)??[];if(u+=a.length,a.length===0)continue;let l=i(a);if(l==="?")return $;c.push({v:l,cur:o.length>0?i(o):void 0,drop:s})}return T(Y(e),n)>u?$:c}function J(e,t,n){let s=t.w.indexOf("=");if(s<=0||t.w.slice(0,s).includes("$"))return!1;let r=t.w.slice(0,s),o=t.w.slice(s+1);try{r=decodeURIComponent(r.replace(/\+/g," ")),n&&(o=decodeURIComponent(o.replace(/\+/g," ")))}catch{return!1}return z(e,r,{w:o,d:t.d&&o.includes("$"),x:!1}),!0}function yt(e,t,n,s,r){let o=[],i=new Map;for(let l=0;l<n.length;l++){let{w:f,d:m}=n[l];if(f.startsWith("--")){let p=f.indexOf("="),h=(p<0?f.slice(2):f.slice(2,p)).replace(/-/g,"_");if(p<0&&gt.test(h))continue;let g=p>=0?{w:f.slice(p+1),d:m,x:!1}:n[++l];if(!g||p<0&&/^-./.test(g.w))return $;if(h==="data"){if(!J(i,g,!1))return $}else z(i,h,g)}else if(/^-./.test(f)){let p=1;for(;p<f.length&&"chs".includes(f[p]);)p++;if(p===f.length)continue;let h=p+1<f.length?{w:f.slice(p+1),d:m,x:!1}:n[++l];if(!h||p+1===f.length&&/^-./.test(h.w)||f[p]==="d"&&!J(i,h,!1))return $}else o.push(n[l])}let[c="",u=""]=o.map(l=>l.w);if(c==="get"||u==="list"||u==="retrieve")return"read";let d=`${c} ${u}`,a=Object.hasOwn(t,d)?d:/^(?:post|delete)$/.test(c)&&u[0]==="/"?be(t,u.split("?")[0]).find(l=>!l.includes(" ")):void 0;if(!a)return r;if(a!==d){if(o[1].d)return $;for(let[l,f]of new URLSearchParams(u.includes("?")?u.slice(u.indexOf("?")+1):""))z(i,l,{w:f,d:!1,x:!1})}return $e(t[a],i,s,!!e.nameless?.includes(a))}function wt(e){try{return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?new URL(e):/^[\w-]+(?:\.[\w-]+)+(?::\d+)?(?:\/|$)/.test(e)?new URL(`https://${e}`):null}catch{return null}}var bt=(e,t)=>{let n=wt(t);return n&&e.hosts.some(s=>n.hostname===s||n.hostname.endsWith(`.${s}`))?n:null};function $t(e,t,n,s,r){let o=null,i="",c="",u=!1,d=!1,a=[];for(let y=0;y<n.length;y++){let{w:b,d:w}=n[y];if(b.startsWith("--")){let k=b.slice(2);if(/^(?:next|config|variable|expand-.*|upload-file)$|=/.test(k))return $;if(/^(?:no-)?(?:get|head)$/.test(k)&&(u=k[0]!=="n"),/^(?:no-)?globoff$/.test(k)&&(d=k[0]!=="n"),ft.test(k))continue;let _=n[++y];if(!_)return $;pt.test(k)?a.push({v:_,how:k}):k==="request"&&(c=_.w.toUpperCase())}else if(/^-./.test(b))for(let k=1;k<b.length;k++){let _=b[k];if(_==="K"||_===":"||_==="T")return $;if((_==="G"||_==="I")&&(u=!0),_==="g"&&(d=!0),dt.includes(_))continue;let A=k+1<b.length?{w:b.slice(k+1),d:w,x:!1}:n[++y];if(!A)return $;_==="d"||_==="F"?a.push({v:A,how:_==="d"?"data":"form"}):_==="X"&&(c=A.w.toUpperCase());break}else{let k=bt(e,b);if(!k)continue;if(w||o)return $;o=k,i=b}}if(!o)return null;if(/^(?:GET|HEAD|OPTIONS)$/.test(c||(u||a.length===0?"GET":"POST")))return"read";if(!d&&/[{}[\]]/.test(i))return lt;if(e.json&&u&&a.length>0)return $;let l;try{l=decodeURIComponent(o.pathname)}catch{return $}let f=be(t,l),m=f.find(y=>!y.includes(" "));if(!m&&f.length===0)return r;let p=new Map;for(let[y,b]of o.searchParams)z(p,y,{w:b,d:!1,x:!1});let h;for(let{v:y,how:b}of a){let w=y.w.trim();if(w[0]==="{"||w[0]==="["){if(y.d||h!==void 0)return $;try{h=JSON.parse(w)}catch{return $}}else for(let k of w.split("&"))if(!J(p,{w:k,d:y.d,x:!1},!/urlencode|form/.test(b)))return $}if((h!==void 0||e.json)&&p.size>0)return $;if(!m){let y=h===void 0||p.size>0?$:ht(e,t,f,h);return typeof y=="string"?y:{many:y}}let g=!!e.nameless?.includes(m);return h!==void 0?X(e,t[m],h,s,g):$e(t[m],p,s,g)}function kt(e,t,n,s){let r=n.input?.command,o=typeof r=="string"&&!ct.test(r)?mt(r):null;if(!o)return $;let i=[],c=new RegExp([...e.servers,...e.clis].join("|"),"i");for(let u of o){let d=u.map(p=>p.w).join(" "),a=0;for(;a<u.length&&ut.test(u[a].w);)a++;let l=(u[a]?.w??"").replace(/^.*\//,""),f=u.slice(a+1),m=e.clis.includes(l)?yt(e,t,f,d,s):l==="curl"?$t(e,t,f,d,s):null;if(m===null){if(!/^(?:cd|pushd)$/.test(l)&&u.some(p=>c.test(p.w)))return $;continue}if(f.some(p=>p.x||p.g&&!p.w.includes("://")))return"Anvil can't read a word the shell expands (an unquoted $ or *)";m!=="read"&&i.push(...typeof m=="object"&&!Array.isArray(m)?m.many:[m])}return i.length<n.parts.filter(u=>O(u)===e).length?$:i}var Q="this call doesn't say how much it moves",me=e=>typeof e=="number"?Number.isFinite(e)&&e>=0?String(e):"":typeof e=="string"?e.trim():"",he=/^(\d+)(?:\.(\d+))?$/;function ke(e,t,n){if(e.length===0)return Q;let s=0n,r=0;for(let{v:o,cur:i,drop:c,q:u}of e){let d=c&&(i===void 0||typeof i=="string"&&i.toLowerCase()===n.currency)?void 0:i,a=d===void 0?n.bare?n.currency:null:typeof d=="string"&&/^[a-z]{3}$/i.test(d)?d.toLowerCase():"?";if(a===null)return"Anvil can't tell which currency this moves";if(a!==n.currency)return a==="?"?$:`it's in ${a.toUpperCase()}, not ${n.currency.toUpperCase()}`;let l=(t.minor?/^(\d+)()$/:he).exec(me(o)),f=u===void 0?null:he.exec(me(u));if(!l||u!==void 0&&!f||(l[1]+(l[2]??"")).length>30||f!==null&&(f[1]+(f[2]??"")).length>30)return $;let m=(t.minor?t.digits?.[a]??n.digits:(l[2]??"").length)+(f?.[2]??"").length,p=Math.max(r,m);s=s*10n**BigInt(p-r)+BigInt(l[1]+(l[2]??""))*BigInt(f?f[1]+(f[2]??""):1)*10n**BigInt(p-m),r=p}return[s,r]}function ye(e,t,n){let s=e.toString().padStart(t+1,"0"),r=s.slice(0,s.length-t),o="";for(let i=r.length;i>0;i-=3)o=`${r.slice(Math.max(0,i-3),i)}${o?`,${o}`:""}`;return`${n}${o}${t>0?`.${s.slice(-t)}`:""}`}function ve(e,t,n){let s=O(t),r=e.invoice?s?.invoices:s?.at,o=n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):"",i=n.input,c=!i||Object.hasOwn(r??{},o)?o:`${o} ${String(i.service).toLowerCase()} ${String(i.method)}`,u=e.invoice?we:$;return!s||!r||!e.apps.includes(s.app)?$:t.action!==V?kt(s,r,n,u):i&&Object.hasOwn(r,c)?[X(s,r[c],i,JSON.stringify(i),s.nameless?.includes(c))]:u}function vt(e,t,n){let s=ve(e,t,n);if(typeof s=="string")return s;if(s.length===0)return Q;let r=0n;for(let o of s){let i=typeof o=="string"?o:ke(o,O(t),e);if(typeof i=="string")return i;let[c,u]=i,d=10n**BigInt(Math.abs(u-e.digits));r+=u<=e.digits?c*d:(c+d-1n)/d}return r<=BigInt(Number.MAX_SAFE_INTEGER)?Number(r):"Anvil can't count an amount that large"}function _t(e,t){let n=e.money;if(!n||!/^[a-z]{3}$/.test(n.currency)||!Number.isInteger(n.digits)||n.digits<0||n.digits>4||!Array.isArray(n.apps))return"Anvil can't use this cap's currency";let s=t?.parts.filter(i=>e.kinds.includes(i.action)&&(!e.match||K(e.match,[i],t)!==null))??[];if(s.length===0)return"Anvil can't tell how much this moves";let r=0,o=new Set;for(let i of s){let c=O(i),u=c?`${c.app}\0${i.action===V}`:null;if(u!==null&&o.has(u))continue;u!==null&&o.add(u);let d=vt(n,i,t);if(typeof d=="string")return d;r+=d}return Number.isSafeInteger(r)?r:"Anvil can't count an amount that large"}function _e(e,t,n){try{return Ct(e,t,n)}catch{return{hit:"unknown",why:"Anvil can't read the amount this moves"}}}function Ct(e,t,n){let s=O(t),r=ve(e,t,n),o=c=>e.invoice&&c===Q?we:c;if(typeof r=="string")return{hit:"unknown",why:o(r)};let i=null;for(let c of r){let u=typeof c=="string"?c:ke(c,s,e);if(typeof u=="string"){i??=u;continue}let[d,a]=u,l=Math.max(a,e.digits),f=d*10n**BigInt(l-a),m=BigInt(e.value)*10n**BigInt(l-e.digits),[p,h]=[f,l];for(;h>e.digits&&p%10n===0n;)[p,h]=[p/10n,h-1];if(e.op==="over"?f>m:e.op==="at_least"?f>=m:e.op==="under"?f<m:f<=m)return{hit:"match",detail:`${ye(p,h,e.sign)} is ${it[e.op]} ${ye(BigInt(e.value),e.digits,e.sign).replace(/\.0+$/,"")}`}}return i===null?null:{hit:"unknown",why:o(i)}}import{existsSync as G,readdirSync as an,statSync as Ue}from"fs";import{dirname as ae,isAbsolute as ln,join as C,posix as cn,resolve as W}from"path";import{posix as On}from"path";var xt=null;function D(){return xt??process.platform==="win32"}function Ce(e){if(!D())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 F(e){return D()?Ce(e)??e:e}import{createHash as Wr}from"crypto";import{appendFileSync as zr,closeSync as nn,constants as He,fstatSync as rn,mkdirSync as Dr,openSync as on,readdirSync as Fr,readFileSync as qr,readSync as sn,renameSync as Hr,statSync as Ur,unlinkSync as Gr,writeFileSync as Br}from"fs";import{homedir as Zr}from"os";import{dirname as Jr,join as Vr}from"path";import{domainToASCII as At}from"url";var Rt="to cc bcc torecipients ccrecipients bccrecipients toaddresses ccaddresses bccaddresses toaddress ccaddress bccaddress rcptto recipient recipients attendee attendees optionalattendees requiredattendees guests invitees recipientemail extrarecipients toemail toemails ccemails bccemails",Nt="klaviyo himalaya convertkit api.kit.com activecampaign api-us1.com activehosted constantcontact constant_contact api.cc.email beehiiv helpscout help_scout freshdesk substack",ne=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),St=null,re={has:e=>(St??=new Set(Rt.split(" "))).has(e)},Pe=/^(?:from|sender|replyto|returnpath|envelopefrom|mailfrom|bounce)|^(?:useremail|usergoogleemail|account|accountemail|organizer|owner|user|mailbox|asm)$/,oe=/(?:contact|member|participant|attendee|guest|invitee|person|people|subscriber|customer|recipient|audience|segment|list|group)(?:id|ids|s)?$|userids$|identifiers$|campaignids?$/,Ee=/^(?:draft|(?:draft|message|msg|email|thread|conversation|originalmessage|replytomessage|parentmessage)ids?|inreplyto|references)$/,jt=/^(?:instructions?|prompt|task)$/,Oe=/ids?$/,Me=/^(?:subject|body|text|html|content|contents|textbody|htmlbody|htmlcontent|textcontent|textpart|htmlpart|message|comment|description|summary|title|location|notes?|signature|snippet|preheader|plaintext|markdown|name|displayname)$|body$|html$/,Pt=/^(?:email|emailaddress|address|mail|addr)$/,Et=null,Ot={exec:e=>(Et??=new RegExp(`(?:^|[^a-z0-9])(${Nt.replace(/\./g,"\\.").replace(/ /g,"|")})`)).exec(e)},se=/send.{0,20}draft|draft.{0,20}send|(?<!no-?)reply|\/messages\/[^/?\s]+\/[^?\s]{0,200}send/,Ie=/\$batch|(?:^|[^a-z])(?:batch|jmap)(?:[^a-z]|$)|multi_?execute|(?:^|[^a-z])execute(?:[^a-z]|$)|graphql|(?:^|[^a-z])(?:api_?)?request(?:[^a-z]|$)/,Mt=/^(?:all|everyone|everybody|team|staff|group|list|lists|members|announce(?:ments)?|all-?hands|employees|company)$|^(?:all|team|list|everyone)[._-]|[._-](?:all|team|list|group|members|announce|everyone|staff)$|[%!]/,It=/(?:^|\.)(?:googlegroups\.com|groups\.io)$|^(?:lists?|groups?)\./;function ie(e){let t=At(e.normalize("NFKC").toLowerCase().replace(/\.$/,""));return/^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$/.test(t)?t:""}function Lt(e){let t=e.trim().replace(/^mailto:/i,""),n=/<([^<>]*)>$/.exec(t);n&&(t=n[1].trim());let s=t.length;for(;s>0&&`"'`.includes(t[s-1]);)s--;t=t.slice(0,s).replace(/^["']+/,"");let r=/^([^\s@<>(),;:"[\]]+)@([^\s@<>(),;:"[\]]+)$/u.exec(t),o=r?ie(r[2]):"";if(!o)return null;let i=r[1].normalize("NFKC").toLowerCase().replace(/(?<=.)\+.*$/,"");return(o==="gmail.com"||o==="googlemail.com")&&(i=i.replace(/\./g,""),o="gmail.com"),{shown:t,local:i,domain:o,alien:/[^\x00-\x7f]/.test(t)||/(?:^|\.)xn--/.test(o),group:Mt.test(i)||It.test(o)}}function U(e){let t=[],n=!/[<"]/.test(e),s="",r=!1,o=!1;for(let i=0;i<e.length;i++){let c=e[i];if(r&&c==="\\"){s+=c+(e[++i]??"");continue}c==='"'?r=!r:c==="<"?o=!0:c===">"&&(o=!1),!r&&!o&&(c===","||c===";"||n&&/\s/.test(c))?(t.push(s),s=""):s+=c}return t.push(s),r||o?[null]:t.filter(i=>i.trim()).map(i=>(i.replace(/"(?:[^"\\]|\\.)*"/g,"").match(/@/g)??[]).length===1?Lt(i):null)}var v="Anvil can't read who this goes to",j="Anvil can't read who this goes to: it is built when the line runs",xe="Anvil can't read who this goes to: its body can't be read",I="Anvil can't read who this goes to: a reply, or a draft sent by its id, goes to whoever the thread or the draft names",Le="Anvil can't read who this goes to: it runs a batch, or any request";function S(e,t){for(let n of U(e))n?(t.list.push(n),t.known=!0):t.why??=`${v} ("${e.trim().slice(0,40)}")`}function We(e,t){let n=e.includes(`
5
+ `)?e:Buffer.from(e,"base64").toString("utf8"),s=/\r?\n\r?\n/.exec(n),r=s?n.slice(0,s.index+s[0].length):n;(!/^[\w-]+:/.test(r)||/\r(?!\n)/.test(r)||n.includes(`\r
6
+ `)&&/(?<!\r)\n/.test(r))&&(t.why??=`${v}: its message can't be read`);for(let o of r.replace(/\r?\n[ \t]+/g," ").split(/\r?\n/)){let i=/^(?:resent-)?(?:to|cc|bcc)\s*:/i.exec(o);i&&S(o.slice(i[0].length),t)}}function Ae(e){let t=0;for(let n=0;n<e.length;n++){if(e[n]!=='"')continue;for(n++;n<e.length&&e[n]!=='"';n++)e[n]==="\\"&&n++;let s=n+1;for(;/\s/.test(e[s]??"");)s++;e[s]===":"&&t++}return t}function Te(e,t){let n;try{n=/^\s*[[{]/.test(e)?JSON.parse(e):void 0}catch{n=void 0}return n!==void 0&&Ae(e)!==Ae(JSON.stringify(n))&&(t.why??=`${v}: it names a field twice`),n}function R(e,t,n=!1,s=0,r=!1,o=!1){if(s>12)t.why??=v;else if(typeof e=="string"){if(n)S(e,t);else if(!r&&!/[\s@]/.test(e)&&/[/_.]/.test(e)&&se.test(e.toLowerCase()))t.why??=I;else if(!r){let i=Te(e,t),c=i===void 0?U(e):[];if(i!==void 0)R(i,t,!1,s+1,!1,o);else if(c.length>0&&c.every(u=>u!==null))for(let u of c)t.list.push(u);else/[^\s@]@[^\s@.]+\.[^\s@]/.test(e)&&(t.why??=`${v} ("${e.trim().slice(0,40)}")`)}}else if(Array.isArray(e))for(let i of e)R(i,t,n,s+1,r,o);else if(e&&typeof e=="object"){let i=!1;for(let[c,u]of Object.entries(e)){let d=ne(c);u==null||u===""||Array.isArray(u)&&u.length===0||(n?Pt.test(d)&&(i=!0,R(u,t,!0,s+1)):re.has(d)?R(u,t,!0,s+1):d==="raw"&&typeof u=="string"?We(u,t):(Ee.test(d)||d==="id"&&s===0)&&(typeof u!="object"||Array.isArray(u))?(!o||d.startsWith("draft"))&&(t.why??=I):oe.test(d)?t.why??=`${v}: it names a list ("${c}")`:jt.test(d)?t.why??=`${v}: another tool picks who it reaches`:d==="calendarid"&&typeof u=="string"&&!/calendar\.google\.com$/i.test(u)?R(u,t,!1,s+1,r,o):!Pe.test(d)&&!Oe.test(d)&&R(u,t,!1,s+1,r||Me.test(d),o))}n&&!i&&(t.why??=v)}else n&&e!==null&&e!==void 0&&(t.why??=v)}var ee=(e,t)=>e[t]==="`"||e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="(";function Wt(e){let t=[],n=[],s=!1,r=[],o=[],i="",c=!1,u=!1,d=0,a=[],l=()=>{u&&(d?d===2&&!/^(?:\d+|-)$/.test(i)&&n.push({f:i,dyn:c}):(r.push(i),o.push(c)),d=0),i="",c=u=!1},f=()=>{l(),r.length>0&&t.push({w:r,dyn:o}),r=[],o=[]};for(let m=0;m<e.length;m++){let p=e[m],h=e[m+1];if(p==="\\")h!==void 0&&h!==`
7
+ `&&(i+=h,u=!0),m++;else if(p==="'"||p==="$"&&h==="'"){let g=p==="$"?m+2:m+1,y=e.indexOf("'",g);i+=e.slice(g,y<0?void 0:y),c||=p==="$"||y<0,u=!0,m=y<0?e.length:y}else if(p==='"'){let g=m+1;for(;g<e.length&&e[g]!=='"';g++){let y=e[g+1];e[g]==="\\"&&y!==void 0&&'"\\$`\n'.includes(y)?i+=e[++g]===`
8
+ `?"":y:(s||=ee(e,g),c||=e[g]==="$"||e[g]==="`",i+=e[g])}c||=g>=e.length,u=!0,m=g}else if(p==="$"||p==="`")s||=ee(e,m),i+=p,c=u=!0;else if(p==="#"&&!u){let g=e.indexOf(`
9
+ `,m);m=(g<0?e.length:g)-1}else if(p==="<"&&h==="<"&&e[m+2]!=="<"){l();let g=/^<<(-?)[ \t]*((?:[^\s;&|<>()'"\\]|'[^']*'|"[^"]*"|\\.)+)/.exec(e.slice(m));g&&a.push([g[2].replace(/'([^']*)'|"([^"]*)"|\\(.)/g,"$1$2$3"),g[1]==="-",/['"\\]/.test(g[2])]),m+=(g?.[0].length??2)-1}else if(p==="<"||p===">"||p==="&"&&h===">"){/^\d+$/.test(i)&&!c&&(u=!1),l();let g=p;for(;/[<>&|]/.test(e[m+1]??"");)g+=e[++m];d=g.includes(">")?2:1}else if(/[;&|()\n]/.test(p)){if(f(),p===`
10
+ `)for(let[g,y,b]of a.splice(0)){let w=m+1;for(;;){let k=e.indexOf(`
11
+ `,w),_=e.slice(w,k<0?void 0:k);if(w=k<0?e.length:k+1,k<0||(y?_.replace(/^\t+/,""):_)===g)break;for(let A=0;!b&&A<_.length;A++)_[A]==="\\"?A++:s||=ee(_,A)}m=w-1}}else/\s/.test(p)?l():(i+=p,u=!0)}return f(),{list:t,sub:s,writes:n}}function Tt(e){let t=0;for(;t<e.w.length&&(/^[A-Za-z_]\w*\+?=/.test(e.w[t])||/^(?:env|sudo|doas|nohup|exec|command|time|nice|stdbuf)$/.test(e.w[t])||t>0&&e.w[t].startsWith("-"));)t++;let n=e.w[t];return n!==void 0&&!e.dyn[t]?{name:(/^(?:\/(?:usr\/(?:local\/)?|opt\/(?:homebrew|local)\/)?s?bin\/)?[^/]+$/.test(n)?n.slice(n.lastIndexOf("/")+1):n).toLowerCase(),at:t+1}:null}var te=["srAaSqTOuC","cb","tfHE"],Re=["sifmQd","cb","HeF"],zt=E({mail:te,mailx:te,"s-nail":te,sendmail:["fFOpRVNLBXh","","tC"],msmtp:["afCX","","t"],mutt:Re,neomutt:Re}),Ne=/^\s*(?:to|cc|bcc)\s*:/i,q="Anvil can't read who this goes to: it may read them from the message or its settings";function Dt(e,t,n,s,r){let o=zt[e];if(!o){let a=!1;for(let l=s;l<t.length;l++){let f=/^(?:--(to|cc|bcc|recipients?|attendees?)|-(t))(?:=([^]*))?$/.exec(t[l]);if(!f||f[2]&&e!=="swaks")continue;let m=f[3]??t[++l];a=!0,m===void 0||n[l]?r.why??=j:S(m,r)}a||(r.why??=v);return}let[i,c,u]=o,d=!1;for(let a=s;a<t.length;a++){let l=t[a];if(d||!l.startsWith("-")||l==="-")n[a]?r.why??=j:S(l,r);else if(l==="--")d=!0;else if(l.startsWith("--")){let f=/^--([\w-]+)(=?)/.exec(l),m=f?.[1]??"";if(/^(?:append|subject|return-address|from|attach|content-type|encoding|account|host|port|user)$/.test(m)){let p=f?.[2]?l.slice(l.indexOf("=")+1):t[++a];p!==void 0&&Ne.test(p)&&(n[a]?r.why??=j:S(p.slice(p.indexOf(":")+1),r))}else/^(?:norc|nosum|ignore|quit|debug|verbose|auth|tls|read-envelope-from|skip-empty-attachments)$/.test(m)||(r.why??=q)}else if(e==="sendmail"&&/^-b[^m]/.test(l))r.why??=q;else if(/mutt/.test(e)&&l.startsWith("-a"))for(;a+1<t.length&&t[a+1]!=="--";)a++;else for(let f=1;f<l.length;f++){let m=l[f];if(u.includes(m)&&(r.why??=q),!i.includes(m)&&!c.includes(m))continue;let p=f+1<l.length?l.slice(f+1):t[++a];/^\s*(?:sendmail|mta)\s*=/i.test(p??"")&&(r.why??=q),n[a]&&"aTC".includes(m)&&i.includes(m)&&(r.why??=j);let h=p!==void 0&&Ne.test(p);if(!c.includes(m)&&!h)break;p===void 0||n[a]?r.why??=j:S(h?p.slice(p.indexOf(":")+1):p,r);break}}}function Se(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`)}catch{return null}}var Ft="AbcCdDeEFHKmoPQrtTuUwxXyYz",qt=/^(?:data(?:-ascii|-binary|-raw|-urlencode)?|json|form(?:-string)?|url|header)$/,je=/^(?:config|upload-file|url-query|variable|request-target|mail-rcpt|expand-[\w.-]+)$/,Ht=/^(?:request|user|user-agent|referer|cookie|cookie-jar|output|output-dir|dump-header|max-time|connect-timeout|retry|retry-delay|retry-max-time|max-redirs|write-out|oauth2-bearer|cacert|capath|cert|key|cert-type|key-type|pass|proto|proto-default|proto-redir|limit-rate|max-filesize|aws-sigv4|mail-from|mail-auth|noproxy|keepalive-time|expect100-timeout|tls-max|ciphers|interface|stderr|trace|trace-ascii|libcurl|etag-save|etag-compare|hsts|alt-svc|range|continue-at|time-cond|speed-limit|speed-time|netrc-file)$/,Ut=/^(?:silent|show-error|fail|fail-with-body|fail-early|location|location-trusted|verbose|include|insecure|compressed|http1\.0|http1\.1|http2|http2-prior-knowledge|http3|globoff|get|head|progress-bar|progress-meter|ipv4|ipv6|tlsv1\.2|tlsv1\.3|ssl-reqd|retry-all-errors|retry-connrefused|path-as-is|disable|tcp-nodelay|buffer|keepalive|clobber|remote-name|remote-name-all|create-dirs|netrc|netrc-optional|junk-session-cookies|raw|tr-encoding|trace-time|styled-output|parallel|parallel-immediate|anyauth|basic|digest|ntlm|negotiate|post301|post302|post303|ca-native|form-escape|remove-on-error)$/,Gt=/^(?:[oDc]|output|output-dir|dump-header|cookie-jar|stderr|trace|trace-ascii|libcurl|etag-save|hsts|alt-svc)$/,H="Anvil can't read who this goes to: curl takes part of it from elsewhere";function M(e,t,n){(t||/(?:^|\/)(?:\.?(?:curlrc|mailrc|nailrc|muttrc|msmtprc)|mail\.rc|s-nail\.rc|curl|mailx?|s-nail|sendmail|msmtp|(?:neo)?mutt|swaks)$|\/\.?(?:curl|mutt|msmtp|s-nail)\//.test(e))&&(n.why??=`${v}: this line writes a file a send may read or run (${e.slice(0,60)})`)}function Bt(e,t,n,s,r,o){let i=0,c=0,u=[],d=[],a=!1,l=!1,f=e.some((p,h)=>h>=n&&(/^-[^-]*O/.test(p)||p.startsWith("--remote-name"))),m=p=>{if(!r(p))return;let h=Se(p);if(h?.hostname.toLowerCase().replace(/\.$/,"")!==s)o.why??=`${v}: a URL Anvil reads two ways`;else{c++;let g=h.pathname.toLowerCase();try{g=decodeURIComponent(g)}catch{o.why??=v}se.test(g)?o.why??=I:Ie.test(g)&&(o.why??=Le);for(let[y,b]of h.searchParams)u.push([y,b,!1,!1])}};for(let p=n;p<=e.length;p++){let h=e[p];if(h===void 0||h==="--next"||h==="-:"){if(c>0){i++;for(let w of d)Kt(w,a&&!l,u,o);Zt(u,o)}[c,u,d,a,l]=[0,[],[],!1,!1];continue}let g="",y;if(h.startsWith("--")){let w=/^--([\w.-]+)(=?)/.exec(h);if(g=w?.[1]??"",Ut.test(g.replace(/^no-/,"")))continue;if(g==="remote-header-name"||!qt.test(g)&&!je.test(g)&&!Ht.test(g)){o.why??=g==="remote-header-name"?H:`${v}: curl takes an option Anvil doesn't know (--${g.slice(0,40)})`;continue}y=w?.[2]?h.slice(h.indexOf("=")+1):e[++p]}else if(h.startsWith("-")&&h.length>1){for(let w=1;w<h.length&&!g;w++)h[w]==="J"&&(o.why??=H),Ft.includes(h[w])&&(g=h[w],y=h.slice(w+1)||e[++p]);if(!g)continue}else{if(f){let w=Se(h)?.pathname.split("/").pop()??"";M(w,!1,o);try{M(decodeURIComponent(w),!1,o)}catch{o.why??=v}}m(h);continue}if(y===void 0){o.why??=v;break}let b=t[p]??!1;if(/^[KT]$/.test(g)||je.test(g))o.why??=H;else if(g==="url")m(y);else if(g==="H"||g==="header"){let w=/^\s*content-type\s*:/i.exec(y);y.startsWith("@")?o.why??=H:w?/json/i.test(y.slice(w[0].length))&&!b?a=!0:l=!0:b&&!/^\s*[\w-]+\s*:/.test(y)&&(l=!0)}else if(Gt.test(g))M(y,b,o);else if(g==="F"||g.startsWith("form")||g==="data-urlencode"){let w=y.indexOf("="),k=y.indexOf("@"),_=g==="data-urlencode"?k>=0&&(w<0||k<w):g!=="form-string"&&/^[@<]/.test(y.slice(w+1));u.push([w>0?y.slice(0,w):"",y.slice(w+1),b,_])}else(g==="d"||g.startsWith("data")||g==="json")&&(b||g!=="data-raw"&&y.startsWith("@")?o.why??=`${v}: its body is ${b?"built when the line runs":"read from a file"}`:(a||=g==="json",d.push(y)))}return i}function Kt(e,t,n,s){let r=Te(e,s);if(r!==void 0?R(r,s):t&&(s.why??=xe),!t){r===void 0&&/^[\w-]+\s*:/.test(e)&&We(e,s);for(let o of e.split("&")){let i=o.indexOf("=");try{let c=decodeURIComponent(o.slice(0,Math.max(i,0)).replace(/\+/g," "));/^[\w.[\]-]*$/.test(c)&&(r===void 0||c.split(/[.[\]]+/).map(ne).some(u=>re.has(u)||oe.test(u)))&&n.push([c,decodeURIComponent(o.slice(i+1).replace(/\+/g," ")),!1,!1])}catch{s.why??=xe}}}}function Zt(e,t){for(let[n,s,r,o]of e){let i=n.split(/[.[\]]+/).map(ne).filter(Boolean),c=i[i.length-1]??"";if(i.some(u=>re.has(u)))o||r?t.why??=`${v}: it is ${o?"read from a file":"built when the line runs"}`:S(s,t);else if(i.some(u=>oe.test(u)))t.why??=`${v}: it names a list ("${n}")`;else if(i.some(u=>Ee.test(u)))t.why??=I;else{if(i.some(u=>Pe.test(u))||Oe.test(c)||i.some(u=>Me.test(u)))continue;r?t.why??=j:o||R(s,t)}}}var Yt=/^(?:echo|printf|cat|jq|grep|egrep|fgrep|head|tail|wc|cut|tr|date|sleep|true|false|:|cd|pwd|ls|test|\[|export|unset|column|fold|rev|nl|paste|basename|dirname|realpath|mkdir|touch|tee|curl)$/;function Jt(e,t,n,s){let r=t.includes("."),o=new RegExp(`(?<![\\w.-])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-]|\\.\\w)`),i=l=>o.test(l.replace(/['"\\]/g,"").toLowerCase()),{list:c,sub:u,writes:d}=Wt(e);u&&(s.why??=`${v}: this line runs a command inside another ($(\u2026) or \`\u2026\`), which Anvil doesn't read`);for(let l of d)M(l.f,l.dyn,s);let a=0;for(let l of c){let f=Tt(l);if(((f?.name==="export"?l.w:l.w.slice(0,f?f.at-1:void 0)).some(m=>/^(?:\w*PATH|path|\w*HOME|\w*RC|LD_\w*|DYLD_\w*|(?:BASH_)?ENV)\+?=/.test(m))||f?.name==="printf"&&l.w.slice(f.at).some(m=>/^-\w*v/.test(m)))&&(s.why??=`${v}: this line sets where a program or its settings come from`),f?.name==="tee")for(let m=f.at;m<l.w.length;m++)l.w[m].startsWith("-")||M(l.w[m],l.dyn[m],s);!f&&l.w.every(m=>/^[A-Za-z_]\w*\+?=/.test(m))||(f&&r&&f.name==="curl"?a+=Bt(l.w,l.dyn,f.at,t,i,s):f&&!r&&f.name===t?(a++,Dt(f.name,l.w,l.dyn,f.at,s)):(!f||!Yt.test(f.name))&&(s.why??=`${v}: this line also runs ${f?f.name:"a command built when it runs"}, which Anvil doesn't read`))}(a===0||a<n)&&(s.why??=`${v}: Anvil reads a plain curl request or mail program, not this`)}function ze(e,t){let n={list:[],why:null},s=(e.host??"").toLowerCase(),r=e.action==="claude.mcp.side_effect",o=`${s} ${r?t.tool??"":/^[a-z][a-z0-9+.-]*:\/\//i.test(e.target??"")?e.target:""}`.toLowerCase(),i=Ot.exec(o)?.[1];return i?n.why=`Anvil can't read who ${i} sends reach: they go to a list or a ticket`:se.test(o)?n.why=I:Ie.test(o)?n.why=Le:r&&t.input?R(t.input,n,!1,0,!1,/forward/.test((t.tool??"").split("__").pop().toLowerCase())):!r&&t.command&&s?Jt(t.command,s,t.parts.filter(c=>c.action===e.action&&(c.host??"").toLowerCase()===s).length,n):n.why=v,n.known||(n.why??=v),n}function Vt(e){let t=i=>Array.isArray(i)&&i.every(c=>typeof c=="string")?i:null,n=t(e.domains??[]),s=t(e.addresses??[]);if(!n||!s)return"a recipient condition's domains and addresses must be lists";if(e.outside!==void 0&&e.outside!==!0)return"a recipient condition's outside must be true";let r=n.map(ie),o=s.map(i=>{let[c,u]=U(i);return c&&!u?`${c.local}@${c.domain}`:""});return r.includes("")||o.includes("")?"a recipient condition names an address or a domain Anvil can't read":r.length+o.length===0?"a recipient condition needs an address or a domain":{type:"recipient",said:String(e.said),...e.outside===!0?{outside:!0}:{},domains:r,addresses:o}}var De=new WeakMap;function Fe(e,t,n){let s=De.get(e);if(s===void 0&&De.set(e,s=Vt(e)),typeof s=="string")return{hit:"unknown",why:`Anvil can't use this rule's recipients (${s})`};let r;try{r=ze(t,n)}catch{return{hit:"unknown",why:"Anvil can't read who this goes to"}}let o=r.why;for(let i of r.list){let c=s.addresses.includes(`${i.local}@${i.domain}`)||s.domains.some(u=>i.domain===u||i.domain.endsWith(`.${u}`));if(s.outside?!c:c)return{hit:"match",detail:s.outside?`${i.shown} is outside ${[...s.domains,...s.addresses.length>0?["the addresses your rule names"]:[]].join(" and ")}`:`it goes to ${i.shown}`};i.group?o??=`${i.shown} may reach ${s.outside?"people outside":"anyone"} (a list or a relay)`:i.alien&&!s.outside&&(o??=`${i.shown} is in letters from another alphabet`)}return o===null?null:{hit:"unknown",why:o}}var Xt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");function Qt(e,t){if(e&&/^:?[+-]?\d/.test(e))return!0;let n=e?/^:?(?:<[^>]*>|[a-z]{3,})([+-]?)(\d{1,2})(?::(\d\d))?(<|[a-z]{3})?/i.exec(e):null;if(!n)return!1;let s=(n[1]==="-"?1:-1)*(Number(n[2])*60+Number(n[3]??0)),r=-t.getTimezoneOffset();return r!==s&&!(n[4]!==void 0&&r===s+60)}function qe(e,t,n){let s=new Date(n.now??NaN),r=s.getDay(),o=s.getHours(),i=o*60+s.getMinutes();if(!((n.now??0)>0&&r>=0))return{hit:"unknown",why:"Anvil can't tell when this call was made"};let c=process.env.TZ,u=`:${String(i%60).padStart(2,"0")}`;if(c!==void 0||s.getTimezoneOffset()===0){let d="";try{let a=Intl.DateTimeFormat().resolvedOptions().timeZone;a&&!Qt(c,s)&&(d=s.toLocaleTimeString("en-GB",{timeZone:a,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}))}catch{}if(d!==`${String(o).padStart(2,"0")}${u}`)return{hit:"unknown",why:`Anvil can't read your Mac's time zone${c===void 0?"":` (TZ is "${c}")`}`}}return e.at.some(d=>d.days.includes(r)&&i>=d.from&&i<d.to)?{hit:"match",detail:`it's ${Xt[r]} ${o%12||12}${u}${o<12?"am":"pm"}`}:null}import{existsSync as or,readdirSync as sr,realpathSync as ir}from"fs";import{basename as lr,dirname as cr,join as ur}from"path";function L(e,t=8*1024*1024){let n;try{n=on(e,He.O_RDONLY|He.O_NONBLOCK)}catch(s){if(s.code==="ENOENT"||s.code==="ENOTDIR")return null;throw s}try{let s=rn(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 i=sn(n,r,o,s.size-o,o);if(i===0)break;o+=i}return r.subarray(0,o)}finally{nn(n)}}var Qr=256*1024,eo=1024*1024;function Be(e,t){try{let n=typeof e.repo_dir=="string"?F(e.repo_dir):e.repo_dir,s=t===null?null:F(t),r=e.repo_via,o=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:r==="gh"&&process.env.GH_REPO||null;if(typeof n!="string"||!ln(n)||!G(n)||r!=="git"&&r!=="gh"||/[$`]/.test(o??""))return null;if(r==="gh"&&o!==null)return Ge([o],n);let i=un(n,s);if(i===null)return null;let c=new Map;for(let a of i)a.section==="remote"&&a.sub!==null&&(a.key==="url"||(r==="git"?a.key==="pushurl":a.key==="gh-resolved"&&a.value!=="base"))&&c.set(a.sub,[...c.get(a.sub)??[],a.value]);if(o!==null&&!c.has(o)&&!/^[./]|[/:]/.test(o))return null;let u=o!==null?c.get(o)??[o]:[...c.values()].flat();if(o===null)for(let a of i)(a.section==="branch"&&/^(push)?remote$/.test(a.key)||a.section==="remote"&&a.sub===null&&a.key==="pushdefault")&&a.value!=="."&&!c.has(a.value)&&u.push(a.value);let d=new Set(u);for(let a of u)for(let l of i)l.section==="url"&&l.sub!==null&&/^(push)?insteadof$/.test(l.key)&&l.value&&a.startsWith(l.value)&&d.add(l.sub+a.slice(l.value.length));return d.size>0?Ge([...d],n):null}catch{return null}}function Ge(e,t){let n=[];for(let s of e){let r=decodeURIComponent(s.trim()),o=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(r)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(r),c=(o?cn.resolve("/",o[1]??o[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(r)&&!r.startsWith(".")?r:W(t,r)).replace(/[?#].*$/,"").split(/[\\/]/).filter(f=>f&&f!=="."),u=c.findIndex((f,m)=>m>=2&&/^pulls?$/.test(f));u>=2&&(c=c.slice(0,u));let[d,a]=c.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),l=a??d;if(!l||l==="..")return null;n.push(a!==void 0&&d!==".."?`${d}/${a}`:l)}return n}function un(e,t){let n=process.env;if(n.GIT_CONFIG_COUNT||n.GIT_CONFIG_PARAMETERS||n.GIT_DIR||n.GIT_COMMON_DIR)return null;let s=dn(e);if(s===null)return null;let r=process.platform==="win32"?[C(n.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),C(n.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(d=>`${d}/gitconfig`),o=n.GIT_CONFIG_NOSYSTEM?[]:n.GIT_CONFIG_SYSTEM?[n.GIT_CONFIG_SYSTEM]:r;n.GIT_CONFIG_GLOBAL?o.push(n.GIT_CONFIG_GLOBAL):t&&o.push(C(n.XDG_CONFIG_HOME||C(t,".config"),"git","config"),C(t,".gitconfig")),o.push(C(s.common,"config"),C(s.gitDir,"config.worktree"));let i=[],c=24,u=(d,a)=>{let l=--c<0||a>5?void 0:L(d,1048576);if(l===void 0)return!1;for(let f of fn(l?.toString("utf8")??""))if(i.push(f),f.key==="path"&&/^include(if)?$/.test(f.section)){let m=f.value.startsWith("~/")?t&&C(t,f.value.slice(2)):!/^[~%]/.test(f.value)&&W(ae(d),f.value);if(!m||!u(m,a+1))return!1}return!0};return o.every(d=>u(d,0))?i:null}function dn(e){let t=n=>/^(ref: refs\/|[0-9a-f]{40})/.test(L(C(n,"HEAD"),4096)?.toString("utf8")??"");for(let n=W(e),s=0;s<64;s++,n=ae(n)){let r=C(n,".git"),o=["objects","refs"].every(i=>G(C(n,i)))&&t(n)?n:null;if(G(r)){let i=Ue(r);if(i.isDirectory())t(r)&&(o=r);else if(o=i.isFile()?/^gitdir:\s*(.+)$/m.exec(L(r,65536)?.toString("utf8")??"")?.[1]?.trim():null,!o)return null}if(o){let i=W(n,o),c=L(C(i,"commondir"),65536),u=c===null?i:W(i,c.toString("utf8").trim());for(let d of["remotes","branches"]){let a=C(u,d);if(G(a)&&(!Ue(a).isDirectory()||an(a).length>0))return null}return{gitDir:i,common:u}}if(ae(n)===n)return null}return null}function fn(e){let t=[],n="",s=null;for(let r of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){r=r.trim();let o=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(r);if(o){let[c,...u]=o[1].toLowerCase().split(".");n=c,s=o[2]?.replace(/\\(.)/g,"$1")??(u.length>0?u.join("."):null),r=r.slice(o[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(r);i&&t.push({section:n,sub:s,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(c,u,d)=>u??d??"").trim()})}return t}var pn={slack:"channel",github:"repo",linear:"team",jira:"project"};var gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function x(e,t,n=!1){let s=e==="jira"&&typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?String(t):t;if(typeof s!="string")return null;let r=s.normalize("NFKC").trim().replace(/^(["'])(.*)\1$/,"$2");if(!r||r.length>300||/[$`\u0000-\u001f]/.test(r)||/[^\u0000-\u007f]/.test(r)&&new RegExp("\\p{Script=Latin}","u").test(r)&&new RegExp("(?!\\p{Script=Latin})\\p{L}","u").test(r))return null;if(e==="slack"){if(r=/^<#([A-Z0-9]+)(?:\|[^>]*)?>$/.exec(r)?.[1]??/\/archives\/([A-Z0-9]{6,})(?:[/?#]|$)/.exec(r)?.[1]??r,r.startsWith("@")||/^[DUW][A-Z0-9]{6,}$/.test(r))return"dm";if(/^[A-Z0-9]+$/.test(r))return/^[CG][A-Z0-9]{6,}$/.test(r)?`id:${r}`:null;let c=r.replace(/^#/,"").toLowerCase();return/^[a-z0-9][a-z0-9._-]{0,79}$/.test(c)||/^[\p{L}\p{N}][\p{L}\p{N}._-]{0,79}$/u.test(c)?`name:${c}`:null}if(e==="github"){let c=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s?#]+)/i.exec(r)??/^https?:\/\/(?:api|uploads)\.github\.com\/repos\/([^/\s]+)\/([^/\s?#]+)/i.exec(r)??/^([\w.-]+)\/([\w.-]+)$/.exec(r),u=a=>/^[\w.-]+$/.test(a)&&!/^\.+$/.test(a),d=a=>a.toLowerCase().replace(/\.git$/,"");return c?u(c[1])&&u(c[2])?`repo:${d(c[1])}/${d(c[2])}`:null:u(r)?`repo:?/${d(r)}`:null}let o=e==="linear"?"[A-Za-z][A-Za-z0-9]{0,6}":"[A-Z][A-Z0-9_]{1,9}",i=new RegExp(`^(${o})-\\d+$`).exec(r)??new RegExp(`(?:/issue/|/browse/)(${o})-\\d+`).exec(r);return i?`key:${i[1].toLowerCase()}`:n?null:(e==="linear"?gn.test(r):/^\d+$/.test(r))?`id:${r.toLowerCase()}`:new RegExp(`^${e==="linear"?"[A-Z0-9]{1,7}":"[A-Z][A-Z0-9_]{1,9}"}$`).test(r)?`key:${r.toLowerCase()}`:`name:${r.toLowerCase().replace(/\s+/g," ")}`}function P(e,t){if(!t||e!=="linear"&&e!=="jira"||!t.startsWith("name:"))return[t??"?"];let n=t.slice(5);return(e==="linear"?/^[a-z][a-z0-9]{0,6}$/:/^[a-z][a-z0-9_]{1,9}$/).test(n)?[`key:${n}`,t]:[t]}var ce={slack:/^(?:(?:to|target|dest|destination|source|from|in)_?)?(?:channel|conversation)s?(?:_?(?:ids?|names?|url|link))?$|^(?:target|chat_?id|permalink|message_?(?:url|link))$/i,github:/^(?:(?:parent|item|base|head|target|source)_?)?(?:repo|repository)(?:_?name)?s?$|^(?:repo_?full_?name|full_?name|name_?with_?owner|html_?url|pull_?request_?url|issue_?url)$/i,linear:/^(?:new_?)?team(?:_?(?:id|key|name))?s?$/i,jira:/^projects?(?:_?(?:key|id|id_?or_?key))?s?$/i},Ze={linear:/^(?:id|ids|issues?|issue_?ids?|identifiers?|issue_?identifiers?|parent_?id|url)$/i,jira:/^(?:key|keys|issues?|issue_?keys?|issue_?ids?|issue_?id_?or_?key|parent|parent_?key|url)$/i},mn=/^(?:user|users|user_?ids?|recipient|recipients)$/i,hn=/^(?:arguments|args|params|parameters|input|data|payload|body|request|message|fields|issue|issues|items|options|update)$/i,le=/^channels?$|^channel_ids?$/,yn=/^(?:text|body|title|description|content|comment|summary|markdown|blocks|attachments)$/i;function wn(e,t){let n=0,s=(r,o)=>++n>2e3||o>6?!1:typeof r=="string"?P(e.app,x(e.app,r)).some(i=>Xe(e,i)):Array.isArray(r)?r.slice(0,200).some(i=>s(i,o+1)):!!(r&&typeof r=="object")&&Object.entries(r).some(([i,c])=>!yn.test(i)&&!ce[e.app].test(i)&&!Ze[e.app]?.test(i)&&s(c,o+1));return s(t,0)}function Ye(e,t,n=!1){if(!t)return null;let s=[],r=0,o=(i,c,u)=>{for(let[d,a]of Object.entries(i)){if(++r>2e3)return void s.push("?");let l=u?"":"~",f=Array.isArray(a)?a:[a];f.length>200&&s.push("?");let m=f.slice(0,200).flatMap(p=>p&&typeof p=="object"&&!Array.isArray(p)?["key","id","name"].map(h=>p[h]).filter(h=>h!==void 0):e==="slack"&&typeof p=="string"?p.split(","):[p]);if(ce[e].test(d)||Ze[e]?.test(d)){let p=!ce[e].test(d),h=e==="github"?/^(.*?)(_?)(?:repo|repository)(?:_?name)?$/i.exec(d):null,g=h?i[`${h[1]}${h[2]}owner`]:void 0;for(let y of m.length>0?m:[void 0])for(let b of P(e,x(e,typeof g=="string"&&typeof y=="string"&&!y.includes("/")?`${g.trim()}/${y.trim()}`:y,p)))s.push(b==="?"?"?":`${l}${b}`)}else if(e==="slack"&&mn.test(d))for(let p of m)s.push(x("slack",p)==="dm"?`${l}dm`:"?");else if(c<6&&a&&typeof a=="object")for(let p of f.slice(0,200))p&&typeof p=="object"&&!Array.isArray(p)&&o(p,c+1,n||u&&c<2&&hn.test(d))}};return o(t,0,!0),s.length>0?s.every(i=>i.startsWith("~"))?[...s,"?"]:s:null}function bn(e){let t=[],n="",s=null;for(let r=0;r<e.length;r++){let o=e[r];if(o==="\\"&&s!=="'"){n+=o+(e[++r]??"");continue}if(s)s=o===s?null:s;else if(o==="'"||o==='"')s=o;else if(o===";"||o==="&"||o==="|"||o===`
12
+ `){n.trim()&&t.push(n),n="";continue}n+=o}return n.trim()&&t.push(n),t}function Je(e){let t=[],n="",s=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];s==="'"?i==="'"?s=null:n+=i:s==='"'?i==='"'?s=null:n+=i==="\\"&&o+1<e.length?e[++o]:i:i==="'"||i==='"'?(s=i,r=!0):i==="\\"?(n+=e[++o]??"",r=!0):/\s/.test(i)?((n||r)&&t.push(n),n="",r=!1):(n+=i,r=!0)}return s?null:((n||r)&&t.push(n),t)}var Ke=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`/${e.replace(/^\/+/,"")}`,"https://x").pathname}catch{return"\0"}};function $n(e){let t=Je(e),n=t?t.findIndex(d=>/(?:^|\/)gh$/.test(d)):-1;if(!t||n<0)return["?"];let s=t.slice(0,n).flatMap(d=>d.startsWith("GH_REPO=")?[d.slice(8)]:[]).pop(),r=t.slice(n+1),o;for(let d=0;d<r.length;d++){let a=r[d];a==="-R"||a==="--repo"?o=r[++d]??"":a.startsWith("--repo=")?o=a.slice(7):/^-R[^-]/.test(a)?o=a.slice(2):/^-[A-Za-z]+R/.test(a)&&(o="?")}let i=r[0]==="repo"&&r[1]!=="rename"&&r[2]!==void 0&&!r[2].startsWith("-")?r[2]:void 0,c=o??s??i,u=r.filter(d=>/^https?:\/\/(?:www\.)?github\.com\/[^/]+\/[^/]+\/(?:pull|issues)\/\d+/i.test(d)).map(d=>`~${x("github",d)??"?"}`);return[c===void 0?"none":x("github",c)??"?",...u]}var kn=(e,t)=>Be(e.attributes,t.home)?.map(n=>x("github",n)??"?")??["?"];function vn(e,t){let n=Je(t),s=n?n.findIndex(a=>/(?:^|\/)(?:curl|wget)$/.test(a)):-1;if(!n||s<0)return["?"];let r=[],o=[],i=n.slice(s+1);for(let a=0;a<i.length;a++){let l=i[a],f=/^(--data(?:-ascii|-binary|-raw|-urlencode)?|--json|--form(?:-string)?|--post-data|--body-data)(?:=([\s\S]*))?$/.exec(l);f?r.push(f[2]??i[++a]??""):l==="-d"||l==="-F"?r.push(i[++a]??""):/^-[dF]./.test(l)?r.push(l.slice(2)):/^https?:\/\//i.test(l)&&o.push(l)}let c=[],u=a=>{for(let l of[a].flat().flatMap(f=>typeof f=="string"?f.split(","):[f]))c.push(...P(e,x(e,l)))},d=a=>{let l=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!l)return void c.push("?");if(e==="slack"){let f=Object.keys(l).filter(m=>le.test(m));f.length===0&&c.push("?");for(let m of f)u(l[m])}else if(e==="jira"){let f=(l.fields&&typeof l.fields=="object"?l.fields:l).project,m=f&&typeof f=="object"?f:null;c.push(...m?[m.key,m.id].filter(p=>p!==void 0).flatMap(p=>P(e,x(e,p))):["?"])}else{let f=Ye("linear",l.variables??{},!0)??[],p=[...(typeof l.query=="string"?l.query:"").matchAll(/\b(teamId|teamKey|team|id|issueId|identifier)\s*:\s*"([^"\\]{1,100})"/g)].flatMap(h=>P(e,x(e,h[2],!/^team/.test(h[1])))).map(h=>`~${h}`);c.push(...f,...p,...f.length===0?["?"]:[])}};for(let a of o)try{for(let[l,f]of new URL(a).searchParams)e==="slack"&&le.test(l)&&u(f)}catch{c.push("?")}for(let a of r){if(/^@|^[\w-]*@/.test(a)){c.push("?");continue}let l;try{l=JSON.parse(a)}catch{l=void 0}if(l!==void 0)d(l);else if(e==="slack"&&/^[\w-]+=/.test(a)){let f=a.split("&").map(m=>[m.slice(0,m.indexOf("=")<0?m.length:m.indexOf("=")),m.slice(m.indexOf("=")+1)]);for(let[m,p]of f){if(!le.test(m))continue;let h=p;try{h=decodeURIComponent(p.replace(/\+/g," "))}catch{c.push("?");continue}u(h)}}else c.push("?")}return c.length>0?c:["?"]}var Ve=e=>/^[a-z][a-z-]*\s+[a-z][a-z-]*$/.test(e)||!/[/:]/.test(e)&&e!=="graphql"&&e.length>0;function _n(e,t,n){let s=t.target??"";if(e==="slack"&&/hooks\.slack\.com/i.test(`${t.host??""} ${s}`))return["?"];let r=e==="github"&&Ve(s);if(e==="github"&&!r){let a=Ke(s),l=/^\/repos\/([^/]+)\/([^/]+)/.exec(a)??(/^https?:\/\/(?:www\.)?github\.com\//i.test(s)?/^\/([^/]+)\/([^/]+)/.exec(a):null);return[l?x("github",`${l[1]}/${l[2]}`)??"?":"?"]}let o=e==="jira"?/\/rest\/api\/(?:2|3|latest)\/(issue|project)\/([^/]+)/.exec(Ke(s)):null;if(o)return P("jira",x("jira",o[2],o[1]==="issue"));let i=n.command??(typeof n.input?.command=="string"?n.input.command:"");if(i.length>65536)return["?"];let c=bn(i),u=c.filter(a=>r?/(?:^|[\s/])gh\s/.test(a)&&(/\s/.test(s)?a.includes(s.split(/\s+/)[1]):a.includes(s)):s.length>0&&a.includes(s)),d=a=>r?$n(a).flatMap(l=>l==="none"?kn(t,n):[l]):vn(e,a);return u.length>0?u.flatMap(d):[...c.flatMap(d).filter(a=>a!=="?"&&!a.startsWith("~")).map(a=>`~${a}`),"?"]}function Cn(e,t){return t==="dm"?e.app==="slack":e.app==="slack"?t.startsWith("name:"):e.app==="github"?t.startsWith("repo:")&&!(t.startsWith("repo:?/")&&e.is.some(n=>n.endsWith(`/${t.slice(7)}`))):e.as!==void 0&&t.startsWith(`${e.as}:`)}function Xe(e,t){return e.is.includes(t)?!0:e.app!=="github"||!t.startsWith("repo:")?!1:e.is.includes(`repo:${t.startsWith("repo:?/")?t.slice(7):t.slice(t.indexOf("/")+1)}`)}var B=e=>e.startsWith("key:")?e.slice(4).toUpperCase():e.replace(/^(?:name|id|repo):(?:\?\/)?/,"");function Qe(e,t,n){let s=pn[e.app],r=e.said.replace(/^in /,""),o=t.action==="claude.mcp.side_effect"?Ye(e.app,n.input):_n(e.app,t,n),i=`Anvil can't tell which ${s} this acts in${e.app==="github"&&t.action!=="claude.mcp.side_effect"&&Ve(t.target??"")?" (gh says it with --repo)":""}`;if(!o||o.length===0)return{hit:"unknown",why:i};let c=o.map(a=>a.replace(/^~/,"")).find(a=>Xe(e,a));if(c)return{hit:"match",detail:c.startsWith("id:")?`${B(c)} is ${r}`:e.app==="github"?B(c):r};let u=o.find(a=>a==="?"||a.startsWith("~")||!(e.not??[]).includes(a)&&!Cn(e,a));if(u===void 0)return t.action==="claude.mcp.side_effect"&&wn(e,n.input)?{hit:"unknown",why:`Anvil can't tell whether this acts in ${r}: the call names it in a field Anvil doesn't read`}:null;let d=u.replace(/^~/,"");return{hit:"unknown",why:d==="?"?i:`Anvil can't tell whether ${d.startsWith("id:")?`${s} ${B(d)}`:B(d)} is ${r}`}}function mo(e,t,n){switch(e.type){case"amount":return _e(e,t,n);case"recipient":return Fe(e,t,n);case"part":return Qe(e,t,n);case"when":return qe(e,t,n)}}async function ho(){}export{_t as capMoved,mo as matchCondition,ho as preloadConditions};
@@ -1,12 +1,12 @@
1
- import{createHash as Pe}from"crypto";import{readdirSync as M,readFileSync as Me,rmdirSync as Le,rmSync as Ie,statSync as Te,unlinkSync as ae}from"fs";import{basename as B,dirname as L,join as h,resolve as De}from"path";import{existsSync as It,readdirSync as Tt,statSync as Dt}from"fs";import{dirname as Ft,isAbsolute as zt,join as qt,posix as Ht,resolve as Ut}from"path";import{posix as X}from"path";var we=null;function j(){return we??process.platform==="win32"}var V=/^([A-Za-z]):(.*)$/s,be=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function D(e,t){let n=X.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function C(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,i=t?o:o.replace(/[. ]+$/,"");return i===""?".":i}).join("/")}function W(e){if(!j())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let s=r[2];if(r[1]===".")return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(s))t=`\\\\${s.slice(4)}`;else if(V.test(s))t=s;else return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let s=`/unc/${C(o[1],n).toLowerCase()}${o[2]?`/${C(o[2],n).toLowerCase()}`:""}`;return D(s,C(o[3]??"",n).toLowerCase())}let i=V.exec(t);if(i){let s=i[2];return s===""?`/${i[1].toLowerCase()}`:s.startsWith("/")?D(`/${i[1].toLowerCase()}`,C(s,n).toLowerCase()):null}let l=be.exec(t);if(l)return D(`/${l[1].toLowerCase()}`,C(l[2]??"",n).toLowerCase());let c=C(t,n).toLowerCase();if(c.startsWith("/")){let s=X.normalize(c);return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}return c}function $e(e){return W(e)??e}function F(e){return!j()||typeof e!="string"||e===""?e:$e(e)}import{createHash as wt}from"crypto";import{appendFileSync as ke,closeSync as ee,constants as Q,fstatSync as te,mkdirSync as ve,openSync as ne,readdirSync as $t,readFileSync as kt,readSync as re,renameSync as vt,statSync as xe,unlinkSync as xt,writeFileSync as _t}from"fs";import{homedir as At}from"os";import{dirname as St,join as Nt}from"path";var _e=3500;function A(e,t=8*1024*1024){try{let n=xe(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function R(e,t=8*1024*1024){let n;try{n=ne(e,Q.O_RDONLY|Q.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=te(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),i=0;for(;i<r.size;){let l=re(n,o,i,r.size-i,i);if(l===0)break;i+=l}return o.subarray(0,i)}finally{ee(n)}}function y(e,t){let n=t.endsWith(`
1
+ import{createHash as Me}from"crypto";import{readdirSync as L,readFileSync as Le,rmdirSync as Ie,rmSync as Te,statSync as De,unlinkSync as le}from"fs";import{basename as G,dirname as I,join as h,resolve as We}from"path";import{existsSync as Wt,readdirSync as Ft,statSync as zt}from"fs";import{dirname as Ht,isAbsolute as Ut,join as Bt,posix as Gt,resolve as Kt}from"path";import{posix as Q}from"path";var be=null;function P(){return be??process.platform==="win32"}var X=/^([A-Za-z]):(.*)$/s,$e=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function W(e,t){let n=Q.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function C(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,i=t?o:o.replace(/[. ]+$/,"");return i===""?".":i}).join("/")}function F(e){if(!P())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let s=r[2];if(r[1]===".")return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(s))t=`\\\\${s.slice(4)}`;else if(X.test(s))t=s;else return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let s=`/unc/${C(o[1],n).toLowerCase()}${o[2]?`/${C(o[2],n).toLowerCase()}`:""}`;return W(s,C(o[3]??"",n).toLowerCase())}let i=X.exec(t);if(i){let s=i[2];return s===""?`/${i[1].toLowerCase()}`:s.startsWith("/")?W(`/${i[1].toLowerCase()}`,C(s,n).toLowerCase()):null}let l=$e.exec(t);if(l)return W(`/${l[1].toLowerCase()}`,C(l[2]??"",n).toLowerCase());let c=C(t,n).toLowerCase();if(c.startsWith("/")){let s=Q.normalize(c);return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}return c}function ke(e){return F(e)??e}function z(e){return!P()||typeof e!="string"||e===""?e:ke(e)}import{createHash as kt}from"crypto";import{appendFileSync as ve,closeSync as te,constants as ee,fstatSync as ne,mkdirSync as xe,openSync as re,readdirSync as xt,readFileSync as _t,readSync as oe,renameSync as At,statSync as _e,unlinkSync as Ct,writeFileSync as Rt}from"fs";import{homedir as Nt}from"os";import{dirname as Et,join as jt}from"path";var Ae=3500;function R(e,t=8*1024*1024){try{let n=_e(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function S(e,t=8*1024*1024){let n;try{n=re(e,ee.O_RDONLY|ee.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=ne(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),i=0;for(;i<r.size;){let l=oe(n,o,i,r.size-i,i);if(l===0)break;i+=l}return o.subarray(0,i)}finally{te(n)}}function y(e,t){let n=t.endsWith(`
2
2
  `)?t:`${t}
3
- `;if(Buffer.byteLength(n)>_e)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(A(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);ke(e,n,{mode:384})}function S(e){ve(e,{recursive:!0,mode:448})}function P(e,t){if(A(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=ne(e,"r")}catch{return""}try{let r=te(n).size,o=Math.max(0,r-t),i=r-o;if(i<=0)return"";let l=Buffer.alloc(i);re(n,l,0,i,o);let c=l.toString("utf8");if(o>0){let s=c.indexOf(`
4
- `);c=s<0?"":c.slice(s+1)}return c}finally{ee(n)}}var Ot=256*1024,jt=1024*1024;import{domainToASCII as Xt}from"url";var sn="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as _n,readdirSync as Cn,realpathSync as An}from"fs";import{basename as Sn,dirname as Nn,join as En}from"path";function oe(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Re(t,e.project_dir))}function Re(e,t){let n=F(e),r=F(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}var k={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Se(e){if(!e){let s=a=>a;return{on:!1,bold:s,dim:s,blue:s,grey:s,amber:s,mark:s,field:s}}let t=e==="truecolor",n=s=>a=>`\x1B[${s}m${a}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),i=n(t?"38;2;245;165;36":"38;5;214"),l=n(t?"38;2;34;197;94":"32"),c={[k.on]:r,[k.blocked]:r,[k.held]:r,[k.next]:r,[k.watching]:o,[k.problem]:i,[k.ok]:l};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:i,mark:s=>(c[s]??(a=>a))(s),field:s=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Ee(s)}\x1B[0m`}}var Qn=Se(!1),Ne=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ee(e){return e.replace(Ne,"")}var se=[{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)"}}],Oe="home and project wipes and force-pushes to main",ir=`always blocking ${Oe}`,ar=new Map(se.map(e=>[e.id,e]));var je=new Set(se.flatMap(e=>Object.keys(e.slugs)));var z="anvil-claude";function N(e){let t=e.trim();return t===z||t.endsWith(` ${z}`)||t.endsWith(`/${z}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ie="\u{1F539}",x=e=>`${ie} ${e} ${ie}`;var q=(e,t)=>`they run \`${N(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${t}`;var le="claude.agent.helper",We=6e4,Fe=30*6e4,ze=30*6e4,ce=6e4,qe="workflow-subagent",He=4*1024*1024,ue=[2,1,318],Ue="/.anvil/claude/bin/claude-hook.js",Be=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",de=40,m=e=>typeof e=="string"&&e.length>0?e:null,G=e=>e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Pe("sha256").update(e).digest("hex").slice(0,24):"none",Ge=/^[A-Za-z0-9_-]{1,64}$/,Ke=e=>e[0].toUpperCase()+e.slice(1),K=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`},_=e=>h(e.dir,"helpers"),J=(e,t)=>h(_(e),"live",`${G(t)}.log`);function Je(e,t){let n=null,r=null;for(let o of e)for(let i of o.helpers?.models??[])i.types===null?n=i:i.types.includes(t)&&(r=i);return r??(t==="fork"?null:n)}function Ye(e){let t=null;for(let n of e)for(let r of n.helpers?.at_once??[])(!t||r.limit<t.limit)&&(t=r);return t}function Ze(e,t){let n=m(e.env.CLAUDE_CONFIG_DIR),r=h(n?De(n):h(e.home,".claude"),"settings.json"),o=m(e.env.CLAUDE_PROJECT_DIR)??m(t.cwd);return o?[r,h(o,".claude","settings.local.json"),h(o,".claude","settings.json")]:[r]}function Or(e){let t=Ze(e.deps,e.payload),n=e.modes?.kill_switch===!0,r=e.payload.tool_input&&typeof e.payload.tool_input=="object"&&!Array.isArray(e.payload.tool_input)?e.payload.tool_input:{},o=typeof r.subagent_type=="string"&&r.subagent_type.trim()?r.subagent_type.trim():"general-purpose",i=m(e.payload.session_id),l=e.table.policies.filter(p=>p.helpers&&oe(p,e.projectDir)),c=[],s=(p,d)=>{tt(e.paths,i,p)&&c.push(d)},a=n?null:Je(l,o);a&&r.model===a.model&&(a=null);let g=n?null:Ye(l),f=a||g?Qe(t,o,e.managed??Be):null;if(f==="deny"&&(a=null),o==="fork"&&!n){let p=l.flatMap(d=>d.helpers?.models??[]).find(d=>d.types===null);p&&s(`fork-${p.id}`,`${x("Anvil")} a fork helper keeps this session's model \xB7 ${p.text} can't switch it`)}let u=m(e.payload.tool_use_id)??`${e.now}-${process.pid}`,w=J(e.paths,i),b=!1,v=null,$=0;if(g&&f!=="deny"){let p=Ve(e,t);if(p)s(`count-${g.id}`,`${x("Anvil")} can't count helper agents here (${p}) \xB7 ${g.text} isn't enforced`);else{try{let d=st(w,u,g.limit,e.now);b=d===null,d!==null&&($=d)}catch(d){$=-1,v={action:le,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_unreadable",source:g.source},mode:"enforce",floor:null,why:`couldn't count helper agents for ${g.text} (${d?.code??(d instanceof Error?d.message.slice(0,60):"unreadable")})`,target:o}}$>0&&(v={action:le,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_reached",source:g.source},mode:"enforce",floor:null,why:`${$} helper ${$===1?"agent":"agents"} running or starting (cap: ${g.text})`,target:o})}}let I=()=>{if(b){b=!1;try{y(w,JSON.stringify({t:e.now,op:"x",k:u}))}catch{}}},me=()=>{if(!b)return;let p=m(e.payload.transcript_path),d=m(e.payload.tool_use_id);try{y(w,JSON.stringify({t:e.now,op:"q",k:u,...p&&d&&p.length<1024&&d.length<256?{tr:p,c:d}:{}}))}catch{}};return{stop:v,agent:p=>$<0?`${x("Held by Anvil")} ${v.why}. Nothing ran. Tell the user${p?`: to let it start once, ${q(e.cli,"tell you to launch it again")}`:"; once it is fixed, launch it again"}. Do not try another way.`:`${x("Held by Anvil")} ${$} helper ${$===1?"agent is":"agents are"} running or starting in this session, and the user's cap is ${g?.text??"reached"}. Nothing ran. Wait for one of them to finish, then launch this one again; don't retry it before then.${p?` To let it start now, ${q(e.cli,"tell you to launch it")}.`:""}`,release:I,ran:()=>{if(a)try{it(e.paths,{t:e.now,session:i?G(i):null,type:o,from:typeof r.model=="string"?r.model.slice(0,40):null,to:a.model,rule:a.id,project:e.projectDir?B(e.projectDir):null})}catch{}},finish:p=>{let d={};try{d=p.stdout?JSON.parse(p.stdout):{}}catch{return I(),p}let Y=d.hookSpecificOutput&&typeof d.hookSpecificOutput=="object"?d.hookSpecificOutput:null,E=Y?.permissionDecision;E==="deny"?I():(E==="ask"||f==="ask")&&me();let O=c.join(`
5
- `);if(!a&&!O)return p;if(a&&E!=="deny"){let T={...r,model:a.model},Z=`switched this helper to ${Ke(a.model)} \xB7 ${a.text}`;E==="ask"?d.hookSpecificOutput={...Y,updatedInput:T}:f==="ask"?d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:`${x("Anvil")} ${Z}; your own rule asks before helper agents`,updatedInput:T}:d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`${x("Anvil")} ${Z}`,updatedInput:T}}return O&&(d.systemMessage=typeof d.systemMessage=="string"?`${d.systemMessage}
6
- ${O}`:O),{stdout:`${JSON.stringify(d)}
7
- `,exitCode:0}}}}function Ve(e,t){if(!Xe(t))return e.deps.plugin===!0?`the plugin isn't told when helpers start and stop; ${N(e.cli)} on is`:`its helper start and stop entries aren't set up: run ${N(e.cli)} on, which names any Claude Code that keeps them out`;let n=et(m(e.payload.transcript_path));if(!n)return"this session's Claude Code version can't be read";for(let r=0;r<3;r++)if(n[r]!==ue[r])return n[r]>ue[r]?null:`Claude Code ${n.join(".")} doesn't report helpers starting and stopping; 2.1.318 does`;return null}function fe(e){try{if(A(e,4*1024*1024)!==!0)return null;let t=JSON.parse(Me(e,"utf8").replace(/^/,""));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Xe(e){return e.some(t=>{let n=fe(t)?.hooks;return["SubagentStart","SubagentStop"].every(r=>JSON.stringify(n?.[r]??null).includes(Ue))})}function Qe(e,t,n){let r=null;for(let o of[n,...e]){let i=fe(o)?.permissions;for(let l of["deny","ask"]){let s=(Array.isArray(i?.[l])?i[l]:[]).some(a=>{let g=typeof a=="string"?/^\s*(?:Agent|Task)\s*(?:\(\s*([^)]*?)\s*\))?\s*$/.exec(a):null;return g!==null&&(g[1]===void 0||g[1]===""||g[1]==="*"||g[1]===t)});if(s&&l==="deny")return"deny";s&&(r="ask")}}return r}function et(e){if(!e)return null;try{let t=null;for(let n of P(e,256*1024).matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)){let r=[Number(n[1]),Number(n[2]),Number(n[3])];(!t||r[0]>t[0]||r[0]===t[0]&&(r[1]>t[1]||r[1]===t[1]&&r[2]>t[2]))&&(t=r)}return t}catch{return null}}function tt(e,t,n){try{let r=h(e.state,`helpers-said-${G(t)}`);return P(r,64*1024).split(`
8
- `).includes(n)?!1:(S(e.state),y(r,n),!0)}catch{return!0}}function H(e){let t=R(e,He);if(!t)return[];let n=[];for(let r of t.toString("utf8").split(`
9
- `))if(r)try{let o=JSON.parse(r);typeof o.t=="number"&&typeof o.op=="string"&&n.push(o)}catch{}return n}var U=e=>{try{return Te(e).mtimeMs}catch{return 0}};function nt(e){let t=U(e);if(t>0)return t;let n=0;try{let r=h(L(e),"workflows");for(let o of M(r).slice(0,512))n=Math.max(n,U(h(r,o,B(e))))}catch{}return n}function pe(e,t,n=e.length,r=nt){return ge(e,t,n,r).count}function ge(e,t,n,r){let o=new Map,i=new Map,l=new Set,c=f=>f.q?Fe:We;for(let f=0;f<Math.min(n,e.length);f++){let u=e[f];if(u.op==="z")o.clear(),i.clear();else if(u.op==="r"&&u.k)o.set(u.k,{t:u.t,q:null});else if(u.op==="q"&&u.k){let w=o.get(u.k);w&&(w.q=u)}else if(u.op==="x"&&u.k)o.delete(u.k);else if((u.op==="s"||u.op==="e")&&u.a){if(u.op==="s"&&!i.has(u.a)&&!l.has(u.a)){if(!u.w){for(let[b,v]of o)u.t-v.t>=c(v)&&o.delete(b);let w=[...o].find(([,b])=>!b.q)?.[0]??o.keys().next().value;w!==void 0&&o.delete(w)}i.set(u.a,u)}u.op==="e"&&(i.delete(u.a),l.add(u.a))}}let s=f=>f>t+ce?0:f,a=0,g=[];for(let f of o.values())f.t>t+ce||t-f.t>=c(f)||(a++,f.q&&g.push(f.q));for(let f of i.values())t-Math.max(s(f.t),f.f?s(r(f.f)):0)<ze&&a++;return{count:a,asked:g}}function rt(e,t,n){let r=0;for(let o of ge(t,n,t.length,()=>0).asked)r>=4||!o.tr||!o.c||n-o.t<1e3||(r++,ot(o.tr,o.c)&&y(e,JSON.stringify({t:n,op:"x",k:o.k})))}function ot(e,t){try{let n=P(e,1048576),r=`"tool_use_id":"${t}"`;for(let o=n.indexOf(r);o>=0;o=n.indexOf(r,o+r.length)){let i=n.indexOf(`
3
+ `;if(Buffer.byteLength(n)>Ae)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(R(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);ve(e,n,{mode:384})}function N(e){xe(e,{recursive:!0,mode:448})}function M(e,t){if(R(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=re(e,"r")}catch{return""}try{let r=ne(n).size,o=Math.max(0,r-t),i=r-o;if(i<=0)return"";let l=Buffer.alloc(i);oe(n,l,0,i,o);let c=l.toString("utf8");if(o>0){let s=c.indexOf(`
4
+ `);c=s<0?"":c.slice(s+1)}return c}finally{te(n)}}var Mt=256*1024,Lt=1024*1024;import{domainToASCII as nn}from"url";var dn="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Nn,readdirSync as On,realpathSync as En}from"fs";import{basename as Pn,dirname as Mn,join as Ln}from"path";function se(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Se(t,e.project_dir))}function Se(e,t){let n=z(e),r=z(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}var k={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Ne(e){if(!e){let s=a=>a;return{on:!1,bold:s,dim:s,blue:s,grey:s,amber:s,mark:s,field:s}}let t=e==="truecolor",n=s=>a=>`\x1B[${s}m${a}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),i=n(t?"38;2;245;165;36":"38;5;214"),l=n(t?"38;2;34;197;94":"32"),c={[k.on]:r,[k.blocked]:r,[k.held]:r,[k.next]:r,[k.watching]:o,[k.problem]:i,[k.ok]:l};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:i,mark:s=>(c[s]??(a=>a))(s),field:s=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Ee(s)}\x1B[0m`}}var sr=Ne(!1),Oe=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ee(e){return e.replace(Oe,"")}var ie=[{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)"}}],je="home and project wipes and force-pushes to main",pr=`always blocking ${je}`,gr=new Map(ie.map(e=>[e.id,e]));var Pe=new Set(ie.flatMap(e=>Object.keys(e.slugs)));var q="anvil-claude";function O(e){let t=e.trim();return t===q||t.endsWith(` ${q}`)||t.endsWith(`/${q}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ae="\u{1F539}",x=e=>`${ae} ${e} ${ae}`;var H=(e,t)=>`they run \`${O(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${t}`;var ce="claude.agent.helper",Fe=6e4,ze=30*6e4,qe=30*6e4,ue=6e4,He="workflow-subagent",Ue=4*1024*1024,de=[2,1,318],Be="/.anvil/claude/bin/claude-hook.js",Ge=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",fe=40,m=e=>typeof e=="string"&&e.length>0?e:null,K=e=>e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Me("sha256").update(e).digest("hex").slice(0,24):"none",Ke=/^[A-Za-z0-9_-]{1,64}$/,Je=e=>e[0].toUpperCase()+e.slice(1),J=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`},_=e=>h(e.dir,"helpers"),Y=(e,t)=>h(_(e),"live",`${K(t)}.log`);function Ye(e,t){let n=null,r=null;for(let o of e)for(let i of o.helpers?.models??[])i.types===null?n=i:i.types.includes(t)&&(r=i);return r??(t==="fork"?null:n)}function Ze(e){let t=null;for(let n of e)for(let r of n.helpers?.at_once??[])(!t||r.limit<t.limit)&&(t=r);return t}function Ve(e,t){let n=m(e.env.CLAUDE_CONFIG_DIR),r=h(n?We(n):h(e.home,".claude"),"settings.json"),o=m(e.env.CLAUDE_PROJECT_DIR)??m(t.cwd);return o?[r,h(o,".claude","settings.local.json"),h(o,".claude","settings.json")]:[r]}function Fr(e){let t=Ve(e.deps,e.payload),n=e.modes?.kill_switch===!0,r=e.payload.tool_input&&typeof e.payload.tool_input=="object"&&!Array.isArray(e.payload.tool_input)?e.payload.tool_input:{},o=typeof r.subagent_type=="string"&&r.subagent_type.trim()?r.subagent_type.trim():"general-purpose",i=m(e.payload.session_id),l=e.table.policies.filter(p=>p.helpers&&se(p,e.projectDir)),c=[],s=(p,d)=>{nt(e.paths,i,p)&&c.push(d)},a=n?null:Ye(l,o);a&&r.model===a.model&&(a=null);let g=n?null:Ze(l),f=a||g?et(t,o,e.managed??Ge):null;if(f==="deny"&&(a=null),o==="fork"&&!n){let p=l.flatMap(d=>d.helpers?.models??[]).find(d=>d.types===null);p&&s(`fork-${p.id}`,`${x("Anvil")} a fork helper keeps this session's model \xB7 ${p.text} can't switch it`)}let u=m(e.payload.tool_use_id)??`${e.now}-${process.pid}`,w=Y(e.paths,i),b=!1,v=null,$=0;if(g&&f!=="deny"){let p=Xe(e,t);if(p)s(`count-${g.id}`,`${x("Anvil")} can't count helper agents here (${p}) \xB7 ${g.text} isn't enforced`);else{try{let d=it(w,u,g.limit,e.now);b=d===null,d!==null&&($=d)}catch(d){$=-1,v={action:ce,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_unreadable",source:g.source},mode:"enforce",floor:null,why:`couldn't count helper agents for ${g.text} (${d?.code??(d instanceof Error?d.message.slice(0,60):"unreadable")})`,target:o}}$>0&&(v={action:ce,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_reached",source:g.source},mode:"enforce",floor:null,why:`${$} helper ${$===1?"agent":"agents"} running or starting (cap: ${g.text})`,target:o})}}let T=()=>{if(b){b=!1;try{y(w,JSON.stringify({t:e.now,op:"x",k:u}))}catch{}}},ye=()=>{if(!b)return;let p=m(e.payload.transcript_path),d=m(e.payload.tool_use_id);try{y(w,JSON.stringify({t:e.now,op:"q",k:u,...p&&d&&p.length<1024&&d.length<256?{tr:p,c:d}:{}}))}catch{}};return{stop:v,agent:p=>$<0?`${x("Held by Anvil")} ${v.why}. Nothing ran. Tell the user${p?`: to let it start once, ${H(e.cli,"tell you to launch it again")}`:"; once it is fixed, launch it again"}. Do not try another way.`:`${x("Held by Anvil")} ${$} helper ${$===1?"agent is":"agents are"} running or starting in this session, and the user's cap is ${g?.text??"reached"}. Nothing ran. Wait for one of them to finish, then launch this one again; don't retry it before then.${p?` To let it start now, ${H(e.cli,"tell you to launch it")}.`:""}`,release:T,ran:()=>{if(a)try{at(e.paths,{t:e.now,session:i?K(i):null,type:o,from:typeof r.model=="string"?r.model.slice(0,40):null,to:a.model,rule:a.id,project:e.projectDir?G(e.projectDir):null})}catch{}},finish:p=>{let d={};try{d=p.stdout?JSON.parse(p.stdout):{}}catch{return T(),p}let Z=d.hookSpecificOutput&&typeof d.hookSpecificOutput=="object"?d.hookSpecificOutput:null,E=Z?.permissionDecision;E==="deny"?T():(E==="ask"||f==="ask")&&ye();let j=c.join(`
5
+ `);if(!a&&!j)return p;if(a&&E!=="deny"){let D={...r,model:a.model},V=`switched this helper to ${Je(a.model)} \xB7 ${a.text}`;E==="ask"?d.hookSpecificOutput={...Z,updatedInput:D}:f==="ask"?d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:`${x("Anvil")} ${V}; your own rule asks before helper agents`,updatedInput:D}:d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`${x("Anvil")} ${V}`,updatedInput:D}}return j&&(d.systemMessage=typeof d.systemMessage=="string"?`${d.systemMessage}
6
+ ${j}`:j),{stdout:`${JSON.stringify(d)}
7
+ `,exitCode:0}}}}function Xe(e,t){if(!Qe(t))return e.deps.plugin===!0?`the plugin isn't told when helpers start and stop; ${O(e.cli)} on is`:`its helper start and stop entries aren't set up: run ${O(e.cli)} on, which names any Claude Code that keeps them out`;let n=tt(m(e.payload.transcript_path));if(!n)return"this session's Claude Code version can't be read";for(let r=0;r<3;r++)if(n[r]!==de[r])return n[r]>de[r]?null:`Claude Code ${n.join(".")} doesn't report helpers starting and stopping; 2.1.318 does`;return null}function pe(e){try{if(R(e,4*1024*1024)!==!0)return null;let t=JSON.parse(Le(e,"utf8").replace(/^/,""));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Qe(e){return e.some(t=>{let n=pe(t)?.hooks;return["SubagentStart","SubagentStop"].every(r=>JSON.stringify(n?.[r]??null).includes(Be))})}function et(e,t,n){let r=null;for(let o of[n,...e]){let i=pe(o)?.permissions;for(let l of["deny","ask"]){let s=(Array.isArray(i?.[l])?i[l]:[]).some(a=>{let g=typeof a=="string"?/^\s*(?:Agent|Task)\s*(?:\(\s*([^)]*?)\s*\))?\s*$/.exec(a):null;return g!==null&&(g[1]===void 0||g[1]===""||g[1]==="*"||g[1]===t)});if(s&&l==="deny")return"deny";s&&(r="ask")}}return r}function tt(e){if(!e)return null;try{let t=null;for(let n of M(e,256*1024).matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)){let r=[Number(n[1]),Number(n[2]),Number(n[3])];(!t||r[0]>t[0]||r[0]===t[0]&&(r[1]>t[1]||r[1]===t[1]&&r[2]>t[2]))&&(t=r)}return t}catch{return null}}function nt(e,t,n){try{let r=h(e.state,`helpers-said-${K(t)}`);return M(r,64*1024).split(`
8
+ `).includes(n)?!1:(N(e.state),y(r,n),!0)}catch{return!0}}function U(e){let t=S(e,Ue);if(!t)return[];let n=[];for(let r of t.toString("utf8").split(`
9
+ `))if(r)try{let o=JSON.parse(r);typeof o.t=="number"&&typeof o.op=="string"&&n.push(o)}catch{}return n}var B=e=>{try{return De(e).mtimeMs}catch{return 0}};function rt(e){let t=B(e);if(t>0)return t;let n=0;try{let r=h(I(e),"workflows");for(let o of L(r).slice(0,512))n=Math.max(n,B(h(r,o,G(e))))}catch{}return n}function ge(e,t,n=e.length,r=rt){return he(e,t,n,r).count}function he(e,t,n,r){let o=new Map,i=new Map,l=new Set,c=f=>f.q?ze:Fe;for(let f=0;f<Math.min(n,e.length);f++){let u=e[f];if(u.op==="z")o.clear(),i.clear();else if(u.op==="r"&&u.k)o.set(u.k,{t:u.t,q:null});else if(u.op==="q"&&u.k){let w=o.get(u.k);w&&(w.q=u)}else if(u.op==="x"&&u.k)o.delete(u.k);else if((u.op==="s"||u.op==="e")&&u.a){if(u.op==="s"&&!i.has(u.a)&&!l.has(u.a)){if(!u.w){for(let[b,v]of o)u.t-v.t>=c(v)&&o.delete(b);let w=[...o].find(([,b])=>!b.q)?.[0]??o.keys().next().value;w!==void 0&&o.delete(w)}i.set(u.a,u)}u.op==="e"&&(i.delete(u.a),l.add(u.a))}}let s=f=>f>t+ue?0:f,a=0,g=[];for(let f of o.values())f.t>t+ue||t-f.t>=c(f)||(a++,f.q&&g.push(f.q));for(let f of i.values())t-Math.max(s(f.t),f.f?s(r(f.f)):0)<qe&&a++;return{count:a,asked:g}}function ot(e,t,n){let r=0;for(let o of he(t,n,t.length,()=>0).asked)r>=4||!o.tr||!o.c||n-o.t<1e3||(r++,st(o.tr,o.c)&&y(e,JSON.stringify({t:n,op:"x",k:o.k})))}function st(e,t){try{let n=M(e,1048576),r=`"tool_use_id":"${t}"`;for(let o=n.indexOf(r);o>=0;o=n.indexOf(r,o+r.length)){let i=n.indexOf(`
10
10
  `,o);try{let l=JSON.parse(n.slice(n.lastIndexOf(`
11
- `,o)+1,i<0?void 0:i)),s=(Array.isArray(l.message?.content)?l.message.content:[]).find(a=>a.type==="tool_result"&&a.tool_use_id===t);if(s)return s.is_error===!0}catch{}}return!1}catch{return!1}}function st(e,t,n,r,o){try{rt(e,H(e),r)}catch{}let i=()=>{S(L(e)),y(e,JSON.stringify({t:r,op:"r",k:t}))};try{i()}catch(a){if(a.code!=="ENOENT")throw a;i()}o?.();let l=H(e),c=l.findIndex(a=>a.op==="r"&&a.k===t&&a.t===r);if(c<0)throw new Error("its place wasn't read back");let s=pe(l,r,c+1);return s<=n?null:(y(e,JSON.stringify({t:r,op:"x",k:t})),s-1)}function jr(e,t,n){return pe(H(J(e,t)),n)}function Pr(e,t,n){try{let r=m(e.hook_event_name),o=m(e.session_id);if(!o)return;if(!R(t.compiled,16*1024*1024)?.includes('"at_once"'))return void Ie(h(_(t),"live"),{recursive:!0,force:!0});let i=J(t,o),l=A(i,Number.MAX_SAFE_INTEGER)===!0;if(r==="SessionStart"){l&&m(e.source)==="resume"&&y(i,JSON.stringify({t:n,op:"z"}));return}let c=m(e.agent_id);if(!c||!Ge.test(c)||r!=="SubagentStart"&&r!=="SubagentStop")return;if(l||he(t,n),S(L(i)),r==="SubagentStop")return y(i,JSON.stringify({t:n,op:"e",a:c}));let s=m(e.transcript_path),a=s&&s.startsWith("/")&&s.endsWith(".jsonl")?h(L(s),B(s,".jsonl"),"subagents",`agent-${c}.jsonl`):null;y(i,JSON.stringify({t:n,op:"s",a:c,...a&&a.length<1024?{f:a}:{},...m(e.agent_type)===qe?{w:1}:{}}))}catch{}}function it(e,t){let n=_(e),r=h(n,`${K(t.t)}.log`);S(n),A(r)===null&&he(e,t.t),y(r,JSON.stringify(t))}function Mr(e,t,n){let r={},o=0,i=new Date(Math.max(t,n-(de+1)*864e5));for(i.setHours(0,0,0,0);i.getTime()<=n;i.setDate(i.getDate()+1)){let l="";try{l=R(h(_(e),`${K(i.getTime())}.log`),16*1024*1024)?.toString("utf8")??""}catch{l=""}for(let c of l.split(`
12
- `))if(c)try{let s=JSON.parse(c);if(typeof s.t!="number"||s.t<t||s.t>n||typeof s.to!="string")continue;r[s.to]=(r[s.to]??0)+1,o++}catch{}}return{total:o,byModel:r}}function he(e,t){try{let n=K(t-de*864e5);for(let r of M(_(e)))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&ae(h(_(e),r))}catch{}try{let n=h(_(e),"live");for(let r of M(n))r.endsWith(".log")&&t-U(h(n,r))>2*864e5&&ae(h(n,r));M(n).length===0&&Le(n)}catch{}}export{Fe as ASK_MS,le as HELPER_ACTION,We as RESERVE_MS,ze as STALE_MS,st as admit,Ye as atOnceFor,_ as helpersDir,Or as launchStep,J as ledgerFile,pe as liveAt,Je as modelRuleFor,Pr as onEvent,Qe as ownAgentRule,H as readLedger,ot as refusedIn,jr as runningNow,Ze as settingsFiles,Xe as subagentEntries,Mr as switchesIn,nt as transcriptChanged};
11
+ `,o)+1,i<0?void 0:i)),s=(Array.isArray(l.message?.content)?l.message.content:[]).find(a=>a.type==="tool_result"&&a.tool_use_id===t);if(s)return s.is_error===!0}catch{}}return!1}catch{return!1}}function it(e,t,n,r,o){try{ot(e,U(e),r)}catch{}let i=()=>{N(I(e)),y(e,JSON.stringify({t:r,op:"r",k:t}))};try{i()}catch(a){if(a.code!=="ENOENT")throw a;i()}o?.();let l=U(e),c=l.findIndex(a=>a.op==="r"&&a.k===t&&a.t===r);if(c<0)throw new Error("its place wasn't read back");let s=ge(l,r,c+1);return s<=n?null:(y(e,JSON.stringify({t:r,op:"x",k:t})),s-1)}function zr(e,t,n){return ge(U(Y(e,t)),n)}function qr(e,t,n){try{let r=m(e.hook_event_name),o=m(e.session_id);if(!o)return;if(!S(t.compiled,16*1024*1024)?.includes('"at_once"'))return void Te(h(_(t),"live"),{recursive:!0,force:!0});let i=Y(t,o),l=R(i,Number.MAX_SAFE_INTEGER)===!0;if(r==="SessionStart"){l&&m(e.source)==="resume"&&y(i,JSON.stringify({t:n,op:"z"}));return}let c=m(e.agent_id);if(!c||!Ke.test(c)||r!=="SubagentStart"&&r!=="SubagentStop")return;if(l||me(t,n),N(I(i)),r==="SubagentStop")return y(i,JSON.stringify({t:n,op:"e",a:c}));let s=m(e.transcript_path),a=s&&s.startsWith("/")&&s.endsWith(".jsonl")?h(I(s),G(s,".jsonl"),"subagents",`agent-${c}.jsonl`):null;y(i,JSON.stringify({t:n,op:"s",a:c,...a&&a.length<1024?{f:a}:{},...m(e.agent_type)===He?{w:1}:{}}))}catch{}}function at(e,t){let n=_(e),r=h(n,`${J(t.t)}.log`);N(n),R(r)===null&&me(e,t.t),y(r,JSON.stringify(t))}function Hr(e,t,n){let r={},o=0,i=new Date(Math.max(t,n-(fe+1)*864e5));for(i.setHours(0,0,0,0);i.getTime()<=n;i.setDate(i.getDate()+1)){let l="";try{l=S(h(_(e),`${J(i.getTime())}.log`),16*1024*1024)?.toString("utf8")??""}catch{l=""}for(let c of l.split(`
12
+ `))if(c)try{let s=JSON.parse(c);if(typeof s.t!="number"||s.t<t||s.t>n||typeof s.to!="string")continue;r[s.to]=(r[s.to]??0)+1,o++}catch{}}return{total:o,byModel:r}}function me(e,t){try{let n=J(t-fe*864e5);for(let r of L(_(e)))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&le(h(_(e),r))}catch{}try{let n=h(_(e),"live");for(let r of L(n))r.endsWith(".log")&&t-B(h(n,r))>2*864e5&&le(h(n,r));L(n).length===0&&Ie(n)}catch{}}export{ze as ASK_MS,ce as HELPER_ACTION,Fe as RESERVE_MS,qe as STALE_MS,it as admit,Ze as atOnceFor,_ as helpersDir,Fr as launchStep,Y as ledgerFile,ge as liveAt,Ye as modelRuleFor,qr as onEvent,et as ownAgentRule,U as readLedger,st as refusedIn,zr as runningNow,Ve as settingsFiles,Qe as subagentEntries,Hr as switchesIn,rt as transcriptChanged};