@useanvil/claude-code 0.9.1 → 0.10.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.
- package/CHANGELOG.md +703 -0
- package/README.md +128 -38
- package/dist/Anvil +0 -0
- package/dist/claude-approve.js +23 -0
- package/dist/claude-conditions.js +19 -12
- package/dist/claude-helpers.js +9 -9
- package/dist/claude-hook-core.js +88 -80
- package/dist/claude-hook.js +38 -37
- package/dist/claude-meter.js +52 -48
- package/dist/claude-powershell.cjs +17 -17
- package/dist/claude-sync.js +26 -26
- package/dist/cli/claude-main.js +5392 -2510
- package/docs/coding-agents/YOUR-RULES.md +507 -654
- package/package.json +1 -1
|
@@ -1,12 +1,19 @@
|
|
|
1
|
-
function
|
|
2
|
-
`){f++;continue}e[f]==="\\"&&/["\\$`]/.test(e[f+1]??"")?f++:e[f]==="$"&&(
|
|
3
|
-
`)n+=e[a]??"",i=!0;else if(!
|
|
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&>.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"),
|
|
6
|
-
`)&&/(?<!\r)\n/.test(
|
|
7
|
-
`&&(i+=h,u=!0),
|
|
8
|
-
`?"":y:(
|
|
9
|
-
`,
|
|
10
|
-
`)for(let[
|
|
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
|
|
1
|
+
function z(e){return Object.assign(Object.create(null),e)}var Oe=[{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 Ie=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,Dt=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,Mt=/(?:^|[^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]|$)/,De=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),Me=(e,t)=>e.split("+").every(n=>n[0]==="="?t.split(/[^a-z0-9]+/).includes(n.slice(1)):t.includes(n));function Lt(e,t){let n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),r=t.replace(/_/g,"");return e.servers.some(s=>{let o=s.replace(/_/g,"");return`_${t}_`.includes(`_${s}_`)||n.includes(`_${s}_`)||(o.length>4?r.includes(o):o.length>3&&(r.startsWith(o)||r.endsWith(o)))})}function Wt(e,t,n){let r=t.normalize("NFKC").toLowerCase().replace(/\.+$/,""),s=/^[a-z0-9.-]+$/.test(r);if(!r.includes("."))return s?(e.clis??[]).includes(r)?"this":"other":"?";let o=r.split("."),i=u=>r===u||r.endsWith(`.${u}`)||u.includes("*")&&u.split(".").every((d,a,c)=>c.length===o.length&&(d==="*"||d===o[a])),l=!1;return e.hosts.some(u=>{let d=u.indexOf("/");return d<0?i(u):(l||=i(u.slice(0,d))&&/^(?:\/batch\/?|\u0000)$/.test(n),i(u.slice(0,d))&&n.includes(u.slice(d)))})?"this":s&&!l?"other":"?"}function Tt(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 O(e,t,n,r){let s=De(n);return e.toolWords.length===0||e.toolWords.some(o=>Me(o,s))?{hit:"match",part:t,why:e.said}:r===3||/\u0000|%00/.test(s)||Mt.test(s)||!/[a-z]{3}/.test(s.replace(/[a-z]*\d[a-z0-9]*/g,""))||r===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(s)?{hit:"unknown",part:t,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function zt(e,t,n){let r=c=>({hit:"unknown",part:t,why:`Anvil can't tell ${c}, so it holds it (your rule: ${e.said})`});if(t.action==="claude.mcp.side_effect"){let c=t.host;if(!c)return r("which app this tool belongs to");let f=`mcp.${c}.`,g=De(n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):t.target?.startsWith(f)?t.target.slice(f.length):"");if(Lt(e,c))return O(e,t,g,1);let p=(e.anywhere??[]).some(m=>Me(m,g))?{hit:"match",part:t,why:e.said}:null;if(!Ie.test(c)&&!Dt.test(c))return p;let h=e.toolPrefixes.find(m=>g.startsWith(m));return h?O(e,t,g.slice(h.length),1):e.servers.some(m=>m.length>2&&`_${g}_`.includes(`_${m}_`))?O(e,t,g,1):p||(e.others??[]).includes(c)?p:r(`which app ${Ie.test(c)?`the connector ${c.slice(0,8)}\u2026`:c} acts on`)}let s=t.target??"",o=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(s)?`https://${s}`:s,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(o),l="";try{i&&(l=decodeURIComponent(new URL(o).pathname).replace(/\/{2,}/g,"/"))}catch{l="\0"}if(!t.host&&!t.service)return r("where this writes");let u=[t.host,t.service,...Array.isArray(t.attributes.hosts)?t.attributes.hosts:[],Tt(o)].filter(c=>typeof c=="string"&&c!==""),d=u.map(c=>Wt(e,c,l)),a=[s,...u].some(c=>/^smtps?[:.]/i.test(c));if(d.includes("this")||a&&e.hosts.includes("smtp:")){let c=u.find((g,p)=>d[p]==="this"&&!g.includes(".")),f=s.includes("/")?3:2;return c?O(e,t,`cli:${c.toLowerCase()} ${s}`,f):a?O(e,t,"send mail",2):i?O(e,t,l,3):O(e,t,s,f)}return d.includes("?")?r(`where this writes (${u[0].replace(/[\u0000-\u001f]/g,"")})`):n.tool?.startsWith("mcp__")?r("what else this tool's command writes"):null}function ie(e,t,n){let r=null;for(let s of t){let o=zt(e,s,n);if(o?.hit==="match")return o;r??=o}return r??(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 Ft={over:"over",at_least:"at least",under:"under",at_most:"at most"};var k="Anvil can't read how much this moves",Fe="Anvil can't read this invoice's total (only drafting or replacing one says it)",qt="Anvil can't add up this total (a tax, a discount, shipping, a tip, a template or a series changes it)",Le="Anvil can't tell which currency this moves (it names two)",Gt="Anvil can't tell how many requests this makes (curl expands {\u2026} and [\u2026] in a URL)",ue="claude.mcp.side_effect",Ut=/\$\(|\$'|\$"|`|<<|(?:^|[\s;&|])(?:eval|xargs|source|exec)(?=\s|$)|\b(?:ba|z|k|da)?sh\s+-\w*c\b/,Ht=/^(?:[A-Za-z_]\w*=.*|env|sudo|time|nohup|command|builtin|nice)$/,Bt="012346#aBfgGiIjJklLMnNOpqRsSvVZ",Kt=/^(?: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)$/,Zt=/^(?:data(?:-raw|-binary|-ascii|-urlencode)?|form(?:-string)?|json)$/,Vt=/^(?:live|confirm|help|version|dark_style|show_headers|dry_run|reverse_transfer|refund_application_fee|capture|final_capture)$/;function F(e){let t=(e.host??"").toLowerCase(),n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),r=Oe.filter(s=>e.action===ue?s.servers.some(o=>`_${t}_`.includes(`_${o}_`)||n.includes(`_${o}_`)):s.clis.includes(t)||s.hosts.some(o=>t===o||t.endsWith(`.${o}`)));return r.length===1?r[0]:null}function Jt(e){let t=[[]],n="",r=!1,s=!1,o=!1,i=!1,l=!1,u=!1,d=()=>{l&&u?u=!1:l&&t[t.length-1].push({w:n,d:r,x:s,g:o}),n="",r=s=o=i=l=!1};for(let a=0;a<e.length;a++){let c=e[a];if(c==="'"){let f=e.indexOf("'",a+1);if(f<0)return null;n+=e.slice(a+1,f),a=f,i=!0}else if(c==='"'){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]==="$"&&(r=!0),n+=e[f]}if(f>=e.length)return null;a=f,i=!0}else if(c==="\\"){if(a++,e[a]!==`
|
|
3
|
+
`)n+=e[a]??"",i=!0;else if(!l)continue}else if(c==="#"&&!l){if(a=e.indexOf(`
|
|
4
|
+
`,a)-1,a<0)break;continue}else{if(/[(){}]/.test(c))return null;if(c==="<"||c===">"||c==="&"&&e[a+1]===">"){if((i||!/^\d+$/.test(n))&&d(),n="",r=s=o=i=l=!1,u)return null;c==="&"&&a++,(e[a]===">"?/[>|&]/:/[&>]/).test(e[a+1]??"")&&a++,u=!0;continue}else if(/[;|&\n]/.test(c)){if(d(),u)return null;t[t.length-1].length>0&&t.push([]);continue}else if(c===" "||c===" "){d();continue}else{if(/\s/.test(c))return null;c==="$"&&(r=s=!0),/[*?[]/.test(c)&&(o=!0),n+=c}}l=!0}return d(),u?null:t}function qe(e,t){let n=t.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1").split("/");return Object.keys(e).filter(r=>{let s=r.split(" ")[0].split("/");return r[0]==="/"&&s.length===n.length&&s.every((o,i)=>o==="*"?n[i]!=="":o===n[i])})}var le=e=>e.filter(t=>t[0]!=="!"&&t[0]!=="$").map(t=>t.replace(/^~/,"").split(" ")[0]);function Z(e,t){return[...new Set(e.map(n=>n.split(".").pop()))].reduce((n,r)=>n+(t.match(new RegExp(`(?:(?<![a-z0-9_]|[a-z0-9]-)|(?<=(?:^|\\s)-[a-z]+))${r.replace(/_/g,"[-_]")}(?![a-z0-9_]|-[a-z0-9])`,"gi"))?.length??0),0)}function de(e,t,n,r,s){let o=[],i=[],l=0;for(let d of t){let a=/^[!~$]/.test(d)?d[0]:"",[c="",f]=d.slice(a.length).split(" \xD7 "),g=[{v:n,up:null,curs:[]}];for(let p of c.split(".")){let h=[];for(let{v:m,curs:y}of g)if(m!=null){if(p==="*"?!Array.isArray(m):typeof m!="object"||Array.isArray(m))return k;if(p==="*")h.push(...m.map(b=>({v:b,up:null,curs:y})));else if(Object.hasOwn(m,p)){let b=m;h.push({v:b[p],up:b,curs:b.currency===void 0?y:[...y,b.currency]})}}g=h.filter(m=>m.v!==void 0&&m.v!==null)}if(a==="!"&&g.some(p=>p.v!==!1))return qt;if(a==="~"&&(l+=g.length),a==="$")for(let{v:p}of g){if(typeof p!="string")return k;i.push(p.toLowerCase())}if(!a)for(let{v:p,up:h,curs:m}of g){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))];o.push({v:b[e.obj[0]],cur:w.length>1?"?":w[0],q:y})}}else{let b=[...new Set(m)];o.push({v:p,cur:b.length>1?"?":b[0],drop:s,q:y})}}}if(i.length>0){if(new Set(i).size>1)return Le;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 Le}let u=le(t);return Math.max(Z(u,r),Z(u,JSON.stringify(n)))>o.length+l?k:o}var ae=/[\s,]+|#[^\n\r]*|("(?:[^"\\\n\r]|\\.)*")|(\.\.\.|[!$&():=@[\]{|}])|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([_A-Za-z]\w*)/y;function Yt(e,t,n,r){let s=r,o=s?.variables??{},i=s?.query;if(!s||typeof s!="object"||Array.isArray(s)||typeof i!="string"||i.includes('"""')||typeof o!="object"||Array.isArray(o))return k;let l=[];for(ae.lastIndex=0;ae.lastIndex<i.length;){let h=ae.exec(i);if(!h)return k;let m=h[1]??h[2]??h[3]??h[4];m!==void 0&&l.push(m)}let u=0,d=()=>l[u],a=h=>{let m=l[u++];if(m===void 0||h!==void 0&&m!==h)throw new Error;return m},c=()=>{let h=a();if(!/^[_A-Za-z]/.test(h))throw new Error;return h},f=()=>{let h=a();if(h==="$"){let m=c();if(!Object.hasOwn(o,m))throw new Error;return o[m]}if(h==="["){let m=[];for(;d()!=="]";)m.push(f());return a(),m}if(h==="{"){let m={};for(;d()!=="}";){let y=c();a(":"),m[y]=f()}return a(),m}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},g=()=>{let h={};if(d()!=="(")return h;for(a();d()!==")";){let m=c();a(":"),h[m]=f()}return a(),h},p=()=>{for(let h=1;h>0;){let m=a();h+=m==="{"?1:m==="}"?-1:0}};try{let h="query";if(d()!=="{"&&(h=a(),d()!=="("&&d()!=="{"&&c(),d()==="(")){for(a();a()!==")";)if(l[u-1]==="=")throw new Error}a("{");let m=[];if(h==="query")p();else{if(h!=="mutation")throw new Error;for(;d()!=="}";){let y=c();d()===":"&&(a(),y=c());let b=g();for(;d()==="@";){if(a(),c()!=="idempotent")throw new Error;g()}d()==="{"&&(a(),p());let w=n.find($=>$.endsWith(` ${y}`));m.push(w?de(e,t[w],b,JSON.stringify(b),e.nameless?.includes(w)):k)}if(a(),m.length===0)throw new Error}if(u<l.length)throw new Error;return h==="query"?"read":m}catch{return k}}var V=(e,t,n)=>{e.set(t,[...e.get(t)??[],n])};function Ge(e,t,n,r){let s=le(e);if([...t.keys()].some(d=>!e.includes(d)&&Z(s,d)>0))return k;let o=t.get("currency")??[],i=d=>d.some(a=>a.d)||new Set(d.map(a=>a.w)).size>1?"?":d[0]?.w,l=[],u=0;for(let d of e){let a=t.get(d)??[];if(u+=a.length,a.length===0)continue;let c=i(a);if(c==="?")return k;l.push({v:c,cur:o.length>0?i(o):void 0,drop:r})}return Z(le(e),n)>u?k:l}function ce(e,t,n){let r=t.w.indexOf("=");if(r<=0||t.w.slice(0,r).includes("$"))return!1;let s=t.w.slice(0,r),o=t.w.slice(r+1);try{s=decodeURIComponent(s.replace(/\+/g," ")),n&&(o=decodeURIComponent(o.replace(/\+/g," ")))}catch{return!1}return V(e,s,{w:o,d:t.d&&o.includes("$"),x:!1}),!0}function Xt(e,t,n,r,s){let o=[],i=new Map;for(let c=0;c<n.length;c++){let{w:f,d:g}=n[c];if(f.startsWith("--")){let p=f.indexOf("="),h=(p<0?f.slice(2):f.slice(2,p)).replace(/-/g,"_");if(p<0&&Vt.test(h))continue;let m=p>=0?{w:f.slice(p+1),d:g,x:!1}:n[++c];if(!m||p<0&&/^-./.test(m.w))return k;if(h==="data"){if(!ce(i,m,!1))return k}else V(i,h,m)}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:g,x:!1}:n[++c];if(!h||p+1===f.length&&/^-./.test(h.w)||f[p]==="d"&&!ce(i,h,!1))return k}else o.push(n[c])}let[l="",u=""]=o.map(c=>c.w);if(l==="get"||u==="list"||u==="retrieve")return"read";let d=`${l} ${u}`,a=Object.hasOwn(t,d)?d:/^(?:post|delete)$/.test(l)&&u[0]==="/"?qe(t,u.split("?")[0]).find(c=>!c.includes(" ")):void 0;if(!a)return s;if(a!==d){if(o[1].d)return k;for(let[c,f]of new URLSearchParams(u.includes("?")?u.slice(u.indexOf("?")+1):""))V(i,c,{w:f,d:!1,x:!1})}return Ge(t[a],i,r,!!e.nameless?.includes(a))}function Qt(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 en=(e,t)=>{let n=Qt(t);return n&&e.hosts.some(r=>n.hostname===r||n.hostname.endsWith(`.${r}`))?n:null};function tn(e,t,n,r,s){let o=null,i="",l="",u=!1,d=!1,a=[];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"),Kt.test($))continue;let v=n[++y];if(!v)return k;Zt.test($)?a.push({v,how:$}):$==="request"&&(l=v.w.toUpperCase())}else if(/^-./.test(b))for(let $=1;$<b.length;$++){let v=b[$];if(v==="K"||v===":"||v==="T")return k;if((v==="G"||v==="I")&&(u=!0),v==="g"&&(d=!0),Bt.includes(v))continue;let S=$+1<b.length?{w:b.slice($+1),d:w,x:!1}:n[++y];if(!S)return k;v==="d"||v==="F"?a.push({v:S,how:v==="d"?"data":"form"}):v==="X"&&(l=S.w.toUpperCase());break}else{let $=en(e,b);if(!$)continue;if(w||o)return k;o=$,i=b}}if(!o)return null;if(/^(?:GET|HEAD|OPTIONS)$/.test(l||(u||a.length===0?"GET":"POST")))return"read";if(!d&&/[{}[\]]/.test(i))return Gt;if(e.json&&u&&a.length>0)return k;let c;try{c=decodeURIComponent(o.pathname)}catch{return k}let f=qe(t,c),g=f.find(y=>!y.includes(" "));if(!g&&f.length===0)return s;let p=new Map;for(let[y,b]of o.searchParams)V(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 k;try{h=JSON.parse(w)}catch{return k}}else for(let $ of w.split("&"))if(!ce(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(!g){let y=h===void 0||p.size>0?k:Yt(e,t,f,h);return typeof y=="string"?y:{many:y}}let m=!!e.nameless?.includes(g);return h!==void 0?de(e,t[g],h,r,m):Ge(t[g],p,r,m)}function nn(e,t,n,r){let s=n.input?.command,o=typeof s=="string"&&!Ut.test(s)?Jt(s):null;if(!o)return k;let i=[],l=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&&Ht.test(u[a].w);)a++;let c=(u[a]?.w??"").replace(/^.*\//,""),f=u.slice(a+1),g=e.clis.includes(c)?Xt(e,t,f,d,r):c==="curl"?tn(e,t,f,d,r):null;if(g===null){if(!/^(?:cd|pushd)$/.test(c)&&u.some(p=>l.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 *)";g!=="read"&&i.push(...typeof g=="object"&&!Array.isArray(g)?g.many:[g])}return i.length<n.parts.filter(u=>F(u)===e).length?k:i}var fe="this call doesn't say how much it moves",We=e=>typeof e=="number"?Number.isFinite(e)&&e>=0?String(e):"":typeof e=="string"?e.trim():"",Te=/^(\d+)(?:\.(\d+))?$/;function Ue(e,t,n){if(e.length===0)return fe;let r=0n,s=0;for(let{v:o,cur:i,drop:l,q:u}of e){let d=l&&(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==="?"?k:`it's in ${a.toUpperCase()}, not ${n.currency.toUpperCase()}`;let c=(t.minor?/^(\d+)()$/:Te).exec(We(o)),f=u===void 0?null:Te.exec(We(u));if(!c||u!==void 0&&!f||(c[1]+(c[2]??"")).length>30||f!==null&&(f[1]+(f[2]??"")).length>30)return k;let g=(t.minor?t.digits?.[a]??n.digits:(c[2]??"").length)+(f?.[2]??"").length,p=Math.max(s,g);r=r*10n**BigInt(p-s)+BigInt(c[1]+(c[2]??""))*BigInt(f?f[1]+(f[2]??""):1)*10n**BigInt(p-g),s=p}return[r,s]}function ze(e,t,n){let r=e.toString().padStart(t+1,"0"),s=r.slice(0,r.length-t),o="";for(let i=s.length;i>0;i-=3)o=`${s.slice(Math.max(0,i-3),i)}${o?`,${o}`:""}`;return`${n}${o}${t>0?`.${r.slice(-t)}`:""}`}function He(e,t,n){let r=F(t),s=e.invoice?r?.invoices:r?.at,o=n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):"",i=n.input,l=!i||Object.hasOwn(s??{},o)?o:`${o} ${String(i.service).toLowerCase()} ${String(i.method)}`,u=e.invoice?Fe:k;return!r||!s||!e.apps.includes(r.app)?k:t.action!==ue?nn(r,s,n,u):i&&Object.hasOwn(s,l)?[de(r,s[l],i,JSON.stringify(i),r.nameless?.includes(l))]:u}function rn(e,t,n){let r=He(e,t,n);if(typeof r=="string")return r;if(r.length===0)return fe;let s=0n;for(let o of r){let i=typeof o=="string"?o:Ue(o,F(t),e);if(typeof i=="string")return i;let[l,u]=i,d=10n**BigInt(Math.abs(u-e.digits));s+=u<=e.digits?l*d:(l+d-1n)/d}return s<=BigInt(Number.MAX_SAFE_INTEGER)?Number(s):"Anvil can't count an amount that large"}function sn(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 r=t?.parts.filter(i=>e.kinds.includes(i.action)&&(!e.match||ie(e.match,[i],t)!==null))??[];if(r.length===0)return"Anvil can't tell how much this moves";let s=0,o=new Set;for(let i of r){let l=F(i),u=l?`${l.app}\0${i.action===ue}`:null;if(u!==null&&o.has(u))continue;u!==null&&o.add(u);let d=rn(n,i,t);if(typeof d=="string")return d;s+=d}return Number.isSafeInteger(s)?s:"Anvil can't count an amount that large"}function Be(e,t,n){try{return on(e,t,n)}catch{return{hit:"unknown",why:"Anvil can't read the amount this moves"}}}function on(e,t,n){let r=F(t),s=He(e,t,n),o=l=>e.invoice&&l===fe?Fe:l;if(typeof s=="string")return{hit:"unknown",why:o(s)};let i=null;for(let l of s){let u=typeof l=="string"?l:Ue(l,r,e);if(typeof u=="string"){i??=u;continue}let[d,a]=u,c=Math.max(a,e.digits),f=d*10n**BigInt(c-a),g=BigInt(e.value)*10n**BigInt(c-e.digits),[p,h]=[f,c];for(;h>e.digits&&p%10n===0n;)[p,h]=[p/10n,h-1];if(e.op==="over"?f>g:e.op==="at_least"?f>=g:e.op==="under"?f<g:f<=g)return{hit:"match",detail:`${ze(p,h,e.sign)} is ${Ft[e.op]} ${ze(BigInt(e.value),e.digits,e.sign).replace(/\.0+$/,"")}`}}return i===null?null:{hit:"unknown",why:o(i)}}import{createHash as eo}from"crypto";import{existsSync as Q,readdirSync as qn,statSync as pt}from"fs";import{dirname as $e,isAbsolute as Gn,join as A,posix as Un,resolve as U}from"path";import{posix as Pr}from"path";var an=null;function M(){return an??process.platform==="win32"}function Ke(e){if(!M())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 I(e){return M()?Ke(e)??e:e}import{createHash as Is}from"crypto";import{appendFileSync as Ms,closeSync as Wn,constants as ft,fstatSync as Tn,mkdirSync as Ls,openSync as zn,readdirSync as Ws,readFileSync as Ts,readSync as Fn,renameSync as zs,statSync as Fs,unlinkSync as qs,writeFileSync as Gs}from"fs";import{homedir as Hs}from"os";import{dirname as Ks,join as Zs}from"path";import{domainToASCII as ln}from"url";var cn="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",un="klaviyo himalaya convertkit api.kit.com activecampaign api-us1.com activehosted constantcontact constant_contact api.cc.email beehiiv helpscout help_scout freshdesk substack",me=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),dn=null,he={has:e=>(dn??=new Set(cn.split(" "))).has(e)},et=/^(?:from|sender|replyto|returnpath|envelopefrom|mailfrom|bounce)|^(?:useremail|usergoogleemail|account|accountemail|organizer|owner|user|mailbox|asm)$/,ye=/(?:contact|member|participant|attendee|guest|invitee|person|people|subscriber|customer|recipient|audience|segment|list|group)(?:id|ids|s)?$|userids$|identifiers$|campaignids?$/,tt=/^(?:draft|(?:draft|message|msg|email|thread|conversation|originalmessage|replytomessage|parentmessage)ids?|inreplyto|references)$/,fn=/^(?:instructions?|prompt|task)$/,nt=/ids?$/,rt=/^(?: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$/,pn=/^(?:email|emailaddress|address|mail|addr)$/,gn=null,mn={exec:e=>(gn??=new RegExp(`(?:^|[^a-z0-9])(${un.replace(/\./g,"\\.").replace(/ /g,"|")})`)).exec(e)},we=/send.{0,20}draft|draft.{0,20}send|(?<!no-?)reply|\/messages\/[^/?\s]+\/[^?\s]{0,200}send/,st=/\$batch|(?:^|[^a-z])(?:batch|jmap)(?:[^a-z]|$)|multi_?execute|(?:^|[^a-z])execute(?:[^a-z]|$)|graphql|(?:^|[^a-z])(?:api_?)?request(?:[^a-z]|$)/,hn=/^(?: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)$|[%!]/,yn=/(?:^|\.)(?:googlegroups\.com|groups\.io)$|^(?:lists?|groups?)\./;function be(e){let t=ln(e.normalize("NFKC").toLowerCase().replace(/\.$/,""));return/^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$/.test(t)?t:""}function wn(e){let t=e.trim().replace(/^mailto:/i,""),n=/<([^<>]*)>$/.exec(t);n&&(t=n[1].trim());let r=t.length;for(;r>0&&`"'`.includes(t[r-1]);)r--;t=t.slice(0,r).replace(/^["']+/,"");let s=/^([^\s@<>(),;:"[\]]+)@([^\s@<>(),;:"[\]]+)$/u.exec(t),o=s?be(s[2]):"";if(!o)return null;let i=s[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:hn.test(i)||yn.test(o)}}function X(e){let t=[],n=!/[<"]/.test(e),r="",s=!1,o=!1;for(let i=0;i<e.length;i++){let l=e[i];if(s&&l==="\\"){r+=l+(e[++i]??"");continue}l==='"'?s=!s:l==="<"?o=!0:l===">"&&(o=!1),!s&&!o&&(l===","||l===";"||n&&/\s/.test(l))?(t.push(r),r=""):r+=l}return t.push(r),s||o?[null]:t.filter(i=>i.trim()).map(i=>(i.replace(/"(?:[^"\\]|\\.)*"/g,"").match(/@/g)??[]).length===1?wn(i):null)}var x="Anvil can't read who this goes to",L="Anvil can't read who this goes to: it is built when the line runs",Ze="Anvil can't read who this goes to: its body can't be read",G="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",ot="Anvil can't read who this goes to: it runs a batch, or any request";function D(e,t){for(let n of X(e))n?(t.list.push(n),t.known=!0):t.why??=`${x} ("${e.trim().slice(0,40)}")`}function it(e,t){let n=e.includes(`
|
|
5
|
+
`)?e:Buffer.from(e,"base64").toString("utf8"),r=/\r?\n\r?\n/.exec(n),s=r?n.slice(0,r.index+r[0].length):n;(!/^[\w-]+:/.test(s)||/\r(?!\n)/.test(s)||n.includes(`\r
|
|
6
|
+
`)&&/(?<!\r)\n/.test(s))&&(t.why??=`${x}: its message can't be read`);for(let o of s.replace(/\r?\n[ \t]+/g," ").split(/\r?\n/)){let i=/^(?:resent-)?(?:to|cc|bcc)\s*:/i.exec(o);i&&D(o.slice(i[0].length),t)}}function Ve(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 r=n+1;for(;/\s/.test(e[r]??"");)r++;e[r]===":"&&t++}return t}function at(e,t){let n;try{n=/^\s*[[{]/.test(e)?JSON.parse(e):void 0}catch{n=void 0}return n!==void 0&&Ve(e)!==Ve(JSON.stringify(n))&&(t.why??=`${x}: it names a field twice`),n}function P(e,t,n=!1,r=0,s=!1,o=!1){if(r>12)t.why??=x;else if(typeof e=="string"){if(n)D(e,t);else if(!s&&!/[\s@]/.test(e)&&/[/_.]/.test(e)&&we.test(e.toLowerCase()))t.why??=G;else if(!s){let i=at(e,t),l=i===void 0?X(e):[];if(i!==void 0)P(i,t,!1,r+1,!1,o);else if(l.length>0&&l.every(u=>u!==null))for(let u of l)t.list.push(u);else/[^\s@]@[^\s@.]+\.[^\s@]/.test(e)&&(t.why??=`${x} ("${e.trim().slice(0,40)}")`)}}else if(Array.isArray(e))for(let i of e)P(i,t,n,r+1,s,o);else if(e&&typeof e=="object"){let i=!1;for(let[l,u]of Object.entries(e)){let d=me(l);u==null||u===""||Array.isArray(u)&&u.length===0||(n?pn.test(d)&&(i=!0,P(u,t,!0,r+1)):he.has(d)?P(u,t,!0,r+1):d==="raw"&&typeof u=="string"?it(u,t):(tt.test(d)||d==="id"&&r===0)&&(typeof u!="object"||Array.isArray(u))?(!o||d.startsWith("draft"))&&(t.why??=G):ye.test(d)?t.why??=`${x}: it names a list ("${l}")`:fn.test(d)?t.why??=`${x}: another tool picks who it reaches`:d==="calendarid"&&typeof u=="string"&&!/calendar\.google\.com$/i.test(u)?P(u,t,!1,r+1,s,o):!et.test(d)&&!nt.test(d)&&P(u,t,!1,r+1,s||rt.test(d),o))}n&&!i&&(t.why??=x)}else n&&e!==null&&e!==void 0&&(t.why??=x)}var pe=(e,t)=>e[t]==="`"||e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="(";function bn(e){let t=[],n=[],r=!1,s=[],o=[],i="",l=!1,u=!1,d=0,a=[],c=()=>{u&&(d?d===2&&!/^(?:\d+|-)$/.test(i)&&n.push({f:i,dyn:l}):(s.push(i),o.push(l)),d=0),i="",l=u=!1},f=()=>{c(),s.length>0&&t.push({w:s,dyn:o}),s=[],o=[]};for(let g=0;g<e.length;g++){let p=e[g],h=e[g+1];if(p==="\\")h!==void 0&&h!==`
|
|
7
|
+
`&&(i+=h,u=!0),g++;else if(p==="'"||p==="$"&&h==="'"){let m=p==="$"?g+2:g+1,y=e.indexOf("'",m);i+=e.slice(m,y<0?void 0:y),l||=p==="$"||y<0,u=!0,g=y<0?e.length:y}else if(p==='"'){let m=g+1;for(;m<e.length&&e[m]!=='"';m++){let y=e[m+1];e[m]==="\\"&&y!==void 0&&'"\\$`\n'.includes(y)?i+=e[++m]===`
|
|
8
|
+
`?"":y:(r||=pe(e,m),l||=e[m]==="$"||e[m]==="`",i+=e[m])}l||=m>=e.length,u=!0,g=m}else if(p==="$"||p==="`")r||=pe(e,g),i+=p,l=u=!0;else if(p==="#"&&!u){let m=e.indexOf(`
|
|
9
|
+
`,g);g=(m<0?e.length:m)-1}else if(p==="<"&&h==="<"&&e[g+2]!=="<"){c();let m=/^<<(-?)[ \t]*((?:[^\s;&|<>()'"\\]|'[^']*'|"[^"]*"|\\.)+)/.exec(e.slice(g));m&&a.push([m[2].replace(/'([^']*)'|"([^"]*)"|\\(.)/g,"$1$2$3"),m[1]==="-",/['"\\]/.test(m[2])]),g+=(m?.[0].length??2)-1}else if(p==="<"||p===">"||p==="&"&&h===">"){/^\d+$/.test(i)&&!l&&(u=!1),c();let m=p;for(;/[<>&|]/.test(e[g+1]??"");)m+=e[++g];d=m.includes(">")?2:1}else if(/[;&|()\n]/.test(p)){if(f(),p===`
|
|
10
|
+
`)for(let[m,y,b]of a.splice(0)){let w=g+1;for(;;){let $=e.indexOf(`
|
|
11
|
+
`,w),v=e.slice(w,$<0?void 0:$);if(w=$<0?e.length:$+1,$<0||(y?v.replace(/^\t+/,""):v)===m)break;for(let S=0;!b&&S<v.length;S++)v[S]==="\\"?S++:r||=pe(v,S)}g=w-1}}else/\s/.test(p)?c():(i+=p,u=!0)}return f(),{list:t,sub:r,writes:n}}function $n(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 ge=["srAaSqTOuC","cb","tfHE"],Je=["sifmQd","cb","HeF"],kn=z({mail:ge,mailx:ge,"s-nail":ge,sendmail:["fFOpRVNLBXh","","tC"],msmtp:["afCX","","t"],mutt:Je,neomutt:Je}),Ye=/^\s*(?:to|cc|bcc)\s*:/i,J="Anvil can't read who this goes to: it may read them from the message or its settings";function _n(e,t,n,r,s){let o=kn[e];if(!o){let a=!1;for(let c=r;c<t.length;c++){let f=/^(?:--(to|cc|bcc|recipients?|attendees?)|-(t))(?:=([^]*))?$/.exec(t[c]);if(!f||f[2]&&e!=="swaks")continue;let g=f[3]??t[++c];a=!0,g===void 0||n[c]?s.why??=L:D(g,s)}a||(s.why??=x);return}let[i,l,u]=o,d=!1;for(let a=r;a<t.length;a++){let c=t[a];if(d||!c.startsWith("-")||c==="-")n[a]?s.why??=L:D(c,s);else if(c==="--")d=!0;else if(c.startsWith("--")){let f=/^--([\w-]+)(=?)/.exec(c),g=f?.[1]??"";if(/^(?:append|subject|return-address|from|attach|content-type|encoding|account|host|port|user)$/.test(g)){let p=f?.[2]?c.slice(c.indexOf("=")+1):t[++a];p!==void 0&&Ye.test(p)&&(n[a]?s.why??=L:D(p.slice(p.indexOf(":")+1),s))}else/^(?:norc|nosum|ignore|quit|debug|verbose|auth|tls|read-envelope-from|skip-empty-attachments)$/.test(g)||(s.why??=J)}else if(e==="sendmail"&&/^-b[^m]/.test(c))s.why??=J;else if(/mutt/.test(e)&&c.startsWith("-a"))for(;a+1<t.length&&t[a+1]!=="--";)a++;else for(let f=1;f<c.length;f++){let g=c[f];if(u.includes(g)&&(s.why??=J),!i.includes(g)&&!l.includes(g))continue;let p=f+1<c.length?c.slice(f+1):t[++a];/^\s*(?:sendmail|mta)\s*=/i.test(p??"")&&(s.why??=J),n[a]&&"aTC".includes(g)&&i.includes(g)&&(s.why??=L);let h=p!==void 0&&Ye.test(p);if(!l.includes(g)&&!h)break;p===void 0||n[a]?s.why??=L:D(h?p.slice(p.indexOf(":")+1):p,s);break}}}function Xe(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`)}catch{return null}}var vn="AbcCdDeEFHKmoPQrtTuUwxXyYz",xn=/^(?:data(?:-ascii|-binary|-raw|-urlencode)?|json|form(?:-string)?|url|header)$/,Qe=/^(?:config|upload-file|url-query|variable|request-target|mail-rcpt|expand-[\w.-]+)$/,Cn=/^(?: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)$/,An=/^(?: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)$/,Rn=/^(?:[oDc]|output|output-dir|dump-header|cookie-jar|stderr|trace|trace-ascii|libcurl|etag-save|hsts|alt-svc)$/,Y="Anvil can't read who this goes to: curl takes part of it from elsewhere";function q(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??=`${x}: this line writes a file a send may read or run (${e.slice(0,60)})`)}function Sn(e,t,n,r,s,o){let i=0,l=0,u=[],d=[],a=!1,c=!1,f=e.some((p,h)=>h>=n&&(/^-[^-]*O/.test(p)||p.startsWith("--remote-name"))),g=p=>{if(!s(p))return;let h=Xe(p);if(h?.hostname.toLowerCase().replace(/\.$/,"")!==r)o.why??=`${x}: a URL Anvil reads two ways`;else{l++;let m=h.pathname.toLowerCase();try{m=decodeURIComponent(m)}catch{o.why??=x}we.test(m)?o.why??=G:st.test(m)&&(o.why??=ot);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(l>0){i++;for(let w of d)Nn(w,a&&!c,u,o);Pn(u,o)}[l,u,d,a,c]=[0,[],[],!1,!1];continue}let m="",y;if(h.startsWith("--")){let w=/^--([\w.-]+)(=?)/.exec(h);if(m=w?.[1]??"",An.test(m.replace(/^no-/,"")))continue;if(m==="remote-header-name"||!xn.test(m)&&!Qe.test(m)&&!Cn.test(m)){o.why??=m==="remote-header-name"?Y:`${x}: curl takes an option Anvil doesn't know (--${m.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&&!m;w++)h[w]==="J"&&(o.why??=Y),vn.includes(h[w])&&(m=h[w],y=h.slice(w+1)||e[++p]);if(!m)continue}else{if(f){let w=Xe(h)?.pathname.split("/").pop()??"";q(w,!1,o);try{q(decodeURIComponent(w),!1,o)}catch{o.why??=x}}g(h);continue}if(y===void 0){o.why??=x;break}let b=t[p]??!1;if(/^[KT]$/.test(m)||Qe.test(m))o.why??=Y;else if(m==="url")g(y);else if(m==="H"||m==="header"){let w=/^\s*content-type\s*:/i.exec(y);y.startsWith("@")?o.why??=Y:w?/json/i.test(y.slice(w[0].length))&&!b?a=!0:c=!0:b&&!/^\s*[\w-]+\s*:/.test(y)&&(c=!0)}else if(Rn.test(m))q(y,b,o);else if(m==="F"||m.startsWith("form")||m==="data-urlencode"){let w=y.indexOf("="),$=y.indexOf("@"),v=m==="data-urlencode"?$>=0&&(w<0||$<w):m!=="form-string"&&/^[@<]/.test(y.slice(w+1));u.push([w>0?y.slice(0,w):"",y.slice(w+1),b,v])}else(m==="d"||m.startsWith("data")||m==="json")&&(b||m!=="data-raw"&&y.startsWith("@")?o.why??=`${x}: its body is ${b?"built when the line runs":"read from a file"}`:(a||=m==="json",d.push(y)))}return i}function Nn(e,t,n,r){let s=at(e,r);if(s!==void 0?P(s,r):t&&(r.why??=Ze),!t){s===void 0&&/^[\w-]+\s*:/.test(e)&&it(e,r);for(let o of e.split("&")){let i=o.indexOf("=");try{let l=decodeURIComponent(o.slice(0,Math.max(i,0)).replace(/\+/g," "));/^[\w.[\]-]*$/.test(l)&&(s===void 0||l.split(/[.[\]]+/).map(me).some(u=>he.has(u)||ye.test(u)))&&n.push([l,decodeURIComponent(o.slice(i+1).replace(/\+/g," ")),!1,!1])}catch{r.why??=Ze}}}}function Pn(e,t){for(let[n,r,s,o]of e){let i=n.split(/[.[\]]+/).map(me).filter(Boolean),l=i[i.length-1]??"";if(i.some(u=>he.has(u)))o||s?t.why??=`${x}: it is ${o?"read from a file":"built when the line runs"}`:D(r,t);else if(i.some(u=>ye.test(u)))t.why??=`${x}: it names a list ("${n}")`;else if(i.some(u=>tt.test(u)))t.why??=G;else{if(i.some(u=>et.test(u))||nt.test(l)||i.some(u=>rt.test(u)))continue;s?t.why??=L:o||P(r,t)}}}var jn=/^(?: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 En(e,t,n,r){let s=t.includes("."),o=new RegExp(`(?<![\\w.-])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-]|\\.\\w)`),i=c=>o.test(c.replace(/['"\\]/g,"").toLowerCase()),{list:l,sub:u,writes:d}=bn(e);u&&(r.why??=`${x}: this line runs a command inside another ($(\u2026) or \`\u2026\`), which Anvil doesn't read`);for(let c of d)q(c.f,c.dyn,r);let a=0;for(let c of l){let f=$n(c);if(((f?.name==="export"?c.w:c.w.slice(0,f?f.at-1:void 0)).some(g=>/^(?:\w*PATH|path|\w*HOME|\w*RC|LD_\w*|DYLD_\w*|(?:BASH_)?ENV)\+?=/.test(g))||f?.name==="printf"&&c.w.slice(f.at).some(g=>/^-\w*v/.test(g)))&&(r.why??=`${x}: this line sets where a program or its settings come from`),f?.name==="tee")for(let g=f.at;g<c.w.length;g++)c.w[g].startsWith("-")||q(c.w[g],c.dyn[g],r);!f&&c.w.every(g=>/^[A-Za-z_]\w*\+?=/.test(g))||(f&&s&&f.name==="curl"?a+=Sn(c.w,c.dyn,f.at,t,i,r):f&&!s&&f.name===t?(a++,_n(f.name,c.w,c.dyn,f.at,r)):(!f||!jn.test(f.name))&&(r.why??=`${x}: this line also runs ${f?f.name:"a command built when it runs"}, which Anvil doesn't read`))}(a===0||a<n)&&(r.why??=`${x}: Anvil reads a plain curl request or mail program, not this`)}function lt(e,t){let n={list:[],why:null},r=(e.host??"").toLowerCase(),s=e.action==="claude.mcp.side_effect",o=`${r} ${s?t.tool??"":/^[a-z][a-z0-9+.-]*:\/\//i.test(e.target??"")?e.target:""}`.toLowerCase(),i=mn.exec(o)?.[1];return i?n.why=`Anvil can't read who ${i} sends reach: they go to a list or a ticket`:we.test(o)?n.why=G:st.test(o)?n.why=ot:s&&t.input?P(t.input,n,!1,0,!1,/forward/.test((t.tool??"").split("__").pop().toLowerCase())):!s&&t.command&&r?En(t.command,r,t.parts.filter(l=>l.action===e.action&&(l.host??"").toLowerCase()===r).length,n):n.why=x,n.known||(n.why??=x),n}function On(e){let t=i=>Array.isArray(i)&&i.every(l=>typeof l=="string")?i:null,n=t(e.domains??[]),r=t(e.addresses??[]);if(!n||!r)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 s=n.map(be),o=r.map(i=>{let[l,u]=X(i);return l&&!u?`${l.local}@${l.domain}`:""});return s.includes("")||o.includes("")?"a recipient condition names an address or a domain Anvil can't read":s.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:s,addresses:o}}var ct=new WeakMap;function ut(e,t,n){let r=ct.get(e);if(r===void 0&&ct.set(e,r=On(e)),typeof r=="string")return{hit:"unknown",why:`Anvil can't use this rule's recipients (${r})`};let s;try{s=lt(t,n)}catch{return{hit:"unknown",why:"Anvil can't read who this goes to"}}let o=s.why;for(let i of s.list){let l=r.addresses.includes(`${i.local}@${i.domain}`)||r.domains.some(u=>i.domain===u||i.domain.endsWith(`.${u}`));if(r.outside?!l:l)return{hit:"match",detail:r.outside?`${i.shown} is outside ${[...r.domains,...r.addresses.length>0?["the addresses your rule names"]:[]].join(" and ")}`:`it goes to ${i.shown}`};i.group?o??=`${i.shown} may reach ${r.outside?"people outside":"anyone"} (a list or a relay)`:i.alien&&!r.outside&&(o??=`${i.shown} is in letters from another alphabet`)}return o===null?null:{hit:"unknown",why:o}}var In="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");function Dn(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 r=(n[1]==="-"?1:-1)*(Number(n[2])*60+Number(n[3]??0)),s=-t.getTimezoneOffset();return s!==r&&!(n[4]!==void 0&&s===r+60)}function dt(e,t,n){let r=new Date(n.now??NaN),s=r.getDay(),o=r.getHours(),i=o*60+r.getMinutes();if(!((n.now??0)>0&&s>=0))return{hit:"unknown",why:"Anvil can't tell when this call was made"};let l=process.env.TZ,u=`:${String(i%60).padStart(2,"0")}`;if(l!==void 0||r.getTimezoneOffset()===0){let d="";try{let a=Intl.DateTimeFormat().resolvedOptions().timeZone;a&&!Dn(l,r)&&(d=r.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${l===void 0?"":` (TZ is "${l}")`}`}}return e.at.some(d=>d.days.includes(s)&&i>=d.from&&i<d.to)?{hit:"match",detail:`it's ${In[s]} ${o%12||12}${u}${o<12?"am":"pm"}`}:null}import{existsSync as ts,readdirSync as ns,realpathSync as rs}from"fs";import{basename as os,dirname as is,join as as}from"path";function j(e,t=8*1024*1024){let n;try{n=zn(e,ft.O_RDONLY|ft.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=Tn(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 s=Buffer.alloc(r.size),o=0;for(;o<r.size;){let i=Fn(n,s,o,r.size-o,o);if(i===0)break;o+=i}return s.subarray(0,o)}finally{Wn(n)}}var Js=256*1024,Ys=1024*1024;function mt(e,t){try{let n=typeof e.repo_dir=="string"?I(e.repo_dir):e.repo_dir,r=t===null?null:I(t),s=e.repo_via,o=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:s==="gh"&&process.env.GH_REPO||null;if(typeof n!="string"||!Gn(n)||!Q(n)||s!=="git"&&s!=="gh"||/[$`]/.test(o??""))return null;if(s==="gh"&&o!==null)return gt([o],n);let i=Hn(n,r);if(i===null)return null;let l=new Map;for(let a of i)a.section==="remote"&&a.sub!==null&&(a.key==="url"||(s==="git"?a.key==="pushurl":a.key==="gh-resolved"&&a.value!=="base"))&&l.set(a.sub,[...l.get(a.sub)??[],a.value]);if(o!==null&&!l.has(o)&&!/^[./]|[/:]/.test(o))return null;let u=o!==null?l.get(o)??[o]:[...l.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!=="."&&!l.has(a.value)&&u.push(a.value);let d=new Set(u);for(let a of u)for(let c of i)c.section==="url"&&c.sub!==null&&/^(push)?insteadof$/.test(c.key)&&c.value&&a.startsWith(c.value)&&d.add(c.sub+a.slice(c.value.length));return d.size>0?gt([...d],n):null}catch{return null}}function gt(e,t){let n=[];for(let r of e){let s=decodeURIComponent(r.trim()),o=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(s)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(s),l=(o?Un.resolve("/",o[1]??o[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(s)&&!s.startsWith(".")?s:U(t,s)).replace(/[?#].*$/,"").split(/[\\/]/).filter(f=>f&&f!=="."),u=l.findIndex((f,g)=>g>=2&&/^pulls?$/.test(f));u>=2&&(l=l.slice(0,u));let[d,a]=l.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),c=a??d;if(!c||c==="..")return null;n.push(a!==void 0&&d!==".."?`${d}/${a}`:c)}return n}function Hn(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 r=Zn(e);return r&&Kn(r,t)}function Bn(e,t){let n=process.env,r=process.platform==="win32"?[A(n.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),A(n.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(o=>`${o}/gitconfig`),s=n.GIT_CONFIG_NOSYSTEM?[]:n.GIT_CONFIG_SYSTEM?[n.GIT_CONFIG_SYSTEM]:r;return n.GIT_CONFIG_GLOBAL?s.push(n.GIT_CONFIG_GLOBAL):t&&s.push(A(n.XDG_CONFIG_HOME||A(t,".config"),"git","config"),A(t,".gitconfig")),s.push(A(e.common,"config"),A(e.gitDir,"config.worktree")),s.filter(o=>o!=="/dev/null")}function Kn(e,t,n=[]){let r=[],s=24,o=(l,u)=>{n.push(l);let d=--s<0||u>5?void 0:j(l,1024*1024);if(d===void 0)return!1;for(let a of Vn(d?.toString("utf8")??""))if(r.push(a),a.key==="path"&&/^include(if)?$/.test(a.section)){let c=a.value.startsWith("~/")?t&&A(t,a.value.slice(2)):!/^[~%]/.test(a.value)&&U($e(l),a.value);if(!c||!o(c,u+1))return!1}return!0},i=!0;for(let l of Bn(e,t))i=o(l,0)&&i;return i?r:null}function Zn(e,t=!1){let n=r=>/^(ref: refs\/|[0-9a-f]{40})/.test(j(A(r,"HEAD"),4096)?.toString("utf8")??"");for(let r=U(e),s=0;s<64;s++,r=$e(r)){let o=A(r,".git"),i=["objects","refs"].every(l=>Q(A(r,l)))&&n(r)?r:null;if(Q(o)){let l=pt(o);if(l.isDirectory())n(o)&&(i=o);else if(i=l.isFile()?/^gitdir:\s*(.+)$/m.exec(j(o,65536)?.toString("utf8")??"")?.[1]?.trim():null,!i)return null}if(i){let l=U(r,i),u=j(A(l,"commondir"),65536),d=u===null?l:U(l,u.toString("utf8").trim());for(let a of t?[]:["remotes","branches"]){let c=A(d,a);if(Q(c)&&(!pt(c).isDirectory()||qn(c).length>0))return null}return{gitDir:l,common:d,top:r}}if($e(r)===r)return null}return null}function Vn(e){let t=[],n="",r=null;for(let s of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){s=s.trim();let o=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(s);if(o){let[l,...u]=o[1].toLowerCase().split(".");n=l,r=o[2]?.replace(/\\(.)/g,"$1")??(u.length>0?u.join("."):null),s=s.slice(o[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(s);i&&t.push({section:n,sub:r,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(l,u,d)=>u??d??"").trim()})}return t}var Jn={slack:"channel",github:"repo",linear:"team",jira:"project"};var Yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(e,t,n=!1){let r=e==="jira"&&typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?String(t):t;if(typeof r!="string")return null;let s=r.normalize("NFKC").trim().replace(/^(["'])(.*)\1$/,"$2");if(!s||s.length>300||/[$`\u0000-\u001f]/.test(s)||/[^\u0000-\u007f]/.test(s)&&new RegExp("\\p{Script=Latin}","u").test(s)&&new RegExp("(?!\\p{Script=Latin})\\p{L}","u").test(s))return null;if(e==="slack"){if(s=/^<#([A-Z0-9]+)(?:\|[^>]*)?>$/.exec(s)?.[1]??/\/archives\/([A-Z0-9]{6,})(?:[/?#]|$)/.exec(s)?.[1]??s,s.startsWith("@")||/^[DUW][A-Z0-9]{6,}$/.test(s))return"dm";if(/^[A-Z0-9]+$/.test(s))return/^[CG][A-Z0-9]{6,}$/.test(s)?`id:${s}`:null;let l=s.replace(/^#/,"").toLowerCase();return/^[a-z0-9][a-z0-9._-]{0,79}$/.test(l)||/^[\p{L}\p{N}][\p{L}\p{N}._-]{0,79}$/u.test(l)?`name:${l}`:null}if(e==="github"){let l=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s?#]+)/i.exec(s)??/^https?:\/\/(?:api|uploads)\.github\.com\/repos\/([^/\s]+)\/([^/\s?#]+)/i.exec(s)??/^([\w.-]+)\/([\w.-]+)$/.exec(s),u=a=>/^[\w.-]+$/.test(a)&&!/^\.+$/.test(a),d=a=>a.toLowerCase().replace(/\.git$/,"");return l?u(l[1])&&u(l[2])?`repo:${d(l[1])}/${d(l[2])}`:null:u(s)?`repo:?/${d(s)}`: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(s)??new RegExp(`(?:/issue/|/browse/)(${o})-\\d+`).exec(s);return i?`key:${i[1].toLowerCase()}`:n?null:(e==="linear"?Yn.test(s):/^\d+$/.test(s))?`id:${s.toLowerCase()}`:new RegExp(`^${e==="linear"?"[A-Z0-9]{1,7}":"[A-Z][A-Z0-9_]{1,9}"}$`).test(s)?`key:${s.toLowerCase()}`:`name:${s.toLowerCase().replace(/\s+/g," ")}`}function W(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 _e={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},yt={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},Xn=/^(?:user|users|user_?ids?|recipient|recipients)$/i,Qn=/^(?:arguments|args|params|parameters|input|data|payload|body|request|message|fields|issue|issues|items|options|update)$/i,ke=/^channels?$|^channel_ids?$/,er=/^(?:text|body|title|description|content|comment|summary|markdown|blocks|attachments)$/i;function tr(e,t){let n=0,r=(s,o)=>++n>2e3||o>6?!1:typeof s=="string"?W(e.app,N(e.app,s)).some(i=>kt(e,i)):Array.isArray(s)?s.slice(0,200).some(i=>r(i,o+1)):!!(s&&typeof s=="object")&&Object.entries(s).some(([i,l])=>!er.test(i)&&!_e[e.app].test(i)&&!yt[e.app]?.test(i)&&r(l,o+1));return r(t,0)}function wt(e,t,n=!1){if(!t)return null;let r=[],s=0,o=(i,l,u)=>{for(let[d,a]of Object.entries(i)){if(++s>2e3)return void r.push("?");let c=u?"":"~",f=Array.isArray(a)?a:[a];f.length>200&&r.push("?");let g=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(_e[e].test(d)||yt[e]?.test(d)){let p=!_e[e].test(d),h=e==="github"?/^(.*?)(_?)(?:repo|repository)(?:_?name)?$/i.exec(d):null,m=h?i[`${h[1]}${h[2]}owner`]:void 0;for(let y of g.length>0?g:[void 0])for(let b of W(e,N(e,typeof m=="string"&&typeof y=="string"&&!y.includes("/")?`${m.trim()}/${y.trim()}`:y,p)))r.push(b==="?"?"?":`${c}${b}`)}else if(e==="slack"&&Xn.test(d))for(let p of g)r.push(N("slack",p)==="dm"?`${c}dm`:"?");else if(l<6&&a&&typeof a=="object")for(let p of f.slice(0,200))p&&typeof p=="object"&&!Array.isArray(p)&&o(p,l+1,n||u&&l<2&&Qn.test(d))}};return o(t,0,!0),r.length>0?r.every(i=>i.startsWith("~"))?[...r,"?"]:r:null}function nr(e){let t=[],n="",r=null;for(let s=0;s<e.length;s++){let o=e[s];if(o==="\\"&&r!=="'"){n+=o+(e[++s]??"");continue}if(r)r=o===r?null:r;else if(o==="'"||o==='"')r=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 bt(e){let t=[],n="",r=null,s=!1;for(let o=0;o<e.length;o++){let i=e[o];r==="'"?i==="'"?r=null:n+=i:r==='"'?i==='"'?r=null:n+=i==="\\"&&o+1<e.length?e[++o]:i:i==="'"||i==='"'?(r=i,s=!0):i==="\\"?(n+=e[++o]??"",s=!0):/\s/.test(i)?((n||s)&&t.push(n),n="",s=!1):(n+=i,s=!0)}return r?null:((n||s)&&t.push(n),t)}var ht=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`/${e.replace(/^\/+/,"")}`,"https://x").pathname}catch{return"\0"}};function rr(e){let t=bt(e),n=t?t.findIndex(d=>/(?:^|\/)gh$/.test(d)):-1;if(!t||n<0)return["?"];let r=t.slice(0,n).flatMap(d=>d.startsWith("GH_REPO=")?[d.slice(8)]:[]).pop(),s=t.slice(n+1),o;for(let d=0;d<s.length;d++){let a=s[d];a==="-R"||a==="--repo"?o=s[++d]??"":a.startsWith("--repo=")?o=a.slice(7):/^-R[^-]/.test(a)?o=a.slice(2):/^-[A-Za-z]+R/.test(a)&&(o="?")}let i=s[0]==="repo"&&s[1]!=="rename"&&s[2]!==void 0&&!s[2].startsWith("-")?s[2]:void 0,l=o??r??i,u=s.filter(d=>/^https?:\/\/(?:www\.)?github\.com\/[^/]+\/[^/]+\/(?:pull|issues)\/\d+/i.test(d)).map(d=>`~${N("github",d)??"?"}`);return[l===void 0?"none":N("github",l)??"?",...u]}var sr=(e,t)=>mt(e.attributes,t.home)?.map(n=>N("github",n)??"?")??["?"];function or(e,t){let n=bt(t),r=n?n.findIndex(a=>/(?:^|\/)(?:curl|wget)$/.test(a)):-1;if(!n||r<0)return["?"];let s=[],o=[],i=n.slice(r+1);for(let a=0;a<i.length;a++){let c=i[a],f=/^(--data(?:-ascii|-binary|-raw|-urlencode)?|--json|--form(?:-string)?|--post-data|--body-data)(?:=([\s\S]*))?$/.exec(c);f?s.push(f[2]??i[++a]??""):c==="-d"||c==="-F"?s.push(i[++a]??""):/^-[dF]./.test(c)?s.push(c.slice(2)):/^https?:\/\//i.test(c)&&o.push(c)}let l=[],u=a=>{for(let c of[a].flat().flatMap(f=>typeof f=="string"?f.split(","):[f]))l.push(...W(e,N(e,c)))},d=a=>{let c=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!c)return void l.push("?");if(e==="slack"){let f=Object.keys(c).filter(g=>ke.test(g));f.length===0&&l.push("?");for(let g of f)u(c[g])}else if(e==="jira"){let f=(c.fields&&typeof c.fields=="object"?c.fields:c).project,g=f&&typeof f=="object"?f:null;l.push(...g?[g.key,g.id].filter(p=>p!==void 0).flatMap(p=>W(e,N(e,p))):["?"])}else{let f=wt("linear",c.variables??{},!0)??[],p=[...(typeof c.query=="string"?c.query:"").matchAll(/\b(teamId|teamKey|team|id|issueId|identifier)\s*:\s*"([^"\\]{1,100})"/g)].flatMap(h=>W(e,N(e,h[2],!/^team/.test(h[1])))).map(h=>`~${h}`);l.push(...f,...p,...f.length===0?["?"]:[])}};for(let a of o)try{for(let[c,f]of new URL(a).searchParams)e==="slack"&&ke.test(c)&&u(f)}catch{l.push("?")}for(let a of s){if(/^@|^[\w-]*@/.test(a)){l.push("?");continue}let c;try{c=JSON.parse(a)}catch{c=void 0}if(c!==void 0)d(c);else if(e==="slack"&&/^[\w-]+=/.test(a)){let f=a.split("&").map(g=>[g.slice(0,g.indexOf("=")<0?g.length:g.indexOf("=")),g.slice(g.indexOf("=")+1)]);for(let[g,p]of f){if(!ke.test(g))continue;let h=p;try{h=decodeURIComponent(p.replace(/\+/g," "))}catch{l.push("?");continue}u(h)}}else l.push("?")}return l.length>0?l:["?"]}var $t=e=>/^[a-z][a-z-]*\s+[a-z][a-z-]*$/.test(e)||!/[/:]/.test(e)&&e!=="graphql"&&e.length>0;function ir(e,t,n){let r=t.target??"";if(e==="slack"&&/hooks\.slack\.com/i.test(`${t.host??""} ${r}`))return["?"];let s=e==="github"&&$t(r);if(e==="github"&&!s){let a=ht(r),c=/^\/repos\/([^/]+)\/([^/]+)/.exec(a)??(/^https?:\/\/(?:www\.)?github\.com\//i.test(r)?/^\/([^/]+)\/([^/]+)/.exec(a):null);return[c?N("github",`${c[1]}/${c[2]}`)??"?":"?"]}let o=e==="jira"?/\/rest\/api\/(?:2|3|latest)\/(issue|project)\/([^/]+)/.exec(ht(r)):null;if(o)return W("jira",N("jira",o[2],o[1]==="issue"));let i=n.command??(typeof n.input?.command=="string"?n.input.command:"");if(i.length>65536)return["?"];let l=nr(i),u=l.filter(a=>s?/(?:^|[\s/])gh\s/.test(a)&&(/\s/.test(r)?a.includes(r.split(/\s+/)[1]):a.includes(r)):r.length>0&&a.includes(r)),d=a=>s?rr(a).flatMap(c=>c==="none"?sr(t,n):[c]):or(e,a);return u.length>0?u.flatMap(d):[...l.flatMap(d).filter(a=>a!=="?"&&!a.startsWith("~")).map(a=>`~${a}`),"?"]}function ar(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 kt(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 ee=e=>e.startsWith("key:")?e.slice(4).toUpperCase():e.replace(/^(?:name|id|repo):(?:\?\/)?/,"");function _t(e,t,n){let r=Jn[e.app],s=e.said.replace(/^in /,""),o=t.action==="claude.mcp.side_effect"?wt(e.app,n.input):ir(e.app,t,n),i=`Anvil can't tell which ${r} this acts in${e.app==="github"&&t.action!=="claude.mcp.side_effect"&&$t(t.target??"")?" (gh says it with --repo)":""}`;if(!o||o.length===0)return{hit:"unknown",why:i};let l=o.map(a=>a.replace(/^~/,"")).find(a=>kt(e,a));if(l)return{hit:"match",detail:l.startsWith("id:")?`${ee(l)} is ${s}`:e.app==="github"?[...new Set(o.filter(a=>a!=="?").map(a=>ee(a.replace(/^~/,""))))].join(", "):s};let u=o.find(a=>a==="?"||a.startsWith("~")||!(e.not??[]).includes(a)&&!ar(e,a));if(u===void 0)return t.action==="claude.mcp.side_effect"&&tr(e,n.input)?{hit:"unknown",why:`Anvil can't tell whether this acts in ${s}: 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:")?`${r} ${ee(d)}`:ee(d)} is ${s}`}}import{existsSync as Se,readdirSync as hr}from"fs";import{basename as oe,dirname as K,join as R}from"path";var ve=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|~[\\/]|file:|link:|[A-Za-z]:[\\/])|\.(?:tgz|tar|tar\.gz|whl|zip|gem|deb|rpm|nupkg|rb)$/i,E=/^(?:git\+|git:|git@|github:|gitlab:|bitbucket:|gist:|hg\+|svn\+|bzr\+|https?:|ssh:)/i;var lr=/^https?:\/\/(?:registry\.npmjs\.org|registry\.yarnpkg\.com|pypi\.org\/simple|pypi\.python\.org\/simple|(?:repo\.)?packagist\.org)\/*$/i;var xe=e=>e!==""&&!lr.test(e)&&!ve.test(e),Ce={npm:/^((?:@[\w.-]+\/)?[\w.-]+)(?:@.*)?$/,PyPI:/^([A-Za-z0-9](?:[\w.-]*[A-Za-z0-9])?)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;@,( ].*)?$/,"crates.io":/^([A-Za-z][\w-]*)(?:@.*)?$/,Go:/^([\w~-]+(?:\.[\w~-]+)+(?:\/[\w.~-]+)*)(?:@.*)?$/,RubyGems:/^([A-Za-z0-9][\w.-]*)(?::.*)?$/,Packagist:/^([\w.-]+\/[\w.-]+)(?:[:=@].*)?$/,NuGet:/^([A-Za-z0-9_][\w.-]*)$/},cr=/^(@?[\w][\w.+@:/-]*?)(?:[=:]\S*)?$/;function te(e,t){let n=e==="Go"?t:t.toLowerCase();return e==="PyPI"?n.replace(/[-_.]+/g,"-"):e==="crates.io"?n.replace(/_/g,"-"):n}function vt(e,t){return t.length<=214&&!/[\s\0]|^[-.]|\.\./.test(t)&&(Ce[e]??cr).test(t)}function xt(e,t){return(e==="npm"?/^@?[^@]+@(.*)$/:e==="PyPI"?/^[\w.-]+\s*(?:\[[^\]]*\])?\s*@\s*(.*)$/:/^$/).exec(t)?.[1]??""}var H=e=>ve.test(e)&&!E.test(e);function ne(e,t){let n=xt(e,t);return n!==""&&(H(n)||/^(?:portal|workspace):/.test(n))?n:null}function re(e,t){let n=xt(e,t);return n===""||E.test(t)?null:E.test(n)||/[:/]/.test(n)&&!ve.test(n)&&!/^(?:portal|workspace|catalog):/.test(n)?n:null}function B(e,t=!1){return e==="package.json"||e==="pnpm-workspace.yaml"?"npm":/^(?:requirements[\w.-]*\.(?:txt|in)|pyproject\.toml|Pipfile)$/.test(e)||t&&/^[^/\\]+\.(?:txt|in)$/.test(e)?"PyPI":e==="Cargo.toml"?"crates.io":e==="go.mod"||e==="go.work"?"Go":e==="Gemfile"?"RubyGems":e==="composer.json"?"Packagist":/\.(?:cs|fs|vb)proj$|^Directory\.Packages\.props$|^packages\.config$/.test(e)?"NuGet":null}var ur={names:[],members:[],includes:[]};function At(e){return Ce.PyPI.exec(e.trim())?.[1]??null}function dr(e){let t=[],n=[],r=[],s=[],o=a=>{let c=At(a);c&&t.push(c);let f=c?re("PyPI",a.trim()):null;f&&r.push([c,f]);let g=c?ne("PyPI",a.trim()):null;g&&s.push([c,g])},i=a=>{n.push(a)},l=(a,c)=>{for(let f of a.replace(/\{[^}]*\}/g,"").matchAll(/"([^"]*)"|'([^']*)'/g))c(f[1]??f[2])},u="",d=null;for(let a of e.split(`
|
|
13
|
+
`)){let c=a.replace(/(?:^|\s)#.*$/,"").trim();if(d){l(c,d),c.includes("]")&&(d=null);continue}let f=/^\[\[?([^\]]+)\]\]?$/.exec(c);if(f){u=f[1].replace(/["'\s]/g,"");let w=/(?:^|\.)(?:dependencies|dev-dependencies|build-dependencies)\.([\w.-]+)$/.exec(u);w&&t.push(w[1]);continue}let g=/^["']?([\w.-]+)["']?\s*=\s*(.*)$/.exec(c);if(!g)continue;let p=g[1],h=g[2],m=/(?:^|\.)(?:dependencies|dev-dependencies|build-dependencies|optional-dependencies|dependency-groups)$|^(?:packages|dev-packages)$/.test(u),y=/(?:^|\.)(?:dependencies|dev-dependencies|build-dependencies)\.([\w.-]+)$/.exec(u)?.[1];if(y&&/^(?:git|url|registry|package)$/.test(p)&&/^["']/.test(h)&&r.push([y,`${/^(?:git|url)$/.test(p)?"":`${p} `}${h.replace(/^["']([^"']*)["'].*$/,"$1")}`]),y&&p==="path"&&/^["']/.test(h)&&s.push([y,h.replace(/^["']([^"']*)["'].*$/,"$1")]),!h.startsWith("[")){m&&p!=="python"&&t.push(p);let w=(m||/^tool\.uv\.sources$|^patch\./.test(u))&&p!=="python",$=w?fr(h):null;$&&r.push([p,$]);let v=w?pr(h,u==="tool.uv.sources"):null;v&&s.push([p,v]);continue}let b=m||/^(?:dependencies|requires|dev-dependencies)$/.test(p)?o:p==="members"&&/(?:^|\.)workspace$/.test(u)?i:null;b&&(l(h,b),h.includes("]")||(d=b))}return{names:t,members:n,includes:[],from:r,local:s}}function fr(e){let t=/^\{.*?\b(git|url|file|registry|index|source|package)\s*=\s*["']([^"']*)["']/.exec(e);return!t||t[1]==="file"&&!E.test(t[2])?null:/^(?:git|url|file)$/.test(t[1])?t[2]:`${t[1]} ${t[2]}`}function pr(e,t){let n=/^\{.*?\b(path|file)\s*=\s*["']([^"']*)["']/.exec(e);return n&&!E.test(n[2])?n[2]:t&&/^\{.*?\bworkspace\s*=\s*true\b/.test(e)?"workspace":null}function Ae(e){let t=[],n=[],r=[],s=[],o=[];for(let i of e.split(`
|
|
14
|
+
`)){let l=i.replace(/(?:^|\s)#.*$/,"").trim(),u=/^(?:-r|--requirement)[\s=]+(\S+)/.exec(l);u&&E.test(u[1])?r.push([u[1],""]):u&&n.push(u[1]);let d=/^(?:-i|--index-url|--extra-index-url|-f|--find-links)(?:\s*=\s*|\s+)(\S+)/.exec(l)?.[1];d!==void 0&&xe(d)&&o.push(d);let a=/#egg=([\w.-]+)/.exec(i),c=(/^(?:(?:-e|--editable)[\s=]+)?(\S+)/.exec(i.trim())?.[1]??"").replace(/#.*$/,"");if(E.test(c)&&r.push(a?[a[1],c]:[c,""]),a)t.push(a[1]);else if(l&&!l.startsWith("-")&&!E.test(l)){let f=At(l);f&&t.push(f);let g=f?re("PyPI",l):null;g&&r.push([f,g]);let p=f?ne("PyPI",l):null;p&&s.push([f,p])}}return{names:t,members:[],includes:n,from:r,local:s,indexes:o}}function Ct(e,t,n){let r=JSON.parse(e),s=[],o=[],i=[],l=a=>{if(!(!n||!a||typeof a!="object"||Array.isArray(a)))for(let[c,f]of Object.entries(a)){if(typeof f!="string")continue;let g=re("npm",`x@${f}`);g?o.push([c,g]):ne("npm",`x@${f}`)&&i.push([c,f])}};for(let a of t){let c=r[a];Array.isArray(c)?s.push(...c.filter(f=>typeof f=="string")):c&&typeof c=="object"&&s.push(...Object.keys(c)),l(c)}for(let a of[r.overrides,r.resolutions,r.pnpm?.overrides])l(a);let u=r.workspaces,d=n?Array.isArray(u)?u:u&&typeof u=="object"&&Array.isArray(u.packages)?u.packages:[]:[];return{names:s,members:d.filter(a=>typeof a=="string"),includes:[],from:o,local:i}}function gr(e){let t=[],n=[],r=e.repositories;for(let s of Array.isArray(r)?r:r&&typeof r=="object"?Object.values(r):[]){let{type:o,url:i,package:l}=s&&typeof s=="object"?s:{};if(o==="package")for(let u of Array.isArray(l)?l:[l]){let d=u?.dist?.url??u?.source?.url;typeof u?.name=="string"&&typeof d=="string"&&(H(d)?n:t).push([u.name,d])}else typeof i=="string"&&i!==""&&(o==="path"||o==="artifact"||H(i)?n.push([i,""]):xe(i)&&t.push([i,""]))}return{from:t,local:n}}var mr=["dependencies","devDependencies","peerDependencies","optionalDependencies","bundleDependencies","bundledDependencies"];function Re(e,t,n=!1){if(e==="package.json"){let r=Ct(t,mr,!0),s=n?JSON.parse(t).name:void 0;return typeof s=="string"?{...r,names:[...r.names,s]}:r}if(e==="composer.json")return{...Ct(t,["require","require-dev"],!1),...gr(JSON.parse(t))};if(e==="pnpm-workspace.yaml"){let r=[],s=[],o="";for(let i of t.split(`
|
|
15
|
+
`)){let l=/^([\w-]+):/.exec(i);if(l)o=l[1];else if(o==="packages"){let u=/^\s*-\s*["']?([^"'#\s]+)/.exec(i);u&&s.push(u[1])}else if(o.startsWith("catalog")){let u=/^\s+["']?(@?[\w./-]+)["']?\s*:/.exec(i);u&&r.push(u[1])}}return{names:r,members:s,includes:[]}}if(/\.toml$|^Pipfile$/.test(e))return dr(t);if(/\.(?:txt|in)$/.test(e))return Ae(t);if(e==="go.mod"||e==="go.work"){let r=[],s=[],o=[],i=[],l="";for(let u of t.split(`
|
|
16
|
+
`)){let d=u.replace(/\/\/.*$/,"").trim(),a=/^(require|use|tool|replace)\s*\($/.exec(d);if(a)l=a[1];else if(d===")")l="";else{let c=/^(?:(require|use|tool|replace)\s+)?(\S+)/.exec(d),f=c?.[1]??l,g=f==="replace"?/^(?:replace\s+)?(\S+)(?:\s+\S+)?\s+=>\s+(\S+)(?:\s+(\S+))?/.exec(d):null;g&&g[2]!==g[1]?(H(g[2])?i:o).push([g[1],g[3]?`${g[2]} ${g[3]}`:g[2]]):c&&f&&f!=="replace"&&(f==="use"?s:r).push(c[2])}}return{names:r,members:s,includes:[],from:o,local:i}}if(e==="Gemfile"){let r=[...t.matchAll(/^\s*gem\s*\(?\s*["']([^"']+)["']([^\n]*)/gm)],s=r.flatMap(i=>{let l=/(?:\b(git|github|gist|bitbucket|source)\s*:|:(git|github|gist|bitbucket|source)\s*=>)\s*["']([^"']+)["']/.exec(i[2]),u=l?.[1]??l?.[2];return l?[[i[1],`${u==="git"||u==="source"?"":`${u}:`}${l[3]}`]]:[]}),o=r.flatMap(i=>{let l=/(?:\bpath\s*:|:path\s*=>)\s*["']([^"']+)["']/.exec(i[2]);return l?[[i[1],l[1]]]:[]});return{names:r.map(i=>i[1]),members:[],includes:[],from:s,local:o}}return B(e)==="NuGet"?{names:[...t.matchAll(/<(?:Package(?:Reference|Version)\s+(?:Include|Update)|package\s+id)\s*=\s*"([^"]+)"/gi)].map(r=>r[1]),members:[],includes:[]}:ur}var Rt={npm:["package.json","pnpm-workspace.yaml"],PyPI:["pyproject.toml","Pipfile"],"crates.io":["Cargo.toml"],Go:["go.mod","go.work"],RubyGems:["Gemfile"],Packagist:["composer.json"],NuGet:["Directory.Packages.props","packages.config"]};function St(e,t){let n=t&&typeof t=="object"?t:{};if(typeof n.content=="string")return n.content;if(typeof n.append=="string")return e+n.append;let r=Array.isArray(n.edits)?n.edits:[n],s=e;for(let o of r){let i=o&&typeof o=="object"?o:{},l=i.old_string,u=i.new_string;if(typeof l!="string"||typeof u!="string"||l!==""&&!s.includes(l))return null;s=l===""?u:i.replace_all===!0?s.split(l).join(u):s.replace(l,()=>u)}return s}var yr=300,jt=2e3,je=2*1024*1024,Et=32,T=class extends Error{};function se(e){try{return hr(e)}catch{return[]}}function wr(e,t,n){if(t.startsWith("!"))return[];let r=[e];for(let s of t.replace(/^\.\//,"").replace(/\/+$/,"").split("/")){if(s===""||s===".")continue;if(!/[*?]/.test(s)){r=r.map(i=>R(i,s));continue}let o=new RegExp(`^${s.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,"[^/]*").replace(/\?/g,".")}$`);if(r=r.flatMap(i=>[...s==="**"?[i]:[],...se(i).filter(l=>!l.startsWith(".")&&l!=="node_modules"&&o.test(l)).map(l=>R(i,l))]),r.length>n.left)throw new T}return r}function Nt(e,t,n,r){let s=new Set,o=new Set,i={left:jt},l=(d,a,c=0)=>{if(o.has(d))return null;if(o.add(d),--i.left<0||r()>n)throw new T;let f=j(d,je);if(f===null)return null;let g=Re(oe(d),f.toString("utf8"),a);for(let p of g.names)s.add(te(t,p));if(c<3)for(let p of g.includes)l(R(K(d),p),!1,c+1);return g},u=(d,a)=>{let c=(Rt[t]??[]).slice(0,a?1:void 0);return t==="PyPI"&&c.push(...se(d).filter(f=>/^requirements[\w.-]*\.(?:txt|in)$/.test(f)),...se(R(d,"requirements")).filter(f=>/\.(?:txt|in)$/.test(f)).map(f=>R("requirements",f))),t==="NuGet"&&c.push(...se(d).filter(f=>/\.(?:cs|fs|vb)proj$/.test(f))),c.map(f=>l(R(d,f),a)).filter(f=>f!==null)};for(let d=e,a=0;a<Et;a++){for(let f of u(d,!1))for(let g of f.members)for(let p of wr(d,g,i))u(p,!0);let c=K(d);if(c===d)break;d=c}return s}function Pt(e,t,n){let r=te(t,n);return e.has(r)?!0:t==="Go"&&[...e].some(s=>r.startsWith(`${s}/`))}function br(e,t){let n=t.replace(/^@[^/]+\//,"");for(let r=e,s=0;s<Et;s++){let o=R(r,"node_modules");if(Se(R(o,t,"package.json"))||Se(R(o,".bin",n))||M()&&Se(R(o,".bin",`${n}.cmd`)))return!0;let i=K(r);if(i===r)return!1;r=i}return!1}var Ne=e=>e.replace(/[\0-\x1f\x7f]+/g," ").slice(0,160);function Pe(e){let t=new Set([...e.from??[],...e.local??[]].map(([n])=>n));return e.names.filter(n=>!t.has(n))}function $r(e,t,n,r){let s=new Set,o=new Set,i=new Set,l=(u,d)=>{if(i.has(u))return;if(i.add(u),i.size>jt||r()>n)throw new T;let a=j(u,je);if(a===null)return;let c=Ae(a.toString("utf8"));if(B(oe(u),oe(K(u))==="requirements")===null){if((c.from??[]).length>0)throw new T;for(let f of c.indexes??[])s.add(f)}for(let f of Pe(c))o.add(f);if(d<3)for(let f of c.includes)l(R(K(u),f),d+1)};for(let u of e)l(I(u),0);return[...[...s].map(u=>`from ${u}`),...s.size>0||t?o:[]].map(Ne).join(`
|
|
17
|
+
`)}function kr(e,t={}){let[n="",r="",...s]=(e.arg??"").split(" ");if(e.kind!=="deps"||!e.cwd||!e.cwd.startsWith("/"))return null;let o=t.now??Date.now,i=o()+(t.ms??yr);try{let l=I(e.cwd);if(n==="i"||n==="I")return r==="PyPI"&&s.length>0&&s.every(d=>d.startsWith("/"))?$r(s,n==="I",i,o):null;if(n==="e"){let d=B(r,oe(l)==="requirements");if(!d||r.includes("/")||r.includes("\\"))return null;let a=j(R(l,r),je),c=a===null?"":a.toString("utf8"),f=St(c,JSON.parse(s.join(" ")));if(f===null)return"";let g=_=>_.trim()===""?{names:[],members:[],includes:[]}:Re(r,_),p=_=>te(d,_),h=g(c),m=g(f),y=new Set((h.from??[]).map(([_,C])=>`${p(_)}\0${C}`)),b=(m.indexes??[]).filter(_=>!(h.indexes??[]).includes(_)).join(" or "),w=[...(m.from??[]).filter(([_,C])=>!y.has(`${p(_)}\0${C}`)),...b?Pe(m).length===0?[[b,""]]:Pe(m).map(_=>[_,b]):[]],$=new Set((h.local??[]).map(([_,C])=>`${p(_)}\0${C}`)),v=(m.local??[]).filter(([_,C])=>!$.has(`${p(_)}\0${C}`)),S=new Set([...h.names,...w.map(([_])=>_),...(m.local??[]).map(([_])=>_)].map(p)),Ee=[...new Set(m.names.filter(_=>!S.has(p(_))))],Ot=Ee.length===0?null:Nt(l,d,i,o),It=[...Ee.filter(_=>!Pt(Ot,d,_)),...w.map(([_,C])=>C?`${_} from ${C}`:_)].map(Ne);return[...new Set([...It,...v.map(([_,C])=>` ${Ne(C?`${_} from ${C}`:_)}`)])].join(`
|
|
18
|
+
`)}if(n!=="a"&&n!=="r"||s.length===0||!s.every(d=>vt(r,d)))return null;let u=Nt(l,r,i,o);return s.filter(d=>!Pt(u,r,d)&&!(n==="r"&&r==="npm"&&br(l,d))).join(`
|
|
19
|
+
`)}catch{return null}}function xo(e,t,n){switch(e.type){case"amount":return Be(e,t,n);case"recipient":return ut(e,t,n);case"part":return _t(e,t,n);case"when":return dt(e,t,n)}}async function Co(){}export{kr as answerDeps,sn as capMoved,xo as matchCondition,Co as preloadConditions};
|
package/dist/claude-helpers.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{createHash as
|
|
1
|
+
import{createHash as Le}from"crypto";import{readdirSync as L,readFileSync as Ie,rmdirSync as Te,rmSync as De,statSync as We,unlinkSync as le}from"fs";import{basename as B,dirname as I,join as h,resolve as Fe}from"path";import{createHash as Wt}from"crypto";import{existsSync as zt,readdirSync as Ht,statSync as qt}from"fs";import{dirname as Gt,isAbsolute as Bt,join as Kt,posix as Jt,resolve as Yt}from"path";import{posix as Q}from"path";var $e=null;function P(){return $e??process.platform==="win32"}var X=/^([A-Za-z]):(.*)$/s,ke=/^\/(?: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=ke.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 ve(e){return F(e)??e}function z(e){return!P()||typeof e!="string"||e===""?e:ve(e)}import{createHash as kt}from"crypto";import{appendFileSync as xe,closeSync as te,constants as ee,fstatSync as ne,mkdirSync as _e,openSync as re,readdirSync as xt,readFileSync as _t,readSync as oe,renameSync as At,statSync as Ae,unlinkSync as Ct,writeFileSync as Rt}from"fs";import{homedir as Nt}from"os";import{dirname as Ot,join as jt}from"path";var Ce=3500;function R(e,t=8*1024*1024){try{let n=Ae(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)>
|
|
4
|
-
`);c=s<0?"":c.slice(s+1)}return c}finally{te(n)}}var Mt=256*1024,Lt=1024*1024;import{domainToASCII as
|
|
5
|
-
`);if(!a&&!j)return p;if(a&&
|
|
3
|
+
`;if(Buffer.byteLength(n)>Ce)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`);xe(e,n,{mode:384})}function N(e){_e(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 on}from"url";var pn="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as On,readdirSync as jn,realpathSync as Pn}from"fs";import{basename as Ln,dirname as In,join as Tn}from"path";function se(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Ne(t,e.project_dir))}function Ne(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 Ee(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${je(s)}\x1B[0m`}}var ar=Ee(!1),Oe=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function je(e){return e.replace(Oe,"")}var ie=[{id:"protect",verdict:"block",short:"wiping your home folder or the project",slugs:["protected"]},{id:"protect-main",verdict:"block",short:"force-pushing main",slugs:["protected"]},{id:"protect-processes",verdict:"block",short:"killing every process",slugs:["protected"]},{id:"keep-work",verdict:"hold",short:"throwing away uncommitted work",slugs:["uncommitted"]},{id:"stay-in-project",verdict:"hold",short:"deletes outside your project",slugs:["outside-folder"]},{id:"stay-out-of-prod",verdict:"hold",short:"changes aimed at production",slugs:["prod-changes"]},{id:"keep-anvil-on",verdict:"hold",short:"changes to Anvil",slugs:["agent-controls"]},{id:"stop-loops",verdict:"hold",short:"delete bursts and repeats",slugs:["delete-burst","repeat"]},{id:"stop-helper-bursts",verdict:"hold",short:"helper bursts",slugs:["helper-burst"]},{id:"keep-keys-in",verdict:"hold",short:"use of your account keys",slugs:["credentials","secrets-expose"]},{id:"keep-env-out",verdict:"hold",short:"showing secrets files in the chat",slugs:["env-in-chat"]},{id:"hold-unchecked",verdict:"hold",short:"actions it can't check",slugs:["could-not-check","too-long-to-check"]}],Pe="home and project wipes and force-pushes to main",hr=`always blocking ${Pe}`,mr=new Map(ie.map(e=>[e.id,e]));var Me=new Set(ie.flatMap(e=>e.slugs));var H="anvil-claude";function E(e){let t=e.trim();return t===H||t.endsWith(` ${H}`)||t.endsWith(`/${H}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ae="\u{1F539}",x=e=>`${ae} ${e} ${ae}`;var q=(e,t)=>`they run \`${E(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",ze=6e4,He=30*6e4,qe=30*6e4,ue=6e4,Ue="workflow-subagent",Ge=4*1024*1024,de=[2,1,318],Be="/.anvil/claude/bin/claude-hook.js",Ke=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",pe=40,m=e=>typeof e=="string"&&e.length>0?e:null,K=e=>e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Le("sha256").update(e).digest("hex").slice(0,24):"none",Je=/^[A-Za-z0-9_-]{1,64}$/,fe=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?Fe(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 Hr(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??Ke):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{}}},we=()=>{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,model:a?.model??null,starts:a?`it starts on ${fe(a.model)}, by your rule`:null,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: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?B(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,O=Z?.permissionDecision;O==="deny"?T():(O==="ask"||f==="ask")&&we();let j=c.join(`
|
|
5
|
+
`);if(!a&&!j)return p;if(a&&O!=="deny"){let D={...r,model:a.model},V=`switched this helper to ${fe(a.model)} \xB7 ${a.text}`;O==="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
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; ${
|
|
8
|
-
`).includes(n)?!1:(N(e.state),y(r,n),!0)}catch{return!0}}function U(e){let t=S(e,
|
|
9
|
-
`))if(r)try{let o=JSON.parse(r);typeof o.t=="number"&&typeof o.op=="string"&&n.push(o)}catch{}return n}var
|
|
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; ${E(e.cli)} on is`:`its helper start and stop entries aren't set up: run ${E(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 ge(e){try{if(R(e,4*1024*1024)!==!0)return null;let t=JSON.parse(Ie(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=ge(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=ge(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,Ge);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 G=e=>{try{return We(e).mtimeMs}catch{return 0}};function rt(e){let t=G(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,G(h(r,o,B(e))))}catch{}return n}function he(e,t,n=e.length,r=rt){return me(e,t,n,r).count}function me(e,t,n,r){let o=new Map,i=new Map,l=new Set,c=f=>f.q?He:ze;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 me(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 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=
|
|
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
|
|
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=he(l,r,c+1);return s<=n?null:(y(e,JSON.stringify({t:r,op:"x",k:t})),s-1)}function qr(e,t,n){return he(U(Y(e,t)),n)}function Ur(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 De(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||!Je.test(c)||r!=="SubagentStart"&&r!=="SubagentStop")return;if(l||ye(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),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)===Ue?{w:1}:{}}))}catch{}}function at(e,t){let n=_(e),r=h(n,`${J(t.t)}.log`);N(n),R(r)===null&&ye(e,t.t),y(r,JSON.stringify(t))}function Gr(e,t,n){let r={},o=0,i=new Date(Math.max(t,n-(pe+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 ye(e,t){try{let n=J(t-pe*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-G(h(n,r))>2*864e5&&le(h(n,r));L(n).length===0&&Te(n)}catch{}}export{He as ASK_MS,ce as HELPER_ACTION,ze as RESERVE_MS,qe as STALE_MS,it as admit,Ze as atOnceFor,_ as helpersDir,Hr as launchStep,Y as ledgerFile,he as liveAt,Ye as modelRuleFor,Ur as onEvent,et as ownAgentRule,U as readLedger,st as refusedIn,qr as runningNow,Ve as settingsFiles,Qe as subagentEntries,Gr as switchesIn,rt as transcriptChanged};
|