@useanvil/claude-code 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,40 @@
1
- import{existsSync as Pr,readFileSync as Mu,writeSync as Lu}from"fs";import{homedir as Ct,tmpdir as Du}from"os";import{basename as At,dirname as xn,join as Ce}from"path";import{fileURLToPath as Fu,pathToFileURL as Nr}from"url";import Hu from"vm";import{Worker as zu}from"worker_threads";import{spawnSync as Af}from"child_process";import{createHash as Ef}from"crypto";import{chmodSync as Nf,existsSync as Of,lstatSync as Fl,mkdirSync as If,readdirSync as Wf,readFileSync as Hl,readlinkSync as zl,realpathSync as qo,rmdirSync as jf,statSync as et,unlinkSync as Tf,writeFileSync as Mf}from"fs";import{dirname as Ul,join as Df,resolve as Bl}from"path";var ke={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function $i(e){if(!e){let a=c=>c;return{on:!1,bold:a,dim:a,blue:a,grey:a,amber:a,mark:a,field:a}}let n=e==="truecolor",t=a=>c=>`\x1B[${a}m${c}\x1B[0m`,r=t(n?"38;2;76;139;255":"38;5;69"),o=t(n?"38;2;130;134;150":"90"),s=t(n?"38;2;245;165;36":"38;5;214"),i=t(n?"38;2;34;197;94":"32"),l={[ke.on]:r,[ke.blocked]:r,[ke.held]:r,[ke.next]:r,[ke.watching]:o,[ke.problem]:s,[ke.ok]:i};return{on:!0,bold:t("1"),dim:t("2"),blue:r,grey:o,amber:s,mark:a=>(l[a]??(c=>c))(a),field:a=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${_i(a)}\x1B[0m`}}var Qu=$i(!1),Si=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function _i(e){return e.replace(Si,"")}var Ie="claude";function Ue(e){return e==="ghost"||e==="enforce"?e:null}function Lr(e,n){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let t=Ue(e.services?.[Ie]?.actions?.[n]?.mode);return t||(Ue(e.default_mode)??"ghost")}function Wt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[Ie]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function qn(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function Dr(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:Wt(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[Ie]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[Ie]?.actions??{}};for(let i of t)s[i]={mode:n};return{version:1,kill_switch:o.kill_switch===!0,default_mode:Ue(o.default_mode)??"ghost",services:{...o.services??{},[Ie]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function Ci(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:Ue(e.default_mode)==="enforce"?!0:Object.values(e.services?.[Ie]?.actions??{}).some(n=>Ue(n?.mode)==="enforce")}var Zn="claude.agent.controls";function Vn(e,n){return n===Zn&&Ci(e)?"enforce":Lr(e,n)}var Mr={off:0,ghost:1,enforce:2};function Sn(e,n){return e===null?n:n===null?e:Mr[n]>Mr[e]?n:e}function Fr(e,n){return!e||typeof e!="object"?null:Ue(e.services?.[Ie]?.actions?.[n]?.mode)??(Ue(e.default_mode)==="enforce"?"enforce":null)}function Hr(e,n,t,r=!1){let s=Sn(Fr(e,n),t)??(r&&qn(e)?"enforce":Vn(e,n));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function zr(e,n,t){return Sn(Fr(e,n),t)===null&&qn(e)&&Vn(e,n)!=="enforce"}function ve(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}var sn=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],Ai="home and project wipes and force-pushes to main",sd=`always blocking ${Ai}`,Ri=new Map(sn.map(e=>[e.id,e]));function Be(e){return Ri.get(e)}var Ei={"block-protected-targets":"protect","hold-delete-bursts":"stop-loops","hold-repeated-side-effect":"stop-loops","hold-helper-bursts":"stop-helper-bursts"},Ur=new Set(["hold-delete-bursts","hold-helper-bursts"]),Br=new Set(sn.flatMap(e=>Object.keys(e.slugs)));var qr={"block-protected-targets":["protect"],"hold-delete-bursts":["stop-loops"],"hold-repeated-side-effect":["stop-loops"],"hold-helper-bursts":["stop-helper-bursts"],"hold-risky-actions":["keep-anvil-on","keep-keys-in"]};function jt(e){let n=new Set(ji(e));return sn.filter(t=>!Object.entries(qr).some(([r,o])=>o.includes(t.id)&&n.has(r)))}var Tt=new Set([Zn,"claude.bash.secrets.expose"]),Pi=new Set(["claude.file.read_secret","claude.file.write_secret","claude.bash.secrets.print"]),Ni=/^(?:\.ssh\/(?!known_hosts|authorized_keys|config$|environment$|rc$)[^/]+(?<!\.pub)|\.aws\/credentials|\.kube\/config|\.docker\/config\.json|\.gnupg\/[^/].*|\.config\/gh\/hosts\.yml|\.npmrc|\.pypirc|\.netrc|\.git-credentials|\.pgpass|\.vault-token|\.config\/gcloud\/[^/].*|\.azure\/[^/].*|\.config\/solana\/id\.json)$/;function Oi(e,n){if(e.startsWith("~/")){let o=ve(e.slice(2));return o.startsWith("/")?o.slice(1):o}let t=n?ve(n):null,r=ve(e);return t&&t!=="/"&&r.startsWith(`${t}/`)?r.slice(t.length+1):null}function Ii(e,n){if(!e)return!1;let t=Oi(e,n);return t!==null&&Ni.test(t)}function Wi(e,n,t,r=[]){if(!e||!n)return!0;let o=ve(e.startsWith("~/")&&t?`${t}${e.slice(1)}`:e);if(!o.startsWith("/")||/[\n\r\u2028\u2029]/.test(o))return!0;let s=o.indexOf("/.git");for(;s!==-1&&s+5<o.length&&o[s+5]!=="/";)s=o.indexOf("/.git",s+1);if(s===-1)return!0;let i=o.slice(0,s)||"/";if(r.some(a=>`${i}/.git`===ve(a)))return!0;let l=ve(n)||"/";return l===i||i==="/"||l.startsWith(`${i}/`)}function Mt(e){if(e.decision.verdict==="allow")return null;let n=e.baseline.ruleId?Ei[e.baseline.ruleId]:void 0;if(n==="protect"){if(!(e.service==="fs.git_dir"&&!Wi(e.target,e.projectDir,e.home,e.histories)))return Be("protect")}else if(n)return Be(n);return e.action===Zn?Be("keep-anvil-on"):e.action==="claude.bash.secrets.expose"||Pi.has(e.action)&&Ii(e.target,e.home)?Be("keep-keys-in"):null}function Zr(e,n,t){return e.id==="keep-keys-in"&&n!=="claude.bash.secrets.expose"?"credentials":e.slugs[t]!==void 0?t:Object.keys(e.slugs)[0]}function ji(e){let n=new Set(e.policies.filter(t=>t.origin==="baseline").flatMap(t=>t.rules.map(r=>r.id)));return Object.keys(qr).filter(t=>!n.has(t))}var qe={"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"discard uncommitted work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}};function Kr(e){if(!qn(e))return null;let n="cluster, cloud and database destroys";return{what:n,context:`It also holds ${n} and cloud-credential prints, until the user sets a mode for their kinds.`}}var Vr={"block-protected-targets":{slug:"protected",text:"never: home, root, project root, .git, main, every process"},"hold-repeated-side-effect":{slug:"repeat",text:"the same MCP action again within 10 minutes"},"hold-delete-bursts":{slug:"delete-burst",text:"more than 20 deletes in a minute"},"hold-helper-bursts":{slug:"helper-burst",text:"more than 20 helper launches in 10 minutes"},"too-long-to-check":{slug:"too-long-to-check",text:"too long to check in time"},"could-not-check":{slug:"could-not-check",text:"could not be checked"}};function Kn(e,n){return e&&Vr[e]?Vr[e].slug:!e||e==="hold-risky-actions"?qe[n]?.slug??n:e.replace(/@.*$/,"")}function Gr(e,n,t,r){return r&&n==="baseline"?Zr(Be(r),t,Kn(e,t)):!r&&e==="block-protected-targets"?qe[t]?.slug??t:Kn(e,t)}function Gn(e){return qe[e]?.text??e}function Lt(e){let n=new Set(Br);for(let t of e.policies)for(let r of t.rules)if(r.primitive!=="durable_key_dedup")if(r.id==="hold-risky-actions")for(let o of r.applies_to??[])n.add(Kn(null,o));else n.add(Kn(r.id,""));return n.size}function Dt(e){let n=new Set;for(let t of e.policies)for(let r of t.rules)if(r.primitive!=="durable_key_dedup")for(let o of r.applies_to??t.allowed_actions)n.add(o);return[...n]}function Ft(e,n){let t=Dt(e).filter(o=>qe[o]),r=t.filter(o=>Vn(n,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===t.length?"enforce":`${r.length} enforced, rest ghost`}}var Ht="anvil-claude";function O(e){let n=e.trim();return n===Ht||n.endsWith(` ${Ht}`)||n.endsWith(`/${Ht}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var Jr="\u{1F539}",D=e=>`${Jr} ${e} ${Jr}`;var Ze=e=>`
2
- ${ke.next} ${e}`;function Ti(e,n,t){return`${Ze(`To ${e}, run this in a terminal (not in this chat):`)}
3
- ${n}${t?Ze(`Then ${t}.`):""}`}var Mi=72;function xe(e,n){let t=`To ${e}, run in a terminal: ${n}`;return t.length+5<=Mi?Ze(t):`${Ze(`To ${e}, run in a terminal:`)}
4
- ${n}`}var Li=(e,n)=>`they run \`${O(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${n}`;var Yr="blocking unsafe actions automatically";var $e="anvil";function _n(e){$e=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}function Ve(){return $e}var oe=e=>`${O($e)} ${e}`;function Di(e,n=$e,t){return`${D("Anvil isn't working")} ${e}.
5
- Every command waits until it's fixed, so nothing runs unchecked.${t?Ze(t):""}${xe("fix it",`${O(n)} on`)}${xe("turn Anvil off instead",`${O(n)} off`)}`}function Fi(e,n=$e,t){return`${D("Anvil isn't working")} ${e}, so Claude Code holds every tool call until the user fixes it${t?` (${t})`:""} by running \`${O(n)} on\` in a terminal (not in this chat: Claude can't run it). Tell the user, then stop and wait. Do not retry, and do not try another way or another tool.`}function Xr(e){return`${D("Held by Anvil")} ${e}${Ze("Claude can do it in smaller steps, each one checked")}`}function Qr(e){return`${D("Held by Anvil")} ${e}, so nothing ran. Do it in smaller steps, each under that size.`}function Se(e,n,t=$e,r){let o=Fi(n,t,r);return{systemMessage:Di(n,t,r),hookSpecificOutput:e==="SessionStart"?{hookEventName:e,additionalContext:o}:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:o}}}function eo(e,n,t=$e){let r=Hi(e.replace(/^Anvil:? /,""),t);return`${D("Anvil")} ${r.said}${n>0?` (and ${n} more)`:""}${r.fix??xe("see details",`${O(t)} report`)}`}function Hi(e,n){let t=e.lastIndexOf(` run ${O(n)} on`),r=t>0?e[t-1]:"";if(t<=0||r!==":"&&r!==";")return{said:e,fix:null};let o=e.slice(t+` run ${O(n)} on`.length);return o!==""&&!/^ to [a-z][a-z ]*$/.test(o)?{said:e,fix:null}:{said:e.slice(0,t-1),fix:xe("fix it",`${O(n)} on`)}}function no(e,n,t=null){return`${D(`Anvil would've ${e==="block"?"blocked this":"held this for review"}`)} ${n} \xB7 it ran${t?xe("hold these for your OK",`${O($e)} enforce ${t}`):""}`}function to(e,n,t,r,o=!1){let s=`${D("Held by Anvil for your OK")} ${o?`${e} \xB7 always on`:e}`;return t?`${s}${Ti("allow it once",`${O(n)} allow ${t}`,"tell Claude to go on")}`:`${s}${Ze(`it can't be allowed right now: ${r}`)}`}function ro(e,n,t=$e){return n?`${D("Held by Anvil")} ${e}. Nothing ran. Tell the user: to allow it once, ${Li(t,"tell you to go on")}. When they say so, run exactly the same command again, with nothing added to it (the OK covers one call). Do not try another way.`:`${D("Held by Anvil")} ${e}. Nothing ran, and it can't be allowed right now; the user has been told how to fix that. Do not try another way.`}function oo(e){return`${D("Held by Anvil for your OK")} ${e}`}function so(e,n){return`${D("Blocked by Anvil")} ${e}${xe("change the rule",`${O(n)} rules edit`)}`}function io(e){return`${D("Blocked by Anvil")} ${e}. Nothing ran, and it can't be allowed once. Do not try another way.`}function lo(e){return`${D("Blocked by Anvil")} ${e} \xB7 can't be overridden`}function ao(e){return`${D("Blocked by Anvil")} ${e}. Nothing ran, and this can't be overridden. Do not try another way.`}function co(e){return`${D("Allowed once, with your OK")} ${e}`}import{createHash as Pl}from"crypto";import{appendFileSync as Do,closeSync as Fo,constants as jo,fstatSync as Ho,mkdirSync as Nl,openSync as zo,readdirSync as Ol,readFileSync as Il,readSync as Uo,renameSync as Wl,statSync as Jt,unlinkSync as To,writeFileSync as jl}from"fs";import{homedir as Tl}from"os";import{dirname as Ml,join as q}from"path";var Cn,zi,uo="its file (claude-conditions.js) is missing or won't load";function fo(){return zi??=import(new URL("claude-conditions.js",import.meta.url).href).then(e=>{Cn=typeof e.matchCondition=="function"&&typeof e.capMoved=="function"?e:void 0},()=>{})}function po(e,n,t){return Cn?Cn.matchCondition(e,n,t):{hit:"unknown",why:`Anvil can't check this rule's condition: ${uo}`}}function go(e,n){return Cn?Cn.capMoved(e,n):`Anvil can't read amounts: ${uo}`}var mo=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,Ui=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,Bi=/(?:^|[^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]|$)/,ho=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),yo=(e,n)=>e.split("+").every(t=>t[0]==="="?n.split(/[^a-z0-9]+/).includes(t.slice(1)):n.includes(t));function qi(e,n){let t=`_${n}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),r=n.replace(/_/g,"");return e.servers.some(o=>{let s=o.replace(/_/g,"");return`_${n}_`.includes(`_${o}_`)||t.includes(`_${o}_`)||(s.length>4?r.includes(s):s.length>3&&(r.startsWith(s)||r.endsWith(s)))})}function Zi(e,n,t){let r=n.normalize("NFKC").toLowerCase().replace(/\.+$/,""),o=/^[a-z0-9.-]+$/.test(r);if(!r.includes("."))return o?(e.clis??[]).includes(r)?"this":"other":"?";let s=r.split("."),i=a=>r===a||r.endsWith(`.${a}`)||a.includes("*")&&a.split(".").every((c,d,u)=>u.length===s.length&&(c==="*"||c===s[d])),l=!1;return e.hosts.some(a=>{let c=a.indexOf("/");return c<0?i(a):(l||=i(a.slice(0,c))&&/^(?:\/batch\/?|\u0000)$/.test(t),i(a.slice(0,c))&&t.includes(a.slice(c)))})?"this":o&&!l?"other":"?"}function Vi(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 Ke(e,n,t,r){let o=ho(t);return e.toolWords.length===0||e.toolWords.some(s=>yo(s,o))?{hit:"match",part:n,why:e.said}:r===3||/\u0000|%00/.test(o)||Bi.test(o)||!/[a-z]{3}/.test(o.replace(/[a-z]*\d[a-z0-9]*/g,""))||r===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(o)?{hit:"unknown",part:n,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function Ki(e,n,t){let r=u=>({hit:"unknown",part:n,why:`Anvil can't tell ${u}, so it holds it (your rule: ${e.said})`});if(n.action==="claude.mcp.side_effect"){let u=n.host;if(!u)return r("which app this tool belongs to");let g=`mcp.${u}.`,h=ho(t.tool?.startsWith("mcp__")?t.tool.split("__").slice(2).join("__"):n.target?.startsWith(g)?n.target.slice(g.length):"");if(qi(e,u))return Ke(e,n,h,1);let v=(e.anywhere??[]).some(j=>yo(j,h))?{hit:"match",part:n,why:e.said}:null;if(!mo.test(u)&&!Ui.test(u))return v;let x=e.toolPrefixes.find(j=>h.startsWith(j));return x?Ke(e,n,h.slice(x.length),1):e.servers.some(j=>j.length>2&&`_${h}_`.includes(`_${j}_`))?Ke(e,n,h,1):v||(e.others??[]).includes(u)?v:r(`which app ${mo.test(u)?`the connector ${u.slice(0,8)}\u2026`:u} acts on`)}let o=n.target??"",s=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(o)?`https://${o}`:o,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),l="";try{i&&(l=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{l="\0"}if(!n.host&&!n.service)return r("where this writes");let a=[n.host,n.service,...Array.isArray(n.attributes.hosts)?n.attributes.hosts:[],Vi(s)].filter(u=>typeof u=="string"&&u!==""),c=a.map(u=>Zi(e,u,l)),d=[o,...a].some(u=>/^smtps?[:.]/i.test(u));if(c.includes("this")||d&&e.hosts.includes("smtp:")){let u=a.find((h,v)=>c[v]==="this"&&!h.includes(".")),g=o.includes("/")?3:2;return u?Ke(e,n,`cli:${u.toLowerCase()} ${o}`,g):d?Ke(e,n,"send mail",2):i?Ke(e,n,l,3):Ke(e,n,o,g)}return c.includes("?")?r(`where this writes (${a[0].replace(/[\u0000-\u001f]/g,"")})`):t.tool?.startsWith("mcp__")?r("what else this tool's command writes"):null}function An(e,n,t){let r=null;for(let o of n){let s=Ki(e,o,t);if(s?.hit==="match")return s;r??=s}return r??(t.parts.length>15&&n[0]?{hit:"unknown",part:n[0],why:`Anvil can't read everything this line does, so it holds it (your rule: ${e.said})`}:null)}import{existsSync as Yn,readdirSync as Xi,statSync as ko}from"fs";import{dirname as Ut,isAbsolute as Qi,join as ne,posix as el,resolve as Rn}from"path";import{posix as bo}from"path";var Gi=null;function z(){return Gi??process.platform==="win32"}var wo=/^([A-Za-z]):(.*)$/s,Ji=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function zt(e,n){let t=bo.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function ln(e,n){return e.split("/").map(t=>{if(t===""||t==="."||t===".."||/[\u0000\u0001]/.test(t))return t;let r=t.indexOf(":"),o=r>=0?t.slice(0,r):t,s=n?o:o.replace(/[. ]+$/,"");return s===""?".":s}).join("/")}function le(e){if(!z())return e;let n=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),t=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(n);if(r){let a=r[2];if(r[1]===".")return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(a))n=`\\\\${a.slice(4)}`;else if(wo.test(a))n=a;else return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;t=!0}n=n.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(n);if(o){let a=`/unc/${ln(o[1],t).toLowerCase()}${o[2]?`/${ln(o[2],t).toLowerCase()}`:""}`;return zt(a,ln(o[3]??"",t).toLowerCase())}let s=wo.exec(n);if(s){let a=s[2];return a===""?`/${s[1].toLowerCase()}`:a.startsWith("/")?zt(`/${s[1].toLowerCase()}`,ln(a,t).toLowerCase()):null}let i=Ji.exec(n);if(i)return zt(`/${i[1].toLowerCase()}`,ln(i[2]??"",t).toLowerCase());let l=ln(n,t).toLowerCase();if(l.startsWith("/")){let a=bo.normalize(l);return a.length>1&&a.endsWith("/")?a.slice(0,-1):a}return l}function Yi(e){return le(e)??e}function Jn(e){if(!z())return e;let n=/^\/([a-z])(\/.*)?$/s.exec(e);if(n)return`${n[1].toUpperCase()}:${(n[2]??"/").replace(/\//g,"\\")}`;let t=/^\/unc\/(.+)$/s.exec(e);return t?`\\\\${t[1].replace(/\//g,"\\")}`:null}function B(e){return z()?Jn(e)??e:e}function Ge(e){return!z()||typeof e!="string"||e===""?e:Yi(e)}var nl=(e,n)=>{let t=n.endsWith("/")?n.slice(0,-1):n;return e===t||e.startsWith(`${t}/`)},tl={vercel:"vercel deploy --prod, or --target staging",netlify:"netlify deploy --prod, or --context staging",fly:"fly deploy -a <an app named for staging>",flyctl:"flyctl deploy -a <an app named for staging>",railway:"railway up -e staging",modal:"modal deploy -e staging, or MODAL_ENVIRONMENT=staging",kubectl:"kubectl --context staging",helm:"helm --kube-context staging",terraform:"terraform workspace select staging, or -chdir=envs/staging",gh:"gh workflow run \u2026 -f environment=staging",firebase:"firebase deploy -P staging",serverless:"serverless deploy --stage staging",wrangler:"wrangler deploy --env staging"};function xo(e,n,t){if(n.length===0)return null;let r=null,o=(s,i)=>{let l=s.action.endsWith(".deploy")&&s.host?tl[s.host]:void 0;r??={hit:"unknown",part:s,why:`Anvil can't tell ${i}, so it holds it (your rule: ${e.said})${l?`. Say where it goes (${l}) and a deploy that isn't production runs`:""}`}};for(let s of n){let i=s.attributes;if(e.field==="outside_project"){let l=s.target,a=t.projectDir?[l,...t.touched?.full??[]].find(c=>c?.startsWith("/")&&!nl(c,t.projectDir)):null;if(a)return{hit:"match",part:s,why:`${e.said} (${a})`};(!l||!l.startsWith("/")||!t.projectDir)&&o(s,"where this deletes")}else if(e.field==="environment"){if(i.environment==="production")return{hit:"match",part:s,why:`${e.said}${typeof i.environment_said=="string"?` (${i.environment_said})`:""}`};i.environment!=="non-production"&&o(s,s.action.endsWith(".destructive")?"which database this destroys":s.action.endsWith(".deploy")?"which environment this deploys to":"where this goes")}else{let l=$o(i,t.home),a=l?.find(c=>(e.value.includes("/")?c:c.split("/").pop())===e.value.toLowerCase().replace(/\.git$/,""));if(a!==void 0)return{hit:"match",part:s,why:`${e.said} (${a})`};l||o(s,"which repository this pushes to")}}return r}function $o(e,n){try{let t=typeof e.repo_dir=="string"?B(e.repo_dir):e.repo_dir,r=n===null?null:B(n),o=e.repo_via,s=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:o==="gh"&&process.env.GH_REPO||null;if(typeof t!="string"||!Qi(t)||!Yn(t)||o!=="git"&&o!=="gh"||/[$`]/.test(s??""))return null;if(o==="gh"&&s!==null)return vo([s],t);let i=rl(t,r);if(i===null)return null;let l=new Map;for(let d of i)d.section==="remote"&&d.sub!==null&&(d.key==="url"||(o==="git"?d.key==="pushurl":d.key==="gh-resolved"&&d.value!=="base"))&&l.set(d.sub,[...l.get(d.sub)??[],d.value]);if(s!==null&&!l.has(s)&&!/^[./]|[/:]/.test(s))return null;let a=s!==null?l.get(s)??[s]:[...l.values()].flat();if(s===null)for(let d of i)(d.section==="branch"&&/^(push)?remote$/.test(d.key)||d.section==="remote"&&d.sub===null&&d.key==="pushdefault")&&d.value!=="."&&!l.has(d.value)&&a.push(d.value);let c=new Set(a);for(let d of a)for(let u of i)u.section==="url"&&u.sub!==null&&/^(push)?insteadof$/.test(u.key)&&u.value&&d.startsWith(u.value)&&c.add(u.sub+d.slice(u.value.length));return c.size>0?vo([...c],t):null}catch{return null}}function vo(e,n){let t=[];for(let r of e){let o=decodeURIComponent(r.trim()),s=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(o)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(o),l=(s?el.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(o)&&!o.startsWith(".")?o:Rn(n,o)).replace(/[?#].*$/,"").split(/[\\/]/).filter(g=>g&&g!=="."),a=l.findIndex((g,h)=>h>=2&&/^pulls?$/.test(g));a>=2&&(l=l.slice(0,a));let[c,d]=l.slice(-2).map(g=>g.replace(/\.git$/i,"").toLowerCase()),u=d??c;if(!u||u==="..")return null;t.push(d!==void 0&&c!==".."?`${c}/${d}`:u)}return t}function rl(e,n){let t=process.env;if(t.GIT_CONFIG_COUNT||t.GIT_CONFIG_PARAMETERS||t.GIT_DIR||t.GIT_COMMON_DIR)return null;let r=ol(e);if(r===null)return null;let o=process.platform==="win32"?[ne(t.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),ne(t.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(c=>`${c}/gitconfig`),s=t.GIT_CONFIG_NOSYSTEM?[]:t.GIT_CONFIG_SYSTEM?[t.GIT_CONFIG_SYSTEM]:o;t.GIT_CONFIG_GLOBAL?s.push(t.GIT_CONFIG_GLOBAL):n&&s.push(ne(t.XDG_CONFIG_HOME||ne(n,".config"),"git","config"),ne(n,".gitconfig")),s.push(ne(r.common,"config"),ne(r.gitDir,"config.worktree"));let i=[],l=24,a=(c,d)=>{let u=--l<0||d>5?void 0:me(c,1048576);if(u===void 0)return!1;for(let g of sl(u?.toString("utf8")??""))if(i.push(g),g.key==="path"&&/^include(if)?$/.test(g.section)){let h=g.value.startsWith("~/")?n&&ne(n,g.value.slice(2)):!/^[~%]/.test(g.value)&&Rn(Ut(c),g.value);if(!h||!a(h,d+1))return!1}return!0};return s.every(c=>a(c,0))?i:null}function ol(e){let n=t=>/^(ref: refs\/|[0-9a-f]{40})/.test(me(ne(t,"HEAD"),4096)?.toString("utf8")??"");for(let t=Rn(e),r=0;r<64;r++,t=Ut(t)){let o=ne(t,".git"),s=["objects","refs"].every(i=>Yn(ne(t,i)))&&n(t)?t:null;if(Yn(o)){let i=ko(o);if(i.isDirectory())n(o)&&(s=o);else if(s=i.isFile()?/^gitdir:\s*(.+)$/m.exec(me(o,65536)?.toString("utf8")??"")?.[1]?.trim():null,!s)return null}if(s){let i=Rn(t,s),l=me(ne(i,"commondir"),65536),a=l===null?i:Rn(i,l.toString("utf8").trim());for(let c of["remotes","branches"]){let d=ne(a,c);if(Yn(d)&&(!ko(d).isDirectory()||Xi(d).length>0))return null}return{gitDir:i,common:a}}if(Ut(t)===t)return null}return null}function sl(e){let n=[],t="",r=null;for(let o of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){o=o.trim();let s=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(o);if(s){let[l,...a]=s[1].toLowerCase().split(".");t=l,r=s[2]?.replace(/\\(.)/g,"$1")??(a.length>0?a.join("."):null),o=o.slice(s[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(o);i&&n.push({section:t,sub:r,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(l,a,c)=>a??c??"").trim()})}return n}import{domainToASCII as Id}from"url";var Fd="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as ll,readdirSync as al,realpathSync as Eo}from"fs";import{basename as cl,dirname as ul,join as dl}from"path";function We(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||z()?n.normalize("NFC").toLowerCase():n}function Bt(e){if(!/[*?[]/.test(e))return null;let n=[...e],t=[],r=!1;for(let o=0;o<n.length;o++){let s=n[o],i=s==="["?n.indexOf("]",o+2):-1;if(s==="*")(t[t.length-1]!==null||t.length===0)&&t.push(null);else if(s==="?")t.push(l=>l!=="/");else if(i>0){let l=n.slice(o+1,i),a=l[0]==="!"||l[0]==="^",c=a?l.slice(1):l,d=[];for(let u=0;u<c.length;u++){let g=c[u].codePointAt(0);if(c[u+1]==="-"&&u+2<c.length){let h=c[u+2].codePointAt(0);g>h&&(r=!0),d.push([g,h]),u+=2}else d.push([g,g])}t.push(u=>u!=="/"&&d.some(([g,h])=>u.codePointAt(0)>=g&&u.codePointAt(0)<=h)!==a),o=i}else t.push(l=>l===s)}return r?{source:"(?!)",test:()=>!1}:{source:e,test(o){let s=[...o],i=0,l=0,a=-1,c=0;for(;l<s.length;){let d=t[i];if(d!=null&&d(s[l]))i++,l++;else if(d===null)a=i++,c=l;else if(a>=0&&s[c]!=="/")i=a+1,l=++c;else return!1}for(;t[i]===null;)i++;return i===t.length}}}var il=e=>e==="**"||/^[*?]+(?:\.[*?]+)*$/.test(e.replace(/\[[^\]]+\]/g,"?"));function So(e){let n=z()?le(e.trim())??e.trim():e.trim();if(/^~[^/]/.test(n))return null;let t=n==="~"||n.startsWith("~/"),r=!t&&n.startsWith("./"),o=(t?n.slice(1):n).replace(/^(?:\.\/)+/,""),s=t?0:o.startsWith("/")?1:r||o.replace(/\/+$/,"").includes("/")?2:3,i=[],l=0;for(let c of o.split("/"))c===""||c==="."||(c!==".."?i.push(c):i.length>0&&i[i.length-1]!=="**"?i.pop():s!==1&&i.length===0&&l++);if(i.length===0||i.every(il))return null;let a=[];for(let c of i){if(c==="**"){a[a.length-1]!==null&&a.push(null);continue}let d=We(c),u=Bt(d);if(u&&u.source==="(?!)")return null;a.push(u??d)}for(;a[a.length-1]===null;)a.pop();return{segs:a,at:l>0&&s===3?2:s,up:l}}var _o=["Write","Edit","MultiEdit","NotebookEdit"],fl=["Read","Grep","NotebookRead","Glob","LS"],pl=["claude.bash.fs.delete_recursive","claude.bash.fs.delete_disposable"],gl=[".git",".anvil/rules.md",".anvil/rules.json"],Co=new Set(["node_modules",".git"]),ml=1e4,hl=/^(?:https?|ftps?|wss?|git|ssh|s3|gs|file):$/;var Ao=new WeakMap,je=e=>We(e).split("/").filter(Boolean);function yl(e,n,t){let r=new Map,o=(s,i)=>{if(s===e.length)return 2;if(i===n.length)return 1;let l=s*(n.length+1)+i,a=r.get(l);if(a!==void 0)return a;let c=e[s],d=n[i],u=0;if(c===null)for(let g=i;g<=n.length&&u<2;g++)u=Math.max(u,o(s+1,g));else if(d==="**")u=2;else{let g=Bt(d);u=(g?typeof c!="string"||g.test(c):typeof c=="string"?c===d:c.test(d))?o(s+1,i+1):0}return r.set(l,u),u};return o(0,t)}function qt(e,n,t,r){let o=e.at===2&&r.length===0?3:e.at,s=o===0?t&&t.length>e.up?[t.slice(0,t.length-e.up)]:[]:o===1?[[],...r]:o===2?r.map(a=>a.slice(0,Math.max(0,a.length-e.up))):r.length===0?[[]]:r,i=0,l=!1;for(let a of s)if(!(a.length>=n.length||a.some((c,d)=>c!==n[d]))){l=!0;for(let c=a.length;c<n.length&&i<2;c+=o===3?1:n.length)i=Math.max(i,yl(e.segs,n,c))}return i===2?2:o===3?l?3:0:i===1&&e.segs.includes(null)?3:i}function Po(e){if(z())return wl(e);let n="";for(let t=e;t.length>1;)try{return Eo.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}function wl(e){let n=Jn(e);if(n===null||process.platform!=="win32")return e;let t=[];for(let r=n;;)try{return le(dl(Eo.native(r),...t))??e}catch{let o=ul(r);if(o===r)return e;t.unshift(cl(r)),r=o}}function bl(e,n,t){let r=e.at===0?n:e.at===1?"":t,o=r===null?null:e.up>0?r.split("/").slice(0,-e.up).join("/"):r,s=0;for(;s<e.segs.length&&typeof e.segs[s]=="string";)s++;if(o===null||s===0)return null;let i=`${o}/${e.segs.slice(0,s).join("/")}`,l=Po(i);return We(l)===We(i)?null:{segs:[...je(l),...e.segs.slice(s)],at:1,up:0}}function kl(e,n){let t=e.split("/").filter(Boolean),r=n?n.split("/").filter(Boolean):null,o=[];for(let s=t.length;s>0&&!(r!==null&&s<=r.length&&r.slice(0,s).every((l,a)=>t[a]===l));s--){let i=`/${t.slice(0,s).join("/")}`;gl.some(l=>ll(B(`${i}/${l}`)))&&o.push(i)}return o}function vl(e,n){if(Co.has(e.slice(e.lastIndexOf("/")+1)))return"no";let t=0,r=[e.replace(/(?<!^)\/+$/,"")];for(let o=0;o<r.length;o++){let s;try{s=al(B(r[o]),{withFileTypes:!0})}catch{continue}for(let i of s){if(++t>ml)return"unsure";let l=`${r[o]}/${i.name}`;if(n(je(l)))return"yes";i.isDirectory()&&!Co.has(i.name)&&r.push(l)}}return"no"}var Ro=new WeakMap;function xl(e,n){if(!n)return!1;let t=Ro.get(e);t||(t=e.paths.map(o=>{let s=We(o.split("/").filter(c=>c!==""&&!/^[*?]+$/.test(c)).pop()??""),i=/^[*?]+[^*?[]+$/.test(s),l=s.replace(/^[*?]+/,"");if(l===""||/[*?[]/.test(l))return!0;let a=l.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&");return new RegExp(`${i?"":"(?:^|[\\s'\"`=:(/])"}${a}(?=$|[\\s'"\`/;|&)<>])`)}),Ro.set(e,t));let r=We(n);return t.some(o=>o===!0||o.test(r))}function No(e,n,t){let r=t,o=n[0];if(!o)return null;let s=r.tool??(o.action==="claude.tool.other"?o.target:null),i=o.attributes.path,l=s!==null?_o.includes(s)||fl.includes(s):i!==void 0;if(l&&(s!==null?!_o.includes(s):o.action==="claude.file.read_secret"))return null;let a=r.touched,c=new Set(a?.written??[]),d=new Set(a?.read??[]),u=l?[...typeof i=="string"?[i]:[],...a?.full??[]]:[...c,...(a?.full??[]).filter(m=>!d.has(m)||c.has(m))],g=l?[]:a?.unknown??[],h=`(your rule: ${e.said})`;if(l&&u.length===0)return{hit:"unknown",part:o,why:`Anvil can't tell which file this writes, so it holds it ${h}`};if(u.length===0&&g.length===0)return null;let v=Ao.get(e);if(v||Ao.set(e,v=e.paths.map(So)),v.includes(null))return{hit:"unknown",part:o,why:`Anvil can't read this rule's paths, so it holds every write ${h}`};let x=m=>r.projectDir&&m.startsWith(`${r.projectDir}/`)?m.slice(r.projectDir.length+1):r.home&&m.startsWith(`${r.home}/`)?`~${m.slice(r.home.length)}`:m,j=(m,R)=>({hit:"unknown",part:{...o,target:R},why:`${m}, so Anvil holds it ${h}`}),Q=typeof r.root=="string"?r.root:null,be=Q??r.projectDir,K=r.home?je(r.home):null,p=m=>[...new Map([...m,...m.map(Po)].map(R=>[je(R).join("/"),je(R)])).values()],S=p(be?.startsWith("/")?[be]:[]),y=new Map,P=m=>{if(Q!==null)return S;let R=y.get(m);if(R===void 0){let E=p(kl(m,r.home)).filter(U=>!S.some(te=>te.join("/")===U.join("/")));R=E.length===0?S:[...S,...E],y.set(m,R)}return R},G=[...new Set(u)].filter(m=>m.startsWith("/")).map(m=>({p:m,w:je(m)})).filter(m=>!m.w.some(R=>hl.test(R))),T=[...S,...[r.projectDir,r.home].filter(m=>typeof m=="string"&&m.startsWith("/")).map(je)],I=(m,R)=>[...T,...P(m)].some(E=>E.length>=R.length&&R.every((U,te)=>E[te]===U)),_=m=>a?.written===void 0||c.has(m)||l?`changes ${x(m)}`:`may change ${x(m)}`,fe=[],Le=[],$n=(m,R)=>{for(let E of G){let U=R(E.p);for(let te of m){let ee=qt(te,E.w,K,U);if(ee===2)return{hit:"match",part:{...o,target:x(E.p)},why:_(E.p)};ee===1&&!I(E.p,E.w)&&fe.push({p:E.p,sure:!0}),ee===3&&!I(E.p,E.w)&&Le.push(E.p)}}return null},Ae=v,C=$n(Ae,P)??$n(Ae.map(m=>bl(m,r.home,be)).filter(m=>m!==null),()=>[]);if(C)return C;let W=m=>We(m).replace(/(?<!^)\/+$/,""),De=m=>n.some(R=>pl.includes(R.action)&&typeof R.target=="string"&&W(R.target)===W(m));for(let m of new Set(Le)){if(fe.some(E=>E.p===m)||!(De(m)||c.has(m)))continue;let R=vl(m,E=>Ae.some(U=>qt(U,E,K,P(m))===2));R!=="no"&&fe.push({p:m,sure:R==="yes"})}let Fe=fe.find(m=>m.sure&&De(m.p));if(Fe)return{hit:"match",part:{...o,target:x(Fe.p)},why:`deletes ${x(Fe.p)}, which holds ${e.paths.join(", ")}`};let Re=fe[0];if(Re!==void 0)return j(`it changes ${x(Re.p)}, a folder that ${Re.sure?"holds":"may hold"} ${e.paths.join(", ")}, and Anvil can't tell what changes in it`,x(Re.p));for(let m of g){let R=m.includes("\0")?m.slice(0,m.indexOf("\0")):m,E=R.slice(0,R.lastIndexOf("/"));if(E.startsWith("/")&&Ae.some(U=>qt(U,je(E),K,P(E))===2))return j(`Anvil can't read the whole path this writes (${x(m.replace(/[\u0000\u0001]/g,""))})`,x(E))}return g.length>0&&xl(e,r.command)?j(`it writes where Anvil can't read, and it names ${e.paths.join(", ")}`,o.target):null}function Oo(e,n,t){switch(e.type){case"app":return An(e,n,t);case"paths":return No(e,n,t);case"target":return xo(e,n,t);case"kind":return n[0]?{hit:"match",part:n[0],why:e.said}:null}}function Io(e,n,t=po){let r=e.kinds?n.parts.filter(l=>e.kinds.includes(l.action)):n.parts;if(e.kinds&&r.length===0)return null;if(!e.when||e.when.length===0)return Oo(e.narrowing,r,n);let o=null,s=n.parts.length>15,i=l=>`${l}, so it holds it (your rule: ${e.text})`;for(let l of r){let a=Oo(e.narrowing,[l],n);if(!a)continue;let c=e.when.map(u=>t(u,a.part,n));if(c.some(u=>u===null)){s&&(o??={hit:"unknown",part:a.part,why:i("Anvil can't read everything this line does")});continue}let d=c.find(u=>u!==null&&u.hit==="unknown");if(a.hit==="match"&&!d){let u=c.map(g=>g&&g.hit==="match"?g.detail:void 0).filter(g=>typeof g=="string"&&g.length>0);return{hit:"match",part:a.part,why:a.why,...u.length>0?{detail:u.join(", ")}:{}}}o??=a.hit==="unknown"?a:{hit:"unknown",part:a.part,why:i(d.why)}}return o}var Zt="anvil-claude-compiled/1";function Vt(e,n){return`mut:${e}:${n}`}var Xn={verdict:"allow",policy:null,origin:null,ruleId:null,blockedBy:null,source:null};function Sl(e){return typeof e!="string"?"":e.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/g,"").trim().toLowerCase()}function _l(e,n){for(let t of n){if(t===e)return!0;if(t.endsWith(".*")){let r=t.slice(0,-2);if(r.length>0&&(e===r||e.startsWith(r+".")))return!0}if(t.startsWith("*.")){let r=t.slice(1);if(e.endsWith(r)&&e.length>r.length)return!0}}return!1}function Cl(e,n){let t=e[n];return typeof t=="string"?t.trim()||null:typeof t=="number"?!Number.isFinite(t)||t===0?null:String(t):null}function Wo(e,n){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(n)}function Al(e,n){if(e.length===0)return!1;let t=n.toLowerCase(),r=t.split(/[^a-z0-9]+/i).filter(Boolean);return e.some(o=>r.includes(o))||e.some(o=>t.includes(o))}function Rl(e,n,t,r){let o=(s,i,l,a)=>({verdict:l??(i==="confirmation_required"?"hold":"block"),policy:e.name,origin:e.origin,ruleId:s,blockedBy:i,source:a});if(!e.allowed_actions.includes(n.action))return e.deny_unlisted?o(null,"allowlist",null,null):Xn;for(let s of e.rules)if(Wo(s,n.action))switch(s.primitive){case"confirmation_gate":{if(s.all_actions===!0||Al(s.trigger_verbs??[],n.action))return o(s.id,"confirmation_required",s.intent,s.source??null);break}case"service_blocklist":{let i=s.blocked??[];if(i.length===0)break;let l=Sl(n.service);if(l&&_l(l,i))return o(s.id,"service_in_blocklist",s.intent,s.source??null);break}case"resource_mutation_rate":{let i=s.rate;if(!i||i.count<=0||i.per_ms<=0||!Number.isFinite(i.count)||!Number.isFinite(i.per_ms))break;let l=Cl(n.metadata,s.resource_field?.trim()||"resource_id");if(!l)break;if(t.recordAndCount(Vt(n.action,l),i.per_ms,r)>i.count)return o(s.id,"resource_mutation_rate_exceeded",s.intent,s.source??null);break}case"durable_key_dedup":break}return Xn}var an={allow:0,hold:1,block:2};function Kt(e,n,t,r,o){let s=Xn,i=Xn;for(let l of e.policies){if(!he(l,o))continue;let a=Rl(l,n,t,r);l.origin==="baseline"&&an[a.verdict]>an[i.verdict]&&(i=a);let c=an[a.verdict]>an[s.verdict],d=a.verdict!=="allow"&&an[a.verdict]===an[s.verdict]&&l.origin!=="baseline";(c||d)&&(s=a)}return{decision:s,baseline:i}}function he(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&El(n,e.project_dir))}function Gt(e,n,t){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!he(o,t))){for(let s of o.rules)s.mode&&Wo(s,n)&&(r=Sn(r,s.mode));o.off?.includes(n)&&(r=Sn(r,"off"))}return r}function El(e,n){let t=Ge(e),r=Ge(n),o=r.endsWith("/")?r.slice(0,-1):r;return t===o||t.startsWith(o+"/")}function Je(e=Tl()){return Te(q(e,".anvil","claude"))}function Te(e){return{dir:e,bin:q(e,"bin"),compiled:q(e,"compiled.json"),modes:q(e,"modes.json"),decisions:q(e,"decisions.jsonl"),install:q(e,"install.json"),state:q(e,"state"),approvals:q(e,"approvals"),counts:q(e,"counts"),backups:q(e,"backups")}}var Ll=3500;function $(e,n=8*1024*1024){try{let t=Jt(e);return t.isFile()&&t.size<=n}catch(t){return t.code==="ENOENT"?null:!1}}function me(e,n=8*1024*1024){let t;try{t=zo(e,jo.O_RDONLY|jo.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=Ho(t);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>n)throw new Error(`${e} is over ${n} bytes`);let o=Buffer.alloc(r.size),s=0;for(;s<r.size;){let i=Uo(t,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Fo(t)}}function Me(e,n){let t=n.endsWith(`
1
+ import{existsSync as Wt,readFileSync as vd,writeSync as $d}from"fs";import{homedir as qn,tmpdir as Sd}from"os";import{basename as Tt,dirname as En,join as ve}from"path";import{fileURLToPath as _d,pathToFileURL as Br}from"url";import Cd from"vm";import{Worker as Ad}from"worker_threads";import{spawnSync as Op}from"child_process";import{createHash as Ip}from"crypto";import{chmodSync as Wp,existsSync as Tp,lstatSync as ha,mkdirSync as Mp,readdirSync as Lp,readFileSync as ya,readlinkSync as wa,realpathSync as os,rmdirSync as Dp,statSync as lt,unlinkSync as Fp,writeFileSync as Hp}from"fs";import{dirname as ba,isAbsolute as Up,join as Bp,relative as qp,resolve as ka}from"path";var $e={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Qi(e){if(!e){let a=c=>c;return{on:!1,bold:a,dim:a,blue:a,grey:a,amber:a,mark:a,field:a}}let n=e==="truecolor",t=a=>c=>`\x1B[${a}m${c}\x1B[0m`,r=t(n?"38;2;76;139;255":"38;5;69"),o=t(n?"38;2;130;134;150":"90"),s=t(n?"38;2;245;165;36":"38;5;214"),i=t(n?"38;2;34;197;94":"32"),l={[$e.on]:r,[$e.blocked]:r,[$e.held]:r,[$e.next]:r,[$e.watching]:o,[$e.problem]:s,[$e.ok]:i};return{on:!0,bold:t("1"),dim:t("2"),blue:r,grey:o,amber:s,mark:a=>(l[a]??(c=>c))(a),field:a=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${nl(a)}\x1B[0m`}}var Dd=Qi(!1),el=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function nl(e){return e.replace(el,"")}var We="claude";function Ye(e){return e==="ghost"||e==="enforce"?e:null}function Xr(e,n){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let t=Ye(e.services?.[We]?.actions?.[n]?.mode);return t||(Ye(e.default_mode)??"ghost")}function qt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[We]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function Xn(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function Qr(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:qt(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[We]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[We]?.actions??{}};for(let i of t)s[i]={mode:n};return{version:1,kill_switch:o.kill_switch===!0,default_mode:Ye(o.default_mode)??"ghost",services:{...o.services??{},[We]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function tl(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:Ye(e.default_mode)==="enforce"?!0:Object.values(e.services?.[We]?.actions??{}).some(n=>Ye(n?.mode)==="enforce")}var Qn="claude.agent.controls";function et(e,n){return n===Qn&&tl(e)?"enforce":Xr(e,n)}var Yr={off:0,ghost:1,enforce:2};function On(e,n){return e===null?n:n===null?e:Yr[n]>Yr[e]?n:e}function eo(e,n){return!e||typeof e!="object"?null:Ye(e.services?.[We]?.actions?.[n]?.mode)??(Ye(e.default_mode)==="enforce"?"enforce":null)}function no(e,n,t,r=!1){let s=On(eo(e,n),t)??(r&&Xn(e)?"enforce":et(e,n));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function to(e,n,t){return On(eo(e,n),t)===null&&Xn(e)&&et(e,n)!=="enforce"}function Se(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function U(e){return Object.assign(Object.create(null),e)}var dn=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],rl="home and project wipes and force-pushes to main",Vd=`always blocking ${rl}`,ol=new Map(dn.map(e=>[e.id,e]));function Xe(e){return ol.get(e)}var sl=U({"block-protected-targets":"protect","hold-delete-bursts":"stop-loops","hold-repeated-side-effect":"stop-loops","hold-helper-bursts":"stop-helper-bursts"}),ro=new Set(["hold-delete-bursts","hold-helper-bursts"]),oo=new Set(dn.flatMap(e=>Object.keys(e.slugs)));var so=U({"block-protected-targets":["protect"],"hold-delete-bursts":["stop-loops"],"hold-repeated-side-effect":["stop-loops"],"hold-helper-bursts":["stop-helper-bursts"],"hold-risky-actions":["keep-anvil-on","keep-keys-in"]});function Kt(e){let n=new Set(dl(e));return dn.filter(t=>!Object.entries(so).some(([r,o])=>o.includes(t.id)&&n.has(r)))}var Vt=new Set([Qn,"claude.bash.secrets.expose"]),il=new Set(["claude.file.read_secret","claude.file.write_secret","claude.bash.secrets.print"]),ll=/^(?:\.ssh\/(?!known_hosts|authorized_keys|config$|environment$|rc$)[^/]+(?<!\.pub)|\.aws\/credentials|\.kube\/config|\.docker\/config\.json|\.gnupg\/[^/].*|\.config\/gh\/hosts\.yml|\.npmrc|\.pypirc|\.netrc|\.git-credentials|\.pgpass|\.vault-token|\.config\/gcloud\/[^/].*|\.azure\/[^/].*|\.config\/solana\/id\.json)$/;function al(e,n){if(e.startsWith("~/")){let o=Se(e.slice(2));return o.startsWith("/")?o.slice(1):o}let t=n?Se(n):null,r=Se(e);return t&&t!=="/"&&r.startsWith(`${t}/`)?r.slice(t.length+1):null}function cl(e,n){if(!e)return!1;let t=al(e,n);return t!==null&&ll.test(t)}function ul(e,n,t,r=[]){if(!e||!n)return!0;let o=Se(e.startsWith("~/")&&t?`${t}${e.slice(1)}`:e);if(!o.startsWith("/")||/[\n\r\u2028\u2029]/.test(o))return!0;let s=o.indexOf("/.git");for(;s!==-1&&s+5<o.length&&o[s+5]!=="/";)s=o.indexOf("/.git",s+1);if(s===-1)return!0;let i=o.slice(0,s)||"/";if(r.some(a=>`${i}/.git`===Se(a)))return!0;let l=Se(n)||"/";return l===i||i==="/"||l.startsWith(`${i}/`)}function Zt(e){if(e.decision.verdict==="allow")return null;let n=e.baseline.ruleId?sl[e.baseline.ruleId]:void 0;if(n==="protect"){if(!(e.service==="fs.git_dir"&&!ul(e.target,e.projectDir,e.home,e.histories)))return Xe("protect")}else if(n)return Xe(n);return e.action===Qn?Xe("keep-anvil-on"):e.action==="claude.bash.secrets.expose"||il.has(e.action)&&cl(e.target,e.home)?Xe("keep-keys-in"):null}function io(e,n,t){return e.id==="keep-keys-in"&&n!=="claude.bash.secrets.expose"?"credentials":e.slugs[t]!==void 0?t:Object.keys(e.slugs)[0]}function dl(e){let n=new Set(e.policies.filter(t=>t.origin==="baseline").flatMap(t=>t.rules.map(r=>r.id)));return Object.keys(so).filter(t=>!n.has(t))}var Te=U({"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"discard uncommitted work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}});function ao(e){if(!Xn(e))return null;let n="cluster, cloud and database destroys";return{what:n,context:`It also holds ${n} and cloud-credential prints, until the user sets a mode for their kinds.`}}var lo=U({"block-protected-targets":{slug:"protected",text:"never: home, root, project root, .git, main, every process"},"hold-repeated-side-effect":{slug:"repeat",text:"the same MCP action again within 10 minutes"},"hold-delete-bursts":{slug:"delete-burst",text:"more than 20 deletes in a minute"},"hold-helper-bursts":{slug:"helper-burst",text:"more than 20 helper launches in 10 minutes"},"too-long-to-check":{slug:"too-long-to-check",text:"too long to check in time"},"could-not-check":{slug:"could-not-check",text:"could not be checked"}});function nt(e,n){return e&&lo[e]?lo[e].slug:!e||e==="hold-risky-actions"?Te[n]?.slug??n:e.replace(/@.*$/,"")}function co(e,n,t,r){return r&&n==="baseline"?io(Xe(r),t,nt(e,t)):!r&&e==="block-protected-targets"?Te[t]?.slug??t:nt(e,t)}function tt(e){return Te[e]?.text??e}function Gt(e){let n=new Set(oo);for(let t of e.policies)for(let r of t.rules)if(r.primitive!=="durable_key_dedup")if(r.id==="hold-risky-actions")for(let o of r.applies_to??[])n.add(nt(null,o));else n.add(nt(r.id,""));return n.size}function Jt(e){let n=new Set;for(let t of e.policies)for(let r of t.rules)if(r.primitive!=="durable_key_dedup")for(let o of r.applies_to??t.allowed_actions)n.add(o);return[...n]}function Yt(e,n){let t=Jt(e).filter(o=>Te[o]),r=t.filter(o=>et(n,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===t.length?"enforce":`${r.length} enforced, rest ghost`}}var Xt="anvil-claude";function j(e){let n=e.trim();return n===Xt||n.endsWith(` ${Xt}`)||n.endsWith(`/${Xt}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var uo="\u{1F539}",H=e=>`${uo} ${e} ${uo}`;var Qe=e=>`
2
+ ${$e.next} ${e}`;function fl(e,n,t){return`${Qe(`To ${e}, run this in a terminal (not in this chat):`)}
3
+ ${n}${t?Qe(`Then ${t}.`):""}`}var pl=72;function _e(e,n){let t=`To ${e}, run in a terminal: ${n}`;return t.length+5<=pl?Qe(t):`${Qe(`To ${e}, run in a terminal:`)}
4
+ ${n}`}var gl=(e,n)=>`they run \`${j(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${n}`;var fo="blocking unsafe actions automatically";var Ce="anvil";function Nn(e){Ce=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}function en(){return Ce}var le=e=>`${j(Ce)} ${e}`;function ml(e,n=Ce,t){return`${H("Anvil isn't working")} ${e}.
5
+ Every command waits until it's fixed, so nothing runs unchecked.${t?Qe(t):""}${_e("fix it",`${j(n)} on`)}${_e("turn Anvil off instead",`${j(n)} off`)}`}function hl(e,n=Ce,t){return`${H("Anvil isn't working")} ${e}, so Claude Code holds every tool call until the user fixes it${t?` (${t})`:""} by running \`${j(n)} on\` in a terminal (not in this chat: Claude can't run it). Tell the user, then stop and wait. Do not retry, and do not try another way or another tool.`}function po(e){return`${H("Held by Anvil")} ${e}${Qe("Claude can do it in smaller steps, each one checked")}`}function go(e){return`${H("Held by Anvil")} ${e}, so nothing ran. Do it in smaller steps, each under that size.`}function Ae(e,n,t=Ce,r){let o=hl(n,t,r);return{systemMessage:ml(n,t,r),hookSpecificOutput:e==="SessionStart"?{hookEventName:e,additionalContext:o}:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:o}}}function mo(e,n,t=Ce){let r=yl(e.replace(/^Anvil:? /,""),t);return`${H("Anvil")} ${r.said}${n>0?` (and ${n} more)`:""}${r.fix??_e("see details",`${j(t)} report`)}`}function yl(e,n){let t=e.lastIndexOf(` run ${j(n)} on`),r=t>0?e[t-1]:"";if(t<=0||r!==":"&&r!==";")return{said:e,fix:null};let o=e.slice(t+` run ${j(n)} on`.length);return o!==""&&!/^ to [a-z][a-z ]*$/.test(o)?{said:e,fix:null}:{said:e.slice(0,t-1),fix:_e("fix it",`${j(n)} on`)}}function ho(e,n,t=null){return`${H(`Anvil would've ${e==="block"?"blocked this":"held this for review"}`)} ${n} \xB7 it ran${t?_e("hold these for your OK",`${j(Ce)} enforce ${t}`):""}`}function yo(e,n,t,r,o=!1){let s=`${H("Held by Anvil for your OK")} ${o?`${e} \xB7 always on`:e}`;return t?`${s}${fl("allow it once",`${j(n)} allow ${t}`,"tell Claude to go on")}`:`${s}${Qe(`it can't be allowed right now: ${r}`)}`}function wo(e,n,t=Ce){return n?`${H("Held by Anvil")} ${e}. Nothing ran. Tell the user: to allow it once, ${gl(t,"tell you to go on")}. When they say so, run exactly the same command again, with nothing added to it (the OK covers one call). Do not try another way.`:`${H("Held by Anvil")} ${e}. Nothing ran, and it can't be allowed right now; the user has been told how to fix that. Do not try another way.`}function bo(e){return`${H("Held by Anvil for your OK")} ${e}`}function ko(e,n){return`${H("Blocked by Anvil")} ${e}${_e("change the rule",`${j(n)} rules edit`)}`}function xo(e){return`${H("Blocked by Anvil")} ${e}. Nothing ran, and it can't be allowed once. Do not try another way.`}function vo(e){return`${H("Blocked by Anvil")} ${e} \xB7 can't be overridden`}function $o(e){return`${H("Blocked by Anvil")} ${e}. Nothing ran, and this can't be overridden. Do not try another way.`}function So(e){return`${H("Allowed once, with your OK")} ${e}`}import{createHash as ia}from"crypto";import{appendFileSync as Xo,closeSync as Qo,constants as Zo,fstatSync as es,mkdirSync as la,openSync as ns,readdirSync as aa,readFileSync as ca,readSync as ts,renameSync as ua,statSync as ar,unlinkSync as Go,writeFileSync as da}from"fs";import{homedir as fa}from"os";import{dirname as pa,join as Z}from"path";var In,wl,_o="its file (claude-conditions.js) is missing or won't load";function Co(){return wl??=import(new URL("claude-conditions.js",import.meta.url).href).then(e=>{In=typeof e.matchCondition=="function"&&typeof e.capMoved=="function"?e:void 0},()=>{})}function Ao(e,n,t){return In?In.matchCondition(e,n,t):{hit:"unknown",why:`Anvil can't check this rule's condition: ${_o}`}}function Ro(e,n){return In?In.capMoved(e,n):`Anvil can't read amounts: ${_o}`}var Eo=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,bl=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,kl=/(?:^|[^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]|$)/,Po=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),Oo=(e,n)=>e.split("+").every(t=>t[0]==="="?n.split(/[^a-z0-9]+/).includes(t.slice(1)):n.includes(t));function xl(e,n){let t=`_${n}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),r=n.replace(/_/g,"");return e.servers.some(o=>{let s=o.replace(/_/g,"");return`_${n}_`.includes(`_${o}_`)||t.includes(`_${o}_`)||(s.length>4?r.includes(s):s.length>3&&(r.startsWith(s)||r.endsWith(s)))})}function vl(e,n,t){let r=n.normalize("NFKC").toLowerCase().replace(/\.+$/,""),o=/^[a-z0-9.-]+$/.test(r);if(!r.includes("."))return o?(e.clis??[]).includes(r)?"this":"other":"?";let s=r.split("."),i=a=>r===a||r.endsWith(`.${a}`)||a.includes("*")&&a.split(".").every((c,d,u)=>u.length===s.length&&(c==="*"||c===s[d])),l=!1;return e.hosts.some(a=>{let c=a.indexOf("/");return c<0?i(a):(l||=i(a.slice(0,c))&&/^(?:\/batch\/?|\u0000)$/.test(t),i(a.slice(0,c))&&t.includes(a.slice(c)))})?"this":o&&!l?"other":"?"}function $l(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 nn(e,n,t,r){let o=Po(t);return e.toolWords.length===0||e.toolWords.some(s=>Oo(s,o))?{hit:"match",part:n,why:e.said}:r===3||/\u0000|%00/.test(o)||kl.test(o)||!/[a-z]{3}/.test(o.replace(/[a-z]*\d[a-z0-9]*/g,""))||r===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(o)?{hit:"unknown",part:n,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function Sl(e,n,t){let r=u=>({hit:"unknown",part:n,why:`Anvil can't tell ${u}, so it holds it (your rule: ${e.said})`});if(n.action==="claude.mcp.side_effect"){let u=n.host;if(!u)return r("which app this tool belongs to");let g=`mcp.${u}.`,h=Po(t.tool?.startsWith("mcp__")?t.tool.split("__").slice(2).join("__"):n.target?.startsWith(g)?n.target.slice(g.length):"");if(xl(e,u))return nn(e,n,h,1);let m=(e.anywhere??[]).some(_=>Oo(_,h))?{hit:"match",part:n,why:e.said}:null;if(!Eo.test(u)&&!bl.test(u))return m;let x=e.toolPrefixes.find(_=>h.startsWith(_));return x?nn(e,n,h.slice(x.length),1):e.servers.some(_=>_.length>2&&`_${h}_`.includes(`_${_}_`))?nn(e,n,h,1):m||(e.others??[]).includes(u)?m:r(`which app ${Eo.test(u)?`the connector ${u.slice(0,8)}\u2026`:u} acts on`)}let o=n.target??"",s=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(o)?`https://${o}`:o,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),l="";try{i&&(l=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{l="\0"}if(!n.host&&!n.service)return r("where this writes");let a=[n.host,n.service,...Array.isArray(n.attributes.hosts)?n.attributes.hosts:[],$l(s)].filter(u=>typeof u=="string"&&u!==""),c=a.map(u=>vl(e,u,l)),d=[o,...a].some(u=>/^smtps?[:.]/i.test(u));if(c.includes("this")||d&&e.hosts.includes("smtp:")){let u=a.find((h,m)=>c[m]==="this"&&!h.includes(".")),g=o.includes("/")?3:2;return u?nn(e,n,`cli:${u.toLowerCase()} ${o}`,g):d?nn(e,n,"send mail",2):i?nn(e,n,l,3):nn(e,n,o,g)}return c.includes("?")?r(`where this writes (${a[0].replace(/[\u0000-\u001f]/g,"")})`):t.tool?.startsWith("mcp__")?r("what else this tool's command writes"):null}function fn(e,n,t){let r=null;for(let o of n){let s=Sl(e,o,t);if(s?.hit==="match")return s;r??=s}return r??(t.parts.length>15&&n[0]?{hit:"unknown",part:n[0],why:`Anvil can't read everything this line does, so it holds it (your rule: ${e.said})`}:null)}import{existsSync as ot,readdirSync as Rl,statSync as jo}from"fs";import{dirname as er,isAbsolute as El,join as oe,posix as Pl,resolve as jn}from"path";import{posix as Io}from"path";var _l=null;function B(){return _l??process.platform==="win32"}var No=/^([A-Za-z]):(.*)$/s,Cl=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function Qt(e,n){let t=Io.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function pn(e,n){return e.split("/").map(t=>{if(t===""||t==="."||t===".."||/[\u0000\u0001]/.test(t))return t;let r=t.indexOf(":"),o=r>=0?t.slice(0,r):t,s=n?o:o.replace(/[. ]+$/,"");return s===""?".":s}).join("/")}function ue(e){if(!B())return e;let n=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),t=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(n);if(r){let a=r[2];if(r[1]===".")return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(a))n=`\\\\${a.slice(4)}`;else if(No.test(a))n=a;else return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;t=!0}n=n.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(n);if(o){let a=`/unc/${pn(o[1],t).toLowerCase()}${o[2]?`/${pn(o[2],t).toLowerCase()}`:""}`;return Qt(a,pn(o[3]??"",t).toLowerCase())}let s=No.exec(n);if(s){let a=s[2];return a===""?`/${s[1].toLowerCase()}`:a.startsWith("/")?Qt(`/${s[1].toLowerCase()}`,pn(a,t).toLowerCase()):null}let i=Cl.exec(n);if(i)return Qt(`/${i[1].toLowerCase()}`,pn(i[2]??"",t).toLowerCase());let l=pn(n,t).toLowerCase();if(l.startsWith("/")){let a=Io.normalize(l);return a.length>1&&a.endsWith("/")?a.slice(0,-1):a}return l}function Al(e){return ue(e)??e}function rt(e){if(!B())return e;let n=/^\/([a-z])(\/.*)?$/s.exec(e);if(n)return`${n[1].toUpperCase()}:${(n[2]??"/").replace(/\//g,"\\")}`;let t=/^\/unc\/(.+)$/s.exec(e);return t?`\\\\${t[1].replace(/\//g,"\\")}`:null}function V(e){return B()?rt(e)??e:e}function tn(e){return!B()||typeof e!="string"||e===""?e:Al(e)}var Ol=(e,n)=>{let t=n.endsWith("/")?n.slice(0,-1):n;return e===t||e.startsWith(`${t}/`)},Nl=U({vercel:"vercel deploy --prod, or --target staging",netlify:"netlify deploy --prod, or --context staging",fly:"fly deploy -a <an app named for staging>",flyctl:"flyctl deploy -a <an app named for staging>",railway:"railway up -e staging",modal:"modal deploy -e staging, or MODAL_ENVIRONMENT=staging",kubectl:"kubectl --context staging",helm:"helm --kube-context staging",terraform:"terraform workspace select staging, or -chdir=envs/staging",gh:"gh workflow run \u2026 -f environment=staging",firebase:"firebase deploy -P staging",serverless:"serverless deploy --stage staging",wrangler:"wrangler deploy --env staging"});function To(e,n,t){if(n.length===0)return null;let r=null,o=(s,i)=>{let l=s.action.endsWith(".deploy")&&s.host?Nl[s.host]:void 0;r??={hit:"unknown",part:s,why:`Anvil can't tell ${i}, so it holds it (your rule: ${e.said})${l?`. Say where it goes (${l}) and a deploy that isn't production runs`:""}`}};for(let s of n){let i=s.attributes;if(e.field==="outside_project"){let l=s.target,a=t.projectDir?[l,...t.touched?.full??[]].find(c=>c?.startsWith("/")&&!Ol(c,t.projectDir)):null;if(a)return{hit:"match",part:s,why:`${e.said} (${a})`};(!l||!l.startsWith("/")||!t.projectDir)&&o(s,"where this deletes")}else if(e.field==="environment"){if(i.environment==="production")return{hit:"match",part:s,why:`${e.said}${typeof i.environment_said=="string"?` (${i.environment_said})`:""}`};i.environment!=="non-production"&&o(s,s.action.endsWith(".destructive")?"which database this destroys":s.action.endsWith(".deploy")?"which environment this deploys to":"where this goes")}else{let l=Mo(i,t.home),a=l?.find(c=>(e.value.includes("/")?c:c.split("/").pop())===e.value.toLowerCase().replace(/\.git$/,""));if(a!==void 0)return{hit:"match",part:s,why:`${e.said} (${a})`};l||o(s,"which repository this pushes to")}}return r}function Mo(e,n){try{let t=typeof e.repo_dir=="string"?V(e.repo_dir):e.repo_dir,r=n===null?null:V(n),o=e.repo_via,s=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:o==="gh"&&process.env.GH_REPO||null;if(typeof t!="string"||!El(t)||!ot(t)||o!=="git"&&o!=="gh"||/[$`]/.test(s??""))return null;if(o==="gh"&&s!==null)return Wo([s],t);let i=Il(t,r);if(i===null)return null;let l=new Map;for(let d of i)d.section==="remote"&&d.sub!==null&&(d.key==="url"||(o==="git"?d.key==="pushurl":d.key==="gh-resolved"&&d.value!=="base"))&&l.set(d.sub,[...l.get(d.sub)??[],d.value]);if(s!==null&&!l.has(s)&&!/^[./]|[/:]/.test(s))return null;let a=s!==null?l.get(s)??[s]:[...l.values()].flat();if(s===null)for(let d of i)(d.section==="branch"&&/^(push)?remote$/.test(d.key)||d.section==="remote"&&d.sub===null&&d.key==="pushdefault")&&d.value!=="."&&!l.has(d.value)&&a.push(d.value);let c=new Set(a);for(let d of a)for(let u of i)u.section==="url"&&u.sub!==null&&/^(push)?insteadof$/.test(u.key)&&u.value&&d.startsWith(u.value)&&c.add(u.sub+d.slice(u.value.length));return c.size>0?Wo([...c],t):null}catch{return null}}function Wo(e,n){let t=[];for(let r of e){let o=decodeURIComponent(r.trim()),s=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(o)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(o),l=(s?Pl.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(o)&&!o.startsWith(".")?o:jn(n,o)).replace(/[?#].*$/,"").split(/[\\/]/).filter(g=>g&&g!=="."),a=l.findIndex((g,h)=>h>=2&&/^pulls?$/.test(g));a>=2&&(l=l.slice(0,a));let[c,d]=l.slice(-2).map(g=>g.replace(/\.git$/i,"").toLowerCase()),u=d??c;if(!u||u==="..")return null;t.push(d!==void 0&&c!==".."?`${c}/${d}`:u)}return t}function Il(e,n){let t=process.env;if(t.GIT_CONFIG_COUNT||t.GIT_CONFIG_PARAMETERS||t.GIT_DIR||t.GIT_COMMON_DIR)return null;let r=jl(e);if(r===null)return null;let o=process.platform==="win32"?[oe(t.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),oe(t.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(c=>`${c}/gitconfig`),s=t.GIT_CONFIG_NOSYSTEM?[]:t.GIT_CONFIG_SYSTEM?[t.GIT_CONFIG_SYSTEM]:o;t.GIT_CONFIG_GLOBAL?s.push(t.GIT_CONFIG_GLOBAL):n&&s.push(oe(t.XDG_CONFIG_HOME||oe(n,".config"),"git","config"),oe(n,".gitconfig")),s.push(oe(r.common,"config"),oe(r.gitDir,"config.worktree"));let i=[],l=24,a=(c,d)=>{let u=--l<0||d>5?void 0:be(c,1048576);if(u===void 0)return!1;for(let g of Wl(u?.toString("utf8")??""))if(i.push(g),g.key==="path"&&/^include(if)?$/.test(g.section)){let h=g.value.startsWith("~/")?n&&oe(n,g.value.slice(2)):!/^[~%]/.test(g.value)&&jn(er(c),g.value);if(!h||!a(h,d+1))return!1}return!0};return s.every(c=>a(c,0))?i:null}function jl(e){let n=t=>/^(ref: refs\/|[0-9a-f]{40})/.test(be(oe(t,"HEAD"),4096)?.toString("utf8")??"");for(let t=jn(e),r=0;r<64;r++,t=er(t)){let o=oe(t,".git"),s=["objects","refs"].every(i=>ot(oe(t,i)))&&n(t)?t:null;if(ot(o)){let i=jo(o);if(i.isDirectory())n(o)&&(s=o);else if(s=i.isFile()?/^gitdir:\s*(.+)$/m.exec(be(o,65536)?.toString("utf8")??"")?.[1]?.trim():null,!s)return null}if(s){let i=jn(t,s),l=be(oe(i,"commondir"),65536),a=l===null?i:jn(i,l.toString("utf8").trim());for(let c of["remotes","branches"]){let d=oe(a,c);if(ot(d)&&(!jo(d).isDirectory()||Rl(d).length>0))return null}return{gitDir:i,common:a}}if(er(t)===t)return null}return null}function Wl(e){let n=[],t="",r=null;for(let o of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){o=o.trim();let s=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(o);if(s){let[l,...a]=s[1].toLowerCase().split(".");t=l,r=s[2]?.replace(/\\(.)/g,"$1")??(a.length>0?a.join("."):null),o=o.slice(s[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(o);i&&n.push({section:t,sub:r,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(l,a,c)=>a??c??"").trim()})}return n}import{domainToASCII as Cf}from"url";var jf="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Ml,readdirSync as Ll,realpathSync as zo}from"fs";import{basename as Dl,dirname as Fl,join as Hl}from"path";function Me(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||B()?n.normalize("NFC").toLowerCase():n}function nr(e){if(!/[*?[]/.test(e))return null;let n=[...e],t=[],r=!1;for(let o=0;o<n.length;o++){let s=n[o],i=s==="["?n.indexOf("]",o+2):-1;if(s==="*")(t[t.length-1]!==null||t.length===0)&&t.push(null);else if(s==="?")t.push(l=>l!=="/");else if(i>0){let l=n.slice(o+1,i),a=l[0]==="!"||l[0]==="^",c=a?l.slice(1):l,d=[];for(let u=0;u<c.length;u++){let g=c[u].codePointAt(0);if(c[u+1]==="-"&&u+2<c.length){let h=c[u+2].codePointAt(0);g>h&&(r=!0),d.push([g,h]),u+=2}else d.push([g,g])}t.push(u=>u!=="/"&&d.some(([g,h])=>u.codePointAt(0)>=g&&u.codePointAt(0)<=h)!==a),o=i}else t.push(l=>l===s)}return r?{source:"(?!)",test:()=>!1}:{source:e,test(o){let s=[...o],i=0,l=0,a=-1,c=0;for(;l<s.length;){let d=t[i];if(d!=null&&d(s[l]))i++,l++;else if(d===null)a=i++,c=l;else if(a>=0&&s[c]!=="/")i=a+1,l=++c;else return!1}for(;t[i]===null;)i++;return i===t.length}}}var Tl=e=>e==="**"||/^[*?]+(?:\.[*?]+)*$/.test(e.replace(/\[[^\]]+\]/g,"?"));function tr(e){let n=B()?ue(e.trim())??e.trim():e.trim();if(/^~[^/]/.test(n))return null;let t=n==="~"||n.startsWith("~/"),r=!t&&n.startsWith("./"),o=(t?n.slice(1):n).replace(/^(?:\.\/)+/,""),s=t?0:o.startsWith("/")?1:r||o.replace(/\/+$/,"").includes("/")?2:3,i=[],l=0;for(let c of o.split("/"))c===""||c==="."||(c!==".."?i.push(c):i.length>0&&i[i.length-1]!=="**"?i.pop():s!==1&&i.length===0&&l++);if(i.length===0||i.every(Tl))return null;let a=[];for(let c of i){if(c==="**"){a[a.length-1]!==null&&a.push(null);continue}let d=Me(c),u=nr(d);if(u&&u.source==="(?!)")return null;a.push(u??d)}for(;a[a.length-1]===null;)a.pop();return{segs:a,at:l>0&&s===3?2:s,up:l}}var Lo=["Write","Edit","MultiEdit","NotebookEdit"],zl=["Read","Grep","NotebookRead","Glob","LS"],Ul=["claude.bash.fs.delete_recursive","claude.bash.fs.delete_disposable"],Bl=[".git",".anvil/rules.md",".anvil/rules.json"],Do=new Set(["node_modules",".git"]),ql=1e4,Kl=/^(?:https?|ftps?|wss?|git|ssh|s3|gs|file):$/;var Fo=new WeakMap,Le=e=>Me(e).split("/").filter(Boolean);function Vl(e,n,t){let r=new Map,o=(s,i)=>{if(s===e.length)return 2;if(i===n.length)return 1;let l=s*(n.length+1)+i,a=r.get(l);if(a!==void 0)return a;let c=e[s],d=n[i],u=0;if(c===null)for(let g=i;g<=n.length&&u<2;g++)u=Math.max(u,o(s+1,g));else if(d==="**")u=2;else{let g=nr(d);u=(g?typeof c!="string"||g.test(c):typeof c=="string"?c===d:c.test(d))?o(s+1,i+1):0}return r.set(l,u),u};return o(0,t)}function rr(e,n,t,r){let o=e.at===2&&r.length===0?3:e.at,s=o===0?t&&t.length>e.up?[t.slice(0,t.length-e.up)]:[]:o===1?[[],...r]:o===2?r.map(a=>a.slice(0,Math.max(0,a.length-e.up))):r.length===0?[[]]:r,i=0,l=!1;for(let a of s)if(!(a.length>=n.length||a.some((c,d)=>c!==n[d]))){l=!0;for(let c=a.length;c<n.length&&i<2;c+=o===3?1:n.length)i=Math.max(i,Vl(e.segs,n,c))}return i===2?2:o===3?l?3:0:i===1&&e.segs.includes(null)?3:i}function Uo(e){if(B())return Zl(e);let n="";for(let t=e;t.length>1;)try{return zo.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}function Zl(e){let n=rt(e);if(n===null||process.platform!=="win32")return e;let t=[];for(let r=n;;)try{return ue(Hl(zo.native(r),...t))??e}catch{let o=Fl(r);if(o===r)return e;t.unshift(Dl(r)),r=o}}function Gl(e,n,t){let r=e.at===0?n:e.at===1?"":t,o=r===null?null:e.up>0?r.split("/").slice(0,-e.up).join("/"):r,s=0;for(;s<e.segs.length&&typeof e.segs[s]=="string";)s++;if(o===null||s===0)return null;let i=`${o}/${e.segs.slice(0,s).join("/")}`,l=Uo(i);return Me(l)===Me(i)?null:{segs:[...Le(l),...e.segs.slice(s)],at:1,up:0}}function Jl(e,n){let t=e.split("/").filter(Boolean),r=n?n.split("/").filter(Boolean):null,o=[];for(let s=t.length;s>0&&!(r!==null&&s<=r.length&&r.slice(0,s).every((l,a)=>t[a]===l));s--){let i=`/${t.slice(0,s).join("/")}`;Bl.some(l=>Ml(V(`${i}/${l}`)))&&o.push(i)}return o}function Yl(e,n){if(Do.has(e.slice(e.lastIndexOf("/")+1)))return"no";let t=0,r=[e.replace(/(?<!^)\/+$/,"")];for(let o=0;o<r.length;o++){let s;try{s=Ll(V(r[o]),{withFileTypes:!0})}catch{continue}for(let i of s){if(++t>ql)return"unsure";let l=`${r[o]}/${i.name}`;if(n(Le(l)))return"yes";i.isDirectory()&&!Do.has(i.name)&&r.push(l)}}return"no"}var Ho=new WeakMap;function Xl(e,n){if(!n)return!1;let t=Ho.get(e);t||(t=e.paths.map(o=>{let s=Me(o.split("/").filter(c=>c!==""&&!/^[*?]+$/.test(c)).pop()??""),i=/^[*?]+[^*?[]+$/.test(s),l=s.replace(/^[*?]+/,"");if(l===""||/[*?[]/.test(l))return!0;let a=l.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&");return new RegExp(`${i?"":"(?:^|[\\s'\"`=:(/])"}${a}(?=$|[\\s'"\`/;|&)<>])`)}),Ho.set(e,t));let r=Me(n);return t.some(o=>o===!0||o.test(r))}function Bo(e,n,t){let r=t,o=n[0];if(!o)return null;let s=r.tool??(o.action==="claude.tool.other"?o.target:null),i=o.attributes.path,l=s!==null?Lo.includes(s)||zl.includes(s):i!==void 0;if(l&&(s!==null?!Lo.includes(s):o.action==="claude.file.read_secret"))return null;let a=r.touched,c=new Set(a?.written??[]),d=new Set(a?.read??[]),u=l?[...typeof i=="string"?[i]:[],...a?.full??[]]:[...c,...(a?.full??[]).filter(y=>!d.has(y)||c.has(y))],g=l?[]:a?.unknown??[],h=`(your rule: ${e.said})`;if(l&&u.length===0)return{hit:"unknown",part:o,why:`Anvil can't tell which file this writes, so it holds it ${h}`};if(u.length===0&&g.length===0)return null;let m=Fo.get(e);if(m||Fo.set(e,m=e.paths.map(tr)),m.includes(null))return{hit:"unknown",part:o,why:`Anvil can't read this rule's paths, so it holds every write ${h}`};let x=y=>r.projectDir&&y.startsWith(`${r.projectDir}/`)?y.slice(r.projectDir.length+1):r.home&&y.startsWith(`${r.home}/`)?`~${y.slice(r.home.length)}`:y,_=(y,P)=>({hit:"unknown",part:{...o,target:P},why:`${y}, so Anvil holds it ${h}`}),z=typeof r.root=="string"?r.root:null,ce=z??r.projectDir,J=r.home?Le(r.home):null,p=y=>[...new Map([...y,...y.map(Uo)].map(P=>[Le(P).join("/"),Le(P)])).values()],A=p(ce?.startsWith("/")?[ce]:[]),b=new Map,I=y=>{if(z!==null)return A;let P=b.get(y);if(P===void 0){let N=p(Jl(y,r.home)).filter(K=>!A.some(se=>se.join("/")===K.join("/")));P=N.length===0?A:[...A,...N],b.set(y,P)}return P},Y=[...new Set(u)].filter(y=>y.startsWith("/")).map(y=>({p:y,w:Le(y)})).filter(y=>!y.w.some(P=>Kl.test(P))),M=[...A,...[r.projectDir,r.home].filter(y=>typeof y=="string"&&y.startsWith("/")).map(Le)],W=(y,P)=>[...M,...I(y)].some(N=>N.length>=P.length&&P.every((K,se)=>N[se]===K)),R=y=>a?.written===void 0||c.has(y)||l?`changes ${x(y)}`:`may change ${x(y)}`,he=[],qe=[],Pn=(y,P)=>{for(let N of Y){let K=P(N.p);for(let se of y){let re=rr(se,N.w,J,K);if(re===2)return{hit:"match",part:{...o,target:x(N.p)},why:R(N.p)};re===1&&!W(N.p,N.w)&&he.push({p:N.p,sure:!0}),re===3&&!W(N.p,N.w)&&qe.push(N.p)}}return null},Pe=m,E=Pn(Pe,I)??Pn(Pe.map(y=>Gl(y,r.home,ce)).filter(y=>y!==null),()=>[]);if(E)return E;let T=y=>Me(y).replace(/(?<!^)\/+$/,""),Ke=y=>n.some(P=>Ul.includes(P.action)&&typeof P.target=="string"&&T(P.target)===T(y));for(let y of new Set(qe)){if(he.some(N=>N.p===y)||!(Ke(y)||c.has(y)))continue;let P=Yl(y,N=>Pe.some(K=>rr(K,N,J,I(y))===2));P!=="no"&&he.push({p:y,sure:P==="yes"})}let Ve=he.find(y=>y.sure&&Ke(y.p));if(Ve)return{hit:"match",part:{...o,target:x(Ve.p)},why:`deletes ${x(Ve.p)}, which holds ${e.paths.join(", ")}`};let Oe=he[0];if(Oe!==void 0)return _(`it changes ${x(Oe.p)}, a folder that ${Oe.sure?"holds":"may hold"} ${e.paths.join(", ")}, and Anvil can't tell what changes in it`,x(Oe.p));for(let y of g){let P=y.includes("\0")?y.slice(0,y.indexOf("\0")):y,N=P.slice(0,P.lastIndexOf("/"));if(N.startsWith("/")&&Pe.some(K=>rr(K,Le(N),J,I(N))===2))return _(`Anvil can't read the whole path this writes (${x(y.replace(/[\u0000\u0001]/g,""))})`,x(N))}return g.length>0&&Xl(e,r.command)?_(`it writes where Anvil can't read, and it names ${e.paths.join(", ")}`,o.target):null}function qo(e,n,t){switch(e.type){case"app":return fn(e,n,t);case"paths":return Bo(e,n,t);case"target":return To(e,n,t);case"kind":return n[0]?{hit:"match",part:n[0],why:e.said}:null}}function Ko(e,n,t=Ao){let r=e.kinds?n.parts.filter(l=>e.kinds.includes(l.action)):n.parts;if(e.kinds&&r.length===0)return null;if(!e.when||e.when.length===0)return qo(e.narrowing,r,n);let o=null,s=n.parts.length>15,i=l=>`${l}, so it holds it (your rule: ${e.text})`;for(let l of r){let a=qo(e.narrowing,[l],n);if(!a)continue;let c=e.when.map(u=>t(u,a.part,n));if(c.some(u=>u===null)){s&&(o??={hit:"unknown",part:a.part,why:i("Anvil can't read everything this line does")});continue}let d=c.find(u=>u!==null&&u.hit==="unknown");if(a.hit==="match"&&!d){let u=c.map(g=>g&&g.hit==="match"?g.detail:void 0).filter(g=>typeof g=="string"&&g.length>0);return{hit:"match",part:a.part,why:a.why,...u.length>0?{detail:u.join(", ")}:{}}}o??=a.hit==="unknown"?a:{hit:"unknown",part:a.part,why:i(d.why)}}return o}var or="anvil-claude-compiled/1";function sr(e,n){return`mut:${e}:${n}`}var st={verdict:"allow",policy:null,origin:null,ruleId:null,blockedBy:null,source:null};function ea(e){return typeof e!="string"?"":e.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/g,"").trim().toLowerCase()}function na(e,n){for(let t of n){if(t===e)return!0;if(t.endsWith(".*")){let r=t.slice(0,-2);if(r.length>0&&(e===r||e.startsWith(r+".")))return!0}if(t.startsWith("*.")){let r=t.slice(1);if(e.endsWith(r)&&e.length>r.length)return!0}}return!1}function ta(e,n){let t=e[n];return typeof t=="string"?t.trim()||null:typeof t=="number"?!Number.isFinite(t)||t===0?null:String(t):null}function Vo(e,n){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(n)}function ra(e,n){if(e.length===0)return!1;let t=n.toLowerCase(),r=t.split(/[^a-z0-9]+/i).filter(Boolean);return e.some(o=>r.includes(o))||e.some(o=>t.includes(o))}function oa(e,n,t,r){let o=(s,i,l,a)=>({verdict:l??(i==="confirmation_required"?"hold":"block"),policy:e.name,origin:e.origin,ruleId:s,blockedBy:i,source:a});if(!e.allowed_actions.includes(n.action))return e.deny_unlisted?o(null,"allowlist",null,null):st;for(let s of e.rules)if(Vo(s,n.action))switch(s.primitive){case"confirmation_gate":{if(s.all_actions===!0||ra(s.trigger_verbs??[],n.action))return o(s.id,"confirmation_required",s.intent,s.source??null);break}case"service_blocklist":{let i=s.blocked??[];if(i.length===0)break;let l=ea(n.service);if(l&&na(l,i))return o(s.id,"service_in_blocklist",s.intent,s.source??null);break}case"resource_mutation_rate":{let i=s.rate;if(!i||i.count<=0||i.per_ms<=0||!Number.isFinite(i.count)||!Number.isFinite(i.per_ms))break;let l=ta(n.metadata,s.resource_field?.trim()||"resource_id");if(!l)break;if(t.recordAndCount(sr(n.action,l),i.per_ms,r)>i.count)return o(s.id,"resource_mutation_rate_exceeded",s.intent,s.source??null);break}case"durable_key_dedup":break}return st}var gn={allow:0,hold:1,block:2};function ir(e,n,t,r,o){let s=st,i=st;for(let l of e.policies){if(!de(l,o))continue;let a=oa(l,n,t,r);l.origin==="baseline"&&gn[a.verdict]>gn[i.verdict]&&(i=a);let c=gn[a.verdict]>gn[s.verdict],d=a.verdict!=="allow"&&gn[a.verdict]===gn[s.verdict]&&l.origin!=="baseline";(c||d)&&(s=a)}return{decision:s,baseline:i}}function de(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&sa(n,e.project_dir))}function lr(e,n,t){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!de(o,t))){for(let s of o.rules)s.mode&&Vo(s,n)&&(r=On(r,s.mode));o.off?.includes(n)&&(r=On(r,"off"))}return r}function sa(e,n){let t=tn(e),r=tn(n),o=r.endsWith("/")?r.slice(0,-1):r;return t===o||t.startsWith(o+"/")}function De(e=fa()){return Fe(Z(e,".anvil","claude"))}function Fe(e){return{dir:e,bin:Z(e,"bin"),compiled:Z(e,"compiled.json"),modes:Z(e,"modes.json"),decisions:Z(e,"decisions.jsonl"),install:Z(e,"install.json"),state:Z(e,"state"),approvals:Z(e,"approvals"),counts:Z(e,"counts"),backups:Z(e,"backups")}}var ga=3500;function C(e,n=8*1024*1024){try{let t=ar(e);return t.isFile()&&t.size<=n}catch(t){return t.code==="ENOENT"?null:!1}}function be(e,n=8*1024*1024){let t;try{t=ns(e,Zo.O_RDONLY|Zo.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=es(t);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>n)throw new Error(`${e} is over ${n} bytes`);let o=Buffer.alloc(r.size),s=0;for(;s<r.size;){let i=ts(t,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Qo(t)}}function He(e,n){let t=n.endsWith(`
6
6
  `)?n:`${n}
7
- `;if(Buffer.byteLength(t)>Ll)throw new Error(`refusing to append a ${Buffer.byteLength(t)}-byte line`);if($(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);Do(e,t,{mode:384})}function F(e){Nl(e,{recursive:!0,mode:448})}function Z(e,n){if($(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let t;try{t=zo(e,"r")}catch{return""}try{let r=Ho(t).size,o=Math.max(0,r-n),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);Uo(t,i,0,s,o);let l=i.toString("utf8");if(o>0){let a=l.indexOf(`
8
- `);l=a<0?"":l.slice(a+1)}return l}finally{Fo(t)}}function Y(e,n,t=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;jl(r,n,{mode:t}),En(r,e)}function En(e,n){for(let t=0;;t++)try{Wl(e,n);return}catch(r){let o=r.code;if(process.platform!=="win32"||t>=12||o!=="EPERM"&&o!=="EACCES"&&o!=="EBUSY")throw r;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20+t*10)}}function Pn(e){if($(e)!==!0)return null;try{return JSON.parse(Il(e,"utf8"))}catch{return null}}var Mo=256*1024,Dl=1024*1024,Qn=class{constructor(n,t=()=>null){this.file=n;this.answer=t}recordAndCount(n,t,r){let o=r-t,s=this.restartedAt(n,r),i=1,l=Z(this.file,Mo);for(let a of l.split(`
9
- `)){let c=a.indexOf(" ");if(c<=0||a.slice(c+1)!==n)continue;let d=Number(a.slice(0,c));Number.isFinite(d)&&d>=o&&d<=r&&d>s&&i++}return this.rotateIfLarge(),Me(this.file,`${r} ${n.replace(/[\r\n]/g," ")}`),i}restart(n,t,r){let o=this.restartDir();F(o),Y(q(o,`${Lo(n)}.json`),JSON.stringify({v:1,at:t,...r?{tr:r.transcript,call:r.call}:{}}));try{for(let s of Ol(o)){let i=q(o,s);Jt(i).mtimeMs<t-864e5&&To(i)}}catch{}}restartedAt(n,t){let r=q(this.restartDir(),`${Lo(n)}.json`),o=me(r,4096);if(!o)return-1/0;try{let s=JSON.parse(o.toString("utf8"));if(typeof s.at!="number"||!Number.isFinite(s.at)||s.at>t)return-1/0;if(typeof s.tr=="string"&&typeof s.call=="string"){let i=this.answer(s.tr,s.call);if(i===null)return-1/0;if(i==="no")return To(r),-1/0;Y(r,JSON.stringify({v:1,at:s.at}))}return s.at}catch{return-1/0}}restartDir(){return q(Ml(this.file),"rate-ok")}rotateIfLarge(){try{if(Jt(this.file).size>Dl){let n=Z(this.file,Mo);Y(this.file,n)}}catch{}}},Lo=e=>Pl("sha256").update(e).digest("hex").slice(0,16);function Bo(e,n){let t=q(e,n.toISOString().slice(0,10));$(t,Number.MAX_SAFE_INTEGER)!==!1&&Do(t,".",{mode:384})}var ql="/.anvil/claude/bin/claude-hook.js",Zl=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var cn=class extends Error{constructor(n){super(n),this.name="SettingsRefused"}};var Vl=["UserPromptSubmit","SubagentStart","SubagentStop","PreModelSwitch"],Nn=e=>typeof e=="string"&&Vl.includes(e);function Zo(e,n){let t=e.startsWith("\uFEFF")?e.slice(1):e;if(t.trim()==="")return{};let r;try{r=JSON.parse(t)}catch(o){throw new cn(`${n} is not valid JSON (${o instanceof Error?o.message:String(o)}). Anvil changed nothing; fix the file and run this again.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new cn(`${n} is not a JSON object. Anvil changed nothing.`);return r}function Kl(e){if(!e||typeof e!="object")return null;let{command:n,args:t}=e;return typeof n!="string"?null:Array.isArray(t)?[n,...t.filter(r=>typeof r=="string")].join(" "):n}var Gl=e=>{let n=Kl(e);return n!==null&&(n.includes(ql)||Zl.test(n))};function Jl(e,n){if(!e||typeof e!="object")return!1;let t=e;return typeof n=="string"?t.command===n:t.command===n.command&&Array.isArray(t.args)&&t.args.length===n.args.length&&t.args.every((r,o)=>r===n.args[o])}function Vo(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function Yl(e){return me(e,64*1024*1024)}function Ko(e){try{if(!Fl(e).isSymbolicLink())return e}catch{return e}try{return qo(e)}catch(n){let t=n.code;throw t==="ENOENT"?new cn(`${e} is a link to ${Xl(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new cn(`${e} is a link Anvil cannot follow (${t??String(n)}). Anvil changed nothing.`)}}function Xl(e){let n=Ul(e);try{n=qo(n)}catch{}return Bl(n,zl(e))}function Yt(e){try{let n=Ko(e),t=et(n);if(!t.isFile()||t.size>4*1024*1024)return!1;let r=Yl(n);if(r===null)return!1;let o=Zo(r.toString("utf8"),e).hooks?.PreToolUse;return Array.isArray(o)&&o.some(s=>{let i=s&&typeof s=="object"?s:null,l=i?.matcher;return(l===void 0||l===""||l==="*")&&Array.isArray(i?.hooks)&&i.hooks.some(a=>Gl(a)&&na(a))})}catch{return!1}}function Go(e,n){let t;try{t=Ko(e)}catch{return"unreadable"}let r;try{r=et(t)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=Zo(Hl(t,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let s=o.hooks?.PreToolUse;return Array.isArray(s)&&s.some(l=>{let a=l&&typeof l=="object"?l:null,c=a?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(a?.hooks)&&a.hooks.some(d=>Jl(d,n))})?"present":"missing"}function Ql(e){let n=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),t=s=>s.startsWith("'")?s.slice(1,-1).replace(/'\\''/g,"'"):s,r=n?n.findIndex(s=>s==="/bin/sh"||s==="sh"):-1,o=n&&r>=0&&(n[r+3]==="PreToolUse"||n[r+3]==="SessionStart")?1:0;if(n&&r>=0&&n[r+3+o]==="||"){let s=r>0&&r%5===0;for(let i=0;s&&i<r;i+=5)s=n[i]==="["&&(n[i+1]==="-s"||n[i+1]==="-f")&&n[i+3]==="]"&&n[i+4]==="&&"&&t(n[i+2])===t(n[r+1]);if(r===0||s)return[t(n[r+1]),t(n[r+2])]}return!n||n.length!==2?null:[t(n[0]),t(n[1])]}function ea(e){if(!e||typeof e!="object")return null;let{command:n,args:t}=e;if(typeof n!="string")return null;if(Array.isArray(t)){let r=t.find(o=>typeof o=="string"&&/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js$/i.test(o));return r?[n,r]:null}return Ql(n)}function na(e){let n=ea(e);if(!n)return!1;try{return et(n[0]).isFile()&&et(n[1]).isFile()}catch{return!1}}import{spawnSync as Gc}from"child_process";import{createHash as Mn}from"crypto";import{readdirSync as Jc,readFileSync as $t,realpathSync as Js,statSync as Yc}from"fs";import{basename as Ln,dirname as Sr,isAbsolute as St,join as b,resolve as hn}from"path";import{closeSync as ta,constants as Jo,fstatSync as ra,openSync as oa,readdirSync as sa,readSync as ia,unlinkSync as la}from"fs";import{join as Yo}from"path";var aa=9,Xo=4*1024*1024;function ca(e){let n;try{n=oa(e,Jo.O_RDONLY|Jo.O_NONBLOCK)}catch(t){if(t.code==="ENOENT")return"";throw t}try{let t=ra(n);if(!t.isFile())throw new Error("the day's cap count is not a regular file");if(t.size>Xo)throw new Error(`the day's cap count is over ${Xo/1024/1024} MB`);let r=Buffer.alloc(t.size),o=0;for(;o<t.size;){let s=ia(n,r,o,t.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{ta(n)}}function nt(e,n){if(e.window==="minute")return n-6e4;if(e.window==="hour")return n-36e5;let t=new Date(n);return t.setHours(0,0,0,0),e.window==="week"&&t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}var Qo=e=>{let n=new Date(e);return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`};function es(e,n,t,r=null){let o=[];for(let s of e.policies)if(he(s,t)){for(let i of s.caps??[])if(i.kinds.some(l=>n.includes(l))){if(i.match&&r){let l=r.parts.filter(a=>i.kinds.includes(a.action));if(l.length>0&&An(i.match,l,r)===null)continue}o.push(i)}}return o}var Ye=class extends Error{};function ns(e,n){let t=String(Math.max(0,Math.round(e))).padStart(n.digits+1,"0"),r=n.digits>0?t.slice(-n.digits):"";return`${n.sign}${t.slice(0,t.length-n.digits).replace(/\B(?=(\d{3})+(?!\d))/g,",")}${r&&!/^0+$/.test(r)?`.${r}`:""}`}function rt(e,n,t=null){if(e.unit==="money"){let s=go(e,t);if(typeof s=="string")throw new Ye(s);return s}if(e.unit==="calls")return 1;let r=n?.machines??1,o=(n?.hours??1)*r;return e.unit==="machines"?r:e.unit==="hours"?o:(e.price?.per==="hour"?o:r)*(e.price?.usd??0)}function ua(e,n,t){try{return rt(e,n,t)}catch(r){if(r instanceof Ye)return e.limit;throw r}}var tt=class{constructor(n){this.dir=n}file(n){return Yo(this.dir,`${Qo(n)}.log`)}write(n){F(this.dir),Me(this.file(n.t),JSON.stringify(n))}read(n,t){let r=[],o=new Date(n);for(o.setHours(0,0,0,0);o.getTime()<=t;o.setDate(o.getDate()+1))for(let s of ca(this.file(o.getTime())).split(`
10
- `))if(s)try{let i=JSON.parse(s);typeof i.t=="number"&&typeof i.cap=="string"&&typeof i.key=="string"&&r.push(i)}catch{}return r}usedIn(n,t,r,o=n.length,s=!1){let i=nt(t,r),l=new Map;for(let c=0;c<o;c++){let d=n[c];d.cap===t.id&&l.set(d.key,d.op==="x"||!l.has(d.key)||l.get(d.key).op==="x"?d:{...l.get(d.key),op:d.op})}let a=0;for(let c of l.values())c.op!=="x"&&c.t>=i&&(s||c.t<=r)&&(a+=c.n);return a}admit(n,t,r,o,s,i=null){if(n.length===0)return null;let l=n.map(u=>rt(u,r,i));this.resolve(n,o),n.forEach((u,g)=>this.write({t:o,op:"ran",cap:u.id,key:t,n:l[g]})),s?.();let a=Math.min(...n.map(u=>nt(u,o))),c=this.read(a,o+6e4),d=null;for(let u of n){let g=c.findIndex(v=>v.cap===u.id&&v.key===t&&v.op==="ran"&&v.t===o);if(g<0){d={cap:u,used:u.limit};break}let h=this.usedIn(c,u,o,g+1,!0);if(h>u.limit){d={cap:u,used:h-c[g].n};break}}if(d)for(let u of n)this.write({t:o,op:"x",cap:u.id,key:t,n:0});return this.prune(o),d}count(n,t,r,o,s="ran",i,l=null){for(let a of n)this.write({t:o,op:s,cap:a.id,key:t,n:ua(a,r,l),...s==="ask"&&i?.tr&&i.call?{tr:i.tr,call:i.call}:{}})}used(n,t){return this.resolve([n],t),this.usedIn(this.read(nt(n,t),t),n,t)}resolve(n,t){let r=new Set(n.map(l=>l.id)),o=Math.min(...n.map(l=>nt(l,t))),s=new Map;for(let l of this.read(o,t)){if(!r.has(l.cap))continue;let a=`${l.cap}\0${l.key}`;l.op==="ask"?s.set(a,l):s.delete(a)}let i=0;for(let l of s.values()){if(i>=4||t-l.t<1e3)continue;i++;let a=Xt(l.tr,l.call);a==="no"?this.write({t:l.t,op:"x",cap:l.cap,key:l.key,n:0}):a==="yes"&&this.write({t:l.t,op:"ran",cap:l.cap,key:l.key,n:l.n})}}prune(n){try{let t=Qo(n-aa*864e5);for(let r of sa(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<t&&la(Yo(this.dir,r))}catch{}}};function Xt(e,n){return!e||!n?null:da(Z(e,4*1024*1024),n)}function da(e,n){let t=e.indexOf(`"tool_use_id":"${n}"`);if(t<0)return null;let r=e.slice(e.lastIndexOf(`
7
+ `;if(Buffer.byteLength(t)>ga)throw new Error(`refusing to append a ${Buffer.byteLength(t)}-byte line`);if(C(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);Xo(e,t,{mode:384})}function D(e){la(e,{recursive:!0,mode:448})}function q(e,n){if(C(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let t;try{t=ns(e,"r")}catch{return""}try{let r=es(t).size,o=Math.max(0,r-n),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);ts(t,i,0,s,o);let l=i.toString("utf8");if(o>0){let a=l.indexOf(`
8
+ `);l=a<0?"":l.slice(a+1)}return l}finally{Qo(t)}}function Q(e,n,t=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;da(r,n,{mode:t}),Wn(r,e)}function Wn(e,n){for(let t=0;;t++)try{ua(e,n);return}catch(r){let o=r.code;if(process.platform!=="win32"||t>=12||o!=="EPERM"&&o!=="EACCES"&&o!=="EBUSY")throw r;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20+t*10)}}function Tn(e){if(C(e)!==!0)return null;try{return JSON.parse(ca(e,"utf8"))}catch{return null}}var Jo=256*1024,ma=1024*1024,it=class{constructor(n,t=()=>null){this.file=n;this.answer=t}recordAndCount(n,t,r){let o=r-t,s=this.restartedAt(n,r),i=1,l=q(this.file,Jo);for(let a of l.split(`
9
+ `)){let c=a.indexOf(" ");if(c<=0||a.slice(c+1)!==n)continue;let d=Number(a.slice(0,c));Number.isFinite(d)&&d>=o&&d<=r&&d>s&&i++}return this.rotateIfLarge(),He(this.file,`${r} ${n.replace(/[\r\n]/g," ")}`),i}restart(n,t,r){let o=this.restartDir();D(o),Q(Z(o,`${Yo(n)}.json`),JSON.stringify({v:1,at:t,...r?{tr:r.transcript,call:r.call}:{}}));try{for(let s of aa(o)){let i=Z(o,s);ar(i).mtimeMs<t-864e5&&Go(i)}}catch{}}restartedAt(n,t){let r=Z(this.restartDir(),`${Yo(n)}.json`),o=be(r,4096);if(!o)return-1/0;try{let s=JSON.parse(o.toString("utf8"));if(typeof s.at!="number"||!Number.isFinite(s.at)||s.at>t)return-1/0;if(typeof s.tr=="string"&&typeof s.call=="string"){let i=this.answer(s.tr,s.call);if(i===null)return-1/0;if(i==="no")return Go(r),-1/0;Q(r,JSON.stringify({v:1,at:s.at}))}return s.at}catch{return-1/0}}restartDir(){return Z(pa(this.file),"rate-ok")}rotateIfLarge(){try{if(ar(this.file).size>ma){let n=q(this.file,Jo);Q(this.file,n)}}catch{}}},Yo=e=>ia("sha256").update(e).digest("hex").slice(0,16);function rs(e,n){let t=Z(e,n.toISOString().slice(0,10));C(t,Number.MAX_SAFE_INTEGER)!==!1&&Xo(t,".",{mode:384})}var ss="/.anvil/claude/bin/claude-hook.js",xa=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var mn=class extends Error{constructor(n){super(n),this.name="SettingsRefused"}};var is=["UserPromptSubmit","SubagentStart","SubagentStop","PreModelSwitch"],hn=e=>typeof e=="string"&&is.includes(e);function ls(e){let n=new Set;for(let t of e)try{let r=cs(ur(t)),o=r===null?null:cr(r.toString("utf8"),t).hooks;for(let s of is)JSON.stringify(o?.[s]??null).includes(ss)&&n.add(s)}catch{}return n}function cr(e,n){let t=e.startsWith("\uFEFF")?e.slice(1):e;if(t.trim()==="")return{};let r;try{r=JSON.parse(t)}catch(o){throw new mn(`${n} is not valid JSON (${o instanceof Error?o.message:String(o)}). Anvil changed nothing; fix the file and run this again.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new mn(`${n} is not a JSON object. Anvil changed nothing.`);return r}function va(e){if(!e||typeof e!="object")return null;let{command:n,args:t}=e;return typeof n!="string"?null:Array.isArray(t)?[n,...t.filter(r=>typeof r=="string")].join(" "):n}var $a=e=>{let n=va(e);return n!==null&&(n.includes(ss)||xa.test(n))};function Sa(e,n){if(!e||typeof e!="object")return!1;let t=e;return typeof n=="string"?t.command===n:t.command===n.command&&Array.isArray(t.args)&&t.args.length===n.args.length&&t.args.every((r,o)=>r===n.args[o])}function as(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function cs(e){return be(e,64*1024*1024)}function ur(e){try{if(!ha(e).isSymbolicLink())return e}catch{return e}try{return os(e)}catch(n){let t=n.code;throw t==="ENOENT"?new mn(`${e} is a link to ${_a(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new mn(`${e} is a link Anvil cannot follow (${t??String(n)}). Anvil changed nothing.`)}}function _a(e){let n=ba(e);try{n=os(n)}catch{}return ka(n,wa(e))}function dr(e){try{let n=ur(e),t=lt(n);if(!t.isFile()||t.size>4*1024*1024)return!1;let r=cs(n);if(r===null)return!1;let o=cr(r.toString("utf8"),e).hooks?.PreToolUse;return Array.isArray(o)&&o.some(s=>{let i=s&&typeof s=="object"?s:null,l=i?.matcher;return(l===void 0||l===""||l==="*")&&Array.isArray(i?.hooks)&&i.hooks.some(a=>$a(a)&&Ra(a))})}catch{return!1}}function us(e,n){let t;try{t=ur(e)}catch{return"unreadable"}let r;try{r=lt(t)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=cr(ya(t,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let s=o.hooks?.PreToolUse;return Array.isArray(s)&&s.some(l=>{let a=l&&typeof l=="object"?l:null,c=a?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(a?.hooks)&&a.hooks.some(d=>Sa(d,n))})?"present":"missing"}function Ca(e){let n=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),t=s=>s.startsWith("'")?s.slice(1,-1).replace(/'\\''/g,"'"):s,r=n?n.findIndex(s=>s==="/bin/sh"||s==="sh"):-1,o=n&&r>=0&&(n[r+3]==="PreToolUse"||n[r+3]==="SessionStart")?1:0;if(n&&r>=0&&n[r+3+o]==="||"){let s=r>0&&r%5===0;for(let i=0;s&&i<r;i+=5)s=n[i]==="["&&(n[i+1]==="-s"||n[i+1]==="-f")&&n[i+3]==="]"&&n[i+4]==="&&"&&t(n[i+2])===t(n[r+1]);if(r===0||s)return[t(n[r+1]),t(n[r+2])]}return!n||n.length!==2?null:[t(n[0]),t(n[1])]}function Aa(e){if(!e||typeof e!="object")return null;let{command:n,args:t}=e;if(typeof n!="string")return null;if(Array.isArray(t)){let r=t.find(o=>typeof o=="string"&&/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js$/i.test(o));return r?[n,r]:null}return Ca(n)}function Ra(e){let n=Aa(e);if(!n)return!1;try{return lt(n[0]).isFile()&&lt(n[1]).isFile()}catch{return!1}}import{spawnSync as ju}from"child_process";import{createHash as zn}from"crypto";import{readdirSync as Ni,readFileSync as Ot,realpathSync as $i,statSync as Wu}from"fs";import{basename as Un,dirname as Dr,isAbsolute as Nt,join as k,resolve as Sn}from"path";import{createHash as Ea}from"crypto";import{closeSync as Pa,constants as ds,fstatSync as Oa,openSync as Na,readdirSync as fs,readFileSync as Ia,readSync as ja,statSync as Wa,unlinkSync as fr,writeFileSync as Ta}from"fs";import{join as rn}from"path";var Ma=9,ps=4*1024*1024,pr=6*36e5,gr="waiting",La=4,gs=16;function Da(e){let n;try{n=Na(e,ds.O_RDONLY|ds.O_NONBLOCK)}catch(t){if(t.code==="ENOENT")return"";throw t}try{let t=Oa(n);if(!t.isFile())throw new Error("the day's cap count is not a regular file");if(t.size>ps)throw new Error(`the day's cap count is over ${ps/1024/1024} MB`);let r=Buffer.alloc(t.size),o=0;for(;o<t.size;){let s=ja(n,r,o,t.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{Pa(n)}}function at(e,n){if(e.window==="minute")return n-6e4;if(e.window==="hour")return n-36e5;let t=new Date(n);return t.setHours(0,0,0,0),e.window==="week"&&t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}var ms=e=>{let n=new Date(e);return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`};function ws(e,n,t,r=null){let o=[];for(let s of e.policies)if(de(s,t)){for(let i of s.caps??[])if(i.kinds.some(l=>n.includes(l))){if(i.match&&r){let l=r.parts.filter(a=>i.kinds.includes(a.action));if(l.length>0&&fn(i.match,l,r)===null)continue}o.push(i)}}return o}var ke=class extends Error{constructor(t,r){super(t);this.cap=r}};function Fa(e,n){return n.parts.filter(t=>e.kinds.includes(t.action)&&(!e.match||fn(e.match,[t],n)!==null))}function Ha(e,n){if(!n)return 1;if(n.parts.length>=gs)throw new ke(`this call has more actions than Anvil counts in one line (${gs})`,e);let t=n.tool?.startsWith("mcp__")===!0,r=n.command??(t?za(n.input):null);if(r!==null&&bs(r))throw new ke("this line repeats what it runs a number of times Anvil can't read",e);if(t&&r!==null&&/[;&|\n]/.test(r))throw new ke("an MCP tool runs this line of several commands, which Anvil can't count one by one",e);return Math.max(1,Fa(e,n).length)}function za(e){for(let n of["command","cmd","script","input","code","cli_command"])if(typeof e?.[n]=="string")return e[n];return null}function Ua(e){let n="",t=[],r=/(?:\b(?:ba|z|da|k|fi)?sh(?:\s+-\S+)*\s+-\w*c\w*|\beval|\bssh\b[^;&|\n]*|\bsu\b[^;&|\n]*-c)\s*$/;for(let o=0;o<e.length;o++){let s=e[o];if(s==="\\"){n+=" ",o++;continue}if(s!=="'"&&s!=='"'){n+=s;continue}let i=o+1,l="";for(;i<e.length&&e[i]!==s;i++)s==='"'&&e[i]==="\\"?l+=e[++i]??"":l+=e[i];t.push({text:l,code:r.test(n)}),n+=" Q ",o=i}return{bare:n,quoted:t}}function bs(e,n=0){let{bare:t,quoted:r}=Ua(e);if(n<3&&r.some(l=>l.code&&bs(l.text,n+1)))return!0;let o=String.raw`(?:^|[;&|(){}\n!]|\b(?:do|then|else|elif|time|coproc)\b)\s*`,s=String.raw`(?:[A-Za-z_]\w*=\S*\s+|(?:sudo|nohup|time|command|builtin|env|exec|nice|ionice|timeout|stdbuf|caffeinate)(?:\s+-\S+)*(?:\s+\d+(?:\.\d+)?[smhd]?)?\s+)*`;if(new RegExp(String.raw`${o}${s}(?:while|until|select|repeat)\b`).test(t)||new RegExp(String.raw`${o}${s}(?:xargs|parallel|watch)\b`).test(t)||/\bfind\b[^;&|\n]*\s-(?:exec|execdir|ok|okdir)\b/.test(t))return!0;for(let l of t.matchAll(/(?<![\w-])([A-Za-z_][\w-]*)\s*\(\s*\)\s*\{([^}]*)/g))if(new RegExp(String.raw`(?:^|[;&|\s{(])${l[1].replace(/-/g,"\\-")}(?:$|[;&|\s)}])`).test(l[2]))return!0;let i=0;for(let l of t.matchAll(new RegExp(String.raw`${o}${s}for\b([^;\n]*)`,"g"))){let a=/^\s*[A-Za-z_]\w*\s+in\s+(.*)$/.exec(l[1]),c=a?a[1].trim().split(/\s+/).filter(Boolean):[];if(!a||c.length===0||c.length>16||c.some(d=>/[$`*?[\]{}~]/.test(d)))return!0;i+=c.length}return i>64}function ks(e,n){let t=String(Math.max(0,Math.round(e))).padStart(n.digits+1,"0"),r=n.digits>0?t.slice(-n.digits):"";return`${n.sign}${t.slice(0,t.length-n.digits).replace(/\B(?=(\d{3})+(?!\d))/g,",")}${r&&!/^0+$/.test(r)?`.${r}`:""}`}function ut(e,n,t=null){if(e.unit==="money"){let i=Ro(e,t);if(typeof i=="string")throw new ke(i,e);return i}let r=Ha(e,t);if(e.unit==="calls")return r;let o=n?.machines??1,s=(n?.hours??1)*o;return e.unit==="machines"?o*r:e.unit==="hours"?s*r:(e.price?.per==="hour"?s:o)*(e.price?.usd??0)*r}function Ba(e,n,t){try{return ut(e,n,t)}catch(r){if(r instanceof ke)return e.limit;throw r}}var Mn=class{constructor(n){this.dir=n}file(n){return rn(this.dir,`${ms(n)}.log`)}write(n){D(this.dir),He(this.file(n.t),JSON.stringify(n)),n.tr&&n.call&&(D(rn(this.dir,gr)),Ta(rn(this.dir,gr,ys(n.cap,n.key)),n.cap,{mode:384}))}settle(n,t,r=null){let o=rn(this.dir,gr),s;try{s=fs(o)}catch{return}if(s.length===0)return;let i=new Set;for(let c of s)try{let d=rn(o,c);t-Wa(d).mtimeMs>pr+36e5?fr(d):i.add(Ia(d,"utf8"))}catch{}let l=n.filter(c=>i.has(c.id)),a=l.length>0?this.resolve(l,t,r).done:[];for(let c of a)try{fr(rn(o,c))}catch{}}read(n,t){let r=[],o=new Date(n);for(o.setHours(0,0,0,0);o.getTime()<=t;o.setDate(o.getDate()+1))for(let s of Da(this.file(o.getTime())).split(`
10
+ `))if(s)try{let i=JSON.parse(s);typeof i.t=="number"&&typeof i.cap=="string"&&typeof i.key=="string"&&r.push(i)}catch{}return r}usedIn(n,t,r,o=n.length,s=!1){let i=at(t,r),l=new Map;for(let c=0;c<o;c++){let d=n[c];d.cap===t.id&&l.set(d.key,d.op==="x"||!l.has(d.key)||l.get(d.key).op==="x"?d:{...l.get(d.key),op:d.op})}let a=0;for(let c of l.values())c.op!=="x"&&c.t>=i&&(s||c.t<=r)&&(a+=c.n);return a}used(n,t,r=null){return this.resolve([n],t,r),this.usedIn(this.read(at(n,t),t),n,t)}resolve(n,t,r=null){let o=new Set(n.map(m=>m.id)),s=Math.min(...n.map(m=>at(m,t))),i=new Map;for(let m of this.read(s,t))o.has(m.cap)&&i.set(`${m.cap}\0${m.key}`,m);let l=[...i.values()].filter(m=>m.tr&&m.call&&(m.op==="x"?typeof m.seen=="number":m.op==="ask"||t-m.t<=pr)),a=[];if(l.length===0)return{left:0,done:a};let c=l.length;l.sort((m,x)=>+(x.op==="x")-+(m.op==="x")||x.t-m.t);let d=new Set(r?.s?l.filter(m=>m.s===r.s).map(m=>m.tr):[]),u=m=>[...new Set(m.map(x=>x.tr))].filter(x=>!d.has(x)).slice(0,La),g=[...new Set([...d,...u(l.filter(m=>m.op==="x")),...u(l.filter(m=>m.op!=="x"))])],h=new Map(g.map(m=>[m,xs(q(m,4*1024*1024),new Set(l.filter(x=>x.tr===m).map(x=>x.call)))]));for(let m of l){let x=h.get(m.tr);if(!x)continue;let _=x.get(m.call)??[],z=ce=>(this.write(ce),c--,void a.push(ys(m.cap,m.key)));m.op==="x"?_.length>1||_.length===1&&!_[0].refused?z({t:m.t,op:"ran",cap:m.cap,key:m.key,n:typeof m.was=="number"&&Number.isFinite(m.was)?m.was:0}):t-m.seen>=pr&&z({t:m.t,op:"x",cap:m.cap,key:m.key,n:0}):_.length===1&&_[0].refused?r&&m.s!==void 0&&r.s===m.s&&(r.a??"")===(m.a??"")&&this.write({t:m.t,op:"x",cap:m.cap,key:m.key,n:0,tr:m.tr,call:m.call,seen:t,was:m.n,s:m.s,a:m.a??""}):_.length>0&&z({t:m.t,op:"ran",cap:m.cap,key:m.key,n:m.n})}return{left:c,done:a}}prune(n){try{let t=ms(n-Ma*864e5);for(let r of fs(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<t&&fr(rn(this.dir,r))}catch{}}},ct=class extends Mn{admit(n,t,r,o,s,i=null,l=null,a=null){if(n.length===0)return null;let c=n.map(h=>ut(h,r,i));this.resolve(n,o,a),n.forEach((h,m)=>this.write({t:o,op:"ran",cap:h.id,key:t,n:c[m],...hs(l)})),s?.();let d=Math.min(...n.map(h=>at(h,o))),u=this.read(d,o+6e4),g=[];if(n.forEach((h,m)=>{let x=u.findIndex(_=>_.cap===h.id&&_.key===t&&_.op==="ran"&&_.t===o);if(x<0)g.push({cap:h,used:h.limit,n:c[m]});else{let _=this.usedIn(u,h,o,x+1,!0);_>h.limit&&g.push({cap:h,used:_-u[x].n,n:c[m]})}}),g.length>0)for(let h of n)this.write({t:o,op:"x",cap:h.id,key:t,n:0});return this.prune(o),g.length>0?{...g[0],...g.length>1?{also:g.slice(1)}:{}}:null}count(n,t,r,o,s="ran",i,l=null){for(let a of n)this.write({t:o,op:s,cap:a.id,key:t,n:Ba(a,r,l),...hs(i)})}},hs=e=>e?.tr&&e.call?{tr:e.tr,call:e.call,...e.s?{s:e.s,a:e.a??""}:{}}:{},ys=(e,n)=>Ea("sha256").update(`${e}\0${n}`).digest("hex").slice(0,32),qa=new Set(["user-rejected","permission-rule","automode-blocked","automode-unavailable","cancelled"]);function Ka(e,n){return xs(e,new Set([n])).get(n)??[]}function xs(e,n){let t=new Map,r=new Map;for(let o of e.matchAll(/"tool_use_id":\s?"([^"\\]{1,200})"/g)){if(!n.has(o[1]))continue;let s=e.lastIndexOf(`
11
+ `,o.index)+1;(r.get(s)??r.set(s,new Set).get(s)).add(o[1])}for(let[o,s]of[...r].sort((i,l)=>i[0]-l[0])){let i=e.indexOf(`
12
+ `,o);try{let l=JSON.parse(e.slice(o,i<0?void 0:i));if(l.type!==void 0&&l.type!=="user")continue;let a=Array.isArray(l.message?.content)?l.message.content:[],c=l.toolDenialKind;for(let d of s){let u=a.find(h=>h&&h.type==="tool_result"&&h.tool_use_id===d);if(!u)continue;(t.get(d)??t.set(d,[]).get(d)).push({refused:u.is_error===!0&&(typeof c=="string"?qa.has(c):l.toolUseResult==="User rejected tool use")})}}catch{for(let l of s)(t.get(l)??t.set(l,[]).get(l)).push({refused:!1})}}return t}function vs(e,n){return!e||!n?null:Va(q(e,4*1024*1024),n)}function Va(e,n){let t=e.indexOf(`"tool_use_id":"${n}"`);if(t<0)return null;let r=e.slice(e.lastIndexOf(`
11
13
  `,t)+1,e.indexOf(`
12
14
  `,t)<0?void 0:e.indexOf(`
13
- `,t));try{let o=JSON.parse(r),i=(Array.isArray(o.message?.content)?o.message.content:[]).find(a=>a.type==="tool_result"&&a.tool_use_id===n);if(!i)return null;let l=typeof i.content=="string"?i.content:JSON.stringify(i.content??"");return i.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(l)?"no":"yes"}catch{return null}}var Qt="[-.\\s\\u2010-\\u2015]",Yf=new RegExp(`(?:\\+?1${Qt}?)?(?:\\(?\\d{3}\\)?${Qt}?\\d{3}${Qt}?\\d{4})`,"g"),fa="[-.\\s()\\u2010-\\u2015]",Xf=new RegExp(`\\+[2-9]\\d(?:${fa}{0,2}\\d){5,13}\\b`,"g");var pa=/\b(?:Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi,ga=/\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b/g,ma=/\b(?:sk|pk|api|key|token|secret)[-_=][A-Za-z0-9]{20,}\b/gi,ts=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,ha=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,ya=/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16}\b/g,wa=/\bgh[opusr]_[A-Za-z0-9]{36,}\b/g,ba=/\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,ka=/\bglpat-[A-Za-z0-9_\-]{20,}\b/g,va=/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,xa=/\bhttps:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+/g,$a=/\bAIza[A-Za-z0-9_\-]{35}\b/g,Sa=/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,_a=/\bSK[0-9a-f]{32}\b/g,Ca=/\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\b/g,Aa=/\bnpm_[A-Za-z0-9]{36}\b/g,Ra=/\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}\b/g,Ea=[pa,ga,ma,ya,wa,ba,ka,va,xa,$a,Sa,_a,Ca,Aa,Ra];function rs(e){let n=e;n=n.replace(ha,"");for(let r of Ea)r.lastIndex=0,n=n.replace(r,"");ts.lastIndex=0;let t=ts.exec(n);return t&&(n=n.slice(0,t.index)),n}var se="***",os=/"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?/.source,ss=/\$\([^)]*\)?|\$\{[^}]*\}?|\\[\s\S]|[^\s"'`;&|<>()\\]/.source,er=new RegExp(`(?:${os}|${ss})(?:${ss}|(?=["'](?![\\s;&|)<>]|$))(?:${os}))*`,"y"),H=/(?:[ \t]|\\\r?\n)+/.source,at=/(?:[ \t]|\\\r?\n)*/.source,Pa=/token|secret|passw(?:or)?d|passphrase|pwd|api[-_]?key|access[-_]?key|private[-_]?key|credentials?|auth|(?:^|[_.:-])(?:pass|sig|signature)$|[_.:-]key$/i,Na=/[a-z0-9](?:Pass|Key|Sig)$/,Oa=/tokens$|tokeniz|author(?!i[sz]ation)|no_?auth$/i,On=e=>(Pa.test(e)||Na.test(e))&&!Oa.test(e),Ia=/key|token|secret|auth|passw|cookie|session|credential|signature/i,Xe=["",'"',"'","`"],un=128,is=/<<-?[ \t]*(["']?)([\w.@-]+)\1/y;function In(e){let n=[],t=new Uint8Array(e.length+1),r=[],o=null,s=0,i=0,l=0;for(let a=0;a<e.length;a++){let c=e[a];if(o!==null){if(c===`
15
+ `,t));try{let o=JSON.parse(r),i=(Array.isArray(o.message?.content)?o.message.content:[]).find(c=>c.type==="tool_result"&&c.tool_use_id===n);if(!i)return null;let l=typeof i.content=="string"?i.content:JSON.stringify(i.content??"");return Ka(r,n)[0]?.refused===!0||i.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(l)?"no":"yes"}catch{return null}}var mr="[-.\\s\\u2010-\\u2015]",ig=new RegExp(`(?:\\+?1${mr}?)?(?:\\(?\\d{3}\\)?${mr}?\\d{3}${mr}?\\d{4})`,"g"),Za="[-.\\s()\\u2010-\\u2015]",lg=new RegExp(`\\+[2-9]\\d(?:${Za}{0,2}\\d){5,13}\\b`,"g");var Ga=/\b(?:Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi,Ja=/\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b/g,Ya=/\b(?:sk|pk|api|key|token|secret)[-_=][A-Za-z0-9]{20,}\b/gi,$s=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,Xa=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,Qa=/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16}\b/g,ec=/\bgh[opusr]_[A-Za-z0-9]{36,}\b/g,nc=/\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,tc=/\bglpat-[A-Za-z0-9_\-]{20,}\b/g,rc=/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,oc=/\bhttps:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+/g,sc=/\bAIza[A-Za-z0-9_\-]{35}\b/g,ic=/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,lc=/\bSK[0-9a-f]{32}\b/g,ac=/\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\b/g,cc=/\bnpm_[A-Za-z0-9]{36}\b/g,uc=/\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}\b/g,dc=[Ga,Ja,Ya,Qa,ec,nc,tc,rc,oc,sc,ic,lc,ac,cc,uc];function Ss(e){let n=e;n=n.replace(Xa,"");for(let r of dc)r.lastIndex=0,n=n.replace(r,"");$s.lastIndex=0;let t=$s.exec(n);return t&&(n=n.slice(0,t.index)),n}var ne="***",_s=/"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?/.source,Cs=/\$\([^)]*\)?|\$\{[^}]*\}?|\\[\s\S]|[^\s"'`;&|<>()\\]/.source,hr=new RegExp(`(?:${_s}|${Cs})(?:${Cs}|(?=["'](?![\\s;&|)<>]|$))(?:${_s}))*`,"y"),S=/(?:[ \t]|\\\r?\n)+/.source,mt=/(?:[ \t]|\\\r?\n)*/.source,fc=/token|secret|passw(?:or)?d|passphrase|pwd|api[-_]?key|access[-_]?key|private[-_]?key|credentials?|auth|(?:^|[_.:-])(?:pass|pw|sig|signature)$|[_.:-]key$/i,pc=/[a-z0-9](?:Pass|Key|Sig)$/,gc=/tokens$|tokeniz|author(?!i[sz]ation)|no_?auth$/i,wn=e=>(fc.test(e)||pc.test(e))&&!gc.test(e),js=/key|token|secret|auth|passw|cookie|session|credential|signature/i,ze=["",'"',"'","`"],on=128,As=/<<-?[ \t]*(["']?)([\w.@-]+)\1/y;function bn(e){let n=[],t=new Uint8Array(e.length+1),r=[],o=null,s=0,i=0,l=0;for(let a=0;a<e.length;a++){let c=e[a];if(o!==null){if(c===`
14
16
  `){let g=e.slice(i,a).trim();n.push({start:s,end:a,op:`
15
17
  `}),s=i=a+1,l=0,g===o&&(o=r.shift()??null);continue}t[a]=l,c==="\\"&&l!==2&&e[a+1]!==`
16
- `?t[++a]=l|un:l?c===Xe[l]&&(l=0):Xe.indexOf(c)>0&&(l=Xe.indexOf(c));continue}if(t[a]=l,l){c==="\\"&&l!==2?t[++a]=l|un:c===Xe[l]&&(l=0);continue}if(c==="\\"){t[++a]=un;continue}let d=Xe.indexOf(c);if(d>0){l=d;continue}if(c==="#"&&(a===s||/\s/.test(e[a-1]))){let g=e.indexOf(`
17
- `,a);if(g<0)break;a=g-1;continue}if(c==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){is.lastIndex=a;let g=is.exec(e);if(g){r.push(g[2]),a+=g[0].length-1;continue}}let u="";c===`
18
+ `?t[++a]=l|on:l?c===ze[l]&&(l=0):ze.indexOf(c)>0&&(l=ze.indexOf(c));continue}if(t[a]=l,l){c==="\\"&&l!==2?t[++a]=l|on:c===ze[l]&&(l=0);continue}if(c==="\\"){t[++a]=on;continue}let d=ze.indexOf(c);if(d>0){l=d;continue}if(c==="#"&&(a===s||/\s/.test(e[a-1]))){let g=e.indexOf(`
19
+ `,a);if(g<0)break;a=g-1;continue}if(c==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){As.lastIndex=a;let g=As.exec(e);if(g){r.push(g[2]),a+=g[0].length-1;continue}}let u="";c===`
18
20
  `||c===";"?u=c:c==="&"?u=e[a+1]==="&"?"&&":e[a-1]===">"||e[a-1]==="<"||e[a+1]===">"?"":"&":c==="|"&&(u=e[a+1]==="|"?"||":e[a+1]==="&"?"|&":"|"),u&&(n.push({start:s,end:a,op:u}),a+=u.length-1,s=a+1,u===`
19
- `&&(i=s,r.length>0&&(o=r.shift())))}return n.push({start:s,end:e.length,op:""}),{segments:n,quotes:t}}var rr=(e,n,t)=>n[t]>0&&n[t]<un&&e[t]===Xe[n[t]];function lt(e,n,t){if(er.lastIndex=n,!er.exec(e))return n;let r=er.lastIndex;if((t[n]&~un)===0)return r;for(let o=n;o<r;o++)if(rr(e,t,o))return o;return r}function dn(e,n,t=()=>!0,r=()=>!0){let{quotes:o}=In(e),s="",i=0;n.lastIndex=0;for(let l=n.exec(e);l;l=n.exec(e)){let a=l.index+l[0].length;if(!t(l))continue;let c=lt(e,a,o);c===a||!r(e.slice(a,c))||(s+=e.slice(i,a)+se,i=n.lastIndex=c)}return s+e.slice(i)}var ae=e=>new RegExp(`(?:^|\\s)(?:${e})(?:=|${at})(?=[^\\s-])`,"g"),ce=e=>new RegExp(`(?:^|[\\s"'(/])(?:${e})(?=$|[\\s"';)])`),Wa=[{when:ce("mysql\\w*|mariadb[\\w-]*"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:ce("redis-cli|keydb-cli|valkey-cli"),flag:ae("-a")},{when:ce("curl"),flag:ae("-[A-Za-z]*[uUb]|--user|--proxy-user")},{when:new RegExp(`(?:^|[\\s(])(?:http|https|xh|xhs)${H}`),flag:ae("-a")},{when:new RegExp(`${ce("sshpass|mongo|mongosh|mongodump|mongorestore|mongoexport|mongoimport").source}|(?:^|\\s)login(?=$|\\s)`),flag:ae("-p")},{when:/\bgh\s+secret\s+set\b/,flag:ae("-b|--body")},{when:/\bsecurity\s+add-(?:generic|internet)-password\b/,flag:ae("-w")},{when:ce("sqlcmd|bcp|osql|isql"),flag:ae("-P")},{when:ce("zip|zipcloak"),flag:ae("-P|--password")},{when:ce("7z|7za|7zr|7zz"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:ce("ldap\\w+"),flag:ae("-w|-s")},{when:ce("openssl"),flag:ae("-k|-K")},{when:ce("ssh-keygen"),flag:ae("-N|-P")},{when:ce("smbclient|rpcclient|smbmap|smbget|smbcacls|net"),flag:new RegExp(`(?:^|\\s)(?:-U|--user(?:name)?)(?:=|${at})[^\\s%"']+%(?=[^\\s])`,"g")},{when:/\bvault\s+login\b/,flag:new RegExp(`\\bvault${H}login(?:${H}-[\\w-]+(?:=[^\\s]*)?)*${H}(?=[^\\s=-][^\\s=]*(?:\\s|$))`,"g")}],ja=new RegExp(`(?:^|[\\s"'(/])htpasswd((?:${H}-(?:[A-Za-z]*[Cr]${H}\\d+|[A-Za-z]+))+)${H}(?:[^\\s]+)${H}(?:[^\\s]+)${H}(?=[^\\s])`,"g"),ls=/\b(?:gh\s+secret\s+set|wrangler\s+(?:pages\s+)?secret\s+put|vercel\s+env\s+add|docker\s+secret\s+create|modal\s+secret\s+create|firebase\s+functions:secrets:set|fly(?:ctl)?\s+secrets\s+(?:set|import)|supabase\s+secrets\s+set|heroku\s+config:set|railway\s+variables\b[^\n]*?\s--set|security\s+add-(?:generic|internet)-password|op\s+item\s+create|vault\s+(?:kv\s+)?put)\b/,Ta=/^(\s*(?:echo|printf)(?:\s+-[A-Za-z]+)*\s+)\S(?:[\s\S]*\S)?/,Ma=new RegExp(`<<<${at}(?=[^\\s-])`,"g");function La(e){let{segments:n}=In(e),t="";for(let r=0;r<n.length;r++){let o=n[r],s=e.slice(o.start,o.end);for(let l of Wa)l.when.test(s)&&(s=dn(s,l.flag));s=dn(s,ja,l=>/b/.test(l[1].replace(/\d+/g,""))),ls.test(s)&&(s=fs(dn(s,Ma),()=>!0));let i=n[r+1];o.op==="|"&&i&&ls.test(e.slice(i.start,i.end))&&(s=s.replace(Ta,`$1${se}`)),t+=s+e.slice(o.end,i?i.start:o.end)}return t}var Da=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#"'`<>]*@/gi,Fa=[/(\bdiscord(?:app)?\.com\/api\/webhooks\/\d+\/)[\w-]+/gi,/(\bapi\.telegram\.org\/(?:file\/)?bot\d+:)[\w-]+/gi,/(\bhooks\.zapier\.com\/hooks\/catch\/\d+\/)[\w-]+/gi,/((?:\.webhook\.office\.com\/webhookb2|\boutlook\.office(?:365)?\.com\/webhook)\/[\w@.-]+\/IncomingWebhook\/)[\w-]+(\/[\w-]+)?/gi,/(\bhooks\.slack\.com\/(?:workflows|triggers)\/(?:[\w-]+\/){1,4})[\w-]{8,}/gi,/(\bmaker\.ifttt\.com\/trigger\/[\w-]+\/with\/key\/)[\w-]+/gi,/(\/(?:api\/)?(?:webhooks?|hooks)(?:\/[\w.-]+){0,3}\/)(?=[\w-]{24,})(?=[\w-]*\d)[\w-]+/gi],Ha=e=>Fa.reduce((n,t)=>n.replace(t,`$1${se}`),e),za=new RegExp(`\\bmachine${H}[^\\s]+(?:${H}login${H}[^\\s]+)?${H}password${H}(?=[^\\s])`,"g"),Ua=/\bhv[sbr]\.[A-Za-z0-9_-]{20,}/g,us=e=>{let n=e.replace(/^["'\\]+|["'\\]+$/g,"");return n.length>=8&&!/\s/.test(n)&&/\d/.test(n)&&/[A-Za-z]/.test(n)},ds=/^(?:key|apikey|api_key_id|k)$/i,Ba=new RegExp(`(?:^|[\\s("'])--?(?!no-|noauth\\b|anyauth\\b|bypass\\b|askpass\\b)(?=[A-Za-z])[\\w-]*?(?:token|api[-_]?key|secret|secret[-_]?string|access[-_]?key|secret[-_]?key|passw(?:or)?d|passphrase|pass(?:in|out)?|otp|auth|cookie|bearer|credentials?)(?:=|${H}(?=[^\\s-]))`,"gi"),ot=new RegExp(`(?:^|\\s)(?:-H|--header)(?:=|${at})(?=[^\\s-])`,"g");function qa(e){let{quotes:n}=In(e),t="",r=0;ot.lastIndex=0;for(let o=ot.exec(e);o;o=ot.exec(e)){let s=o.index+o[0].length,i=lt(e,s,n),l=e.slice(s,i),a=l[0]==='"'||l[0]==="'"?l[0]:"",c=/^([ \t]*([\w-]+)[ \t]*:[ \t]*)\S/.exec(a?l.slice(1):l);!c||!Ia.test(c[2])||(t+=`${e.slice(r,s)}${a}${c[1]}${se}${a}`,r=ot.lastIndex=i)}return t+e.slice(r)}var st=/(?:(?<![\w.$-])|(?<=(?:^|\s)-e))([A-Za-z_][\w.-]*)(?:=(?!=)|[ \t]*=[ \t]*(?=["']))/g;function fs(e,n=On){let{quotes:t}=In(e),r="",o=0;st.lastIndex=0;for(let s=st.exec(e);s;s=st.exec(e)){let i=s.index+s[0].length;if(!n(s[1])&&!(ds.test(s[1])&&us(e.slice(i,lt(e,i,t)))))continue;let l=Xe.indexOf(e[s.index-1]??""),a;if(l>0&&(t[s.index]&~un)===l)for(a=i;a<e.length&&!rr(e,t,a);)a++;else a=lt(e,i,t);a!==i&&(r+=e.slice(o,i)+se,o=st.lastIndex=a)}return r+e.slice(o)}var it=/(?:(\\?["'])([A-Za-z_][\w.-]*)\1|(?<![\w.$:/"'-])([A-Za-z_][\w.-]*))[ \t]*:[ \t]*/g,nr=/[^\s,}\]"'\\{[]+/y;function Za(e){let{quotes:n}=In(e),t="",r=0;it.lastIndex=0;for(let o=it.exec(e);o;o=it.exec(e)){let s=o[2]??o[3],i=!On(s)&&ds.test(s);if(!On(s)&&!i)continue;let l=o.index+o[0].length,a=/^[rRbBuUfF]{1,2}(?=["'])/.exec(e.slice(l,l+3));a&&(l+=a[0].length);let c=e[l],d="",u=-1;if(e.startsWith('\\"',l))d='\\"',u=e.indexOf('\\"',l+2);else if((c==='"'||c==="'")&&!rr(e,n,l)){d=c;let g=l+1;for(;g<e.length&&e[g]!==c;)g+=c==='"'&&e[g]==="\\"?2:1;u=g<e.length?g:-1}else(o[1]!==void 0||i)&&c!=='"'&&c!=="'"&&(nr.lastIndex=l,nr.exec(e)&&(u=nr.lastIndex));u<=l+d.length||i&&!us(e.slice(l+d.length,u))||(t+=e.slice(r,l)+d+se,r=it.lastIndex=u)}return t+e.slice(r)}var Va=/(^|\n)([ \t]*(?:-[ \t]+)?)([A-Za-z_][\w.-]*)([ \t]*:[ \t]+)([^\s"'`#][^\n"'`]*)/g,Ka=e=>e.replace(Va,(n,t,r,o,s)=>On(o)?`${t}${r}${o}${s}${se}`:n),Ga=new RegExp(`\\b(?:config|configure)${H}set${H}(?:-{1,2}\\w[\\w-]*(?:=\\S*)?${H})*((?!-)[^\\s=]+)${H}(?=[^\\s-])`,"g"),Ja=/\b(?:redis|keydb|valkey)-cli\b/,as=/(?:"[^"\n]*"|'[^'\n]*'|[^\s"'\\;&|]+)/.source,Ya=new RegExp(`\\bAUTH[ \\t]+${as}(?:[ \\t]+${as})?`,"g"),Xa=/^(?:to|the|a|an|is|are|for|and|or|of|in|on|it|be|as|at|by|from|with|this|that|flag|option|instead|here|there|if|when|you|your)$/i,Qa=/\b(Bearer|Basic)([ \t]+)([A-Za-z0-9\-._~+/]+=*)/gi,tr="\uE000";function ec(e){return e.includes(tr)?e:e.replace(Qa,(n,t,r,o)=>o.length>=8&&(/[0-9+/=_~]/.test(o)||/[a-z][A-Z]|[A-Z]{2}/.test(o.slice(1)))?`${t}${r}${se}`:`${t}${tr}${r}${o}`)}function cs(e){let n=La(e);return n=n.replace(Da,`$1${se}@`),n=Ha(n),n=qa(n),n=dn(n,Ba,()=>!0,t=>!Xa.test(t)),n=dn(n,za),n=n.replace(Ua,se),n=fs(n),n=Za(n),n=Ka(n),n=dn(n,Ga,t=>On(t[1])),Ja.test(n)&&(n=n.replace(Ya,`AUTH ${se}`)),rs(ec(n)).split(tr).join("")}function ps(e,n=8192){if(e.length<=n)return cs(e);let t=e.slice(0,n),r=t.search(/-----BEGIN [A-Z0-9 ]*-----/);return r>=0&&!/-----END [A-Z0-9 ]*-----/.test(t.slice(r))&&(t=`${t.slice(0,r)}-----BEGIN ${se}`),cs(t)}var gs="held by default",nc={recordAndCount:()=>1},ct={allow:0,hold:1,block:2};function ms(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function or(e){let n={action:e.action,service:e.service,target:e.attributes.target??null,host:e.attributes.host??null,attributes:e.attributes},t=(e.findings??[]).slice(1).map(s=>{let i=s;return{action:s.action,service:s.service,target:s.target,host:typeof i.host=="string"?i.host:null,attributes:i}}),r=new Set([n,...t].map(s=>s.action)),o=e.also.filter(s=>!r.has(s)).map(s=>({action:s,service:null,target:null,host:null,attributes:{}}));return[n,...t,...o]}function sr(e,n,t,r,o,s,i,l=null,a=[]){let c=i?{session_id:i}:{},d=[n.action,...n.also.filter(p=>p!==n.action)],u=(p,S,y)=>S?"enforce":Hr(t,p,Gt(e,p,s),y),g=(p,S,y)=>!S&&y&&zr(t,p,Gt(e,p,s)),h=p=>{if(p===n.action&&n.catastrophic)return{why:n.why};let S=(n.findings??[]).find(y=>y.action===p&&y.catastrophic);return S?{why:S.why}:null},v=[];d.forEach((p,S)=>{let y=S===0,{decision:P,baseline:G}=Kt(e,y?{action:p,service:n.service,metadata:{...n.attributes,...c}}:{action:p,service:null,metadata:c},r,o,s),T=Mt({action:p,decision:P,baseline:G,service:y?n.service:null,target:y?n.attributes.target??null:null,projectDir:s,home:l,histories:a}),I=h(p),_=u(p,T,I!==null);_!=="off"&&(I&&P.verdict!=="allow"&&g(p,T,!0)?v.push({action:p,decision:P,mode:_,floor:T?.id??null,why:`${I.why} \xB7 ${gs}`}):v.push({action:p,decision:P,mode:_,floor:T?.id??null}))});let x=new Set;for(let p of(n.findings??[]).slice(1)){if(!p.service&&!p.target)continue;let S=`${p.action}\0${p.service??""}\0${p.target??""}`;if(x.has(S))continue;x.add(S);let{decision:y,baseline:P}=Kt(e,{action:p.action,service:p.service,metadata:{target:p.target,...c}},nc,o,s);if(y.verdict==="allow")continue;let G=Mt({action:p.action,decision:y,baseline:P,service:p.service,target:p.target,projectDir:s,home:l,histories:a}),T=p.catastrophic===!0,I=u(p.action,G,T);I!=="off"&&v.push({action:p.action,decision:y,mode:I,floor:G?.id??null,why:T&&g(p.action,G,!0)?`${p.why} \xB7 ${gs}`:p.why,target:p.target})}if(e.policies.some(p=>p.narrowed&&p.narrowed.length>0)){let p={tool:n.tool??null,parts:or(n),touched:n.touched??null,projectDir:s,home:l,command:n.command??null,input:n.input??null,...o>0?{now:o}:{}};for(let S of e.policies)if(!(!S.narrowed||!he(S,s)))for(let y of S.narrowed){let P=Io(y,{...p,root:S.origin==="project"?S.project_dir??null:null});if(!P)continue;let G=/^(.*):(\d+) · /.exec(y.source),T=`your rule "${y.text}"${G?` (${G[1]} line ${G[2]})`:""}`,I=P.part===p.parts[0]?n.why:(n.findings??[]).find(_=>_.action===P.part.action&&_.target===P.part.target)?.why??null;v.push({action:P.part.action,decision:{verdict:P.hit==="unknown"?"hold":y.intent,policy:S.name,origin:S.origin,ruleId:y.id,blockedBy:"narrowed_rule",source:y.source},mode:t?.kill_switch===!0?"ghost":y.mode,floor:null,why:P.hit==="unknown"?`${I?`${I}: `:""}${P.why}`:`${I??P.why}${P.detail?` (${P.detail})`:""} \xB7 ${T}`,target:P.part.target})}}let j=v.filter(p=>p.decision.verdict!=="allow");if(j.length===0)return{lead:null,stops:[],mode:"ghost"};let Q=j.filter(p=>p.mode==="enforce"),K=(Q.length>0?Q:j).reduce((p,S)=>ct[S.decision.verdict]>ct[p.decision.verdict]||ct[S.decision.verdict]===ct[p.decision.verdict]&&S.floor&&!p.floor?S:p);return{lead:K,stops:[K,...j.filter(p=>p!==K)],mode:Q.length>0?"enforce":"ghost"}}var tc=["command","cmd","script","input","code"];function ys(e,n){let t=n&&typeof n=="object"?n:{};if(e==="Bash")return hs(typeof t.command=="string"?t.command:"");if(tc.some(o=>typeof t[o]=="string"&&hs(t[o])))return!0;let r=0;try{r=JSON.stringify(n??null)?.length??0}catch{return!0}return r>16384}function hs(e){if(e.length>2048)return!0;let n=0,t=0;for(let o=0;o<e.length;o++){let s=e[o];s===";"||s==="|"||s==="&"||s===`
20
- `?(n++,(s==="|"||s==="&")&&e[o+1]===s&&o++):(s==="`"||(s==="$"||s==="<"||s===">")&&e[o+1]==="(")&&t++}return n>16||t>8||(e.match(/\{[^{}\s]*,[^{}\s]*\}/g)?.length??0)>4?!0:(e.match(/(?:^|[\s;&|(){}`])(?:cd|pushd|popd)(?=$|[\s;&|()])/g)?.length??0)>8}import{createHash as js,randomBytes as Ts}from"crypto";import{readdirSync as gc,renameSync as mc,unlinkSync as kp}from"fs";import{join as wt}from"path";import{createHmac as rc,randomBytes as ir,timingSafeEqual as oc}from"crypto";import{closeSync as vs,existsSync as lr,fsyncSync as xs,linkSync as sc,mkdirSync as $s,openSync as Ss,readdirSync as ic,readFileSync as pn,unlinkSync as _s,writeSync as Cs}from"fs";import{basename as lc,dirname as ft,join as ue}from"path";var _e="_seal";function mt(e){return ue(e.dir,"seal.key")}function fn(e,n){return ue(e.state,"lkg",n)}function ye(e){let n=mt(e);if($(n,1024)!==!0)return null;try{let t=pn(n,"utf8").trim();return/^[0-9a-f]{64}$/.test(t)?Buffer.from(t,"hex"):null}catch{return null}}function ur(e){return ye(e)?"ok":$(mt(e),1024)===null?"missing":"damaged"}var pt=class extends Error{};function ht(e,n){return`Anvil's seal key (${mt(e)}) is ${n==="damaged"?"damaged":"missing"}`}function ac(e){let n=ye(e);if(n)return n;let t=ur(e);if(t==="damaged"||dr(e))throw new pt(`${ht(e,t)}; run ${oe("on")} to restore it`);let{key:r,created:o}=cc(e,!1);return o&&uc(e,r),r}function ws(e,n,t){let r=Ss(e,t,384);try{Cs(r,n),xs(r)}finally{vs(r)}}function cc(e,n){$s(e.dir,{recursive:!0,mode:448});let t=mt(e),r=ue(e.dir,`.seal.key.${process.pid}.${ir(4).toString("hex")}.tmp`);ws(r,`${ir(32).toString("hex")}
21
- `,"wx");let o=!1;try{n?En(r,t):sc(r,t),o=!0}catch(i){let l=i.code??"";if(l!=="EEXIST"){if(n||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(l))throw i;try{ws(t,pn(r,"utf8"),"wx"),o=!0}catch(a){if(a.code!=="EEXIST")throw a}}}finally{try{_s(r)}catch{}}let s=ye(e);if(!s)throw new pt(`${ht(e,"damaged")}; run ${oe("on")} to restore it`);return{key:s,created:o}}function uc(e,n){let t=[[e.modes,dt],[e.compiled,Es],[e.install,void 0]];for(let[r,o]of t)if($(r,8*1024*1024)===!0)try{let s=pn(r,"utf8");if(s.includes(`"${_e}"`))continue;let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let l=`${JSON.stringify(cr(n,i),null,2)}
22
- `;Qe(r,l),o&&Qe(fn(e,o),l)}catch{}if($(e.modes)===null&&$(fn(e,dt))===null){let r=`${JSON.stringify(cr(n,Wt()),null,2)}
23
- `;Qe(e.modes,r),Qe(fn(e,dt),r)}}function ar(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>ar(t===void 0?null:t,n+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(n===0&&r===_e)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${ar(e[r],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function As(e,n){return rc("sha256",e).update(ar(n)).digest("hex")}function ut(e){if(!(_e in e))return e;let n={...e};return delete n[_e],n}function cr(e,n){let t=ut(n);return{...t,[_e]:As(e,t)}}function dc(e,n){let t=n[_e];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let r;try{r=As(e,n)}catch{return!1}return oc(Buffer.from(t,"hex"),Buffer.from(r,"hex"))}function Qe(e,n,t=384){$s(ft(e),{recursive:!0,mode:448});let r=ue(ft(e),`.${lc(e)}.${process.pid}.${Date.now().toString(36)}.${ir(3).toString("hex")}.tmp`);try{let o=Ss(r,"w",t);try{Cs(o,n),xs(o)}finally{vs(o)}En(r,e)}catch(o){try{_s(r)}catch{}throw o}}function de(e,n,t=8*1024*1024){let r=$(e,t);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(pn(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:n?_e in o?dc(n,o)?{status:"ok",value:ut(o)}:{status:"changed",value:ut(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:ut(o)}}function Rs(e,n,t,r){let o=ac(e),s=`${JSON.stringify(cr(o,t),null,2)}
24
- `;Qe(n,s),r&&Qe(fn(e,r),s)}var dt="modes.json",Es="compiled.json";function dr(e){return lr(ue(e.bin,"claude-hook.sh"))||fc(e)}function fc(e){let n=t=>{try{return ic(t).slice(0,200).some(r=>r.endsWith(".json")&&$(ue(t,r),65536)===!0&&pn(ue(t,r),"utf8").includes(`"${_e}"`))}catch{return!1}};if(n(ue(e.state,"lkg"))||n(ue(e.state,"pending"))||n(e.approvals))return!0;for(let t of[e.modes,e.compiled,e.install])if($(t,8*1024*1024)===!0)try{if(pn(t,"utf8").includes(`"${_e}"`))return!0}catch{}return!1}var gt={missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"};function bs(e=new Date){return Dr(null,"enforce","all",e)}function Ps(e,n=ye(e),t={}){if(!n){let i=ur(e);if(t.installed===!0||i==="damaged"||dr(e))return{value:bs(),source:"strict",problem:`${ht(e,i)}, so every rule is enforced until \`${oe("on")}\` restores it`};let l=de(e.modes,null);return{value:l.status==="unkeyed"?l.value:null,source:"unkeyed",problem:null}}let r=de(e.modes,n);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${gt[r.status]??"cannot be used"}`,s=de(fn(e,dt),n);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:bs(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${oe("on")}\` resets it`}}function Ns(e,n,t=ye(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===Zt&&Array.isArray(c.policies),s=()=>{if(!n)return null;let c=de(n,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!t){let c=ur(e),d=r.installed===!0||c==="damaged"||dr(e),u=de(e.compiled,null),g=u.status==="unkeyed"&&o(u.value)?u.value:null;return d?{value:null,source:"strict",problem:`${ht(e,c)}: \`${oe("on")}\` restores it`}:{value:g??s(),source:"unkeyed",problem:null}}let i=de(e.compiled,t);if(i.status==="ok"&&o(i.value))return{value:i.value,source:"file",problem:null};let l=`compiled.json ${i.status==="ok"?"is not a rules table":gt[i.status]??"cannot be used"}`,a=de(fn(e,Es),t);return a.status==="ok"&&o(a.value)?{value:a.value,source:"last-good",problem:`${l}; Anvil keeps the rules it last compiled`}:i.status==="missing"&&a.status==="missing"&&$(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${l}, and so is Anvil's own copy: \`${oe("on")}\` recompiles them`}}function ks(e,n){return n&&(e===n||e.startsWith(`${n}/`))?`~${e.slice(n.length)}`:e}function yt(e,n,t,r=!0){let o=de(e.install,n,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${gt.unreadable}`];if(n&&o.status!=="ok")return[`install.json ${gt[o.status]??"cannot be used"}`];let s=(o.status==="ok"||o.status==="unkeyed")&&o.value.installs&&typeof o.value.installs=="object"?Object.values(o.value.installs):[],i=[];for(let u of s.slice(0,64)){if(!u||typeof u.real_path!="string"||typeof u.command!="string")continue;let g=Go(u.settings_path??u.real_path,Vo(u)),h=ks(u.settings_path??u.real_path,t);g!=="present"&&(g==="no-file"&&u.scope==="project"&&!lr(ft(ft(u.real_path)))||(g==="disabled"?r&&i.push(`${h} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):g==="missing"||g==="no-file"?i.push(`Anvil's hook was taken out of ${h} outside \`${oe("off")}\`, so new sessions are not checked`):i.push(`${h} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let l=o.status==="ok"||o.status==="unkeyed"?o.value:null,a=[...Array.isArray(l?.package_dirs)?l.package_dirs:[],...typeof l?.package_dir=="string"?[l.package_dir]:[]].filter(u=>typeof u=="string"&&u.startsWith("/")).slice(0,16),c=a[a.length-1]??"",d=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return s.length>0&&a.length>0&&a.every(u=>!lr(ue(u,"package.json")))&&i.push(`the Anvil package that installed this hook is gone (${ks(c,t)}): keep Anvil with ${O(d)} on, or remove it with ${O(d)} off --purge`),i}function pc(e){return ue(e.state,"health.json")}function Os(e,n,t){try{let r=pc(e),o=de(r,null,64*1024);if(o.status==="unkeyed"&&JSON.stringify(o.value.problems)===JSON.stringify(n.problems)&&o.value.modes_source===n.modes_source&&o.value.rules_source===n.rules_source&&t-Date.parse(o.value.at)<6e4)return;Qe(r,`${JSON.stringify({v:1,at:new Date(t).toISOString(),...n})}
25
- `)}catch{}}var Sp=600*1e3,hc=1440*60*1e3,Is="23456789abcdefghjkmnpqrstuvwxyz",Ws=8;function bt(e){return wt(e.state,"pending")}function yc(){let e=Ts(Ws),n="";for(let t=0;t<Ws;t++)n+=Is[e[t]%Is.length];return n}function wc(e){return js("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var bc=()=>Ts(8).toString("hex"),fr=e=>`${js("sha256").update(e??"").digest("hex").slice(0,12)}.`;function Ms(e,n,t){let r=yc(),o=bc();F(bt(e));let s={v:2,id:o,code_sha256:wc(r),...n,created_at:new Date(t).toISOString(),expires_at:new Date(t+hc).toISOString()};return Rs(e,wt(bt(e),`${fr(n.session)}${o}.json`),s),{code:r,id:o}}function kc(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function Ls(e,n,t,r,o,s){let i=[];try{i=gc(e.approvals).filter(a=>a.endsWith(".json")&&!a.includes(".used-")).slice(0,2e3)}catch{return{approved:!1,forged:0}}let l=0;for(let a of i){let c=wt(e.approvals,a),d=de(c,n,64*1024);if(d.status==="missing")continue;if(d.status!=="ok"||d.value.v!==2||!Array.isArray(d.value.stops)){l++;continue}let u=d.value;if(Date.parse(u.expires_at)>=s&&!((u.session??null)!==(t??null)||(u.project??null)!==(r??null))&&o.every(g=>u.stops.some(h=>kc(h,g))))try{return mc(c,wt(e.approvals,`${a.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:l}}catch{}}return{approved:!1,forged:l}}import{lstatSync as xc,readdirSync as $c,statSync as Sc,utimesSync as _c}from"fs";import{join as Wn}from"path";import{posix as ig}from"path";import{posix as Gp}from"path";var vc=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});var Tp=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});var Mp=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"});var Lp=Object.freeze({code:"unsupported-blank",message:"a vertical tab, form feed, carriage return or Unicode space is part of a word in bash and zsh, not a separator"}),Dp=Object.freeze({code:"unsupported-parameter-expansion",message:"a line continuation inside ${ }, or a quote or backslash inside ${ } with a substitution in or after it, cannot be analyzed"});var Fp=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});import{createRequire as Up}from"module";var pr=10080*60*1e3;function Ds(e,n,t){let r=t.tmpdir;for(;r.endsWith("/");)r=r.slice(0,-1);return r.length>1&&e.startsWith(`${r}/`)||/^\/(private\/)?(tmp|var\/folders)\//.test(e)||/\/scratchpad\//.test(e)}function gr(e){return!!e&&/(^|[\s;&|(])(rm|rmdir|unlink|rimraf|shred|trash|truncate)(\s|$)|worktree\s+remove|\s-delete\b|(^|[;&|]\s*):\s*>/.test(e.slice(0,65536))}var mr=3600*1e3;var Cc=600,Ac=256*1024;function hr(e,n){return Wn(e.state,"sessions",`${n}.jsonl`)}function Fs(e,n){if(!n)return{made:[],launched:[]};let t=[],r=[];for(let o of Z(hr(e,n),Ac).split(`
26
- `))if(o)try{let s=JSON.parse(o);typeof s.p=="string"&&s.p.startsWith("/")?t.push(s.p):typeof s.l=="string"&&r.push(s.l)}catch{}return{made:t,launched:r}}function Rc(e){try{return xc(e),!0}catch{return!1}}function Hs(e,n,t,r,o=null,s=Date.now()){if(!(!n||t.paths.length===0&&t.launched.length===0))try{F(Wn(e.state,"sessions"));let i=hr(e,n),l=[...r.made];for(let a of t.paths)l.some(c=>a===c||a.startsWith(`${c}/`))||Rc(a)||(Me(i,JSON.stringify(o?{p:a,t:s,d:o}:{p:a})),l.push(a));for(let a of t.launched)r.launched.includes(a)||Me(i,JSON.stringify({l:a.slice(0,Cc)}))}catch{}}function zs(e,n,t=Date.now()){if(n)try{let r=new Date(t);_c(hr(e,n),r,r)}catch{}}function Us(e,n,t,r,o=Date.now()){if(!n||!t)return[];let s=Date.now(),i=new Set,l=0;try{let a=Wn(e.state,"sessions"),c=$c(a).filter(d=>d.endsWith(".jsonl")&&d!==`${n}.jsonl`).map(d=>({f:d,at:Sc(Wn(a,d)).mtimeMs})).filter(d=>o-d.at>=mr&&o-d.at<=pr+mr).sort((d,u)=>u.at-d.at).slice(0,200);for(let{f:d}of c){if(l>4*1024*1024||i.size>=5e3||Date.now()-s>150)break;let u=Z(Wn(a,d),64*1024);l+=u.length;for(let g of u.split(`
27
- `))if(g.includes('"d"'))try{let h=JSON.parse(g);if(typeof h.p!="string"||typeof h.t!="number"||h.d!==t||o-h.t>pr||h.t>o)continue;if(Ds(h.p,t,r)&&i.add(h.p),i.size>=5e3)break}catch{}}}catch{}return[...i]}import{spawnSync as Ec}from"child_process";import{lstatSync as Pc,realpathSync as yr,statSync as Nc}from"fs";import{dirname as Oc}from"path";function gn(e,n,t,r=!1){let o=Ec(e,n,{cwd:t?B(t):void 0,encoding:"utf8",timeout:400,stdio:["ignore","pipe","ignore"],windowsHide:!0});return o.error||o.signal?null:(o.status===0||r)&&typeof o.stdout=="string"?o.stdout:null}function wr(e){try{let n=typeof e=="string"&&e!==""?Nc(e):null;return n&&n.birthtimeMs>0&&n.birthtimeMs!==n.ctimeMs?n.birthtimeMs:null}catch{return null}}function Bs(e){let n=e.arg??"";try{switch(e.kind){case"ps":return gn("ps",["-A","-ww","-o","pid=,ppid=,command="]);case"port":return/^\d{1,5}$/.test(n)?gn("lsof",["-nP","-t","-i",`:${n}`],null,!0):null;case"stashes":return gn("git",["stash","list","--date=unix","--format=%gd"],e.cwd);case"branch":return gn("git",["reflog","show","--date=unix","--format=%gd %gs",`refs/heads/${n}`,"--"],e.cwd);case"ignored":return gn("git",["check-ignore","-q","--",n],e.cwd);case"cwd":{if(!/^\d+$/.test(n))return null;if(process.platform==="linux")return yr(`/proc/${n}/cwd`);let t=/^n(\/.*)$/m.exec(gn("lsof",["-a","-p",n,"-d","cwd","-Fn"],null,!0)??"")?.[1];return t?yr(t):null}case"file":{let t=yr(B(n));return`${z()?le(t)??t:t} ${wr(B(n))??""}`}case"owner":{if(z()||!n.startsWith("/"))return null;for(let t=n;;t=Oc(t))try{return String(Pc(t).uid)}catch{if(t==="/")return null}}}}catch{}return null}var kt=e=>`${e.kind}\0${e.cwd??""}\0${e.arg??""}`;import{existsSync as Ic,readFileSync as br,statSync as Wc}from"fs";import{dirname as jc,isAbsolute as qs,join as kr,resolve as vr}from"path";function Zs(e){return!!e&&e.length<65536&&/\bgh\s+pr\s+(create|edit)\b/.test(e)}function Tc(e,n,t){let r=n?[n]:[];for(let o of e.matchAll(/(?:^|[;&|(\n]\s*|&&\s*)cd\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/g)){let s=o[1].replace(/^["']|["']$/g,"");/[$`*?]/.test(s)||((s==="~"||s.startsWith("~/"))&&(s=t+s.slice(1)),r.push(qs(s)?s:vr(r[r.length-1]??n??t,s)))}return[...new Set(r)].slice(0,8)}function Mc(e){let n=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(e.trim());return n?`${n[1]}/${n[2]}`.toLowerCase():null}function Lc(e){let n=e;for(let t=0;t<12&&n.length>1;t++,n=jc(n)){let r=kr(n,".git");if(!Ic(r))continue;let o=r;if(Wc(r).isFile()){if($(r,64*1024)!==!0)return[];let d=/^gitdir:\s*(.+)$/m.exec(br(r,"utf8"))?.[1]?.trim();if(!d)return[];o=qs(d)?d:vr(n,d);let u=kr(o,"commondir");$(u,64*1024)===!0&&(o=vr(o,br(u,"utf8").trim()))}let s=kr(o,"config");if($(s,1024*1024)!==!0)return[];let i=br(s,"utf8").slice(0,65536),l="",a=[],c=null;for(let d of i.split(`
28
- `)){let u=/^\s*\[(\w+)(?:\s+"([^"]*)")?\]/.exec(d);if(u){c=u[1]==="remote"?u[2]??null:null;continue}let g=/^\s*url\s*=\s*(.+)$/.exec(d),h=c!==null&&g?Mc(g[1]):null;h&&(c==="origin"&&!l?l=h:a.includes(h)||a.push(h))}return[l,...a.filter(d=>d!==l)]}return[]}function Vs(e,n,t){let r={};try{for(let o of Tc(e,n,t))r[o]=Lc(o)}catch{}return r}import{closeSync as Dc,constants as Ks,fstatSync as Fc,openSync as Hc,readSync as zc,statSync as Uc}from"fs";var Bc=64*1024,qc=8;function Gs(e,n){let t={},r=[];for(let o of e.slice(0,qc)){let s=null,i=null,l=!0;try{Uc(B(o)).isFile()&&(s=Hc(B(o),Ks.O_RDONLY|Ks.O_NONBLOCK));let a=s!==null?Fc(s):null;if(s!==null&&a!==null&&a.isFile()&&a.size<=Bc){let c=Buffer.alloc(a.size),d=zc(s,c,0,a.size,0),u=c.subarray(0,d).toString("utf8");u.includes("\0")||(i=u)}}catch(a){a.code==="ENOENT"&&(l=!1)}finally{s!==null&&Dc(s)}i!==null?t[o]=i:l&&n.includes(o)&&r.push(o)}return{scripts:t,unreadable:r}}import{createHash as Eg}from"crypto";import{readdirSync as Ng,readFileSync as Og,renameSync as Ig,statSync as Wg,unlinkSync as jg}from"fs";import{join as Mg}from"path";var Zc=1440*60*1e3;var Vc=64*1024*1024,Kc=14*Zc;var Xc=1e3,Qc=3e3,ri=6e4,eu=new Set(["default","acceptEdits","plan"]),nu="cli",xr=[2,1,153];function tu(e){if(!e)return null;let n="";try{n=Z(e,64*1024)}catch{return null}let t=[...n.matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)],r=t[t.length-1];return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function ru(e,n){if(e.CLAUDE_CODE_ENTRYPOINT!==nu)return!1;let t=tu(n);if(!t)return!1;for(let r=0;r<xr.length;r++)if(t[r]!==xr[r])return t[r]>xr[r];return!0}var ou=8,yn=class extends Error{constructor(n){super(n),this.name="CoreUnavailable"}},wn=class extends Error{constructor(){super("out of time"),this.name="ClassifyTimeout"}},Tn=(e,n,t,r)=>({paths:e,payload:t,table:r,env:n.env,home:n.home,now:n.now(),cli:Ve(),fallbackTable:n.fallbackTable,installed:n.anvilDir!==void 0,...n.planProbe?{probe:n.planProbe}:{}});function $r(e,n){try{return me(e.compiled,64*1024*1024)?.includes(`"${n}"`)===!0}catch{return!1}}function _r(e,n){let t=k(e.env.CLAUDE_PROJECT_DIR)??n;return t&&t.startsWith("/")?ve(t):t}var su="AnvilSelfCheck",k=e=>typeof e=="string"&&e.length>0?e:null;function mn(e,n=160){let t=ps(e,4096).replace(/\s+/g," ").trim();return t.length>n?`${t.slice(0,n-1)}\u2026`:t}function iu(e){if(!e||!St(e))return null;let n=e;for(let t=0;t<64;t++){let r=b(n,".git"),o=!1,s=!1;try{let l=Yc(r);s=!0,o=l.isFile()}catch{}if(s)try{let l=r;if(o){if($(r,64*1024)!==!0)return null;let d=/^gitdir:\s*(.+?)\s*$/m.exec($t(r,"utf8"));if(!d)return null;l=hn(n,d[1])}if($(b(l,"HEAD"),64*1024)!==!0)return null;let a=$t(b(l,"HEAD"),"utf8").trim(),c=/^ref:\s*refs\/heads\/(.+)$/.exec(a);return c?c[1]:null}catch{return null}let i=Sr(n);if(i===n)return null;n=i}return null}function Ys(e){if(!e||!St(e))return[];let n=b(e,".git");try{if($(n,64*1024)!==!0)return[];let t=/^gitdir:\s*(.+?)\s*$/m.exec($t(n,"utf8"));if(!t)return[];let r=/^(.*[\\/]\.git)[\\/]worktrees[\\/][^\\/]+[\\/]?$/.exec(hn(e,t[1]));return r?[Ge(r[1])]:[]}catch{return[]}}function lu(e,n){return(e==="Bash"||e==="PowerShell")&&n&&typeof n=="object"?n.command??null:Cr(n)}function Cr(e,n=0){return n>64?"[nested too deep]":Array.isArray(e)?e.map(t=>Cr(t,n+1)):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Cr(e[t],n+1)])):e}var oi=e=>process.platform==="win32"?Js.native(e):Js(e);function au(e,n){if(!n)return e;let t;try{t=oi(n).replace(/^\/private(?=\/(?:tmp|var|etc)(?:\/|$))/,"")}catch{return e}return t!==n&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))?`${n}${e.slice(t.length)}`:e}var si={Write:"file_path",Edit:"file_path",MultiEdit:"file_path",Read:"file_path",NotebookEdit:"notebook_path"},en=(e,n)=>[...new Set([...e,...n??[]])];function cu(e,n,t){let r=si[e];if(!r||!n||typeof n!="object")return n;let o=n[r];if(typeof o!="string")return n;let s=Dn(o,t,!0);return s===o?n:{...n,[r]:s}}function Dn(e,n,t){if(!St(e)||e.length>4096)return e;let r=hn(e);if(!t){let i=Sr(e);if(i===e)return e;let l=Dn(i,n,!0);return l===i?e:b(l,Ln(e))}let o=[],s=e;for(;;)try{let i=au(b(oi(s),...o.reverse()).replace(/^\/private(?=\/(?:tmp|var|etc)(?:\/|$))/,""),n);return i===r||`/private${i}`===r?r:i}catch{o.push(Ln(s));let i=Sr(s);if(i===s)return e;s=i}}function uu(e,n,t){let r={full:{},parent:{}},o=!1;for(let s of["full","parent"])for(let i of e[s]){if(Date.now()>t)return"out-of-time";let l=z()?le(Dn(B(i),n,s==="full"))??i:Dn(i,n,s==="full");l!==i&&(r[s][i]=l,o=!0)}return o?r:null}async function Xs(e,n,t,r){if(!n)return{classification:await t.classifyInline(e,r),failure:null};let o=await t.classifyInWorker(e,r);return o.kind==="ok"?{classification:o.classification,failure:null}:{classification:null,failure:o.kind==="timeout"?{rule:"too-long-to-check"}:{rule:"could-not-check",error:o.error}}}function du(e,n,t,r){return Mn("sha256").update(JSON.stringify([e??"",n,lu(n,t),r??""])).digest("hex").slice(0,10)}function bn(e){return e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Mn("sha256").update(e).digest("hex").slice(0,24):"none"}function tn(e,n){try{F(e.dir);let t=JSON.stringify(n);Buffer.byteLength(t)>3e3&&(t=JSON.stringify({...n,why:n.why.slice(0,200),target:n.target?n.target.slice(0,200):null,error:n.error?.slice(0,200)})),Me(e.decisions,t)}catch{}}function Qs(e,n,t,r,o,s){tn(e,{v:1,ts:new Date(o).toISOString(),session:k(s?.session_id),tool:k(s?.tool_name)??"unknown",action:"none",verdict:"error",mode:null,delivered:"none",rule:null,slug:null,policy:null,why:`hook error at ${n}`,target:null,project:null,path:"none",ms:Math.max(0,o-r),error:mn(t instanceof Error?t.message:String(t),200)})}var rn={stdout:"",exitCode:0},V=e=>({stdout:`${JSON.stringify(e)}
29
- `,exitCode:0});function Ar(e,n){let t=k(e.env.CLAUDE_CONFIG_DIR),r=b(t?hn(t):b(e.home,".claude"),"settings.json"),o=k(e.env.CLAUDE_PROJECT_DIR)??k(n.cwd);return o?[r,b(o,".claude","settings.local.json"),b(o,".claude","settings.json")]:[r]}function fu(e,n,t){if(e!=="Bash"||!t)return null;let r=n&&typeof n=="object"?n.command:null,o=typeof r=="string"?r.slice(0,65536):"";if(!/\bgit\b/.test(o)||!/\b(clean|stash)\b/.test(o))return null;let s=[".claude/settings.local.json",".anvil/rules.json"].filter(a=>$(b(t,a))===!0);if(s.length===0)return[];let i=Gc("git",["-c","core.fsmonitor=false","status","--porcelain=v1","--ignored","--untracked-files=all","-z","--",...s],{cwd:t,encoding:"utf8",timeout:500,stdio:["ignore","pipe","ignore"],windowsHide:!0});if(i.status!==0||typeof i.stdout!="string")return s.map(a=>({path:b(t,a),ignored:!1}));let l=[];for(let a of i.stdout.split("\0")){let c=a.slice(0,2),d=s.find(u=>a.slice(3)===u||a.slice(3).endsWith(`/${u}`));(c==="??"||c==="!!")&&d!==void 0?l.push({path:b(t,d),ignored:c==="!!"}):(c[0]==="A"||c.includes("M"))&&d!==void 0&&l.push({path:b(t,d),ignored:!1,staged:!0})}return l}function pu(e,n,t,r){if(["Read","Glob","Grep","LS","WebFetch","WebSearch","TodoWrite"].includes(e))return null;let o=b(n,".claude"),s=b(n,".anvil"),l=[...[".zshrc",".zshenv",".zprofile",".bashrc",".bash_profile",".bash_aliases",".profile",b(".config","fish","config.fish"),...process.platform==="win32"?[b("Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),b("Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")]:[]].map(c=>b(n,c)),o,b(o,"settings.json"),b(o,"settings.local.json"),b(o,"hooks"),b(o,"plugins"),b(n,".claude.json"),s,b(s,"claude"),b(s,"claude","modes.json"),b(s,"claude","compiled.json"),b(s,"rules.json"),b(s,"workspace-keys.json")];t&&l.push(t,b(t,"settings.json"),b(t,"hooks")),r&&l.push(b(r,".claude"),b(r,".claude","settings.json"),b(r,".claude","settings.local.json"),b(r,".mcp.json"));let a={};for(let c of l){let d=Dn(c,n,!0);d!==c&&(a[d]=c)}return Object.keys(a).length>0?a:null}function ii(e,n){return b(e.state,"covered",bn(k(n.session_id)))}function gu(e,n,t){try{let r=ii(e,t);if($(r)!==null||!Ar(n,t).some(o=>Yt(o)))return;F(b(e.state,"covered")),Y(r,String(n.now()))}catch{}}async function mu(e,n,t,r){let o=()=>Ar(n,t).some(i=>Yt(i)),s=ii(e,t);if($(s)===!0)return o();if(r!=="SessionStart"||!o())return!1;for(let i=0;i<300;i+=25)if(await new Promise(l=>setTimeout(l,25)),$(s)===!0)return!0;return!1}function hu(e,n){try{F(e.state),Y(b(e.state,"plugin-seen"),String(n))}catch{}}var _t=!1;async function li(e,n){ie=xt=null;let t=n.now(),r=n.anvilDir?Te(n.anvilDir):Je(n.home),o=Pn(r.install)?.cli??n.cli;_n(o),_t=typeof o=="string";let s=null,i=k(n.entry),l=Buffer.byteLength(e)/1048576,a=`(${l.toFixed(1)} MB; Anvil reads up to 8 MB)`;if(l>ou)return Nn(i)?rn:i==="SessionStart"?V(Se("SessionStart",`it can't read what Claude Code sent ${a}`)):yu(r,e,`this call is too large to check ${a}`,t,n);try{if(s=JSON.parse(e),!s||typeof s!="object"||i&&!k(s.hook_event_name))throw new Error("hook input is not a hook event");let c=k(s.hook_event_name),d=()=>{let g=ci(r,k(s.session_id));return g?`${JSON.stringify({systemMessage:g})}
30
- `:null};if(c==="UserPromptSubmit"&&n.modelAtPrompt&&$r(r,"never")){let g=await n.modelAtPrompt({...Tn(r,n,s,null),projectDir:_r(n,k(s.cwd))}).catch(d);if(g)return{stdout:g,exitCode:0}}if(c==="UserPromptSubmit"&&n.budgetAtPrompt&&$r(r,"budgets")){let g=await n.budgetAtPrompt(Tn(r,n,s,null)).catch(d);if(g)return{stdout:g,exitCode:0}}if(c==="PreModelSwitch"&&n.modelAtSwitch&&$r(r,"model_rules")){let g=await n.modelAtSwitch({...Tn(r,n,s,null),projectDir:_r(n,k(s.cwd))}).catch(d);if(g)return{stdout:g,exitCode:0}}if(n.helpers&&(c?.startsWith("Subagent")||s.source==="resume")&&$(b(r.dir,"helpers","live"))!==null&&await n.helpers().then(g=>g.onEvent(s,r,n.now()),()=>0),Nn(c))return rn;if(n.plugin){if(await mu(r,n,s,c))return rn;c==="SessionStart"&&hu(r,n.now())}else n.anvilDir!==void 0&&gu(r,n,s);if(c==="SessionStart")return await $u(r,n,s);if(c===su)return await xu(r,n);if(c!=="PreToolUse")return rn;let u=await wu(s,r,n,t);return xt?.(u)??u}catch(c){let d=(s&&k(s.hook_event_name))??i??(/"hook_event_name"\s*:\s*"SessionStart"/.test(e.slice(0,4096))?"SessionStart":null),u=s&&k(s.hook_event_name)?"its check crashed":"it can't read what Claude Code sent";if(d==="SessionStart")return V(Se("SessionStart",u));if(d&&d!=="PreToolUse")return rn;let g=jn(r,s??{},u,t,n.now(),c);return xt?.(g)??g}}function ai(e,n,t,r,o,s,i){let l=n("cwd");tn(e,{v:1,ts:new Date(s).toISOString(),session:n("session_id"),tool:n("tool_name")??"unknown",action:"claude.bash.unclassified",verdict:"hold",mode:"enforce",floor:"hold-unchecked",delivered:"deny",rule:t,slug:t,policy:null,blocked_by:"time_limit",why:r,target:null,project:l?Ln(l):null,path:"none",ms:Math.max(0,s-o),...i?{error:mn(String(i),200)}:{}})}function jn(e,n,t,r,o,s){return ai(e,i=>k(n[i]),"could-not-check",`Anvil isn't working: ${t}`,r,o,s),V(Se("PreToolUse",t))}function yu(e,n,t,r,o){let s=n.slice(0,4096);return ai(e,i=>new RegExp(`"${i}"\\s*:\\s*"([^"\\\\]{1,200})"`).exec(s)?.[1]??null,"too-long-to-check",t,r,o.now()),V({systemMessage:Xr(t),...vt("deny",Qr(t))})}async function wu(e,n,t,r){let o=t.now(),s=k(e.tool_name)??"unknown",i=k(e.session_id),l=k(e.cwd);try{F(n.counts),Bo(n.counts,new Date(o))}catch{}let a=Rr(n,t,o),c=a.table;if(!c)return jn(n,e,ui(a),r,t.now());let d=a.modes;if(t.coreProblem)return jn(n,e,t.coreProblem,r,t.now());let u=_r(t,l);try{_t||_n(c.cli),ie=bu(n,c,u,i,Ve())}catch{ie=null}let g=Fs(n,i),h=ms(e.tool_input),v=(s==="Bash"||s==="PowerShell")&&typeof h?.command=="string"?h.command:null;zs(n,i,o);let x=gr(v)?Us(n,i,u,{tmpdir:t.tmpdir},o):[],j=x.length>0?{...g,made:[...g.made,...x.filter(f=>!g.made.includes(f))]}:g,Q=null,be=()=>{p?.makings&&Hs(n,i,p.makings,g,u,o),Q?.ran()},K={tool_name:s,tool_input:e.tool_input??null,cwd:l,git_branch:iu(l),project_dir:u,session_id:i,home:t.home,tmpdir:t.tmpdir,claude_config_dir:k(t.env.CLAUDE_CONFIG_DIR),project_controls:fu(s,e.tool_input,u),control_links:pu(s,t.home,k(t.env.CLAUDE_CONFIG_DIR),u),session_facts:{...j,startedAt:wr(e.transcript_path),...Zs(v)?{repoRemotes:Vs(v,l,t.home)}:{}},want_makings:!0},p=null,S="inline",y=null,P=t.timeLimitMs??Xc,G=Date.now()+(t.totalLimitMs??Qc),T=()=>Math.min(P,G-Date.now()),I=null,_=null,fe=()=>{I=p??I,p=null,y={rule:"too-long-to-check"}},Le={},$n=!1,Ae=async(f,w)=>{let A=p;({classification:p,failure:y}=await Xs(f,w,t,T())),!p&&A&&(I=A);let re=p?.touched;re&&_&&(_={full:en(_.full,re.full),parent:en(_.parent,re.parent),read:en(_.read,re.read),written:en(_.written,re.written),unknown:en(_.unknown,re.unknown)})};try{let f=ys(s,e.tool_input);f&&(S="worker");let w={...K,tool_input:cu(s,K.tool_input,t.home),on_disk:"collect"};({classification:p,failure:y}=await Xs(w,f,t,T()));let A=p?.touched;A&&(_={full:[...A.full],parent:[...A.parent],read:[...A.read??[]],written:[...A.written??[]],unknown:[...A.unknown??[]]});let re=si[s],Oe=re&&K.tool_input&&typeof K.tool_input=="object"?K.tool_input[re]:void 0;if(typeof Oe=="string"&&St(Oe)&&Oe.length<=4096){let M=[z()?le(Oe)??hn(Oe):hn(Oe)];_=_?{..._,full:en(_.full,M),written:en(_.written,M)}:{full:M,parent:[],read:[],written:M,unknown:[]}}if(A&&(A.full.length>0||A.parent.length>0)){let M=uu(A,t.home,Math.min(Date.now()+P,G)),pe=(ge,L)=>[...new Set([...ge,...ge.flatMap(Tr=>[L.full[Tr],L.parent[Tr]].filter(xi=>typeof xi=="string"))])];M&&M!=="out-of-time"&&_&&(_={full:[...new Set([..._.full,...Object.values(M.full)])],parent:[...new Set([..._.parent,...Object.values(M.parent)])],read:pe(_.read,M),written:pe(_.written,M),unknown:_.unknown}),M==="out-of-time"?fe():M!==null&&(w={...w,on_disk:M},T()<=0?fe():await Ae(w,f))}let It={...K.session_facts?.scripts??{}},Bn=[];for(let M=0;M<2&&p?.scriptsWanted&&p.scriptsWanted.length>0;M++){let pe=p.scriptsWanted.filter(L=>!(L in It)&&!Bn.includes(L));if(pe.length===0)break;if(T()<=0){fe();break}let ge=Gs(pe,j.made);if(Object.keys(ge.scripts).length===0&&ge.unreadable.length===0)break;if(Object.assign(It,ge.scripts),Bn.push(...ge.unreadable),w={...w,session_facts:{...w.session_facts??{made:[],launched:[]},scripts:{...It},...Bn.length>0?{unreadableScripts:[...Bn]}:{}}},T()<=0){fe();break}await Ae(w,f)}for(let M=0;M<3&&p?.probesWanted;M++){let pe=p.probesWanted.filter(L=>!(kt(L)in Le));for(let L of pe)T()>400&&(Le[kt(L)]=L.kind==="changes"?await t.answerChanges?.(L)??null:Bs(L));if(pe.length===0||T()<=400){$n=T()<=400&&pe.some(L=>L.kind==="changes");break}w={...w,session_facts:{...w.session_facts??{made:[],launched:[]},probed:{...Le}}};let ge={classification:p,failure:y};try{await Ae(w,f)}catch(L){if(!(L instanceof wn))throw L;p=null,y={rule:"too-long-to-check"}}if(!p&&y?.rule==="too-long-to-check"&&ge.classification&&!pe.some(L=>L.kind==="changes")){({classification:p,failure:y}=ge);break}}}catch(f){if(p&&(I=p,p=null),f instanceof yn)return jn(n,e,"its checker can't load",r,t.now(),f);y=f instanceof wn?{rule:"too-long-to-check"}:{rule:"could-not-check",error:f instanceof Error?f.message:String(f)}}($n||p?.probesWanted?.some(f=>f.kind==="changes"&&!(kt(f)in Le)))&&(I=p,p=null,y={rule:"too-long-to-check"}),p?.action===ti&&(c.policies.some(f=>f.allowed_actions.includes(ti))?!y&&c.policies.some(f=>f.helpers&&he(f,u))&&(xt=(Q=(await t.helpers()).launchStep({paths:n,table:c,projectDir:u,payload:e,deps:t,modes:d,now:o,cli:Ve()})).finish):p={...p,action:"claude.tool.other"}),p&&c.policies.some(f=>f.narrowed?.some(w=>(w.when?.length??0)>0)||f.caps?.some(w=>w.unit==="money"))&&await fo();let C=[],W="ghost",De=t.rates??new Qn(b(n.state,"rate.jsonl"),Xt),Fe=Ge(u),Re=Ge(t.home);if(p)try{F(n.state),{stops:C,mode:W}=sr(c,{...p,tool:s,touched:_,command:v,input:h},d,De,o,Fe,i,Re,Ys(u))}catch(f){y={rule:"could-not-check",error:f instanceof Error?f.message:String(f)}}else if(y&&I)try{let f=sr(c,{...I,tool:s,touched:_,command:v,input:h},d,De,o,Fe,i,Re,Ys(u));f.mode==="enforce"&&f.lead?.decision.verdict==="block"&&({stops:C,mode:W}=f,p=I,y=null)}catch{}p?.parse==="limited"&&!y&&!(W==="enforce"&&C[0]?.decision.verdict==="block")&&(y={rule:"could-not-check",why:"too long or nested too deep to read in full"});let m=y?.error!==void 0?await Er(t):null;if(m)return jn(n,e,m,r,t.now());if(y){let f={verdict:"hold",policy:null,origin:null,ruleId:y.rule,blockedBy:"time_limit",source:null};W="enforce",C=[{action:"claude.bash.unclassified",decision:f,mode:W,floor:"hold-unchecked"}]}Q?.stop&&!C.some(f=>f.mode==="enforce"&&f.decision.verdict==="block")&&(C=[Q.stop,...C],W="enforce");let R=p?[p.action,...p.also]:[],E=()=>({note:ci(n,i)??void 0});if(t.modelAtAction&&p&&!y&&d?.kill_switch!==!0&&c.policies.some(f=>he(f,u)&&(f.model_rules?.never?.length||f.model_rules?.guards?.some(w=>w.kinds.some(A=>R.includes(A)))))&&!(W==="enforce"&&C[0]?.decision.verdict==="block")){let f=await t.modelAtAction({...Tn(n,t,e,c),kinds:R,projectDir:u}).catch(E);f?.note&&(ie=ie?`${ie}
31
- ${f.note}`:f.note),f?.stop&&(C=[f.stop,...C],W="enforce")}if(t.budgetAtAction&&p&&!y&&d?.kill_switch!==!0&&c.policies.some(f=>f.budgets?.length)&&!(W==="enforce"&&C[0]?.decision.verdict==="block")){let f=await t.budgetAtAction(Tn(n,t,e,c)).catch(E);f?.note&&(ie=ie?`${ie}
32
- ${f.note}`:f.note),f?.stop&&(W="enforce",C=[f.stop])}let U=p?.units??null,te=p?{tool:s,parts:or({...p,tool:s,touched:_,command:v}),touched:_,projectDir:Fe,home:Re??null,command:v,input:h,now:o}:null,ee=p&&!y?es(c,[p.action,...p.also],u,te):[],Ee=ee.length>0?new tt(b(n.dir,"caps")):null,Fn=k(e.tool_use_id)??`${bn(i)}-${o}-${process.pid}`;if(Ee&&W!=="enforce"){let f;try{f=d?.kill_switch===!0?(Ee.count(ee,Fn,U,o,"ran",void 0,te),null):Ee.admit(ee,Fn,U,o,void 0,te)}catch(w){if(f=null,d?.kill_switch!==!0){let A=w instanceof Ye?ee.find(Oe=>Oe.unit==="money")??ee[0]:ee[0],re={verdict:"hold",policy:"caps",origin:null,ruleId:A.id,blockedBy:"cap_unreadable",source:A.source};W="enforce",C=[{action:p.action,decision:re,mode:W,floor:null,why:w instanceof Ye?`${w.message}, so your cap ${A.text} can't count it`:`couldn't check your cap ${A.text} (${w?.code??(w instanceof Error?w.message.slice(0,60):"unreadable")})`},...C]}}if(f){let w={verdict:"hold",policy:"caps",origin:null,ruleId:f.cap.id,blockedBy:"cap_reached",source:f.cap.source};W="enforce",C=[{action:p.action,decision:w,mode:W,floor:null,why:ni(f.cap,f.used)},...C]}}if(Ee&&W==="enforce"&&C[0]&&p&&!y&&C[0].decision.blockedBy!=="cap_reached"&&C[0].action!=="claude.budget")try{let f=ee.find(w=>Ee.used(w,o)+rt(w,U,te)>w.limit);f&&(C=[{...C[0],why:`${C[0].why??p.why}; and ${ni(f,Ee.used(f,o))}`},...C.slice(1)])}catch{}let Rt=async()=>{try{p&&i&&t.moot&&Jc(bt(n)).some(f=>f.startsWith(fr(i))||/^[0-9a-f]{16}\.json$/.test(f))&&await t.moot({anvilDir:n.dir,session:i,project:u,stops:[p.action,...p.also].map((f,w)=>({kind:f,target:w?null:p.attributes.target??null})),now:o})}catch{}},N=C[0];if(!N)return be(),await Rt(),nn(rn,n,i,a.problems,o);let Hn=W==="enforce"?C.filter(f=>f.mode==="enforce"):C,mi=f=>y?y.why??(y.rule==="too-long-to-check"?"too long to check in time":"could not be checked"):f.why?f.why:p&&f.action===p.action?p.why:Gn(f.action),Et=f=>f.target!==void 0?f.target:p&&f.action===p.action?p.attributes.target??null:null,hi=f=>f.replace(/ ?\((?:a command with no rule of its own, )?read by its (?:words|name)\)/g,"").trim(),yi=f=>{let w=hi(mi(f));if(f.decision.ruleId==="hold-delete-bursts")return`more than 20 recursive deletes in a minute (this one ${w})`;if(f.decision.ruleId==="hold-helper-bursts")return"more than 20 helper agent launches in 10 minutes";if(f.decision.ruleId==="hold-repeated-side-effect")return`the same app change again within 10 minutes (${w})`;let A=Et(f);return f.decision.ruleId==="block-protected-targets"&&!f.floor&&A&&/\/\.git(\/|$)/.test(A)?`deletes the .git of another repository inside the project (${u&&A.startsWith(`${u}/`)?A.slice(u.length+1):A})`:w},J=mn((N.decision.verdict==="block"?[N]:Hn).map(yi).join("; ")),zn=N.decision.verdict==="block"?"block":"hold",Ir=y?null:Et(N),He={v:1,ts:new Date(o).toISOString(),session:i,agent_id:k(e.agent_id),agent_type:k(e.agent_type),tool:s,action:N.action,verdict:zn,mode:W,rule:N.decision.ruleId,slug:Gr(N.decision.ruleId,N.decision.origin,N.action,N.floor),...N.floor?{floor:N.floor}:{},policy:N.decision.policy,blocked_by:N.decision.blockedBy,why:J,target:Ir?mn(Ir,200):null,project:u?Ln(u):null,path:S,...y?.error?{error:mn(y.error,200)}:{},...C.length>1?{also:C.slice(1).map(f=>({action:f.action,verdict:f.decision.verdict,mode:f.mode,rule:f.decision.ruleId,...f.floor?{floor:f.floor}:{}}))}:{},...p?.housekeeping&&N.action===p.action?{housekeeping:!0}:{}};if(W==="ghost"){be(),await Rt();let f=vu(n,i,o);if(tn(n,{...He,delivered:f?"note":"none",ms:t.now()-r}),!f)return nn(rn,n,i,a.problems,o);let w=zn==="hold"&&!p?.housekeeping&&N.decision.blockedBy!=="narrowed_rule"&&qe[N.action]?.slug===He.slug?He.slug:null;return nn(V({systemMessage:no(zn,J,w)}),n,i,a.problems,o)}let Pe=Ve();if(zn==="block"){tn(n,{...He,delivered:"deny",ms:t.now()-r});let f=N.floor?lo(J):so(J,Pe),w=N.floor?ao(J):io(J);return nn(V({systemMessage:f,...vt("deny",w)}),n,i,a.problems,o)}let Wr=Hn.map(f=>({kind:f.action,target:y?`input:${du(i,s,e.tool_input,l)}`:Et(f)})),wi=ye(n),ze={approved:!1,forged:0};try{ze=Ls(n,wi,i,u,Wr,o)}catch{ze={approved:!1,forged:0}}let Pt=ze.forged>0?[...a.problems,`${ze.forged===1?"an approval was":`${ze.forged} approvals were`} written outside \`${O(Pe)} allow\`; ${ze.forged===1?"it releases":"they release"} nothing`]:a.problems;if(ze.approved){be(),await Rt();try{Ee?.count(ee,Fn,U,o,"ran",void 0,te)}catch(f){Qs(n,"caps",f instanceof Error?f:new Error(String(f)),r,t.now(),e)}return ei(De,Hn,i,o),tn(n,{...He,delivered:"approved",ms:t.now()-r}),nn(V({systemMessage:co(J)}),n,i,Pt,o)}let Nt=k(e.permission_mode),bi=!/^sdk-/.test(k(t.env.CLAUDE_CODE_ENTRYPOINT)??"");if(Nt!==null&&bi&&N.action!=="claude.budget"&&(eu.has(Nt)||Nt==="bypassPermissions"&&ru(t.env,k(e.transcript_path)))){y||be();try{Ee?.count(ee,Fn,U,o,"ask",{tr:k(e.transcript_path),call:k(e.tool_use_id)},te)}catch(A){Qs(n,"caps",A instanceof Error?A:new Error(String(A)),r,t.now(),e)}tn(n,{...He,delivered:"ask",call:k(e.tool_use_id),transcript:k(e.transcript_path),ms:t.now()-r});let f=k(e.transcript_path),w=k(e.tool_use_id);return f&&w&&ei(De,Hn,i,o,{transcript:f,call:w}),nn(V(vt("ask",oo(N.floor?`${J} \xB7 always on`:J))),n,i,Pt,o)}let Ne=null,Ot,jr=null;try{let f=v??(/^(Agent|Task)$/.test(s)?p?.why??s:e.tool_input&&typeof e.tool_input=="object"?JSON.stringify(e.tool_input):null);({code:Ne,id:Ot}=Ms(n,{session:i,project:u,stops:Wr,why:J,project_name:u?Ln(u):null,...f?{command:`${s}: ${mn(f,240)}`}:{}},o))}catch(f){Ne=null;let w=f.code;jr=w==="ENOSPC"||w==="EDQUOT"?"the disk is full, so the hold could not be recorded: free some space, then ask Claude to try again":w==="EACCES"||w==="EPERM"||w==="EROFS"?`Anvil's folder (${n.dir}) cannot be written: fix that, then ask Claude to try again`:null}tn(n,{...He,delivered:"deny",...Ot?{hold:Ot}:{},ms:t.now()-r}),Ne&&t.notify?.({session:i,transcript:k(e.transcript_path),why:J,cli:Pe});let Un=Ne?N.said:void 0,ki=Un?Un.user.replace("{why}",()=>J).replace("{code}",Ne):to(J,Pe,Ne,jr??(N.floor?`to repair Anvil, run in a terminal: ${O(Pe)} on`:`to repair Anvil, run in a terminal: ${O(Pe)} on (or change the rule: ${O(Pe)} rules edit)`),N.floor!==void 0&&N.floor!==null),vi=Un?Un.agent:Q?.stop===N?Q.agent(Ne!==null):ro(J,Ne!==null,Pe);return nn(V({systemMessage:ki,...vt("deny",vi)}),n,i,Pt,o)}function ei(e,n,t,r,o){if(!(!t||!e.restart)){for(let s of n)if(!(!s.decision.ruleId||!Ur.has(s.decision.ruleId)))try{e.restart(Vt(s.action,t),r,o)}catch{}}}function vt(e,n){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:e,permissionDecisionReason:n}}}function Rr(e,n,t){let r=ye(e),o=n.anvilDir!==void 0,s=Ns(e,n.fallbackTable,r,{installed:o}),i=Ps(e,r,{installed:o}),l=[];try{l=o?yt(e,r,n.home):[]}catch{l=[]}let a=k(n.env.ANVIL_HOOK_NODE_FALLBACK),c=o&&a?`the Node Anvil was set up with ${k(n.env.ANVIL_HOOK_NODE_WHY)==="broken"?"could not start":"is gone"}, so it runs under ${a}; run ${oe("on")} to set it up again`:null,d=s.value?jt(s.value):sn,u=sn.filter(x=>!d.includes(x));_t||_n(s.value?.cli);let g=Ve(),h=u.length>0?`its always-on stops for ${u.map(x=>x.short).join("; ")} are missing from the rules it judges with, so it may not stop those calls; run ${O(g)} on`:null,v=[s.problem,i.problem,...l,c,h].filter(x=>typeof x=="string"&&x.length>0);return Os(e,{problems:v,modes_source:i.source,rules_source:s.source},t),{table:s.value,modes:i.value,problems:v}}function nn(e,n,t,r,o,s=!1){let i=[];if(r.length>0&&(s||ku(n,t,r,o))){let a=r[0];i.push(a.includes("Anvil is not checking")?a:eo(a,r.length-1))}if(ie&&i.push(ie),ie=null,i.length===0)return e;let l=i.join(`
33
- `);if(!e.stdout)return V({systemMessage:l});try{let a=JSON.parse(e.stdout),c=typeof a.systemMessage=="string"?a.systemMessage:null;return V({...a,systemMessage:c?`${c}
34
- ${l}`:l})}catch{return e}}function ni(e,n){let t=i=>String(Math.round(i*100)/100),r=e.unit==="money"&&e.money?ns(n,e.money):e.unit==="usd"?`$${t(n)}`:t(n),o={minute:"in the last minute",hour:"in the last hour",day:"today",week:"this week"}[e.window],s=e.window==="day"?"; resets at midnight":e.window==="week"?"; resets Monday":"";return`cap reached: ${e.text} (${r} used ${o}${s})`}function ci(e,n){try{let t=b(e.state,`note-${bn(n)}.meter`);if($(t)!==null)return null;F(e.state),Y(t,"")}catch{}return`${D("Anvil")} budgets and model rules can't be checked${xe("fix it",oe("on"))}`}var ie=null,xt=null,ti="claude.agent.helper";function bu(e,n,t,r,o){let s=[],i=new Set,l=d=>{try{let u=$(d,262144);return u===null?"gone":u===!1?"unreadable":Mn("sha256").update($t(d,"utf8")).digest("hex")}catch{return"unreadable"}};for(let d of n.policies){if(!d.from||!he(d,t))continue;i.add(d.from.file);let u=l(d.from.file);u!==d.from.sha256&&s.push(`${d.origin==="project"?".anvil/rules.md":"~/.anvil/rules.md"} ${u==="gone"?"was removed":u==="unreadable"?"can't be read":"changed"}`)}let a=s.length>0,c=t?b(t,".anvil","rules.md"):null;if(c&&!i.has(c)&&l(c)!=="gone"&&s.push(".anvil/rules.md isn't applied yet in this folder"),s.length===0)return null;try{F(e.state);let d=b(e.state,`rules-${bn(r)}`),u=Mn("sha256").update(s.join("|")).digest("hex").slice(0,16);if(Z(d,64).trim()===u)return null;Y(d,u)}catch{}return`${D("Anvil")} ${s.join(" \xB7 ")}${a?" \xB7 the rules applied before still hold":""}${xe("apply it",`${O(o)} sync`)}`}function ku(e,n,t,r){try{F(e.state);let o=b(e.state,`problem-${bn(n)}`),s=Mn("sha256").update(t.join(`
35
- `)).digest("hex").slice(0,16),[i,l]=Z(o,128).trim().split(" ");return i===s&&Number.isFinite(Number(l))&&r-Number(l)<ri&&r>=Number(l)?!1:(Y(o,`${s} ${r}`),!0)}catch{return!0}}function vu(e,n,t){try{F(e.state);let r=b(e.state,`note-${bn(n)}`),o=Number(Z(r,64).trim());return Number.isFinite(o)&&t-o<ri&&t>=o?!1:(Y(r,String(t)),!0)}catch{return!1}}async function Er(e){if(e.coreProblem)return e.coreProblem;try{return(await e.classifyInline({tool_name:"Bash",tool_input:{command:"git push origin main"},cwd:e.tmpdir,git_branch:"feature",project_dir:e.tmpdir,session_id:null,home:e.home,tmpdir:e.tmpdir,claude_config_dir:null,on_disk:null,project_controls:null,control_links:null},2e3)).action==="claude.bash.git.push_main"?null:"its checker answered a known call wrongly"}catch{return"its checker can't load"}}async function xu(e,n){let t=n.now(),r=Rr(e,n,t),o=await Er(n),s=[...r.table?[]:["no rules are compiled"],...o?[o]:[],...r.problems],i=ye(e),l=n.anvilDir!==void 0?yt(e,i,n.home).filter(d=>!yt(e,i,n.home,!1).includes(d)):[],a=s.filter(d=>!l.includes(d)),c={checking:!!r.table&&o===null,ok:a.length===0,problems:s,mode:r.table?Ft(r.table,r.modes).text:"none",rules:r.table?Lt(r.table):0};return V({anvil_self_check:c})}async function $u(e,n,t){let r=n.now();try{await n.sessionChores?.(e.dir,r)}catch{}let o=Rr(e,n,r),s=await Er(n),i=o.table;if(!i)return V(Se("SessionStart",ui(o)));if(s)return V(Se("SessionStart",s));let{enforced:l}=Ft(i,o.modes);_t||_n(i.cli);let a=Ve(),c=[...o.problems],d=[];try{d=n.anvilDir!==void 0&&n.startProblems?await n.startProblems({anvilDir:e.dir,home:n.home,files:Ar(n,t),cli:a}):[]}catch{d=[]}for(let x of d)c.some(j=>j.includes(x)||x.includes(j))||c.push(x);let u=Kr(o.modes),g=null;try{g=await n.sessionWords?.()??null}catch{g=null}let h=g?g.sessionLine(l,Dt(i).filter(x=>qe[x]).length,c,a,u?.what??null):`${D("Anvil is on")} ${Yr}`,v=g?g.sessionContext(jt(i).map(x=>x.context),l.filter(x=>!Tt.has(x)).map(Gn),a,u?.context??null):"Anvil (anvilcontrol.ai) checks every tool call in this session before it runs. Changing Anvil is the user's to do, in their own terminal.";return V({systemMessage:h,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:v}})}function ui(e){return e.problems.join(" ").includes("seal key")?"its seal key is missing or damaged":/^compiled\.json .*changed outside/m.test(e.problems.join(`
36
- `))?"its rules were changed outside Anvil":"its rules are missing"}import{spawn as Su}from"child_process";import{readFileSync as _u,statSync as Cu}from"fs";import{join as kn}from"path";function Au(e){try{let n=JSON.parse(_u(e,"utf8"));return Object.values(n??{}).some(t=>typeof t=="object"&&t!==null&&t.active===!0&&typeof t.apiKey=="string"&&t.apiKey!=="")}catch{return!1}}var Ru="sync-next",Eu="sync-pulled",Pu="claude-sync.js",Nu=6e4,Ou=5*6e4;function fi(e,n){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||kn(n,".anvil","workspace-keys.json")}function Iu(e,n){if(e.ANVIL_API_KEY?.trim())return!0;try{return Cu(fi(e,n)).isFile()}catch{return!1}}var Wu=10*6e4;function pi(e){try{let n=e.env.ANVIL_CLAUDE_SYNC?.trim().toLowerCase();if(n==="off"||n==="0"||n==="false")return!1;if(!Iu(e.env,e.home))return $(kn(e.paths.state,"sync-active.json"))===!0&&di(e.paths,e.now),!1;let t=kn(e.binDir,Pu);if($(t)!==!0)return!1;let r=kn(e.paths.state,Ru),o=Number(Z(r,64).trim());if(Number.isFinite(o)&&o>e.now&&o-e.now<=1440*6e4&&!(e.sessionStart===!0&&ju(e.paths,e.now)))return!1;F(e.paths.state);let s=fi(e.env,e.home);return!e.env.ANVIL_API_KEY?.trim()&&($(s,1024*1024)!==!0||!Au(s))?(di(e.paths,e.now),Y(r,String(e.now+Wu)),!1):(Y(r,String(e.now+Nu)),(e.start??Tu)(e.execPath,t,e.paths.dir),!0)}catch{return!1}}function ju(e,n){let t=Number(Z(kn(e.state,Eu),64).trim());return!(Number.isFinite(t)&&t>0&&t<=n+6e4&&n-t<=Ou)}function di(e,n){let t=kn(e.state,"signed-out.json"),r=Pn(t);typeof r?.open!="string"&&Y(t,`${JSON.stringify({open:new Date(n).toISOString(),windows:Array.isArray(r?.windows)?r.windows:[]})}
37
- `)}function Tu(e,n,t){let r=Su(e,[n],{detached:!0,stdio:"ignore",cwd:t,env:process.env,windowsHide:!0});r.on("error",()=>{}),r.unref()}var X=xn(Fu(import.meta.url)),Uu=Date.now(),Or=Ce(X,"claude-hook-core.js"),we=At(X)==="bin"&&At(xn(X))==="claude"&&At(xn(xn(X)))===".anvil"?xn(X):void 0,Bu=!we&&At(X)==="bin"&&Pr(Ce(xn(X),".claude-plugin","plugin.json")),gi=null;async function qu(e){try{(await import("module")).enableCompileCache?.(Ce(we??Je(e).dir,"cache"))}catch{}}function on(){return gi??=import(Nr(Or).href),gi}var Zu=null,vn=()=>Zu??=import(Nr(Ce(X,"claude-meter.js")).href),Vu=new Hu.Script("globalThis.__anvilClassify()");async function Ku(e,n){let t;try{t=await on()}catch(s){throw new yn(s instanceof Error?s.message:String(s))}let{classifyRequest:r}=t;if(typeof r!="function")throw new yn("no classifier in its file");let o=globalThis;o.__anvilClassify=()=>r(e);try{return Vu.runInThisContext({timeout:n})}catch(s){throw s.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new wn:s}finally{delete o.__anvilClassify}}function Gu(e,n){return new Promise(t=>{let r=!1,o=(l,a)=>{r||(r=!0,clearTimeout(i),a&&a.terminate().catch(()=>{}),t(l))},s;try{s=new zu(Or,{workerData:{anvilClaudeHook:!0,request:e}})}catch(l){t({kind:"error",error:l instanceof Error?l.message:String(l)});return}let i=setTimeout(()=>o({kind:"timeout"},s),n);s.once("message",l=>{o(l.ok&&l.classification?{kind:"ok",classification:l.classification}:{kind:"error",error:l.error??"worker failed"},s)}),s.once("error",l=>o({kind:"error",error:l.message},s)),s.once("exit",l=>o({kind:"error",error:`worker exited (${l}) without an answer`}))})}async function Ju(){try{let e=await vn(),n=e.probeAccount?.(process.env)??null;if(!n||!e.runPlanProbe)return;e.runPlanProbe({paths:we?Te(we):Je(Ct()),env:process.env,now:()=>Date.now(),account:n})}catch{}}async function Yu(){process.argv[2]==="--plan-probe"&&(await Ju(),process.exit(0));let e="",n=null,t=!1,r="";try{let o=Ct();await qu(o);try{r=Mu(0,"utf8")}catch{r=""}if(r.length<64*1024&&r.includes("SessionStart"))try{t=JSON.parse(r).hook_event_name==="SessionStart"}catch{t=!1}e=(await li(r,{home:o,...we?{anvilDir:we}:{},tmpdir:Du(),env:process.env,now:()=>Date.now(),classifyInline:Ku,classifyInWorker:Gu,...Bu?{plugin:!0,fallbackTable:Ce(X,"baseline.json")}:{},...we&&Pr(Ce(X,"baseline.json"))?{fallbackTable:Ce(X,"baseline.json")}:{},coreProblem:Pr(Or)?null:"its checker file is missing",entry:process.env.ANVIL_HOOK_EVENT,cli:process.env.ANVIL_HOOK_CLI,startProblems:async i=>(await on()).startProblems?.(i)??[],sessionChores:async(i,l)=>(await on()).sessionChores?.(i,l),answerChanges:async i=>(await on()).answerChanges?.(i)??null,sessionWords:async()=>{let i=await on();if(!i.sessionLine||!i.sessionContext)throw new Error("an older classifier file");return{sessionLine:i.sessionLine,sessionContext:i.sessionContext}},notify:i=>{n=i},planProbe:{hookFile:Ce(X,"claude-hook.js"),node:process.execPath},budgetAtPrompt:async i=>(await vn()).budgetAtPrompt(i),budgetAtAction:async i=>(await vn()).budgetAtAction(i),modelAtAction:async i=>(await vn()).modelAtAction(i),modelAtSwitch:async i=>(await vn()).modelAtSwitch(i),modelAtPrompt:async i=>(await vn()).modelAtPrompt(i),helpers:()=>import(Nr(Ce(X,"claude-helpers.js")).href),moot:async i=>(await on()).mootHolds?.(i)})).stdout}catch{let o=null;try{o=t?"SessionStart":JSON.parse(r).hook_event_name??null}catch{o=null}e=o==="SessionStart"||o==="PreToolUse"||o===null?`${JSON.stringify(Se(o??"PreToolUse","its check crashed"))}
38
- `:""}try{e&&Lu(1,e)}catch{}if(globalThis.__anvilHookAnswered=!0,n)try{(await on()).heldNotice?.({...n,anvilDir:we??Je(Ct()).dir,now:Date.now(),env:process.env})}catch{}(Nn(process.env.ANVIL_HOOK_EVENT)||/"hook_event_name"\s*:\s*"(?:UserPromptSubmit|SubagentStart|SubagentStop|PreModelSwitch)"/.test(r.slice(0,4096)))&&process.exit(0);try{let o=Ct();pi({paths:we?Te(we):Je(o),binDir:X,home:o,env:process.env,now:Uu,execPath:process.execPath,sessionStart:t})}catch{}process.exit(0)}Yu();
21
+ `&&(i=s,r.length>0&&(o=r.shift())))}return n.push({start:s,end:e.length,op:""}),{segments:n,quotes:t}}var ht=(e,n,t)=>n[t]>0&&n[t]<on&&e[t]===ze[n[t]];function Ln(e,n,t){if(hr.lastIndex=n,!hr.exec(e))return n;let r=hr.lastIndex;if((t[n]&~on)===0)return r;for(let o=n;o<r;o++)if(ht(e,t,o))return o;return r}function Re(e,n,t=()=>!0,r=()=>!0){let{quotes:o}=bn(e),s="",i=0;n.lastIndex=0;for(let l=n.exec(e);l;l=n.exec(e)){let a=l.index+l[0].length;if(!t(l))continue;let c=Ln(e,a,o);c===a||!r(e.slice(a,c))||(s+=e.slice(i,a)+ne,i=n.lastIndex=c)}return s+e.slice(i)}var ee=e=>new RegExp(`(?:^|\\s)(?:${e})(?:=|${mt})(?=[^\\s-])`,"g"),fe=e=>new RegExp(`(?:^|[\\s"'(/])(?:${e})(?=$|[\\s"';)])`),yn=(e,n=0,t="(?!)")=>{let r=`(?:${S}(?:(?:${t})${S}[^\\s-][^\\s]*|(?!(?:${t})${S})-[\\w-]+(?:=[^\\s]*)?))*`;return new RegExp(`(?:^|[\\s"'(/])(?:${e})${r}(?:${S}[^\\s-][^\\s]*${r}){${n}}${S}(?=[^\\s-])`,"g")},Ws=new RegExp(`(?:^|[\\s(])(?:http|https|xh|xhs)${S}`),mc=[{when:fe("mysql\\w*|mariadb[\\w-]*"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:fe("redis-cli|keydb-cli|valkey-cli"),flag:ee("-a")},{when:fe("curl"),flag:ee("-[A-Za-z]*[uUb]|--user|--proxy-user")},{when:Ws,flag:ee("-a")},{when:new RegExp(`${fe("sshpass|mongo|mongosh|mongodump|mongorestore|mongoexport|mongoimport|twine|cqlsh").source}|(?:^|\\s)login(?=$|\\s)`),flag:ee("-p")},{when:/\bgh\s+secret\s+set\b/,flag:ee("-b|--body")},{when:/\bsecurity\s+add-(?:generic|internet)-password\b/,flag:ee("-w")},{when:/\bsecurity\s+(?:unlock-keychain|create-keychain|set-keychain-password)\b/,flag:ee("-p|-o")},{when:/\bsecurity\s+import\b/,flag:ee("-P")},{when:fe("sqlcmd|bcp|osql|isql"),flag:ee("-P")},{when:fe("zip|zipcloak|unzip"),flag:ee("-P|--password")},{when:fe("7z|7za|7zr|7zz"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:fe("ldap\\w+"),flag:ee("-w|-s")},{when:fe("openssl"),flag:ee("-k|-K")},{when:fe("ssh-keygen"),flag:ee("-N|-P")},{when:fe("smbclient|rpcclient|smbmap|smbget|smbcacls|net"),flag:new RegExp(`(?:^|\\s)(?:-U|--user(?:name)?)(?:=|${mt})[^\\s%"']+%(?=[^\\s])`,"g")},{when:/\bvault\s+login\b/,flag:new RegExp(`\\bvault${S}login(?:${S}-[\\w-]+(?:=[^\\s]*)?)*${S}(?=[^\\s=-][^\\s=]*(?:\\s|$))`,"g")},{when:/\bnetlify\s+env:set\b/,flag:yn(`netlify${S}env:set`,1)},{when:/\bconvex\s+env\s+set\b/,flag:yn(`convex${S}env${S}set`,1)},{when:/\bcargo\s+login\b/,flag:yn(`cargo${S}login`,0,"--registry")},{when:/\bpoetry\s+config\b/,flag:yn(`poetry${S}config(?:${S}-[\\w-]+)*${S}pypi-token\\.[\\w.-]+`)},{when:/\bpoetry\s+config\b/,flag:yn(`poetry${S}config(?:${S}-[\\w-]+)*${S}http-basic\\.[\\w.-]+`,1)},{when:/\bngrok\b/,flag:yn(`ngrok${S}(?:config${S}add-(?:authtoken|api-key)|authtoken)`)}],hc=new RegExp(`(?:^|[\\s"'(/])htpasswd((?:${S}-(?:[A-Za-z]*[Cr]${S}\\d+|[A-Za-z]+))+)${S}(?:[^\\s]+)${S}(?:[^\\s]+)${S}(?=[^\\s])`,"g"),Rs=/\b(?:gh\s+secret\s+set|wrangler\s+(?:pages\s+)?secret\s+put|vercel\s+env\s+add|docker\s+secret\s+create|modal\s+secret\s+create|firebase\s+functions:secrets:set|fly(?:ctl)?\s+secrets\s+(?:set|import)|supabase\s+secrets\s+set|heroku\s+config:set|railway\s+variables\b[^\n]*?\s--set|security\s+add-(?:generic|internet)-password|op\s+item\s+create|vault\s+(?:kv\s+)?put|aws\s+ssm\s+put-parameter|az\s+keyvault\s+secret\s+set|gcloud\s+secrets\s+(?:create|versions\s+add)|netlify\s+env:set|convex\s+env\s+set|eas\s+(?:secret|env):create)\b/,yc=ee("--value"),wc=/^(\s*(?:echo|printf)(?:\s+-[A-Za-z]+)*\s+)\S(?:[\s\S]*\S)?/,Es=new RegExp(`<<<${mt}(?=[^\\s-])`,"g"),Ps=e=>/--password-stdin\b|\bchg?passwd\b|\bcargo\s+login\b/.test(e)||/\bsudo\b/.test(e)&&/\s(?:-(?=[A-Za-z]*S)[A-Za-z]+|--stdin)(?=\s|$)/.test(e)||/\bpasswd\b/.test(e)&&/\s--stdin\b/.test(e)||/\bgh\s+auth\s+login\b/.test(e)&&/\s--with-token\b/.test(e),dt=/(?:^|\s)(["']?)([A-Za-z][\w-]*)(==|:(?![=:/]))/g;function bc(e){let{quotes:n}=bn(e),t="",r=0;dt.lastIndex=0;for(let o=dt.exec(e);o;o=dt.exec(e)){let s=o[3]!=="==";if(!(s?js.test(o[2]):wn(o[2])))continue;let i=o.index+o[0].length,l=ze.indexOf(o[1]),a;if(l>0&&(n[i]&~on)===l)for(a=i;a<e.length&&!ht(e,n,a);)a++;else a=Ln(e,i,n);let c=i;for(;c<a&&(e[c]===" "||e[c]===" ");)c++;c===a||s&&/^\d{1,5}(?:[/?#]|$)/.test(e.slice(c,a))||(t+=e.slice(r,c)+ne,r=dt.lastIndex=a)}return t+e.slice(r)}function kc(e){let{segments:n}=bn(e),t="";for(let r=0;r<n.length;r++){let o=n[r],s=e.slice(o.start,o.end);for(let a of mc)a.when.test(s)&&(s=Re(s,a.flag));s=Re(s,hc,a=>/b/.test(a[1].replace(/\d+/g,""))),Ws.test(s)&&(s=bc(s)),Rs.test(s)?s=Ls(Re(Re(s,Es),yc),()=>!0):Ps(s)&&(s=Re(s,Es));let i=n[r+1],l=o.op==="|"&&i?e.slice(i.start,i.end):"";l&&(Rs.test(l)||Ps(l))&&(s=s.replace(wc,`$1${ne}`)),t+=s+e.slice(o.end,i?i.start:o.end)}return t}var xc=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#"'`<>]*@/gi,vc=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#:@[\]"'`<>]*:(?!\d{1,5}(?:[/?#]|$))[^\s@"'`<>]{1,256}@/gi,$c=[/(\bdiscord(?:app)?\.com\/api\/webhooks\/\d+\/)[\w-]+/gi,/(\bapi\.telegram\.org\/(?:file\/)?bot\d+:)[\w-]+/gi,/(\bhooks\.zapier\.com\/hooks\/catch\/\d+\/)[\w-]+/gi,/((?:\.webhook\.office\.com\/webhookb2|\boutlook\.office(?:365)?\.com\/webhook)\/[\w@.-]+\/IncomingWebhook\/)[\w-]+(\/[\w-]+)?/gi,/(\bhooks\.slack\.com\/(?:workflows|triggers)\/(?:[\w-]+\/){1,4})[\w-]{8,}/gi,/(\bmaker\.ifttt\.com\/trigger\/[\w-]+\/with\/key\/)[\w-]+/gi,/(\/(?:api\/)?(?:webhooks?|hooks)(?:\/[\w.-]+){0,3}\/)(?=[\w-]{24,})(?=[\w-]*\d)[\w-]+/gi],Sc=e=>$c.reduce((n,t)=>n.replace(t,`$1${ne}`),e),_c=new RegExp(`\\bmachine${S}[^\\s]+(?:${S}login${S}[^\\s]+)?${S}password${S}(?=[^\\s])`,"g"),Cc=/[._]netrc\b/,Ac=new RegExp(`(?:^|\\n|\\\\n|["'])[ \\t]*(?:login${S}[^\\s]+${S})?password${S}(?=[^\\s])`,"g"),Rc=[/\bhv[sbr]\.[A-Za-z0-9_-]{20,}/g,/\banv_(?:live|test)_[A-Za-z0-9_-]{8,}/g,/\bpypi-AgE[A-Za-z0-9_-]{16,}/g,/\bhf_[A-Za-z0-9]{30,}\b/g,/\bdo[opr]_v1_[A-Za-z0-9]{32,}\b/g],Ts=e=>{let n=e.replace(/^["'\\]+|["'\\]+$/g,"");return n.length>=8&&!/\s/.test(n)&&/\d/.test(n)&&/[A-Za-z]/.test(n)},Ms=/^(?:key|apikey|api_key_id|k)$/i,Ec=new RegExp(`(?:^|[\\s("'])--?(?!no-|noauth\\b|anyauth\\b|bypass\\b|askpass\\b)(?=[A-Za-z])[\\w-]*?(?:token|api[-_]?key|secret|secret[-_]?string|access[-_]?key|secret[-_]?key|passw(?:or)?d|passphrase|pass(?:in|out)?|otp|auth|cookie|bearer|credentials?)(?:=|${S}(?=[^\\s-]))`,"gi"),ft=new RegExp(`(?:^|\\s)(?:-H|--header)(?:=|${mt})(?=[^\\s-])`,"g");function Pc(e){let{quotes:n}=bn(e),t="",r=0;ft.lastIndex=0;for(let o=ft.exec(e);o;o=ft.exec(e)){let s=o.index+o[0].length,i=Ln(e,s,n),l=e.slice(s,i),a=l[0]==='"'||l[0]==="'"?l[0]:"",c=/^([ \t]*([\w-]+)[ \t]*:[ \t]*)\S/.exec(a?l.slice(1):l);!c||!js.test(c[2])||(t+=`${e.slice(r,s)}${a}${c[1]}${ne}${a}`,r=ft.lastIndex=i)}return t+e.slice(r)}var pt=/(?:(?<![\w.$-])|(?<=(?:^|\s)-e))([A-Za-z_][\w.-]*)(?:=(?!=)|[ \t]*=[ \t]*(?=["']))/g;function Ls(e,n=wn){let{quotes:t}=bn(e),r="",o=0;pt.lastIndex=0;for(let s=pt.exec(e);s;s=pt.exec(e)){let i=s.index+s[0].length;if(!n(s[1])&&!(Ms.test(s[1])&&Ts(e.slice(i,Ln(e,i,t)))))continue;let l=ze.indexOf(e[s.index-1]??""),a;if(l>0&&(t[s.index]&~on)===l)for(a=i;a<e.length&&!ht(e,t,a);)a++;else a=Ln(e,i,t);a!==i&&(r+=e.slice(o,i)+ne,o=pt.lastIndex=a)}return r+e.slice(o)}var gt=/(?:(\\?["'])([A-Za-z_][\w.-]*)\1|(?<![\w.$:/"'-])([A-Za-z_][\w.-]*))[ \t]*:[ \t]*/g,yr=/[^\s,}\]"'\\{[]+/y;function Oc(e){let{quotes:n}=bn(e),t="",r=0;gt.lastIndex=0;for(let o=gt.exec(e);o;o=gt.exec(e)){let s=o[2]??o[3],i=!wn(s)&&Ms.test(s);if(!wn(s)&&!i)continue;let l=o.index+o[0].length,a=/^[rRbBuUfF]{1,2}(?=["'])/.exec(e.slice(l,l+3));a&&(l+=a[0].length);let c=e[l],d="",u=-1;if(e.startsWith('\\"',l))d='\\"',u=e.indexOf('\\"',l+2);else if((c==='"'||c==="'")&&!ht(e,n,l)){d=c;let g=l+1;for(;g<e.length&&e[g]!==c;)g+=c==='"'&&e[g]==="\\"?2:1;u=g<e.length?g:-1}else(o[1]!==void 0||i)&&c!=='"'&&c!=="'"&&(yr.lastIndex=l,yr.exec(e)&&(u=yr.lastIndex));u<=l+d.length||i&&!Ts(e.slice(l+d.length,u))||(t+=e.slice(r,l)+d+ne,r=gt.lastIndex=u)}return t+e.slice(r)}var Nc=/(^|\n)([ \t]*(?:-[ \t]+)?)([A-Za-z_][\w.-]*)([ \t]*:[ \t]+)([^\s"'`#][^\n"'`]*)/g,Ic=e=>e.replace(Nc,(n,t,r,o,s)=>wn(o)?`${t}${r}${o}${s}${ne}`:n),jc=new RegExp(`\\b(?:config|configure)${S}set${S}(?:-{1,2}\\w[\\w-]*(?:=\\S*)?${S})*((?!-)[^\\s=]+)${S}(?=[^\\s-])`,"g"),Wc=/\b(?:redis|keydb|valkey)-cli\b/,Os=/(?:"[^"\n]*"|'[^'\n]*'|[^\s"'\\;&|]+)/.source,Tc=new RegExp(`\\bAUTH[ \\t]+${Os}(?:[ \\t]+${Os})?`,"g"),Ns=/^(?:to|the|a|an|is|are|for|and|or|of|in|on|it|be|as|at|by|from|with|this|that|flag|option|instead|here|there|if|when|you|your)$/i,Mc=/\b(Bearer|Basic)([ \t]+)([A-Za-z0-9\-._~+/]+=*)/gi,wr="\uE000";function Lc(e){return e.includes(wr)?e:e.replace(Mc,(n,t,r,o)=>o.length>=8&&(/[0-9+/=_~]/.test(o)||/[a-z][A-Z]|[A-Z]{2}/.test(o.slice(1)))?`${t}${r}${ne}`:`${t}${wr}${r}${o}`)}function Is(e){let n=kc(e);return n=n.replace(xc,`$1${ne}@`).replace(vc,`$1${ne}@`),n=Sc(n),n=Pc(n),n=Re(n,Ec,()=>!0,t=>!Ns.test(t)),n=Re(n,_c),Cc.test(n)&&(n=Re(n,Ac,()=>!0,t=>!Ns.test(t))),n=Rc.reduce((t,r)=>t.replace(r,ne),n),n=Ls(n),n=Oc(n),n=Ic(n),n=Re(n,jc,t=>wn(t[1])),Wc.test(n)&&(n=n.replace(Tc,`AUTH ${ne}`)),Ss(Lc(n)).split(wr).join("")}function Ds(e,n=8192){if(e.length<=n)return Is(e);let t=e.slice(0,n),r=t.search(/-----BEGIN [A-Z0-9 ]*-----/);return r>=0&&!/-----END [A-Z0-9 ]*-----/.test(t.slice(r))&&(t=`${t.slice(0,r)}-----BEGIN ${ne}`),Is(t)}var Fs="held by default",Dc={recordAndCount:()=>1},yt={allow:0,hold:1,block:2};function Hs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function br(e){let n={action:e.action,service:e.service,target:e.attributes.target??null,host:e.attributes.host??null,attributes:e.attributes},t=(e.findings??[]).slice(1).map(s=>{let i=s;return{action:s.action,service:s.service,target:s.target,host:typeof i.host=="string"?i.host:null,attributes:i}}),r=new Set([n,...t].map(s=>s.action)),o=e.also.filter(s=>!r.has(s)).map(s=>({action:s,service:null,target:null,host:null,attributes:{}}));return[n,...t,...o]}function kr(e,n,t,r,o,s,i,l=null,a=[]){let c=i?{session_id:i}:{},d=[n.action,...n.also.filter(p=>p!==n.action)],u=(p,A,b)=>A?"enforce":no(t,p,lr(e,p,s),b),g=(p,A,b)=>!A&&b&&to(t,p,lr(e,p,s)),h=p=>{if(p===n.action&&n.catastrophic)return{why:n.why};let A=(n.findings??[]).find(b=>b.action===p&&b.catastrophic);return A?{why:A.why}:null},m=[];d.forEach((p,A)=>{let b=A===0,{decision:I,baseline:Y}=ir(e,b?{action:p,service:n.service,metadata:{...n.attributes,...c}}:{action:p,service:null,metadata:c},r,o,s),M=Zt({action:p,decision:I,baseline:Y,service:b?n.service:null,target:b?n.attributes.target??null:null,projectDir:s,home:l,histories:a}),W=h(p),R=u(p,M,W!==null);R!=="off"&&(W&&I.verdict!=="allow"&&g(p,M,!0)?m.push({action:p,decision:I,mode:R,floor:M?.id??null,why:`${W.why} \xB7 ${Fs}`}):m.push({action:p,decision:I,mode:R,floor:M?.id??null}))});let x=new Set;for(let p of(n.findings??[]).slice(1)){if(!p.service&&!p.target)continue;let A=`${p.action}\0${p.service??""}\0${p.target??""}`;if(x.has(A))continue;x.add(A);let{decision:b,baseline:I}=ir(e,{action:p.action,service:p.service,metadata:{target:p.target,...c}},Dc,o,s);if(b.verdict==="allow")continue;let Y=Zt({action:p.action,decision:b,baseline:I,service:p.service,target:p.target,projectDir:s,home:l,histories:a}),M=p.catastrophic===!0,W=u(p.action,Y,M);W!=="off"&&m.push({action:p.action,decision:b,mode:W,floor:Y?.id??null,why:M&&g(p.action,Y,!0)?`${p.why} \xB7 ${Fs}`:p.why,target:p.target})}if(e.policies.some(p=>p.narrowed&&p.narrowed.length>0)){let p={tool:n.tool??null,parts:br(n),touched:n.touched??null,projectDir:s,home:l,command:n.command??null,input:n.input??null,...o>0?{now:o}:{}};for(let A of e.policies)if(!(!A.narrowed||!de(A,s)))for(let b of A.narrowed){let I=Ko(b,{...p,root:A.origin==="project"?A.project_dir??null:null});if(!I)continue;let Y=/^(.*):(\d+) · /.exec(b.source),M=`your rule "${b.text}"${Y?` (${Y[1]} line ${Y[2]})`:""}`,W=I.part===p.parts[0]?n.why:(n.findings??[]).find(R=>R.action===I.part.action&&R.target===I.part.target)?.why??null;m.push({action:I.part.action,decision:{verdict:I.hit==="unknown"?"hold":b.intent,policy:A.name,origin:A.origin,ruleId:b.id,blockedBy:"narrowed_rule",source:b.source},mode:t?.kill_switch===!0?"ghost":b.mode,floor:null,why:I.hit==="unknown"?`${W?`${W}: `:""}${I.why}`:`${W??I.why}${I.detail?` (${I.detail})`:""} \xB7 ${M}`,target:I.part.target})}}let _=m.filter(p=>p.decision.verdict!=="allow");if(_.length===0)return{lead:null,stops:[],mode:"ghost"};let z=_.filter(p=>p.mode==="enforce"),J=(z.length>0?z:_).reduce((p,A)=>yt[A.decision.verdict]>yt[p.decision.verdict]||yt[A.decision.verdict]===yt[p.decision.verdict]&&A.floor&&!p.floor?A:p);return{lead:J,stops:[J,..._.filter(p=>p!==J)],mode:z.length>0?"enforce":"ghost"}}var Fc=["command","cmd","script","input","code"];function Us(e,n){let t=n&&typeof n=="object"?n:{};if(e==="Bash")return zs(typeof t.command=="string"?t.command:"");if(Fc.some(o=>typeof t[o]=="string"&&zs(t[o])))return!0;let r=0;try{r=JSON.stringify(n??null)?.length??0}catch{return!0}return r>16384}function zs(e){if(e.length>2048)return!0;let n=0,t=0;for(let o=0;o<e.length;o++){let s=e[o];s===";"||s==="|"||s==="&"||s===`
22
+ `?(n++,(s==="|"||s==="&")&&e[o+1]===s&&o++):(s==="`"||(s==="$"||s==="<"||s===">")&&e[o+1]==="(")&&t++}return n>16||t>8||(e.match(/\{[^{}\s]*,[^{}\s]*\}/g)?.length??0)>4?!0:(e.match(/(?:^|[\s;&|(){}`])(?:cd|pushd|popd)(?=$|[\s;&|()])/g)?.length??0)>8}import{createHash as li,randomBytes as ai}from"crypto";import{readdirSync as Xc,renameSync as Qc,unlinkSync as Pg}from"fs";import{join as Ct}from"path";import{createHmac as Hc,randomBytes as xr,timingSafeEqual as zc}from"crypto";import{closeSync as Vs,existsSync as vr,fsyncSync as Zs,linkSync as Uc,mkdirSync as Gs,openSync as Js,readdirSync as Bc,readFileSync as xn,unlinkSync as Ys,writeSync as Xs}from"fs";import{basename as qc,dirname as kt,join as pe}from"path";var Ee="_seal";function $t(e){return pe(e.dir,"seal.key")}function kn(e,n){return pe(e.state,"lkg",n)}function xe(e){let n=$t(e);if(C(n,1024)!==!0)return null;try{let t=xn(n,"utf8").trim();return/^[0-9a-f]{64}$/.test(t)?Buffer.from(t,"hex"):null}catch{return null}}function _r(e){return xe(e)?"ok":C($t(e),1024)===null?"missing":"damaged"}var xt=class extends Error{};function St(e,n){return`Anvil's seal key (${$t(e)}) is ${n==="damaged"?"damaged":"missing"}`}function Kc(e){let n=xe(e);if(n)return n;let t=_r(e);if(t==="damaged"||Cr(e))throw new xt(`${St(e,t)}; run ${le("on")} to restore it`);let{key:r,created:o}=Vc(e,!1);return o&&Zc(e,r),r}function Bs(e,n,t){let r=Js(e,t,384);try{Xs(r,n),Zs(r)}finally{Vs(r)}}function Vc(e,n){Gs(e.dir,{recursive:!0,mode:448});let t=$t(e),r=pe(e.dir,`.seal.key.${process.pid}.${xr(4).toString("hex")}.tmp`);Bs(r,`${xr(32).toString("hex")}
23
+ `,"wx");let o=!1;try{n?Wn(r,t):Uc(r,t),o=!0}catch(i){let l=i.code??"";if(l!=="EEXIST"){if(n||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(l))throw i;try{Bs(t,xn(r,"utf8"),"wx"),o=!0}catch(a){if(a.code!=="EEXIST")throw a}}}finally{try{Ys(r)}catch{}}let s=xe(e);if(!s)throw new xt(`${St(e,"damaged")}; run ${le("on")} to restore it`);return{key:s,created:o}}function Zc(e,n){let t=[[e.modes,bt],[e.compiled,ni],[e.install,void 0]];for(let[r,o]of t)if(C(r,8*1024*1024)===!0)try{let s=xn(r,"utf8");if(s.includes(`"${Ee}"`))continue;let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let l=`${JSON.stringify(Sr(n,i),null,2)}
24
+ `;sn(r,l),o&&sn(kn(e,o),l)}catch{}if(C(e.modes)===null&&C(kn(e,bt))===null){let r=`${JSON.stringify(Sr(n,qt()),null,2)}
25
+ `;sn(e.modes,r),sn(kn(e,bt),r)}}function $r(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>$r(t===void 0?null:t,n+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(n===0&&r===Ee)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${$r(e[r],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function Qs(e,n){return Hc("sha256",e).update($r(n)).digest("hex")}function wt(e){if(!(Ee in e))return e;let n={...e};return delete n[Ee],n}function Sr(e,n){let t=wt(n);return{...t,[Ee]:Qs(e,t)}}function Gc(e,n){let t=n[Ee];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let r;try{r=Qs(e,n)}catch{return!1}return zc(Buffer.from(t,"hex"),Buffer.from(r,"hex"))}function sn(e,n,t=384){Gs(kt(e),{recursive:!0,mode:448});let r=pe(kt(e),`.${qc(e)}.${process.pid}.${Date.now().toString(36)}.${xr(3).toString("hex")}.tmp`);try{let o=Js(r,"w",t);try{Xs(o,n),Zs(o)}finally{Vs(o)}Wn(r,e)}catch(o){try{Ys(r)}catch{}throw o}}function ge(e,n,t=8*1024*1024){let r=C(e,t);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(xn(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:n?Ee in o?Gc(n,o)?{status:"ok",value:wt(o)}:{status:"changed",value:wt(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:wt(o)}}function ei(e,n,t,r){let o=Kc(e),s=`${JSON.stringify(Sr(o,t),null,2)}
26
+ `;sn(n,s),r&&sn(kn(e,r),s)}var bt="modes.json",ni="compiled.json";function Cr(e){return vr(pe(e.bin,"claude-hook.sh"))||Jc(e)}function Jc(e){let n=t=>{try{return Bc(t).slice(0,200).some(r=>r.endsWith(".json")&&C(pe(t,r),65536)===!0&&xn(pe(t,r),"utf8").includes(`"${Ee}"`))}catch{return!1}};if(n(pe(e.state,"lkg"))||n(pe(e.state,"pending"))||n(e.approvals))return!0;for(let t of[e.modes,e.compiled,e.install])if(C(t,8*1024*1024)===!0)try{if(xn(t,"utf8").includes(`"${Ee}"`))return!0}catch{}return!1}var vt=U({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function qs(e=new Date){return Qr(null,"enforce","all",e)}function ti(e,n=xe(e),t={}){if(!n){let i=_r(e);if(t.installed===!0||i==="damaged"||Cr(e))return{value:qs(),source:"strict",problem:`${St(e,i)}, so every rule is enforced until \`${le("on")}\` restores it`};let l=ge(e.modes,null);return{value:l.status==="unkeyed"?l.value:null,source:"unkeyed",problem:null}}let r=ge(e.modes,n);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${vt[r.status]??"cannot be used"}`,s=ge(kn(e,bt),n);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:qs(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${le("on")}\` resets it`}}function ri(e,n,t=xe(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===or&&Array.isArray(c.policies),s=()=>{if(!n)return null;let c=ge(n,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!t){let c=_r(e),d=r.installed===!0||c==="damaged"||Cr(e),u=ge(e.compiled,null),g=u.status==="unkeyed"&&o(u.value)?u.value:null;return d?{value:null,source:"strict",problem:`${St(e,c)}: \`${le("on")}\` restores it`}:{value:g??s(),source:"unkeyed",problem:null}}let i=ge(e.compiled,t);if(i.status==="ok"&&o(i.value))return{value:i.value,source:"file",problem:null};let l=`compiled.json ${i.status==="ok"?"is not a rules table":vt[i.status]??"cannot be used"}`,a=ge(kn(e,ni),t);return a.status==="ok"&&o(a.value)?{value:a.value,source:"last-good",problem:`${l}; Anvil keeps the rules it last compiled`}:i.status==="missing"&&a.status==="missing"&&C(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${l}, and so is Anvil's own copy: \`${le("on")}\` recompiles them`}}function Ks(e,n){return n&&(e===n||e.startsWith(`${n}/`))?`~${e.slice(n.length)}`:e}function _t(e,n,t,r=!0){let o=ge(e.install,n,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${vt.unreadable}`];if(n&&o.status!=="ok")return[`install.json ${vt[o.status]??"cannot be used"}`];let s=(o.status==="ok"||o.status==="unkeyed")&&o.value.installs&&typeof o.value.installs=="object"?Object.values(o.value.installs):[],i=[];for(let u of s.slice(0,64)){if(!u||typeof u.real_path!="string"||typeof u.command!="string")continue;let g=us(u.settings_path??u.real_path,as(u)),h=Ks(u.settings_path??u.real_path,t);g!=="present"&&(g==="no-file"&&u.scope==="project"&&!vr(kt(kt(u.real_path)))||(g==="disabled"?r&&i.push(`${h} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):g==="missing"||g==="no-file"?i.push(`Anvil's hook was taken out of ${h} outside \`${le("off")}\`, so new sessions are not checked`):i.push(`${h} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let l=o.status==="ok"||o.status==="unkeyed"?o.value:null,a=[...Array.isArray(l?.package_dirs)?l.package_dirs:[],...typeof l?.package_dir=="string"?[l.package_dir]:[]].filter(u=>typeof u=="string"&&u.startsWith("/")).slice(0,16),c=a[a.length-1]??"",d=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return s.length>0&&a.length>0&&a.every(u=>!vr(pe(u,"package.json")))&&i.push(`the Anvil package that installed this hook is gone (${Ks(c,t)}): keep Anvil with ${j(d)} on, or remove it with ${j(d)} off --purge`),i}function Yc(e){return pe(e.state,"health.json")}function oi(e,n,t){try{let r=Yc(e),o=ge(r,null,64*1024);if(o.status==="unkeyed"&&JSON.stringify(o.value.problems)===JSON.stringify(n.problems)&&o.value.modes_source===n.modes_source&&o.value.rules_source===n.rules_source&&t-Date.parse(o.value.at)<6e4)return;sn(r,`${JSON.stringify({v:1,at:new Date(t).toISOString(),...n})}
27
+ `)}catch{}}var jg=600*1e3,eu=1440*60*1e3,si="23456789abcdefghjkmnpqrstuvwxyz",ii=8;function At(e){return Ct(e.state,"pending")}function nu(){let e=ai(ii),n="";for(let t=0;t<ii;t++)n+=si[e[t]%si.length];return n}function tu(e){return li("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var ru=()=>ai(8).toString("hex"),Ar=e=>`${li("sha256").update(e??"").digest("hex").slice(0,12)}.`;function ci(e,n,t){let r=nu(),o=ru();D(At(e));let s={v:2,id:o,code_sha256:tu(r),...n,created_at:new Date(t).toISOString(),expires_at:new Date(t+eu).toISOString()};return ei(e,Ct(At(e),`${Ar(n.session)}${o}.json`),s),{code:r,id:o}}function ou(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function ui(e,n,t,r,o,s){let i=[];try{i=Xc(e.approvals).filter(a=>a.endsWith(".json")&&!a.includes(".used-")).slice(0,2e3)}catch{return{approved:!1,forged:0}}let l=0;for(let a of i){let c=Ct(e.approvals,a),d=ge(c,n,64*1024);if(d.status==="missing")continue;if(d.status!=="ok"||d.value.v!==2||!Array.isArray(d.value.stops)){l++;continue}let u=d.value;if(Date.parse(u.expires_at)>=s&&!((u.session??null)!==(t??null)||(u.project??null)!==(r??null))&&o.every(g=>u.stops.some(h=>ou(h,g))))try{return Qc(c,Ct(e.approvals,`${a.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:l}}catch{}}return{approved:!1,forged:l}}import{lstatSync as iu,readdirSync as lu,statSync as au,utimesSync as cu}from"fs";import{join as Dn}from"path";import{posix as ym}from"path";import{posix as sm}from"path";var su=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});var Kg=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});var Vg=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"});var Zg=Object.freeze({code:"unsupported-blank",message:"a vertical tab, form feed, carriage return or Unicode space is part of a word in bash and zsh, not a separator"}),Gg=Object.freeze({code:"unsupported-parameter-expansion",message:"a line continuation inside ${ }, or a quote or backslash inside ${ } with a substitution in or after it, cannot be analyzed"});var Jg=Object.freeze({code:"unsupported-backtick-escape",message:"a backslash escape inside backticks changes the command the shell runs and cannot be analyzed"});import{createRequire as Qg}from"module";var Rr=10080*60*1e3;function di(e,n,t){let r=t.tmpdir;for(;r.endsWith("/");)r=r.slice(0,-1);return r.length>1&&e.startsWith(`${r}/`)||/^\/(private\/)?(tmp|var\/folders)\//.test(e)||/\/scratchpad\//.test(e)}function Er(e){return!!e&&/(^|[\s;&|(])(rm|rmdir|unlink|rimraf|shred|trash|truncate)(\s|$)|worktree\s+remove|\s-delete\b|(^|[;&|]\s*):\s*>/.test(e.slice(0,65536))}var Pr=3600*1e3;var uu=600,du=256*1024;function Or(e,n){return Dn(e.state,"sessions",`${n}.jsonl`)}function fi(e,n){if(!n)return{made:[],launched:[]};let t=[],r=[];for(let o of q(Or(e,n),du).split(`
28
+ `))if(o)try{let s=JSON.parse(o);typeof s.p=="string"&&s.p.startsWith("/")?t.push(s.p):typeof s.l=="string"&&r.push(s.l)}catch{}return{made:t,launched:r}}function fu(e){try{return iu(e),!0}catch{return!1}}function pi(e,n,t,r,o=null,s=Date.now()){if(!(!n||t.paths.length===0&&t.launched.length===0))try{D(Dn(e.state,"sessions"));let i=Or(e,n),l=[...r.made];for(let a of t.paths)l.some(c=>a===c||a.startsWith(`${c}/`))||fu(a)||(He(i,JSON.stringify(o?{p:a,t:s,d:o}:{p:a})),l.push(a));for(let a of t.launched)r.launched.includes(a)||He(i,JSON.stringify({l:a.slice(0,uu)}))}catch{}}function gi(e,n,t=Date.now()){if(n)try{let r=new Date(t);cu(Or(e,n),r,r)}catch{}}function mi(e,n,t,r,o=Date.now()){if(!n||!t)return[];let s=Date.now(),i=new Set,l=0;try{let a=Dn(e.state,"sessions"),c=lu(a).filter(d=>d.endsWith(".jsonl")&&d!==`${n}.jsonl`).map(d=>({f:d,at:au(Dn(a,d)).mtimeMs})).filter(d=>o-d.at>=Pr&&o-d.at<=Rr+Pr).sort((d,u)=>u.at-d.at).slice(0,200);for(let{f:d}of c){if(l>4*1024*1024||i.size>=5e3||Date.now()-s>150)break;let u=q(Dn(a,d),64*1024);l+=u.length;for(let g of u.split(`
29
+ `))if(g.includes('"d"'))try{let h=JSON.parse(g);if(typeof h.p!="string"||typeof h.t!="number"||h.d!==t||o-h.t>Rr||h.t>o)continue;if(di(h.p,t,r)&&i.add(h.p),i.size>=5e3)break}catch{}}}catch{}return[...i]}import{spawnSync as pu}from"child_process";import{lstatSync as gu,realpathSync as Nr,statSync as mu}from"fs";import{dirname as hu}from"path";function vn(e,n,t,r=!1){let o=pu(e,n,{cwd:t?V(t):void 0,encoding:"utf8",timeout:400,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}});return o.error||o.signal?null:(o.status===0||r)&&typeof o.stdout=="string"?o.stdout:null}function Ir(e){try{let n=typeof e=="string"&&e!==""?mu(e):null;return n&&n.birthtimeMs>0&&n.birthtimeMs!==n.ctimeMs?n.birthtimeMs:null}catch{return null}}function hi(e){let n=e.arg??"";try{switch(e.kind){case"ps":return vn("ps",["-A","-ww","-o","pid=,ppid=,command="]);case"port":return/^\d{1,5}$/.test(n)?vn("lsof",["-nP","-t","-i",`:${n}`],null,!0):null;case"stashes":return vn("git",["stash","list","--date=unix","--format=%gd"],e.cwd);case"branch":return vn("git",["reflog","show","--date=unix","--format=%gd %gs",`refs/heads/${n}`,"--"],e.cwd);case"ignored":return vn("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","check-ignore","-q","--",n],e.cwd);case"cwd":{if(!/^\d+$/.test(n))return null;if(process.platform==="linux")return Nr(`/proc/${n}/cwd`);let t=/^n(\/.*)$/m.exec(vn("lsof",["-a","-p",n,"-d","cwd","-Fn"],null,!0)??"")?.[1];return t?Nr(t):null}case"file":{let t=Nr(V(n));return`${B()?ue(t)??t:t} ${Ir(V(n))??""}`}case"owner":{if(B()||!n.startsWith("/"))return null;for(let t=n;;t=hu(t))try{return String(gu(t).uid)}catch{if(t==="/")return null}}}}catch{}return null}var Rt=e=>`${e.kind}\0${e.cwd??""}\0${e.arg??""}`;import{existsSync as yu,readFileSync as jr,statSync as wu}from"fs";import{dirname as bu,isAbsolute as yi,join as Wr,resolve as Tr}from"path";function wi(e){return!!e&&e.length<65536&&/\bgh\s+pr\s+(create|edit)\b/.test(e)}function ku(e,n,t){let r=n?[n]:[];for(let o of e.matchAll(/(?:^|[;&|(\n]\s*|&&\s*)cd\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/g)){let s=o[1].replace(/^["']|["']$/g,"");/[$`*?]/.test(s)||((s==="~"||s.startsWith("~/"))&&(s=t+s.slice(1)),r.push(yi(s)?s:Tr(r[r.length-1]??n??t,s)))}return[...new Set(r)].slice(0,8)}function xu(e){let n=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(e.trim());return n?`${n[1]}/${n[2]}`.toLowerCase():null}function vu(e){let n=e;for(let t=0;t<12&&n.length>1;t++,n=bu(n)){let r=Wr(n,".git");if(!yu(r))continue;let o=r;if(wu(r).isFile()){if(C(r,64*1024)!==!0)return[];let d=/^gitdir:\s*(.+)$/m.exec(jr(r,"utf8"))?.[1]?.trim();if(!d)return[];o=yi(d)?d:Tr(n,d);let u=Wr(o,"commondir");C(u,64*1024)===!0&&(o=Tr(o,jr(u,"utf8").trim()))}let s=Wr(o,"config");if(C(s,1024*1024)!==!0)return[];let i=jr(s,"utf8").slice(0,65536),l="",a=[],c=null;for(let d of i.split(`
30
+ `)){let u=/^\s*\[(\w+)(?:\s+"([^"]*)")?\]/.exec(d);if(u){c=u[1]==="remote"?u[2]??null:null;continue}let g=/^\s*url\s*=\s*(.+)$/.exec(d),h=c!==null&&g?xu(g[1]):null;h&&(c==="origin"&&!l?l=h:a.includes(h)||a.push(h))}return[l,...a.filter(d=>d!==l)]}return[]}function bi(e,n,t){let r={};try{for(let o of ku(e,n,t))r[o]=vu(o)}catch{}return r}import{closeSync as $u,constants as ki,fstatSync as Su,openSync as _u,readSync as Cu,statSync as Au}from"fs";var Ru=64*1024,Eu=8;function xi(e,n){let t={},r=[];for(let o of e.slice(0,Eu)){let s=null,i=null,l=!0;try{Au(V(o)).isFile()&&(s=_u(V(o),ki.O_RDONLY|ki.O_NONBLOCK));let a=s!==null?Su(s):null;if(s!==null&&a!==null&&a.isFile()&&a.size<=Ru){let c=Buffer.alloc(a.size),d=Cu(s,c,0,a.size,0),u=c.subarray(0,d).toString("utf8");u.includes("\0")||(i=u)}}catch(a){a.code==="ENOENT"&&(l=!1)}finally{s!==null&&$u(s)}i!==null?t[o]=i:l&&n.includes(o)&&r.push(o)}return{scripts:t,unreadable:r}}var Pu=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f؜‎‏‪-‮⁦-⁩]/g;function vi(e){return e.replace(Pu,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}import{createHash as Hm}from"crypto";import{readdirSync as Um,readFileSync as Bm,renameSync as qm,statSync as Km,unlinkSync as Vm}from"fs";import{join as Gm}from"path";var Ou=1440*60*1e3;var Nu=64*1024*1024,Iu=14*Ou;var Tu=1e3,Mu=3e3,Ii=6e4,Lu=new Set(["default","acceptEdits","plan"]),Du=new Set(["default","acceptEdits","plan","auto","dontAsk"]),Fu="cli",Mr=[2,1,153];function Hu(e){if(!e)return null;let n="";try{n=q(e,64*1024)}catch{return null}let t=[...n.matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)],r=t[t.length-1];return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function zu(e,n){if(e.CLAUDE_CODE_ENTRYPOINT!==Fu)return!1;let t=Hu(n);if(!t)return!1;for(let r=0;r<Mr.length;r++)if(t[r]!==Mr[r])return t[r]>Mr[r];return!0}var Uu=8,_n=class extends Error{constructor(n){super(n),this.name="CoreUnavailable"}},Cn=class extends Error{constructor(){super("out of time"),this.name="ClassifyTimeout"}},Hn=(e,n,t,r)=>({paths:e,payload:t,table:r,env:n.env,home:n.home,now:n.now(),cli:en(),fallbackTable:n.fallbackTable,installed:n.anvilDir!==void 0,...n.planProbe?{probe:n.planProbe}:{}});function Lr(e,n){try{return be(e.compiled,64*1024*1024)?.includes(`"${n}"`)===!0}catch{return!1}}function Fr(e,n){let t=v(e.env.CLAUDE_PROJECT_DIR)??n;return t&&t.startsWith("/")?Se(t):t}var Bu="AnvilSelfCheck",v=e=>typeof e=="string"&&e.length>0?e:null;function $n(e,n=160){let t=vi(Ds(e,4096).replace(/\s+/g," ").trim());return t.length>n?`${t.slice(0,n-1)}\u2026`:t}function qu(e){if(!e||!Nt(e))return null;let n=e;for(let t=0;t<64;t++){let r=k(n,".git"),o=!1,s=!1;try{let l=Wu(r);s=!0,o=l.isFile()}catch{}if(s)try{let l=r;if(o){if(C(r,64*1024)!==!0)return null;let d=/^gitdir:\s*(.+?)\s*$/m.exec(Ot(r,"utf8"));if(!d)return null;l=Sn(n,d[1])}if(C(k(l,"HEAD"),64*1024)!==!0)return null;let a=Ot(k(l,"HEAD"),"utf8").trim(),c=/^ref:\s*refs\/heads\/(.+)$/.exec(a);return c?c[1]:null}catch{return null}let i=Dr(n);if(i===n)return null;n=i}return null}function Si(e){if(!e||!Nt(e))return[];let n=k(e,".git");try{if(C(n,64*1024)!==!0)return[];let t=/^gitdir:\s*(.+?)\s*$/m.exec(Ot(n,"utf8"));if(!t)return[];let r=/^(.*[\\/]\.git)[\\/]worktrees[\\/][^\\/]+[\\/]?$/.exec(Sn(e,t[1]));return r?[tn(r[1])]:[]}catch{return[]}}function Ku(e,n){return(e==="Bash"||e==="PowerShell")&&n&&typeof n=="object"?n.command??null:Hr(n)}function Hr(e,n=0){return n>64?"[nested too deep]":Array.isArray(e)?e.map(t=>Hr(t,n+1)):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Hr(e[t],n+1)])):e}var ji=e=>process.platform==="win32"?$i.native(e):$i(e);function Vu(e,n){if(!n)return e;let t;try{t=ji(n).replace(/^\/private(?=\/(?:tmp|var|etc)(?:\/|$))/,"")}catch{return e}return t!==n&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))?`${n}${e.slice(t.length)}`:e}var Wi=U({Write:"file_path",Edit:"file_path",MultiEdit:"file_path",Read:"file_path",NotebookEdit:"notebook_path"}),ln=(e,n)=>[...new Set([...e,...n??[]])];function Zu(e,n,t){let r=Wi[e];if(!r||!n||typeof n!="object")return n;let o=n[r];if(typeof o!="string")return n;let s=Bn(o,t,!0);return s===o?n:{...n,[r]:s}}function Bn(e,n,t){if(!Nt(e)||e.length>4096)return e;let r=Sn(e);if(!t){let i=Dr(e);if(i===e)return e;let l=Bn(i,n,!0);return l===i?e:k(l,Un(e))}let o=[],s=e;for(;;)try{let i=Vu(k(ji(s),...o.reverse()).replace(/^\/private(?=\/(?:tmp|var|etc)(?:\/|$))/,""),n);return i===r||`/private${i}`===r?r:i}catch{o.push(Un(s));let i=Dr(s);if(i===s)return e;s=i}}function Gu(e,n,t){let r={full:{},parent:{}},o=!1;for(let s of["full","parent"])for(let i of e[s]){if(Date.now()>t)return"out-of-time";let l=B()?ue(Bn(V(i),n,s==="full"))??i:Bn(i,n,s==="full");l!==i&&(r[s][i]=l,o=!0)}return o?r:null}async function _i(e,n,t,r){if(!n)return{classification:await t.classifyInline(e,r),failure:null};let o=await t.classifyInWorker(e,r);return o.kind==="ok"?{classification:o.classification,failure:null}:{classification:null,failure:o.kind==="timeout"?{rule:"too-long-to-check"}:{rule:"could-not-check",error:o.error}}}var Ju=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function Yu(e,n,t,r){return zn("sha256").update(JSON.stringify([e??"",n,Ku(n,t),r??""])).digest("hex").slice(0,10)}function An(e){return e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:zn("sha256").update(e).digest("hex").slice(0,24):"none"}function cn(e,n){try{D(e.dir);let t=JSON.stringify(n);Buffer.byteLength(t)>3e3&&(t=JSON.stringify({...n,why:n.why.slice(0,200),target:n.target?n.target.slice(0,200):null,error:n.error?.slice(0,200)})),He(e.decisions,t)}catch{}}function Ci(e,n,t,r,o,s){cn(e,{v:1,ts:new Date(o).toISOString(),session:v(s?.session_id),tool:v(s?.tool_name)??"unknown",action:"none",verdict:"error",mode:null,delivered:"none",rule:null,slug:null,policy:null,why:`hook error at ${n}`,target:null,project:null,path:"none",ms:Math.max(0,o-r),error:$n(t instanceof Error?t.message:String(t),200)})}var Ue={stdout:"",exitCode:0},G=e=>({stdout:`${JSON.stringify(e)}
31
+ `,exitCode:0});function It(e,n){let t=v(e.env.CLAUDE_CONFIG_DIR),r=k(t?Sn(t):k(e.home,".claude"),"settings.json"),o=v(e.env.CLAUDE_PROJECT_DIR)??v(n.cwd);return o?[r,k(o,".claude","settings.local.json"),k(o,".claude","settings.json")]:[r]}function Xu(e,n,t){if(e!=="Bash"||!t)return null;let r=n&&typeof n=="object"?n.command:null,o=typeof r=="string"?r.slice(0,65536):"";if(!/\bgit\b/.test(o)||!/\b(clean|stash)\b/.test(o))return null;let s=[".claude/settings.local.json",".anvil/rules.json"].filter(a=>C(k(t,a))===!0);if(s.length===0)return[];let i=ju("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","status","--porcelain=v1","--ignored","--untracked-files=all","-z","--",...s],{cwd:t,encoding:"utf8",timeout:500,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}});if(i.status!==0||typeof i.stdout!="string")return s.map(a=>({path:k(t,a),ignored:!1}));let l=[];for(let a of i.stdout.split("\0")){let c=a.slice(0,2),d=s.find(u=>a.slice(3)===u||a.slice(3).endsWith(`/${u}`));(c==="??"||c==="!!")&&d!==void 0?l.push({path:k(t,d),ignored:c==="!!"}):(c[0]==="A"||c.includes("M"))&&d!==void 0&&l.push({path:k(t,d),ignored:!1,staged:!0})}return l}function Qu(e,n,t,r){if(["Read","Glob","Grep","LS","WebFetch","WebSearch","TodoWrite"].includes(e))return null;let o=k(n,".claude"),s=k(n,".anvil"),l=[...[".zshrc",".zshenv",".zprofile",".bashrc",".bash_profile",".bash_aliases",".profile",k(".config","fish","config.fish"),...process.platform==="win32"?[k("Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),k("Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")]:[]].map(c=>k(n,c)),o,k(o,"settings.json"),k(o,"settings.local.json"),k(o,"hooks"),k(o,"plugins"),k(n,".claude.json"),s,k(s,"claude"),k(s,"claude","modes.json"),k(s,"claude","compiled.json"),k(s,"rules.json"),k(s,"workspace-keys.json")];t&&l.push(t,k(t,"settings.json"),k(t,"hooks")),r&&l.push(k(r,".claude"),k(r,".claude","settings.json"),k(r,".claude","settings.local.json"),k(r,".mcp.json"));let a={};for(let c of l){let d=Bn(c,n,!0);d!==c&&(a[d]=c)}return Object.keys(a).length>0?a:null}function Ti(e,n){return k(e.state,"covered",An(v(n.session_id)))}function ed(e,n,t){try{let r=Ti(e,t);if(C(r)!==null||!It(n,t).some(o=>dr(o)))return;D(k(e.state,"covered")),Q(r,String(n.now()))}catch{}}async function Ai(e,n,t,r){let o=()=>It(n,t).some(i=>dr(i)),s=Ti(e,t);if(C(s)===!0)return o();if(r!=="SessionStart"||!o())return!1;for(let i=0;i<300;i+=25)if(await new Promise(l=>setTimeout(l,25)),C(s)===!0)return!0;return!1}function nd(e,n){try{D(e.state),Q(k(e.state,"plugin-seen"),String(n))}catch{}}var jt=!1;async function Mi(e,n){ae=Pt=null;let t=n.now(),r=n.anvilDir?Fe(n.anvilDir):De(n.home),o=Tn(r.install)?.cli??n.cli;Nn(o),jt=typeof o=="string";let s=null,i=v(n.entry),l=Buffer.byteLength(e)/1048576,a=`(${l.toFixed(1)} MB; Anvil reads up to 8 MB)`;if(l>Uu)return hn(i)?Ue:i==="SessionStart"?G(Ae("SessionStart",`it can't read what Claude Code sent ${a}`)):td(r,e,`this call is too large to check ${a}`,t,n);try{if(s=JSON.parse(e),!s||typeof s!="object"||i&&!v(s.hook_event_name))throw new Error("hook input is not a hook event");let c=v(s.hook_event_name),d=()=>{let g=Di(r,v(s.session_id));return g?`${JSON.stringify({systemMessage:g})}
32
+ `:null};if(n.plugin&&hn(c)&&ls(It(n,s)).has(c)&&await Ai(r,n,s,c))return Ue;if(c==="UserPromptSubmit"&&n.modelAtPrompt&&Lr(r,"never")){let g=await n.modelAtPrompt({...Hn(r,n,s,null),projectDir:Fr(n,v(s.cwd))}).catch(d);if(g)return{stdout:g,exitCode:0}}if(c==="UserPromptSubmit"&&n.budgetAtPrompt&&Lr(r,"budgets")){let g=await n.budgetAtPrompt(Hn(r,n,s,null)).catch(d);if(g)return{stdout:g,exitCode:0}}if(c==="PreModelSwitch"&&n.modelAtSwitch&&Lr(r,"model_rules")){let g=await n.modelAtSwitch({...Hn(r,n,s,null),projectDir:Fr(n,v(s.cwd))}).catch(d);if(g)return{stdout:g,exitCode:0}}if(n.helpers&&(c?.startsWith("Subagent")||s.source==="resume")&&C(k(r.dir,"helpers","live"))!==null&&await n.helpers().then(g=>g.onEvent(s,r,n.now()),()=>0),hn(c))return Ue;if(n.plugin){if(await Ai(r,n,s,c))return Ue;c==="SessionStart"&&nd(r,n.now())}else n.anvilDir!==void 0&&ed(r,n,s);if(c==="SessionStart")return await ad(r,n,s);if(c===Bu)return await ld(r,n);if(c!=="PreToolUse")return Ue;let u=await rd(s,r,n,t);return Pt?.(u)??u}catch(c){let d=(s&&v(s.hook_event_name))??i??(/"hook_event_name"\s*:\s*"SessionStart"/.test(e.slice(0,4096))?"SessionStart":null),u=s&&v(s.hook_event_name)?"its check crashed":"it can't read what Claude Code sent";if(d==="SessionStart")return G(Ae("SessionStart",u));if(d&&d!=="PreToolUse")return Ue;let g=Fn(r,s??{},u,t,n.now(),c);return Pt?.(g)??g}}function Li(e,n,t,r,o,s,i){let l=n("cwd");cn(e,{v:1,ts:new Date(s).toISOString(),session:n("session_id"),tool:n("tool_name")??"unknown",action:"claude.bash.unclassified",verdict:"hold",mode:"enforce",floor:"hold-unchecked",delivered:"deny",rule:t,slug:t,policy:null,blocked_by:"time_limit",why:r,target:null,project:l?Un(l):null,path:"none",ms:Math.max(0,s-o),...i?{error:$n(String(i),200)}:{}})}function Fn(e,n,t,r,o,s){return Li(e,i=>v(n[i]),"could-not-check",`Anvil isn't working: ${t}`,r,o,s),G(Ae("PreToolUse",t))}function td(e,n,t,r,o){let s=n.slice(0,4096);return Li(e,i=>new RegExp(`"${i}"\\s*:\\s*"([^"\\\\]{1,200})"`).exec(s)?.[1]??null,"too-long-to-check",t,r,o.now()),G({systemMessage:po(t),...Et("deny",go(t))})}async function rd(e,n,t,r){let o=t.now(),s=v(e.tool_name)??"unknown",i=v(e.session_id),l=v(e.cwd);try{D(n.counts),rs(n.counts,new Date(o))}catch{}let a=zr(n,t,o),c=a.table;if(!c)return Fn(n,e,Fi(a),r,t.now());let d=a.modes;if(t.coreProblem)return Fn(n,e,t.coreProblem,r,t.now());try{let f=c.policies.flatMap(w=>w.caps??[]);f.length>0&&new Mn(k(n.dir,"caps")).settle(f,o,{s:i,a:v(e.agent_id)??""})}catch{}let u=Fr(t,l);try{jt||Nn(c.cli),ae=od(n,c,u,i,en())}catch{ae=null}let g=fi(n,i),h=Hs(e.tool_input),m=(s==="Bash"||s==="PowerShell")&&typeof h?.command=="string"?h.command:null;gi(n,i,o);let x=Er(m)?mi(n,i,u,{tmpdir:t.tmpdir},o):[],_=x.length>0?{...g,made:[...g.made,...x.filter(f=>!g.made.includes(f))]}:g,z=null,ce=()=>{p?.makings&&pi(n,i,p.makings,g,u,o),z?.ran()},J={tool_name:s,tool_input:e.tool_input??null,cwd:l,git_branch:qu(l),project_dir:u,session_id:i,home:t.home,tmpdir:t.tmpdir,claude_config_dir:v(t.env.CLAUDE_CONFIG_DIR),project_controls:Xu(s,e.tool_input,u),control_links:Qu(s,t.home,v(t.env.CLAUDE_CONFIG_DIR),u),session_facts:{..._,startedAt:Ir(e.transcript_path),...wi(m)?{repoRemotes:bi(m,l,t.home)}:{}},want_makings:!0},p=null,A="inline",b=null,I=t.timeLimitMs??Tu,Y=Date.now()+(t.totalLimitMs??Mu),M=()=>Math.min(I,Y-Date.now()),W=null,R=null,he=()=>{W=p??W,p=null,b={rule:"too-long-to-check"}},qe={},Pn=!1,Pe=async(f,w)=>{let $=p;({classification:p,failure:b}=await _i(f,w,t,M())),!p&&$&&(W=$);let ie=p?.touched;ie&&R&&(R={full:ln(R.full,ie.full),parent:ln(R.parent,ie.parent),read:ln(R.read,ie.read),written:ln(R.written,ie.written),unknown:ln(R.unknown,ie.unknown)})};try{let f=Us(s,e.tool_input);f&&(A="worker");let w={...J,tool_input:Zu(s,J.tool_input,t.home),on_disk:"collect"};({classification:p,failure:b}=await _i(w,f,t,M()));let $=p?.touched;$&&(R={full:[...$.full],parent:[...$.parent],read:[...$.read??[]],written:[...$.written??[]],unknown:[...$.unknown??[]]});let ie=Wi[s],je=ie&&J.tool_input&&typeof J.tool_input=="object"?J.tool_input[ie]:void 0;if(typeof je=="string"&&Nt(je)&&je.length<=4096){let L=[B()?ue(je)??Sn(je):Sn(je)];R=R?{...R,full:ln(R.full,L),written:ln(R.written,L)}:{full:L,parent:[],read:[],written:L,unknown:[]}}if($&&($.full.length>0||$.parent.length>0)){let L=Gu($,t.home,Math.min(Date.now()+I,Y)),ye=(we,F)=>[...new Set([...we,...we.flatMap(Jr=>[F.full[Jr],F.parent[Jr]].filter(Xi=>typeof Xi=="string"))])];L&&L!=="out-of-time"&&R&&(R={full:[...new Set([...R.full,...Object.values(L.full)])],parent:[...new Set([...R.parent,...Object.values(L.parent)])],read:ye(R.read,L),written:ye(R.written,L),unknown:R.unknown}),L==="out-of-time"?he():L!==null&&(w={...w,on_disk:L},M()<=0?he():await Pe(w,f))}let Bt={...J.session_facts?.scripts??{}},Yn=[];for(let L=0;L<2&&p?.scriptsWanted&&p.scriptsWanted.length>0;L++){let ye=p.scriptsWanted.filter(F=>!(F in Bt)&&!Yn.includes(F));if(ye.length===0)break;if(M()<=0){he();break}let we=xi(ye,_.made);if(Object.keys(we.scripts).length===0&&we.unreadable.length===0)break;if(Object.assign(Bt,we.scripts),Yn.push(...we.unreadable),w={...w,session_facts:{...w.session_facts??{made:[],launched:[]},scripts:{...Bt},...Yn.length>0?{unreadableScripts:[...Yn]}:{}}},M()<=0){he();break}await Pe(w,f)}for(let L=0;L<3&&p?.probesWanted;L++){let ye=p.probesWanted.filter(F=>!(Rt(F)in qe));for(let F of ye)M()>400&&(qe[Rt(F)]=F.kind==="changes"?await t.answerChanges?.(F)??null:hi(F));if(ye.length===0||M()<=400){Pn=M()<=400&&ye.some(F=>F.kind==="changes");break}w={...w,session_facts:{...w.session_facts??{made:[],launched:[]},probed:{...qe}}};let we={classification:p,failure:b};try{await Pe(w,f)}catch(F){if(!(F instanceof Cn))throw F;p=null,b={rule:"too-long-to-check"}}if(!p&&b?.rule==="too-long-to-check"&&we.classification&&!ye.some(F=>F.kind==="changes")){({classification:p,failure:b}=we);break}}}catch(f){if(p&&(W=p,p=null),f instanceof _n)return Fn(n,e,"its checker can't load",r,t.now(),f);b=f instanceof Cn?{rule:"too-long-to-check"}:{rule:"could-not-check",error:f instanceof Error?f.message:String(f)}}(Pn||p?.probesWanted?.some(f=>f.kind==="changes"&&!(Rt(f)in qe)))&&(W=p,p=null,b={rule:"too-long-to-check"}),p?.action===Oi&&(c.policies.some(f=>f.allowed_actions.includes(Oi))?!b&&c.policies.some(f=>f.helpers&&de(f,u))&&(Pt=(z=(await t.helpers()).launchStep({paths:n,table:c,projectDir:u,payload:e,deps:t,modes:d,now:o,cli:en()})).finish):p={...p,action:"claude.tool.other"}),p&&c.policies.some(f=>f.narrowed?.some(w=>(w.when?.length??0)>0)||f.caps?.some(w=>w.unit==="money"))&&await Co(),p&&m!==null&&h?.dangerouslyDisableSandbox===!0&&t.lockHold&&(p=await t.lockHold(p,{anvilDir:n.dir,transcript:v(e.transcript_path)}).catch(()=>null)??p);let E=[],T="ghost",Ke=t.rates??new it(k(n.state,"rate.jsonl"),vs),Ve=tn(u),Oe=tn(t.home);if(p)try{D(n.state),{stops:E,mode:T}=kr(c,{...p,tool:s,touched:R,command:m,input:h},d,Ke,o,Ve,i,Oe,Si(u))}catch(f){b={rule:"could-not-check",error:f instanceof Error?f.message:String(f)}}else if(b&&W)try{let f=kr(c,{...W,tool:s,touched:R,command:m,input:h},d,Ke,o,Ve,i,Oe,Si(u));f.mode==="enforce"&&f.lead?.decision.verdict==="block"&&({stops:E,mode:T}=f,p=W,b=null)}catch{}p?.parse==="limited"&&!b&&!(T==="enforce"&&E[0]?.decision.verdict==="block")&&(b={rule:"could-not-check",why:"too long or nested too deep to read in full"});let y=b?.error!==void 0?await Ur(t):null;if(y)return Fn(n,e,y,r,t.now());if(b){let f={verdict:"hold",policy:null,origin:null,ruleId:b.rule,blockedBy:"time_limit",source:null};T="enforce",E=[{action:"claude.bash.unclassified",decision:f,mode:T,floor:"hold-unchecked"}]}z?.stop&&!E.some(f=>f.mode==="enforce"&&f.decision.verdict==="block")&&(E=[z.stop,...E],T="enforce");let P=p?[p.action,...p.also]:[],N=()=>({note:Di(n,i)??void 0});if(t.modelAtAction&&p&&!b&&d?.kill_switch!==!0&&c.policies.some(f=>de(f,u)&&(f.model_rules?.never?.length||[...f.model_rules?.guards??[],...f.model_rules?.second??[]].some(w=>w.kinds.some($=>P.includes($)))))&&!(T==="enforce"&&E[0]?.decision.verdict==="block")){let f=await t.modelAtAction({...Hn(n,t,e,c),kinds:P,projectDir:u}).catch(N);f?.note&&(ae=ae?`${ae}
33
+ ${f.note}`:f.note),f?.stop&&(E=[f.stop,...E],T="enforce")}if(t.budgetAtAction&&p&&!b&&d?.kill_switch!==!0&&c.policies.some(f=>f.budgets?.length)&&!(T==="enforce"&&E[0]?.decision.verdict==="block")){let f=await t.budgetAtAction(Hn(n,t,e,c)).catch(N);f?.note&&(ae=ae?`${ae}
34
+ ${f.note}`:f.note),f?.stop&&(T="enforce",E=[f.stop])}let K=p?.units??null,se=p?{tool:s,parts:br({...p,tool:s,touched:R,command:m}),touched:R,projectDir:Ve,home:Oe??null,command:m,input:h,now:o}:null,re=p&&!b?ws(c,[p.action,...p.also],u,se):[],Ze=re.length>0?new ct(k(n.dir,"caps")):null,Kn=v(e.tool_use_id)??`${An(i)}-${o}-${process.pid}`,Kr=v(e.permission_mode),Mt={s:i,a:v(e.agent_id)??""},Lt=Kr!==null&&Du.has(Kr)?{tr:Ei(v(e.transcript_path),v(e.agent_id)),call:v(e.tool_use_id),...Mt}:void 0;if(Ze&&T!=="enforce"){let f;try{f=d?.kill_switch===!0?(Ze.count(re,Kn,K,o,"ran",Lt,se),null):Ze.admit(re,Kn,K,o,void 0,se,Lt??null,Mt)}catch(w){if(f=null,d?.kill_switch!==!0){let $=w instanceof ke?w.cap??re.find(je=>je.unit==="money")??re[0]:re[0],ie={verdict:"hold",policy:"caps",origin:null,ruleId:$.id,blockedBy:"cap_unreadable",source:$.source};T="enforce",E=[{action:p.action,decision:ie,mode:T,floor:null,why:w instanceof ke?`${w.message}, so your cap ${$.text} can't count it`:`couldn't check your cap ${$.text} (${w?.code??(w instanceof Error?w.message.slice(0,60):"unreadable")})`},...E]}}if(f){let w={verdict:"hold",policy:"caps",origin:null,ruleId:f.cap.id,blockedBy:"cap_reached",source:f.cap.source};T="enforce",E=[{action:p.action,decision:w,mode:T,floor:null,why:[f,...f.also??[]].map($=>Pi($.cap,$.used,$.n)).join("; and ")},...E]}}if(Ze&&T==="enforce"&&E[0]&&p&&!b&&E[0].decision.blockedBy!=="cap_reached"&&E[0].action!=="claude.budget")try{let f=re.flatMap(w=>{try{let $={c:w,used:Ze.used(w,o,Mt),n:ut(w,K,se)};return $.used+$.n>w.limit?[$]:[]}catch{return[]}});f.length>0&&(E=[{...E[0],why:`${E[0].why??p.why}; and ${f.map(w=>Pi(w.c,w.used,w.n)).join("; and ")}`},...E.slice(1)])}catch{}let Dt=async()=>{try{p&&i&&t.moot&&Ni(At(n)).some(f=>f.startsWith(Ar(i))||/^[0-9a-f]{16}\.json$/.test(f))&&await t.moot({anvilDir:n.dir,session:i,project:u,stops:[p.action,...p.also].map((f,w)=>({kind:f,target:w?null:p.attributes.target??null})),now:o})}catch{}},O=E[0];if(!O)return ce(),await Dt(),an(Ue,n,i,a.problems,o);let Vn=T==="enforce"?E.filter(f=>f.mode==="enforce"):E,qi=f=>b?b.why??(b.rule==="too-long-to-check"?"too long to check in time":"could not be checked"):f.why?f.why:p&&f.action===p.action?p.why:tt(f.action),Zn=f=>f.target!==void 0?f.target:p&&f.action===p.action?p.attributes.target??null:null,Ki=f=>f.replace(/ ?\((?:a command with no rule of its own, )?read by its (?:words|name)\)/g,"").trim(),Vi=f=>{let w=Ki(qi(f));if(f.decision.ruleId==="hold-delete-bursts")return`more than 20 recursive deletes in a minute (this one ${w})`;if(f.decision.ruleId==="hold-helper-bursts")return"more than 20 helper agent launches in 10 minutes";if(f.decision.ruleId==="hold-repeated-side-effect")return`the same app change again within 10 minutes (${w})`;let $=Zn(f);return f.decision.ruleId==="block-protected-targets"&&!f.floor&&$&&/\/\.git(\/|$)/.test($)?`deletes the .git of another repository inside the project (${u&&$.startsWith(`${u}/`)?$.slice(u.length+1):$})`:w},X=$n((O.decision.verdict==="block"?[O]:Vn).map(Vi).join("; ")),Gn=O.decision.verdict==="block"?"block":"hold",Vr=b?null:Zn(O),Ge={v:1,ts:new Date(o).toISOString(),session:i,agent_id:v(e.agent_id),agent_type:v(e.agent_type),tool:s,action:O.action,verdict:Gn,mode:T,rule:O.decision.ruleId,slug:co(O.decision.ruleId,O.decision.origin,O.action,O.floor),...O.floor?{floor:O.floor}:{},policy:O.decision.policy,blocked_by:O.decision.blockedBy,why:X,target:Vr?$n(Vr,200):null,project:u?Un(u):null,path:A,...b?.error?{error:$n(b.error,200)}:{},...E.length>1?{also:E.slice(1).map(f=>({action:f.action,verdict:f.decision.verdict,mode:f.mode,rule:f.decision.ruleId,...f.floor?{floor:f.floor}:{}}))}:{},...p?.housekeeping&&O.action===p.action?{housekeeping:!0}:{}};if(T==="ghost"){ce(),await Dt();let f=id(n,i,o);if(cn(n,{...Ge,delivered:f?"note":"none",ms:t.now()-r}),!f)return an(Ue,n,i,a.problems,o);let w=Gn==="hold"&&!p?.housekeeping&&O.decision.blockedBy!=="narrowed_rule"&&Te[O.action]?.slug===Ge.slug?Ge.slug:null;return an(G({systemMessage:ho(Gn,X,w)}),n,i,a.problems,o)}let Ne=en();if(Gn==="block"){cn(n,{...Ge,delivered:O.action==="claude.advisor.second"?"pause":"deny",ms:t.now()-r});let f=O.said,w=f?.user??(O.floor?vo(X):ko(X,Ne)),$=f?.agent??(O.floor?$o(X):xo(X));return an(G({systemMessage:w,...Et("deny",$)}),n,i,a.problems,o)}let Ft=b!==null||Ju.has(s)||s.startsWith("mcp__")?`input:${Yu(i,s,e.tool_input,l)}`:null,Zr=Vn.map(f=>({kind:f.action,target:b?Ft:Ft?`${Zn(f)??""}#${Ft}`:Zn(f)})),Zi=xe(n),Je={approved:!1,forged:0};try{Je=ui(n,Zi,i,u,Zr,o)}catch{Je={approved:!1,forged:0}}let Ht=Je.forged>0?[...a.problems,`${Je.forged===1?"an approval was":`${Je.forged} approvals were`} written outside \`${j(Ne)} allow\`; ${Je.forged===1?"it releases":"they release"} nothing`]:a.problems;if(Je.approved){ce(),await Dt();try{Ze?.count(re,Kn,K,o,"ran",Lt,se)}catch(f){Ci(n,"caps",f instanceof Error?f:new Error(String(f)),r,t.now(),e)}return Ri(Ke,Vn,i,o),cn(n,{...Ge,delivered:"approved",ms:t.now()-r}),an(G({systemMessage:So(X)}),n,i,Ht,o)}let zt=v(e.permission_mode),Gi=!/^sdk-/.test(v(t.env.CLAUDE_CODE_ENTRYPOINT)??"");if(zt!==null&&Gi&&O.action!=="claude.budget"&&(Lu.has(zt)||zt==="bypassPermissions"&&zu(t.env,v(e.transcript_path)))){b||ce();try{Ze?.count(re,Kn,K,o,"ask",{tr:Ei(v(e.transcript_path),v(e.agent_id)),call:v(e.tool_use_id),s:i,a:v(e.agent_id)??""},se)}catch($){Ci(n,"caps",$ instanceof Error?$:new Error(String($)),r,t.now(),e)}cn(n,{...Ge,delivered:"ask",call:v(e.tool_use_id),transcript:v(e.transcript_path),ms:t.now()-r});let f=v(e.transcript_path),w=v(e.tool_use_id);return f&&w&&Ri(Ke,Vn,i,o,{transcript:f,call:w}),an(G(Et("ask",bo(O.floor?`${X} \xB7 always on`:X))),n,i,Ht,o)}let Ie=null,Ut,Gr=null;try{let f=m??(/^(Agent|Task)$/.test(s)?p?.why??s:e.tool_input&&typeof e.tool_input=="object"?JSON.stringify(e.tool_input):null);({code:Ie,id:Ut}=ci(n,{session:i,project:u,stops:Zr,why:X,project_name:u?Un(u):null,...f?{command:`${s}: ${$n(f,240)}`}:{}},o))}catch(f){Ie=null;let w=f.code;Gr=w==="ENOSPC"||w==="EDQUOT"?"the disk is full, so the hold could not be recorded: free some space, then ask Claude to try again":w==="EACCES"||w==="EPERM"||w==="EROFS"?`Anvil's folder (${n.dir}) cannot be written: fix that, then ask Claude to try again`:null}cn(n,{...Ge,delivered:"deny",...Ut?{hold:Ut}:{},ms:t.now()-r}),Ie&&t.notify?.({session:i,transcript:v(e.transcript_path),why:X,cli:Ne});let Jn=Ie?O.said:void 0,Ji=Jn?Jn.user.replace("{why}",()=>X).replace("{code}",Ie):yo(X,Ne,Ie,Gr??(O.floor?`to repair Anvil, run in a terminal: ${j(Ne)} on`:`to repair Anvil, run in a terminal: ${j(Ne)} on (or change the rule: ${j(Ne)} rules edit)`),O.floor!==void 0&&O.floor!==null),Yi=Jn?Jn.agent:z?.stop===O?z.agent(Ie!==null):wo(X,Ie!==null,Ne);return an(G({systemMessage:Ji,...Et("deny",Yi)}),n,i,Ht,o)}function Ri(e,n,t,r,o){if(!(!t||!e.restart)){for(let s of n)if(!(!s.decision.ruleId||!ro.has(s.decision.ruleId)))try{e.restart(sr(s.action,t),r,o)}catch{}}}function Et(e,n){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:e,permissionDecisionReason:n}}}function zr(e,n,t){let r=xe(e),o=n.anvilDir!==void 0,s=ri(e,n.fallbackTable,r,{installed:o}),i=ti(e,r,{installed:o}),l=[];try{l=o?_t(e,r,n.home):[]}catch{l=[]}let a=v(n.env.ANVIL_HOOK_NODE_FALLBACK),c=o&&a?`the Node Anvil was set up with ${v(n.env.ANVIL_HOOK_NODE_WHY)==="broken"?"could not start":"is gone"}, so it runs under ${a}; run ${le("on")} to set it up again`:null,d=s.value?Kt(s.value):dn,u=dn.filter(x=>!d.includes(x));jt||Nn(s.value?.cli);let g=en(),h=u.length>0?`its always-on stops for ${u.map(x=>x.short).join("; ")} are missing from the rules it judges with, so it may not stop those calls; run ${j(g)} on`:null,m=[s.problem,i.problem,...l,c,h].filter(x=>typeof x=="string"&&x.length>0);return oi(e,{problems:m,modes_source:i.source,rules_source:s.source},t),{table:s.value,modes:i.value,problems:m}}function an(e,n,t,r,o,s=!1){let i=[];if(r.length>0&&(s||sd(n,t,r,o))){let a=r[0];i.push(a.includes("Anvil is not checking")?a:mo(a,r.length-1))}if(ae&&i.push(ae),ae=null,i.length===0)return e;let l=i.join(`
35
+ `);if(!e.stdout)return G({systemMessage:l});try{let a=JSON.parse(e.stdout),c=typeof a.systemMessage=="string"?a.systemMessage:null;return G({...a,systemMessage:c?`${c}
36
+ ${l}`:l})}catch{return e}}function Ei(e,n){if(!e||n===null)return e;if(!/^[A-Za-z0-9_-]{1,80}$/.test(n)||!e.endsWith(".jsonl"))return null;let t=k(e.slice(0,-6),"subagents"),r=`agent-${n}.jsonl`;if(C(k(t,r),Number.MAX_SAFE_INTEGER)===!0)return k(t,r);try{for(let o of Ni(k(t,"workflows")).slice(0,64))if(C(k(t,"workflows",o,r),Number.MAX_SAFE_INTEGER)===!0)return k(t,"workflows",o,r)}catch{}return null}function Pi(e,n,t){let r=a=>String(Math.round(a*100)/100),o=a=>e.unit==="money"&&e.money?ks(a,e.money):e.unit==="usd"?`$${r(a)}`:r(a),s={minute:"in the last minute",hour:"in the last hour",day:"today",week:"this week"}[e.window],i=n<e.limit?` + ${o(t)} in this call`:"",l=e.window==="day"?"; resets at midnight":e.window==="week"?"; resets Monday":"";return`cap reached: ${e.text} (${o(n)} used ${s}${i}${l})`}function Di(e,n){try{let t=k(e.state,`note-${An(n)}.meter`);if(C(t)!==null)return null;D(e.state),Q(t,"")}catch{}return`${H("Anvil")} budgets and model rules can't be checked${_e("fix it",le("on"))}`}var ae=null,Pt=null,Oi="claude.agent.helper";function od(e,n,t,r,o){let s=[],i=new Set,l=d=>{try{let u=C(d,262144);return u===null?"gone":u===!1?"unreadable":zn("sha256").update(Ot(d,"utf8")).digest("hex")}catch{return"unreadable"}};for(let d of n.policies){if(!d.from||!de(d,t))continue;i.add(d.from.file);let u=l(d.from.file);u!==d.from.sha256&&s.push(`${d.origin==="project"?".anvil/rules.md":"~/.anvil/rules.md"} ${u==="gone"?"was removed":u==="unreadable"?"can't be read":"changed"}`)}let a=s.length>0,c=t?k(t,".anvil","rules.md"):null;if(c&&!i.has(c)&&l(c)!=="gone"&&s.push(".anvil/rules.md isn't applied yet in this folder"),s.length===0)return null;try{D(e.state);let d=k(e.state,`rules-${An(r)}`),u=zn("sha256").update(s.join("|")).digest("hex").slice(0,16);if(q(d,64).trim()===u)return null;Q(d,u)}catch{}return`${H("Anvil")} ${s.join(" \xB7 ")}${a?" \xB7 the rules applied before still hold":""}${_e("apply it",`${j(o)} sync`)}`}function sd(e,n,t,r){try{D(e.state);let o=k(e.state,`problem-${An(n)}`),s=zn("sha256").update(t.join(`
37
+ `)).digest("hex").slice(0,16),[i,l]=q(o,128).trim().split(" ");return i===s&&Number.isFinite(Number(l))&&r-Number(l)<Ii&&r>=Number(l)?!1:(Q(o,`${s} ${r}`),!0)}catch{return!0}}function id(e,n,t){try{D(e.state);let r=k(e.state,`note-${An(n)}`),o=Number(q(r,64).trim());return Number.isFinite(o)&&t-o<Ii&&t>=o?!1:(Q(r,String(t)),!0)}catch{return!1}}async function Ur(e){if(e.coreProblem)return e.coreProblem;try{return(await e.classifyInline({tool_name:"Bash",tool_input:{command:"git push origin main"},cwd:e.tmpdir,git_branch:"feature",project_dir:e.tmpdir,session_id:null,home:e.home,tmpdir:e.tmpdir,claude_config_dir:null,on_disk:null,project_controls:null,control_links:null},2e3)).action==="claude.bash.git.push_main"?null:"its checker answered a known call wrongly"}catch{return"its checker can't load"}}async function ld(e,n){let t=n.now(),r=zr(e,n,t),o=await Ur(n),s=[...r.table?[]:["no rules are compiled"],...o?[o]:[],...r.problems],i=xe(e),l=n.anvilDir!==void 0?_t(e,i,n.home).filter(d=>!_t(e,i,n.home,!1).includes(d)):[],a=s.filter(d=>!l.includes(d)),c={checking:!!r.table&&o===null,ok:a.length===0,problems:s,mode:r.table?Yt(r.table,r.modes).text:"none",rules:r.table?Gt(r.table):0};return G({anvil_self_check:c})}async function ad(e,n,t){let r=n.now();try{await n.sessionChores?.(e.dir,r)}catch{}let o=zr(e,n,r),s=await Ur(n),i=o.table;if(!i)return G(Ae("SessionStart",Fi(o)));if(s)return G(Ae("SessionStart",s));let{enforced:l}=Yt(i,o.modes);jt||Nn(i.cli);let a=en(),c=[...o.problems],d=[];try{d=n.anvilDir!==void 0&&n.startProblems?await n.startProblems({anvilDir:e.dir,home:n.home,files:It(n,t),cli:a}):[]}catch{d=[]}for(let x of d)c.some(_=>_.includes(x)||x.includes(_))||c.push(x);let u=ao(o.modes),g=null;try{g=await n.sessionWords?.()??null}catch{g=null}let h=g?g.sessionLine(l,Jt(i).filter(x=>Te[x]).length,c,a,u?.what??null):`${H("Anvil is on")} ${fo}`,m=g?g.sessionContext(Kt(i).map(x=>x.context),l.filter(x=>!Vt.has(x)).map(tt),a,u?.context??null):"Anvil (anvilcontrol.ai) checks every tool call in this session before it runs. Changing Anvil is the user's to do, in their own terminal.";return G({systemMessage:h,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:m}})}function Fi(e){return e.problems.join(" ").includes("seal key")?"its seal key is missing or damaged":/^compiled\.json .*changed outside/m.test(e.problems.join(`
38
+ `))?"its rules were changed outside Anvil":"its rules are missing"}import{spawn as cd}from"child_process";import{readFileSync as ud,statSync as dd}from"fs";import{join as Rn}from"path";function fd(e){try{let n=JSON.parse(ud(e,"utf8"));return Object.values(n??{}).some(t=>typeof t=="object"&&t!==null&&t.active===!0&&typeof t.apiKey=="string"&&t.apiKey!=="")}catch{return!1}}var pd="sync-next",gd="sync-pulled",md="claude-sync.js",hd=6e4,yd=5*6e4;function zi(e,n){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||Rn(n,".anvil","workspace-keys.json")}function wd(e,n){if(e.ANVIL_API_KEY?.trim())return!0;try{return dd(zi(e,n)).isFile()}catch{return!1}}var bd=10*6e4;function Ui(e){try{let n=e.env.ANVIL_CLAUDE_SYNC?.trim().toLowerCase();if(n==="off"||n==="0"||n==="false")return!1;if(!wd(e.env,e.home))return C(Rn(e.paths.state,"sync-active.json"))===!0&&Hi(e.paths,e.now),!1;let t=Rn(e.binDir,md);if(C(t)!==!0)return!1;let r=Rn(e.paths.state,pd),o=Number(q(r,64).trim());if(Number.isFinite(o)&&o>e.now&&o-e.now<=1440*6e4&&!(e.sessionStart===!0&&kd(e.paths,e.now)))return!1;D(e.paths.state);let s=zi(e.env,e.home);return!e.env.ANVIL_API_KEY?.trim()&&(C(s,1024*1024)!==!0||!fd(s))?(Hi(e.paths,e.now),Q(r,String(e.now+bd)),!1):(Q(r,String(e.now+hd)),(e.start??xd)(e.execPath,t,e.paths.dir),!0)}catch{return!1}}function kd(e,n){let t=Number(q(Rn(e.state,gd),64).trim());return!(Number.isFinite(t)&&t>0&&t<=n+6e4&&n-t<=yd)}function Hi(e,n){let t=Rn(e.state,"signed-out.json"),r=Tn(t);typeof r?.open!="string"&&Q(t,`${JSON.stringify({open:new Date(n).toISOString(),windows:Array.isArray(r?.windows)?r.windows:[]})}
39
+ `)}function xd(e,n,t){let r=cd(e,[n],{detached:!0,stdio:"ignore",cwd:t,env:process.env,windowsHide:!0});r.on("error",()=>{}),r.unref()}var te=En(_d(import.meta.url)),Rd=Date.now(),qr=ve(te,"claude-hook-core.js"),me=Tt(te)==="bin"&&Tt(En(te))==="claude"&&Tt(En(En(te)))===".anvil"?En(te):void 0,Ed=!me&&Tt(te)==="bin"&&Wt(ve(En(te),".claude-plugin","plugin.json")),Bi=null;async function Pd(e){try{(await import("module")).enableCompileCache?.(ve(me??De(e).dir,"cache"))}catch{}}function un(){return Bi??=import(Br(qr).href),Bi}var Od=null,Be=()=>Od??=import(Br(ve(te,"claude-meter.js")).href),Nd=new Cd.Script("globalThis.__anvilClassify()");async function Id(e,n){let t;try{t=await un()}catch(s){throw new _n(s instanceof Error?s.message:String(s))}let{classifyRequest:r}=t;if(typeof r!="function")throw new _n("no classifier in its file");let o=globalThis;o.__anvilClassify=()=>r(e);try{return Nd.runInThisContext({timeout:n})}catch(s){throw s.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new Cn:s}finally{delete o.__anvilClassify}}function jd(e,n){return new Promise(t=>{let r=!1,o=(l,a)=>{r||(r=!0,clearTimeout(i),a&&a.terminate().catch(()=>{}),t(l))},s;try{s=new Ad(qr,{workerData:{anvilClaudeHook:!0,request:e}})}catch(l){t({kind:"error",error:l instanceof Error?l.message:String(l)});return}let i=setTimeout(()=>o({kind:"timeout"},s),n);s.once("message",l=>{o(l.ok&&l.classification?{kind:"ok",classification:l.classification}:{kind:"error",error:l.error??"worker failed"},s)}),s.once("error",l=>o({kind:"error",error:l.message},s)),s.once("exit",l=>o({kind:"error",error:`worker exited (${l}) without an answer`}))})}async function Wd(){try{let e=await Be(),n=e.probeAccount?.(process.env)??null;if(!n||!e.runPlanProbe)return;e.runPlanProbe({paths:me?Fe(me):De(qn()),env:process.env,now:()=>Date.now(),account:n})}catch{}}async function Td(){process.argv[2]==="--plan-probe"&&(await Wd(),process.exit(0));let e="",n=null,t=!1,r="";try{let s=qn();await Pd(s);try{r=vd(0,"utf8")}catch{r=""}if(r.length<64*1024&&r.includes("SessionStart"))try{t=JSON.parse(r).hook_event_name==="SessionStart"}catch{t=!1}e=(await Mi(r,{home:s,...me?{anvilDir:me}:{},tmpdir:Sd(),env:process.env,now:()=>Date.now(),classifyInline:Id,classifyInWorker:jd,...Ed?{plugin:!0,fallbackTable:ve(te,"baseline.json")}:{},...me&&Wt(ve(te,"baseline.json"))?{fallbackTable:ve(te,"baseline.json")}:{},coreProblem:Wt(qr)?null:"its checker file is missing",entry:process.env.ANVIL_HOOK_EVENT,cli:process.env.ANVIL_HOOK_CLI,startProblems:async l=>(await un()).startProblems?.(l)??[],sessionChores:async(l,a)=>(await un()).sessionChores?.(l,a),answerChanges:async l=>(await un()).answerChanges?.(l)??null,sessionWords:async()=>{let l=await un();if(!l.sessionLine||!l.sessionContext)throw new Error("an older classifier file");return{sessionLine:l.sessionLine,sessionContext:l.sessionContext}},notify:l=>{n=l},planProbe:{hookFile:ve(te,"claude-hook.js"),node:process.execPath},budgetAtPrompt:async l=>(await Be()).budgetAtPrompt(l),budgetAtAction:async l=>(await Be()).budgetAtAction(l),modelAtAction:async l=>{let a=await Be();return a.modelRulesAt?a.modelRulesAt(l):a.modelAtAction(l)},modelAtSwitch:async l=>(await Be()).modelAtSwitch(l),modelAtPrompt:async l=>(await Be()).modelAtPrompt(l),helpers:()=>import(Br(ve(te,"claude-helpers.js")).href),moot:async l=>(await un()).mootHolds?.(l),lockHold:async(l,a)=>(await Be()).lockHold?.(l,a)??null})).stdout}catch{let s=null;try{s=t?"SessionStart":JSON.parse(r).hook_event_name??null}catch{s=null}e=s==="SessionStart"||s==="PreToolUse"||s===null?`${JSON.stringify(Ae(s??"PreToolUse","its check crashed"))}
40
+ `:""}try{e&&$d(1,e)}catch{}if(globalThis.__anvilHookAnswered=!0,n)try{(await un()).heldNotice?.({...n,anvilDir:me??De(qn()).dir,now:Date.now(),env:process.env})}catch{}(hn(process.env.ANVIL_HOOK_EVENT)||/"hook_event_name"\s*:\s*"(?:UserPromptSubmit|SubagentStart|SubagentStop|PreModelSwitch)"/.test(r.slice(0,4096)))&&process.exit(0);let o=me??De(qn()).dir;Wt(ve(o,"locks.json"))&&await Be().then(s=>s.lockRun?.({anvilDir:o,input:r,sessionStart:t,now:Date.now()}),()=>0);try{let s=qn();Ui({paths:me?Fe(me):De(s),binDir:te,home:s,env:process.env,now:Rd,execPath:process.execPath,sessionStart:t})}catch{}process.exit(0)}Td();