@useanvil/claude-code 0.0.0-stage → 0.8.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.
@@ -0,0 +1,38 @@
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(`
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(`
11
+ `,t)+1,e.indexOf(`
12
+ `,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===`
14
+ `){let g=e.slice(i,a).trim();n.push({start:s,end:a,op:`
15
+ `}),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
+ `||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();