@useanvil/claude-code 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +703 -0
- package/README.md +128 -38
- package/dist/Anvil +0 -0
- package/dist/claude-approve.js +23 -0
- package/dist/claude-conditions.js +19 -12
- package/dist/claude-helpers.js +9 -9
- package/dist/claude-hook-core.js +88 -80
- package/dist/claude-hook.js +38 -37
- package/dist/claude-meter.js +52 -48
- package/dist/claude-powershell.cjs +17 -17
- package/dist/claude-sync.js +26 -26
- package/dist/cli/claude-main.js +5392 -2510
- package/docs/coding-agents/YOUR-RULES.md +507 -654
- package/package.json +1 -1
package/dist/claude-hook.js
CHANGED
|
@@ -1,40 +1,41 @@
|
|
|
1
|
-
import{existsSync as Wt,readFileSync as vd,writeSync as Sd}from"fs";import{homedir as qn,tmpdir as $d}from"os";import{basename as Tt,dirname as En,join as ve}from"path";import{fileURLToPath as _d,pathToFileURL as Br}from"url";import Cd from"vm";import{Worker as Ad}from"worker_threads";import{spawnSync as Op}from"child_process";import{createHash as Ip}from"crypto";import{chmodSync as Wp,existsSync as Tp,lstatSync as ha,mkdirSync as Mp,readdirSync as Lp,readFileSync as ya,readlinkSync as wa,realpathSync as os,rmdirSync as Dp,statSync as lt,unlinkSync as Fp,writeFileSync as Hp}from"fs";import{dirname as ba,isAbsolute as Up,join as Bp,relative as qp,resolve as ka}from"path";var Se={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Qi(e){if(!e){let a=c=>c;return{on:!1,bold:a,dim:a,blue:a,grey:a,amber:a,mark:a,field:a}}let n=e==="truecolor",t=a=>c=>`\x1B[${a}m${c}\x1B[0m`,r=t(n?"38;2;76;139;255":"38;5;69"),o=t(n?"38;2;130;134;150":"90"),s=t(n?"38;2;245;165;36":"38;5;214"),i=t(n?"38;2;34;197;94":"32"),l={[Se.on]:r,[Se.blocked]:r,[Se.held]:r,[Se.next]:r,[Se.watching]:o,[Se.problem]:s,[Se.ok]:i};return{on:!0,bold:t("1"),dim:t("2"),blue:r,grey:o,amber:s,mark:a=>(l[a]??(c=>c))(a),field:a=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${nl(a)}\x1B[0m`}}var Dd=Qi(!1),el=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function nl(e){return e.replace(el,"")}var We="claude";function Ye(e){return e==="ghost"||e==="enforce"?e:null}function Xr(e,n){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let t=Ye(e.services?.[We]?.actions?.[n]?.mode);return t||(Ye(e.default_mode)??"ghost")}function qt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[We]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function Xn(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function Qr(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:qt(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[We]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[We]?.actions??{}};for(let i of t)s[i]={mode:n};return{version:1,kill_switch:o.kill_switch===!0,default_mode:Ye(o.default_mode)??"ghost",services:{...o.services??{},[We]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function tl(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:Ye(e.default_mode)==="enforce"?!0:Object.values(e.services?.[We]?.actions??{}).some(n=>Ye(n?.mode)==="enforce")}var Qn="claude.agent.controls";function et(e,n){return n===Qn&&tl(e)?"enforce":Xr(e,n)}var Yr={off:0,ghost:1,enforce:2};function On(e,n){return e===null?n:n===null?e:Yr[n]>Yr[e]?n:e}function eo(e,n){return!e||typeof e!="object"?null:Ye(e.services?.[We]?.actions?.[n]?.mode)??(Ye(e.default_mode)==="enforce"?"enforce":null)}function no(e,n,t,r=!1){let s=On(eo(e,n),t)??(r&&Xn(e)?"enforce":et(e,n));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function to(e,n,t){return On(eo(e,n),t)===null&&Xn(e)&&et(e,n)!=="enforce"}function $e(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function U(e){return Object.assign(Object.create(null),e)}var dn=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],rl="home and project wipes and force-pushes to main",Vd=`always blocking ${rl}`,ol=new Map(dn.map(e=>[e.id,e]));function Xe(e){return ol.get(e)}var sl=U({"block-protected-targets":"protect","hold-delete-bursts":"stop-loops","hold-repeated-side-effect":"stop-loops","hold-helper-bursts":"stop-helper-bursts"}),ro=new Set(["hold-delete-bursts","hold-helper-bursts"]),oo=new Set(dn.flatMap(e=>Object.keys(e.slugs)));var so=U({"block-protected-targets":["protect"],"hold-delete-bursts":["stop-loops"],"hold-repeated-side-effect":["stop-loops"],"hold-helper-bursts":["stop-helper-bursts"],"hold-risky-actions":["keep-anvil-on","keep-keys-in"]});function Kt(e){let n=new Set(dl(e));return dn.filter(t=>!Object.entries(so).some(([r,o])=>o.includes(t.id)&&n.has(r)))}var Vt=new Set([Qn,"claude.bash.secrets.expose"]),il=new Set(["claude.file.read_secret","claude.file.write_secret","claude.bash.secrets.print"]),ll=/^(?:\.ssh\/(?!known_hosts|authorized_keys|config$|environment$|rc$)[^/]+(?<!\.pub)|\.aws\/credentials|\.kube\/config|\.docker\/config\.json|\.gnupg\/[^/].*|\.config\/gh\/hosts\.yml|\.npmrc|\.pypirc|\.netrc|\.git-credentials|\.pgpass|\.vault-token|\.config\/gcloud\/[^/].*|\.azure\/[^/].*|\.config\/solana\/id\.json)$/;function al(e,n){if(e.startsWith("~/")){let o=$e(e.slice(2));return o.startsWith("/")?o.slice(1):o}let t=n?$e(n):null,r=$e(e);return t&&t!=="/"&&r.startsWith(`${t}/`)?r.slice(t.length+1):null}function cl(e,n){if(!e)return!1;let t=al(e,n);return t!==null&&ll.test(t)}function ul(e,n,t,r=[]){if(!e||!n)return!0;let o=$e(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`===$e(a)))return!0;let l=$e(n)||"/";return l===i||i==="/"||l.startsWith(`${i}/`)}function Zt(e){if(e.decision.verdict==="allow")return null;let n=e.baseline.ruleId?sl[e.baseline.ruleId]:void 0;if(n==="protect"){if(!(e.service==="fs.git_dir"&&!ul(e.target,e.projectDir,e.home,e.histories)))return Xe("protect")}else if(n)return Xe(n);return e.action===Qn?Xe("keep-anvil-on"):e.action==="claude.bash.secrets.expose"||il.has(e.action)&&cl(e.target,e.home)?Xe("keep-keys-in"):null}function io(e,n,t){return e.id==="keep-keys-in"&&n!=="claude.bash.secrets.expose"?"credentials":e.slugs[t]!==void 0?t:Object.keys(e.slugs)[0]}function dl(e){let n=new Set(e.policies.filter(t=>t.origin==="baseline").flatMap(t=>t.rules.map(r=>r.id)));return Object.keys(so).filter(t=>!n.has(t))}var Te=U({"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"discard uncommitted work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}});function ao(e){if(!Xn(e))return null;let n="cluster, cloud and database destroys";return{what:n,context:`It also holds ${n} and cloud-credential prints, until the user sets a mode for their kinds.`}}var lo=U({"block-protected-targets":{slug:"protected",text:"never: home, root, project root, .git, main, every process"},"hold-repeated-side-effect":{slug:"repeat",text:"the same MCP action again within 10 minutes"},"hold-delete-bursts":{slug:"delete-burst",text:"more than 20 deletes in a minute"},"hold-helper-bursts":{slug:"helper-burst",text:"more than 20 helper launches in 10 minutes"},"too-long-to-check":{slug:"too-long-to-check",text:"too long to check in time"},"could-not-check":{slug:"could-not-check",text:"could not be checked"}});function nt(e,n){return e&&lo[e]?lo[e].slug:!e||e==="hold-risky-actions"?Te[n]?.slug??n:e.replace(/@.*$/,"")}function co(e,n,t,r){return r&&n==="baseline"?io(Xe(r),t,nt(e,t)):!r&&e==="block-protected-targets"?Te[t]?.slug??t:nt(e,t)}function tt(e){return Te[e]?.text??e}function Gt(e){let n=new Set(oo);for(let t of e.policies)for(let r of t.rules)if(r.primitive!=="durable_key_dedup")if(r.id==="hold-risky-actions")for(let o of r.applies_to??[])n.add(nt(null,o));else n.add(nt(r.id,""));return n.size}function Jt(e){let n=new Set;for(let t of e.policies)for(let r of t.rules)if(r.primitive!=="durable_key_dedup")for(let o of r.applies_to??t.allowed_actions)n.add(o);return[...n]}function Yt(e,n){let t=Jt(e).filter(o=>Te[o]),r=t.filter(o=>et(n,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===t.length?"enforce":`${r.length} enforced, rest ghost`}}var Xt="anvil-claude";function j(e){let n=e.trim();return n===Xt||n.endsWith(` ${Xt}`)||n.endsWith(`/${Xt}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var uo="\u{1F539}",H=e=>`${uo} ${e} ${uo}`;var Qe=e=>`
|
|
2
|
-
${
|
|
3
|
-
${n}${t?Qe(`Then ${t}.`):""}`}var
|
|
4
|
-
${n}`}var
|
|
5
|
-
Every command waits until it's fixed, so nothing runs unchecked.${t?Qe(t):""}${_e("fix it",`${j(n)} on`)}${_e("turn Anvil off instead",`${j(n)} off`)}`}function hl(e,n=Ce,t){return`${H("Anvil isn't working")} ${e}, so Claude Code holds every tool call until the user fixes it${t?` (${t})`:""} by running \`${j(n)} on\` in a terminal (not in this chat: Claude can't run it). Tell the user, then stop and wait. Do not retry, and do not try another way or another tool.`}function po(e){return`${H("Held by Anvil")} ${e}${Qe("Claude can do it in smaller steps, each one checked")}`}function go(e){return`${H("Held by Anvil")} ${e}, so nothing ran. Do it in smaller steps, each under that size.`}function Ae(e,n,t=Ce,r){let o=hl(n,t,r);return{systemMessage:ml(n,t,r),hookSpecificOutput:e==="SessionStart"?{hookEventName:e,additionalContext:o}:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:o}}}function mo(e,n,t=Ce){let r=yl(e.replace(/^Anvil:? /,""),t);return`${H("Anvil")} ${r.said}${n>0?` (and ${n} more)`:""}${r.fix??_e("see details",`${j(t)} report`)}`}function yl(e,n){let t=e.lastIndexOf(` run ${j(n)} on`),r=t>0?e[t-1]:"";if(t<=0||r!==":"&&r!==";")return{said:e,fix:null};let o=e.slice(t+` run ${j(n)} on`.length);return o!==""&&!/^ to [a-z][a-z ]*$/.test(o)?{said:e,fix:null}:{said:e.slice(0,t-1),fix:_e("fix it",`${j(n)} on`)}}function ho(e,n,t=null){return`${H(`Anvil would've ${e==="block"?"blocked this":"held this for review"}`)} ${n} \xB7 it ran${t?_e("hold these for your OK",`${j(Ce)} enforce ${t}`):""}`}function yo(e,n,t,r,o=!1){let s=`${H("Held by Anvil for your OK")} ${o?`${e} \xB7 always on`:e}`;return t?`${s}${fl("allow it once",`${j(n)} allow ${t}`,"tell Claude to go on")}`:`${s}${Qe(`it can't be allowed right now: ${r}`)}`}function wo(e,n,t=Ce){return n?`${H("Held by Anvil")} ${e}. Nothing ran. Tell the user: to allow it once, ${gl(t,"tell you to go on")}. When they say so, run exactly the same command again, with nothing added to it (the OK covers one call). Do not try another way.`:`${H("Held by Anvil")} ${e}. Nothing ran, and it can't be allowed right now; the user has been told how to fix that. Do not try another way.`}function bo(e){return`${H("Held by Anvil for your OK")} ${e}`}function ko(e,n){return`${H("Blocked by Anvil")} ${e}${_e("change the rule",`${j(n)} rules edit`)}`}function xo(e){return`${H("Blocked by Anvil")} ${e}. Nothing ran, and it can't be allowed once. Do not try another way.`}function vo(e){return`${H("Blocked by Anvil")} ${e} \xB7 can't be overridden`}function So(e){return`${H("Blocked by Anvil")} ${e}. Nothing ran, and this can't be overridden. Do not try another way.`}function $o(e){return`${H("Allowed once, with your OK")} ${e}`}import{createHash as ia}from"crypto";import{appendFileSync as Xo,closeSync as Qo,constants as Zo,fstatSync as es,mkdirSync as la,openSync as ns,readdirSync as aa,readFileSync as ca,readSync as ts,renameSync as ua,statSync as ar,unlinkSync as Go,writeFileSync as da}from"fs";import{homedir as fa}from"os";import{dirname as pa,join as Z}from"path";var In,wl,_o="its file (claude-conditions.js) is missing or won't load";function Co(){return wl??=import(new URL("claude-conditions.js",import.meta.url).href).then(e=>{In=typeof e.matchCondition=="function"&&typeof e.capMoved=="function"?e:void 0},()=>{})}function Ao(e,n,t){return In?In.matchCondition(e,n,t):{hit:"unknown",why:`Anvil can't check this rule's condition: ${_o}`}}function Ro(e,n){return In?In.capMoved(e,n):`Anvil can't read amounts: ${_o}`}var Eo=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,bl=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,kl=/(?:^|[^a-z])(?:api|request|requests|execute|exec|run|call|invoke|http|graphql|rpc|raw|batch|bulk|action|actions|command|operation|perform|proxy|custom|query|sql|services|hooks?|webhooks?|triggers?)(?:[^a-z]|$)/,Po=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),Oo=(e,n)=>e.split("+").every(t=>t[0]==="="?n.split(/[^a-z0-9]+/).includes(t.slice(1)):n.includes(t));function xl(e,n){let t=`_${n}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),r=n.replace(/_/g,"");return e.servers.some(o=>{let s=o.replace(/_/g,"");return`_${n}_`.includes(`_${o}_`)||t.includes(`_${o}_`)||(s.length>4?r.includes(s):s.length>3&&(r.startsWith(s)||r.endsWith(s)))})}function vl(e,n,t){let r=n.normalize("NFKC").toLowerCase().replace(/\.+$/,""),o=/^[a-z0-9.-]+$/.test(r);if(!r.includes("."))return o?(e.clis??[]).includes(r)?"this":"other":"?";let s=r.split("."),i=a=>r===a||r.endsWith(`.${a}`)||a.includes("*")&&a.split(".").every((c,d,u)=>u.length===s.length&&(c==="*"||c===s[d])),l=!1;return e.hosts.some(a=>{let c=a.indexOf("/");return c<0?i(a):(l||=i(a.slice(0,c))&&/^(?:\/batch\/?|\u0000)$/.test(t),i(a.slice(0,c))&&t.includes(a.slice(c)))})?"this":o&&!l?"other":"?"}function Sl(e){if(!e||!/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;try{return new URL(e).hostname.replace(/^\[|\]$/g,"")}catch{return"\0"}}function nn(e,n,t,r){let o=Po(t);return e.toolWords.length===0||e.toolWords.some(s=>Oo(s,o))?{hit:"match",part:n,why:e.said}:r===3||/\u0000|%00/.test(o)||kl.test(o)||!/[a-z]{3}/.test(o.replace(/[a-z]*\d[a-z0-9]*/g,""))||r===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(o)?{hit:"unknown",part:n,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function $l(e,n,t){let r=u=>({hit:"unknown",part:n,why:`Anvil can't tell ${u}, so it holds it (your rule: ${e.said})`});if(n.action==="claude.mcp.side_effect"){let u=n.host;if(!u)return r("which app this tool belongs to");let g=`mcp.${u}.`,h=Po(t.tool?.startsWith("mcp__")?t.tool.split("__").slice(2).join("__"):n.target?.startsWith(g)?n.target.slice(g.length):"");if(xl(e,u))return nn(e,n,h,1);let m=(e.anywhere??[]).some(_=>Oo(_,h))?{hit:"match",part:n,why:e.said}:null;if(!Eo.test(u)&&!bl.test(u))return m;let x=e.toolPrefixes.find(_=>h.startsWith(_));return x?nn(e,n,h.slice(x.length),1):e.servers.some(_=>_.length>2&&`_${h}_`.includes(`_${_}_`))?nn(e,n,h,1):m||(e.others??[]).includes(u)?m:r(`which app ${Eo.test(u)?`the connector ${u.slice(0,8)}\u2026`:u} acts on`)}let o=n.target??"",s=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(o)?`https://${o}`:o,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),l="";try{i&&(l=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{l="\0"}if(!n.host&&!n.service)return r("where this writes");let a=[n.host,n.service,...Array.isArray(n.attributes.hosts)?n.attributes.hosts:[],Sl(s)].filter(u=>typeof u=="string"&&u!==""),c=a.map(u=>vl(e,u,l)),d=[o,...a].some(u=>/^smtps?[:.]/i.test(u));if(c.includes("this")||d&&e.hosts.includes("smtp:")){let u=a.find((h,m)=>c[m]==="this"&&!h.includes(".")),g=o.includes("/")?3:2;return u?nn(e,n,`cli:${u.toLowerCase()} ${o}`,g):d?nn(e,n,"send mail",2):i?nn(e,n,l,3):nn(e,n,o,g)}return c.includes("?")?r(`where this writes (${a[0].replace(/[\u0000-\u001f]/g,"")})`):t.tool?.startsWith("mcp__")?r("what else this tool's command writes"):null}function fn(e,n,t){let r=null;for(let o of n){let s=$l(e,o,t);if(s?.hit==="match")return s;r??=s}return r??(t.parts.length>15&&n[0]?{hit:"unknown",part:n[0],why:`Anvil can't read everything this line does, so it holds it (your rule: ${e.said})`}:null)}import{existsSync as ot,readdirSync as Rl,statSync as jo}from"fs";import{dirname as er,isAbsolute as El,join as oe,posix as Pl,resolve as jn}from"path";import{posix as Io}from"path";var _l=null;function B(){return _l??process.platform==="win32"}var No=/^([A-Za-z]):(.*)$/s,Cl=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function Qt(e,n){let t=Io.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function pn(e,n){return e.split("/").map(t=>{if(t===""||t==="."||t===".."||/[\u0000\u0001]/.test(t))return t;let r=t.indexOf(":"),o=r>=0?t.slice(0,r):t,s=n?o:o.replace(/[. ]+$/,"");return s===""?".":s}).join("/")}function ue(e){if(!B())return e;let n=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),t=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(n);if(r){let a=r[2];if(r[1]===".")return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(a))n=`\\\\${a.slice(4)}`;else if(No.test(a))n=a;else return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;t=!0}n=n.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(n);if(o){let a=`/unc/${pn(o[1],t).toLowerCase()}${o[2]?`/${pn(o[2],t).toLowerCase()}`:""}`;return Qt(a,pn(o[3]??"",t).toLowerCase())}let s=No.exec(n);if(s){let a=s[2];return a===""?`/${s[1].toLowerCase()}`:a.startsWith("/")?Qt(`/${s[1].toLowerCase()}`,pn(a,t).toLowerCase()):null}let i=Cl.exec(n);if(i)return Qt(`/${i[1].toLowerCase()}`,pn(i[2]??"",t).toLowerCase());let l=pn(n,t).toLowerCase();if(l.startsWith("/")){let a=Io.normalize(l);return a.length>1&&a.endsWith("/")?a.slice(0,-1):a}return l}function Al(e){return ue(e)??e}function rt(e){if(!B())return e;let n=/^\/([a-z])(\/.*)?$/s.exec(e);if(n)return`${n[1].toUpperCase()}:${(n[2]??"/").replace(/\//g,"\\")}`;let t=/^\/unc\/(.+)$/s.exec(e);return t?`\\\\${t[1].replace(/\//g,"\\")}`:null}function V(e){return B()?rt(e)??e:e}function tn(e){return!B()||typeof e!="string"||e===""?e:Al(e)}var Ol=(e,n)=>{let t=n.endsWith("/")?n.slice(0,-1):n;return e===t||e.startsWith(`${t}/`)},Nl=U({vercel:"vercel deploy --prod, or --target staging",netlify:"netlify deploy --prod, or --context staging",fly:"fly deploy -a <an app named for staging>",flyctl:"flyctl deploy -a <an app named for staging>",railway:"railway up -e staging",modal:"modal deploy -e staging, or MODAL_ENVIRONMENT=staging",kubectl:"kubectl --context staging",helm:"helm --kube-context staging",terraform:"terraform workspace select staging, or -chdir=envs/staging",gh:"gh workflow run \u2026 -f environment=staging",firebase:"firebase deploy -P staging",serverless:"serverless deploy --stage staging",wrangler:"wrangler deploy --env staging"});function To(e,n,t){if(n.length===0)return null;let r=null,o=(s,i)=>{let l=s.action.endsWith(".deploy")&&s.host?Nl[s.host]:void 0;r??={hit:"unknown",part:s,why:`Anvil can't tell ${i}, so it holds it (your rule: ${e.said})${l?`. Say where it goes (${l}) and a deploy that isn't production runs`:""}`}};for(let s of n){let i=s.attributes;if(e.field==="outside_project"){let l=s.target,a=t.projectDir?[l,...t.touched?.full??[]].find(c=>c?.startsWith("/")&&!Ol(c,t.projectDir)):null;if(a)return{hit:"match",part:s,why:`${e.said} (${a})`};(!l||!l.startsWith("/")||!t.projectDir)&&o(s,"where this deletes")}else if(e.field==="environment"){if(i.environment==="production")return{hit:"match",part:s,why:`${e.said}${typeof i.environment_said=="string"?` (${i.environment_said})`:""}`};i.environment!=="non-production"&&o(s,s.action.endsWith(".destructive")?"which database this destroys":s.action.endsWith(".deploy")?"which environment this deploys to":"where this goes")}else{let l=Mo(i,t.home),a=l?.find(c=>(e.value.includes("/")?c:c.split("/").pop())===e.value.toLowerCase().replace(/\.git$/,""));if(a!==void 0)return{hit:"match",part:s,why:`${e.said} (${a})`};l||o(s,"which repository this pushes to")}}return r}function Mo(e,n){try{let t=typeof e.repo_dir=="string"?V(e.repo_dir):e.repo_dir,r=n===null?null:V(n),o=e.repo_via,s=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:o==="gh"&&process.env.GH_REPO||null;if(typeof t!="string"||!El(t)||!ot(t)||o!=="git"&&o!=="gh"||/[$`]/.test(s??""))return null;if(o==="gh"&&s!==null)return Wo([s],t);let i=Il(t,r);if(i===null)return null;let l=new Map;for(let d of i)d.section==="remote"&&d.sub!==null&&(d.key==="url"||(o==="git"?d.key==="pushurl":d.key==="gh-resolved"&&d.value!=="base"))&&l.set(d.sub,[...l.get(d.sub)??[],d.value]);if(s!==null&&!l.has(s)&&!/^[./]|[/:]/.test(s))return null;let a=s!==null?l.get(s)??[s]:[...l.values()].flat();if(s===null)for(let d of i)(d.section==="branch"&&/^(push)?remote$/.test(d.key)||d.section==="remote"&&d.sub===null&&d.key==="pushdefault")&&d.value!=="."&&!l.has(d.value)&&a.push(d.value);let c=new Set(a);for(let d of a)for(let u of i)u.section==="url"&&u.sub!==null&&/^(push)?insteadof$/.test(u.key)&&u.value&&d.startsWith(u.value)&&c.add(u.sub+d.slice(u.value.length));return c.size>0?Wo([...c],t):null}catch{return null}}function Wo(e,n){let t=[];for(let r of e){let o=decodeURIComponent(r.trim()),s=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(o)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(o),l=(s?Pl.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(o)&&!o.startsWith(".")?o:jn(n,o)).replace(/[?#].*$/,"").split(/[\\/]/).filter(g=>g&&g!=="."),a=l.findIndex((g,h)=>h>=2&&/^pulls?$/.test(g));a>=2&&(l=l.slice(0,a));let[c,d]=l.slice(-2).map(g=>g.replace(/\.git$/i,"").toLowerCase()),u=d??c;if(!u||u==="..")return null;t.push(d!==void 0&&c!==".."?`${c}/${d}`:u)}return t}function Il(e,n){let t=process.env;if(t.GIT_CONFIG_COUNT||t.GIT_CONFIG_PARAMETERS||t.GIT_DIR||t.GIT_COMMON_DIR)return null;let r=jl(e);if(r===null)return null;let o=process.platform==="win32"?[oe(t.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),oe(t.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(c=>`${c}/gitconfig`),s=t.GIT_CONFIG_NOSYSTEM?[]:t.GIT_CONFIG_SYSTEM?[t.GIT_CONFIG_SYSTEM]:o;t.GIT_CONFIG_GLOBAL?s.push(t.GIT_CONFIG_GLOBAL):n&&s.push(oe(t.XDG_CONFIG_HOME||oe(n,".config"),"git","config"),oe(n,".gitconfig")),s.push(oe(r.common,"config"),oe(r.gitDir,"config.worktree"));let i=[],l=24,a=(c,d)=>{let u=--l<0||d>5?void 0:be(c,1048576);if(u===void 0)return!1;for(let g of Wl(u?.toString("utf8")??""))if(i.push(g),g.key==="path"&&/^include(if)?$/.test(g.section)){let h=g.value.startsWith("~/")?n&&oe(n,g.value.slice(2)):!/^[~%]/.test(g.value)&&jn(er(c),g.value);if(!h||!a(h,d+1))return!1}return!0};return s.every(c=>a(c,0))?i:null}function jl(e){let n=t=>/^(ref: refs\/|[0-9a-f]{40})/.test(be(oe(t,"HEAD"),4096)?.toString("utf8")??"");for(let t=jn(e),r=0;r<64;r++,t=er(t)){let o=oe(t,".git"),s=["objects","refs"].every(i=>ot(oe(t,i)))&&n(t)?t:null;if(ot(o)){let i=jo(o);if(i.isDirectory())n(o)&&(s=o);else if(s=i.isFile()?/^gitdir:\s*(.+)$/m.exec(be(o,65536)?.toString("utf8")??"")?.[1]?.trim():null,!s)return null}if(s){let i=jn(t,s),l=be(oe(i,"commondir"),65536),a=l===null?i:jn(i,l.toString("utf8").trim());for(let c of["remotes","branches"]){let d=oe(a,c);if(ot(d)&&(!jo(d).isDirectory()||Rl(d).length>0))return null}return{gitDir:i,common:a}}if(er(t)===t)return null}return null}function Wl(e){let n=[],t="",r=null;for(let o of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){o=o.trim();let s=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(o);if(s){let[l,...a]=s[1].toLowerCase().split(".");t=l,r=s[2]?.replace(/\\(.)/g,"$1")??(a.length>0?a.join("."):null),o=o.slice(s[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(o);i&&n.push({section:t,sub:r,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(l,a,c)=>a??c??"").trim()})}return n}import{domainToASCII as Cf}from"url";var jf="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Ml,readdirSync as Ll,realpathSync as zo}from"fs";import{basename as Dl,dirname as Fl,join as Hl}from"path";function Me(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||B()?n.normalize("NFC").toLowerCase():n}function nr(e){if(!/[*?[]/.test(e))return null;let n=[...e],t=[],r=!1;for(let o=0;o<n.length;o++){let s=n[o],i=s==="["?n.indexOf("]",o+2):-1;if(s==="*")(t[t.length-1]!==null||t.length===0)&&t.push(null);else if(s==="?")t.push(l=>l!=="/");else if(i>0){let l=n.slice(o+1,i),a=l[0]==="!"||l[0]==="^",c=a?l.slice(1):l,d=[];for(let u=0;u<c.length;u++){let g=c[u].codePointAt(0);if(c[u+1]==="-"&&u+2<c.length){let h=c[u+2].codePointAt(0);g>h&&(r=!0),d.push([g,h]),u+=2}else d.push([g,g])}t.push(u=>u!=="/"&&d.some(([g,h])=>u.codePointAt(0)>=g&&u.codePointAt(0)<=h)!==a),o=i}else t.push(l=>l===s)}return r?{source:"(?!)",test:()=>!1}:{source:e,test(o){let s=[...o],i=0,l=0,a=-1,c=0;for(;l<s.length;){let d=t[i];if(d!=null&&d(s[l]))i++,l++;else if(d===null)a=i++,c=l;else if(a>=0&&s[c]!=="/")i=a+1,l=++c;else return!1}for(;t[i]===null;)i++;return i===t.length}}}var Tl=e=>e==="**"||/^[*?]+(?:\.[*?]+)*$/.test(e.replace(/\[[^\]]+\]/g,"?"));function tr(e){let n=B()?ue(e.trim())??e.trim():e.trim();if(/^~[^/]/.test(n))return null;let t=n==="~"||n.startsWith("~/"),r=!t&&n.startsWith("./"),o=(t?n.slice(1):n).replace(/^(?:\.\/)+/,""),s=t?0:o.startsWith("/")?1:r||o.replace(/\/+$/,"").includes("/")?2:3,i=[],l=0;for(let c of o.split("/"))c===""||c==="."||(c!==".."?i.push(c):i.length>0&&i[i.length-1]!=="**"?i.pop():s!==1&&i.length===0&&l++);if(i.length===0||i.every(Tl))return null;let a=[];for(let c of i){if(c==="**"){a[a.length-1]!==null&&a.push(null);continue}let d=Me(c),u=nr(d);if(u&&u.source==="(?!)")return null;a.push(u??d)}for(;a[a.length-1]===null;)a.pop();return{segs:a,at:l>0&&s===3?2:s,up:l}}var Lo=["Write","Edit","MultiEdit","NotebookEdit"],zl=["Read","Grep","NotebookRead","Glob","LS"],Ul=["claude.bash.fs.delete_recursive","claude.bash.fs.delete_disposable"],Bl=[".git",".anvil/rules.md",".anvil/rules.json"],Do=new Set(["node_modules",".git"]),ql=1e4,Kl=/^(?:https?|ftps?|wss?|git|ssh|s3|gs|file):$/;var Fo=new WeakMap,Le=e=>Me(e).split("/").filter(Boolean);function Vl(e,n,t){let r=new Map,o=(s,i)=>{if(s===e.length)return 2;if(i===n.length)return 1;let l=s*(n.length+1)+i,a=r.get(l);if(a!==void 0)return a;let c=e[s],d=n[i],u=0;if(c===null)for(let g=i;g<=n.length&&u<2;g++)u=Math.max(u,o(s+1,g));else if(d==="**")u=2;else{let g=nr(d);u=(g?typeof c!="string"||g.test(c):typeof c=="string"?c===d:c.test(d))?o(s+1,i+1):0}return r.set(l,u),u};return o(0,t)}function rr(e,n,t,r){let o=e.at===2&&r.length===0?3:e.at,s=o===0?t&&t.length>e.up?[t.slice(0,t.length-e.up)]:[]:o===1?[[],...r]:o===2?r.map(a=>a.slice(0,Math.max(0,a.length-e.up))):r.length===0?[[]]:r,i=0,l=!1;for(let a of s)if(!(a.length>=n.length||a.some((c,d)=>c!==n[d]))){l=!0;for(let c=a.length;c<n.length&&i<2;c+=o===3?1:n.length)i=Math.max(i,Vl(e.segs,n,c))}return i===2?2:o===3?l?3:0:i===1&&e.segs.includes(null)?3:i}function Uo(e){if(B())return Zl(e);let n="";for(let t=e;t.length>1;)try{return zo.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}function Zl(e){let n=rt(e);if(n===null||process.platform!=="win32")return e;let t=[];for(let r=n;;)try{return ue(Hl(zo.native(r),...t))??e}catch{let o=Fl(r);if(o===r)return e;t.unshift(Dl(r)),r=o}}function Gl(e,n,t){let r=e.at===0?n:e.at===1?"":t,o=r===null?null:e.up>0?r.split("/").slice(0,-e.up).join("/"):r,s=0;for(;s<e.segs.length&&typeof e.segs[s]=="string";)s++;if(o===null||s===0)return null;let i=`${o}/${e.segs.slice(0,s).join("/")}`,l=Uo(i);return Me(l)===Me(i)?null:{segs:[...Le(l),...e.segs.slice(s)],at:1,up:0}}function Jl(e,n){let t=e.split("/").filter(Boolean),r=n?n.split("/").filter(Boolean):null,o=[];for(let s=t.length;s>0&&!(r!==null&&s<=r.length&&r.slice(0,s).every((l,a)=>t[a]===l));s--){let i=`/${t.slice(0,s).join("/")}`;Bl.some(l=>Ml(V(`${i}/${l}`)))&&o.push(i)}return o}function Yl(e,n){if(Do.has(e.slice(e.lastIndexOf("/")+1)))return"no";let t=0,r=[e.replace(/(?<!^)\/+$/,"")];for(let o=0;o<r.length;o++){let s;try{s=Ll(V(r[o]),{withFileTypes:!0})}catch{continue}for(let i of s){if(++t>ql)return"unsure";let l=`${r[o]}/${i.name}`;if(n(Le(l)))return"yes";i.isDirectory()&&!Do.has(i.name)&&r.push(l)}}return"no"}var Ho=new WeakMap;function Xl(e,n){if(!n)return!1;let t=Ho.get(e);t||(t=e.paths.map(o=>{let s=Me(o.split("/").filter(c=>c!==""&&!/^[*?]+$/.test(c)).pop()??""),i=/^[*?]+[^*?[]+$/.test(s),l=s.replace(/^[*?]+/,"");if(l===""||/[*?[]/.test(l))return!0;let a=l.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&");return new RegExp(`${i?"":"(?:^|[\\s'\"`=:(/])"}${a}(?=$|[\\s'"\`/;|&)<>])`)}),Ho.set(e,t));let r=Me(n);return t.some(o=>o===!0||o.test(r))}function Bo(e,n,t){let r=t,o=n[0];if(!o)return null;let s=r.tool??(o.action==="claude.tool.other"?o.target:null),i=o.attributes.path,l=s!==null?Lo.includes(s)||zl.includes(s):i!==void 0;if(l&&(s!==null?!Lo.includes(s):o.action==="claude.file.read_secret"))return null;let a=r.touched,c=new Set(a?.written??[]),d=new Set(a?.read??[]),u=l?[...typeof i=="string"?[i]:[],...a?.full??[]]:[...c,...(a?.full??[]).filter(y=>!d.has(y)||c.has(y))],g=l?[]:a?.unknown??[],h=`(your rule: ${e.said})`;if(l&&u.length===0)return{hit:"unknown",part:o,why:`Anvil can't tell which file this writes, so it holds it ${h}`};if(u.length===0&&g.length===0)return null;let m=Fo.get(e);if(m||Fo.set(e,m=e.paths.map(tr)),m.includes(null))return{hit:"unknown",part:o,why:`Anvil can't read this rule's paths, so it holds every write ${h}`};let x=y=>r.projectDir&&y.startsWith(`${r.projectDir}/`)?y.slice(r.projectDir.length+1):r.home&&y.startsWith(`${r.home}/`)?`~${y.slice(r.home.length)}`:y,_=(y,P)=>({hit:"unknown",part:{...o,target:P},why:`${y}, so Anvil holds it ${h}`}),z=typeof r.root=="string"?r.root:null,ce=z??r.projectDir,J=r.home?Le(r.home):null,p=y=>[...new Map([...y,...y.map(Uo)].map(P=>[Le(P).join("/"),Le(P)])).values()],A=p(ce?.startsWith("/")?[ce]:[]),b=new Map,I=y=>{if(z!==null)return A;let P=b.get(y);if(P===void 0){let N=p(Jl(y,r.home)).filter(K=>!A.some(se=>se.join("/")===K.join("/")));P=N.length===0?A:[...A,...N],b.set(y,P)}return P},Y=[...new Set(u)].filter(y=>y.startsWith("/")).map(y=>({p:y,w:Le(y)})).filter(y=>!y.w.some(P=>Kl.test(P))),M=[...A,...[r.projectDir,r.home].filter(y=>typeof y=="string"&&y.startsWith("/")).map(Le)],W=(y,P)=>[...M,...I(y)].some(N=>N.length>=P.length&&P.every((K,se)=>N[se]===K)),R=y=>a?.written===void 0||c.has(y)||l?`changes ${x(y)}`:`may change ${x(y)}`,he=[],qe=[],Pn=(y,P)=>{for(let N of Y){let K=P(N.p);for(let se of y){let re=rr(se,N.w,J,K);if(re===2)return{hit:"match",part:{...o,target:x(N.p)},why:R(N.p)};re===1&&!W(N.p,N.w)&&he.push({p:N.p,sure:!0}),re===3&&!W(N.p,N.w)&&qe.push(N.p)}}return null},Pe=m,E=Pn(Pe,I)??Pn(Pe.map(y=>Gl(y,r.home,ce)).filter(y=>y!==null),()=>[]);if(E)return E;let T=y=>Me(y).replace(/(?<!^)\/+$/,""),Ke=y=>n.some(P=>Ul.includes(P.action)&&typeof P.target=="string"&&T(P.target)===T(y));for(let y of new Set(qe)){if(he.some(N=>N.p===y)||!(Ke(y)||c.has(y)))continue;let P=Yl(y,N=>Pe.some(K=>rr(K,N,J,I(y))===2));P!=="no"&&he.push({p:y,sure:P==="yes"})}let Ve=he.find(y=>y.sure&&Ke(y.p));if(Ve)return{hit:"match",part:{...o,target:x(Ve.p)},why:`deletes ${x(Ve.p)}, which holds ${e.paths.join(", ")}`};let Oe=he[0];if(Oe!==void 0)return _(`it changes ${x(Oe.p)}, a folder that ${Oe.sure?"holds":"may hold"} ${e.paths.join(", ")}, and Anvil can't tell what changes in it`,x(Oe.p));for(let y of g){let P=y.includes("\0")?y.slice(0,y.indexOf("\0")):y,N=P.slice(0,P.lastIndexOf("/"));if(N.startsWith("/")&&Pe.some(K=>rr(K,Le(N),J,I(N))===2))return _(`Anvil can't read the whole path this writes (${x(y.replace(/[\u0000\u0001]/g,""))})`,x(N))}return g.length>0&&Xl(e,r.command)?_(`it writes where Anvil can't read, and it names ${e.paths.join(", ")}`,o.target):null}function qo(e,n,t){switch(e.type){case"app":return fn(e,n,t);case"paths":return Bo(e,n,t);case"target":return To(e,n,t);case"kind":return n[0]?{hit:"match",part:n[0],why:e.said}:null}}function Ko(e,n,t=Ao){let r=e.kinds?n.parts.filter(l=>e.kinds.includes(l.action)):n.parts;if(e.kinds&&r.length===0)return null;if(!e.when||e.when.length===0)return qo(e.narrowing,r,n);let o=null,s=n.parts.length>15,i=l=>`${l}, so it holds it (your rule: ${e.text})`;for(let l of r){let a=qo(e.narrowing,[l],n);if(!a)continue;let c=e.when.map(u=>t(u,a.part,n));if(c.some(u=>u===null)){s&&(o??={hit:"unknown",part:a.part,why:i("Anvil can't read everything this line does")});continue}let d=c.find(u=>u!==null&&u.hit==="unknown");if(a.hit==="match"&&!d){let u=c.map(g=>g&&g.hit==="match"?g.detail:void 0).filter(g=>typeof g=="string"&&g.length>0);return{hit:"match",part:a.part,why:a.why,...u.length>0?{detail:u.join(", ")}:{}}}o??=a.hit==="unknown"?a:{hit:"unknown",part:a.part,why:i(d.why)}}return o}var or="anvil-claude-compiled/1";function sr(e,n){return`mut:${e}:${n}`}var st={verdict:"allow",policy:null,origin:null,ruleId:null,blockedBy:null,source:null};function ea(e){return typeof e!="string"?"":e.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/g,"").trim().toLowerCase()}function na(e,n){for(let t of n){if(t===e)return!0;if(t.endsWith(".*")){let r=t.slice(0,-2);if(r.length>0&&(e===r||e.startsWith(r+".")))return!0}if(t.startsWith("*.")){let r=t.slice(1);if(e.endsWith(r)&&e.length>r.length)return!0}}return!1}function ta(e,n){let t=e[n];return typeof t=="string"?t.trim()||null:typeof t=="number"?!Number.isFinite(t)||t===0?null:String(t):null}function Vo(e,n){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(n)}function ra(e,n){if(e.length===0)return!1;let t=n.toLowerCase(),r=t.split(/[^a-z0-9]+/i).filter(Boolean);return e.some(o=>r.includes(o))||e.some(o=>t.includes(o))}function oa(e,n,t,r){let o=(s,i,l,a)=>({verdict:l??(i==="confirmation_required"?"hold":"block"),policy:e.name,origin:e.origin,ruleId:s,blockedBy:i,source:a});if(!e.allowed_actions.includes(n.action))return e.deny_unlisted?o(null,"allowlist",null,null):st;for(let s of e.rules)if(Vo(s,n.action))switch(s.primitive){case"confirmation_gate":{if(s.all_actions===!0||ra(s.trigger_verbs??[],n.action))return o(s.id,"confirmation_required",s.intent,s.source??null);break}case"service_blocklist":{let i=s.blocked??[];if(i.length===0)break;let l=ea(n.service);if(l&&na(l,i))return o(s.id,"service_in_blocklist",s.intent,s.source??null);break}case"resource_mutation_rate":{let i=s.rate;if(!i||i.count<=0||i.per_ms<=0||!Number.isFinite(i.count)||!Number.isFinite(i.per_ms))break;let l=ta(n.metadata,s.resource_field?.trim()||"resource_id");if(!l)break;if(t.recordAndCount(sr(n.action,l),i.per_ms,r)>i.count)return o(s.id,"resource_mutation_rate_exceeded",s.intent,s.source??null);break}case"durable_key_dedup":break}return st}var gn={allow:0,hold:1,block:2};function ir(e,n,t,r,o){let s=st,i=st;for(let l of e.policies){if(!de(l,o))continue;let a=oa(l,n,t,r);l.origin==="baseline"&&gn[a.verdict]>gn[i.verdict]&&(i=a);let c=gn[a.verdict]>gn[s.verdict],d=a.verdict!=="allow"&&gn[a.verdict]===gn[s.verdict]&&l.origin!=="baseline";(c||d)&&(s=a)}return{decision:s,baseline:i}}function de(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&sa(n,e.project_dir))}function lr(e,n,t){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!de(o,t))){for(let s of o.rules)s.mode&&Vo(s,n)&&(r=On(r,s.mode));o.off?.includes(n)&&(r=On(r,"off"))}return r}function sa(e,n){let t=tn(e),r=tn(n),o=r.endsWith("/")?r.slice(0,-1):r;return t===o||t.startsWith(o+"/")}function De(e=fa()){return Fe(Z(e,".anvil","claude"))}function Fe(e){return{dir:e,bin:Z(e,"bin"),compiled:Z(e,"compiled.json"),modes:Z(e,"modes.json"),decisions:Z(e,"decisions.jsonl"),install:Z(e,"install.json"),state:Z(e,"state"),approvals:Z(e,"approvals"),counts:Z(e,"counts"),backups:Z(e,"backups")}}var ga=3500;function C(e,n=8*1024*1024){try{let t=ar(e);return t.isFile()&&t.size<=n}catch(t){return t.code==="ENOENT"?null:!1}}function be(e,n=8*1024*1024){let t;try{t=ns(e,Zo.O_RDONLY|Zo.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=es(t);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>n)throw new Error(`${e} is over ${n} bytes`);let o=Buffer.alloc(r.size),s=0;for(;s<r.size;){let i=ts(t,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Qo(t)}}function He(e,n){let t=n.endsWith(`
|
|
1
|
+
import{existsSync as yr,readFileSync as sp,writeSync as ip}from"fs";import{homedir as Xn,tmpdir as lp}from"os";import{basename as wr,dirname as et,join as $e}from"path";import{fileURLToPath as ap,pathToFileURL as br}from"url";import cp from"vm";import{Worker as up}from"worker_threads";import{spawnSync as pm}from"child_process";import{createHash as mm}from"crypto";import{chmodSync as ym,existsSync as wm,lstatSync as Mc,mkdirSync as bm,readdirSync as km,readFileSync as Lc,readlinkSync as Dc,realpathSync as ai,rmdirSync as vm,statSync as zt,unlinkSync as xm,writeFileSync as $m}from"fs";import{dirname as Fc,isAbsolute as _m,join as Am,relative as Cm,resolve as Hc}from"path";var Me={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function ya(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"),l=t(n?"38;2;34;197;94":"32"),i={[Me.on]:r,[Me.blocked]:r,[Me.held]:r,[Me.next]:r,[Me.watching]:o,[Me.problem]:s,[Me.ok]:l};return{on:!0,bold:t("1"),dim:t("2"),blue:r,grey:o,amber:s,mark:a=>(i[a]??(c=>c))(a),field:a=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${ba(a)}\x1B[0m`}}var kp=ya(!1),wa=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function ba(e){return e.replace(wa,"")}var os="production";function Ye(e){let n=e?.turned_off;return Array.isArray(n)?n:[]}var ts=e=>e.length>0?{turned_off:e}:{};var Je="claude";function hn(e){return e==="ghost"||e==="enforce"?e:null}function ss(e,n){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let t=hn(e.services?.[Je]?.actions?.[n]?.mode);return t||(hn(e.default_mode)??"ghost")}function Wr(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[Je]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function Ot(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function is(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:Wr(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[Je]:{actions:{}}},updated_at:r.toISOString(),...ts(n==="enforce"?[]:Ye(o))};let s={...o.services?.[Je]?.actions??{}};for(let l of t)s[l]={mode:n};return{version:1,kill_switch:o.kill_switch===!0,default_mode:hn(o.default_mode)??"ghost",services:{...o.services??{},[Je]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{},...ts(Ye(o))}}function ka(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:hn(e.default_mode)==="enforce"?!0:Object.values(e.services?.[Je]?.actions??{}).some(n=>hn(n?.mode)==="enforce")}var Pt="claude.agent.controls";function Nt(e,n){return n===Pt&&ka(e)?"enforce":ss(e,n)}var rs={off:0,ghost:1,enforce:2};function ot(e,n){return e===null?n:n===null?e:rs[n]>rs[e]?n:e}function ls(e,n){return!e||typeof e!="object"?null:hn(e.services?.[Je]?.actions?.[n]?.mode)??(hn(e.default_mode)==="enforce"?"enforce":null)}function It(e,n,t,r=!1){let s=ot(ls(e,n),t)??(r&&Ot(e)?"enforce":Nt(e,n));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function Tr(e,n,t){return ot(ls(e,n),t)===null&&Ot(e)&&Nt(e,n)!=="enforce"}function Ce(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function J(e){return Object.assign(Object.create(null),e)}var Nn=[{id:"protect",verdict:"block",short:"wiping your home folder or the project",slugs:["protected"]},{id:"protect-main",verdict:"block",short:"force-pushing main",slugs:["protected"]},{id:"protect-processes",verdict:"block",short:"killing every process",slugs:["protected"]},{id:"keep-work",verdict:"hold",short:"throwing away uncommitted work",slugs:["uncommitted"]},{id:"stay-in-project",verdict:"hold",short:"deletes outside your project",slugs:["outside-folder"]},{id:"stay-out-of-prod",verdict:"hold",short:"changes aimed at production",slugs:["prod-changes"]},{id:"keep-anvil-on",verdict:"hold",short:"changes to Anvil",slugs:["agent-controls"]},{id:"stop-loops",verdict:"hold",short:"delete bursts and repeats",slugs:["delete-burst","repeat"]},{id:"stop-helper-bursts",verdict:"hold",short:"helper bursts",slugs:["helper-burst"]},{id:"keep-keys-in",verdict:"hold",short:"use of your account keys",slugs:["credentials","secrets-expose"]},{id:"keep-env-out",verdict:"hold",short:"showing secrets files in the chat",slugs:["env-in-chat"]},{id:"hold-unchecked",verdict:"hold",short:"actions it can't check",slugs:["could-not-check","too-long-to-check"]}],va="home and project wipes and force-pushes to main",Rp=`always blocking ${va}`,xa=new Map(Nn.map(e=>[e.id,e]));function Re(e){return xa.get(e)}var $a=J({"block-protected-targets":"protect","hold-delete-bursts":"stop-loops","hold-repeated-side-effect":"stop-loops","hold-helper-bursts":"stop-helper-bursts"});function Mr(e,n){let t=e?$a[e]:void 0;return t!=="protect"?t:n.service==="git.main"?"protect-main":n.service==="proc.all"?"protect-processes":n.service==="fs.git_dir"&&!Ra(n.target,n.projectDir,n.home,n.histories)?void 0:t}var Lr=new Set(["hold-delete-bursts","hold-helper-bursts"]),as=new Set(Nn.flatMap(e=>e.slugs));var cs=J({"block-protected-targets":["protect","protect-main","protect-processes"],"hold-delete-bursts":["stop-loops"],"hold-repeated-side-effect":["stop-loops"],"hold-helper-bursts":["stop-helper-bursts"],"hold-risky-actions":["keep-work","stay-in-project","stay-out-of-prod","keep-anvil-on","keep-keys-in","keep-env-out"]});function Dr(e,n=[]){let t=new Set(Ea(e));return Nn.filter(r=>!n.includes(r.id)&&!Object.entries(cs).some(([o,s])=>s.includes(r.id)&&t.has(o)))}var st=new Set([Pt,"claude.bash.secrets.expose"]),Sa=new Set(["claude.file.read_secret","claude.file.write_secret","claude.bash.secrets.print"]),_a=/^(?:\.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 Aa(e,n){if(e.startsWith("~/")){let o=Ce(e.slice(2));return o.startsWith("/")?o.slice(1):o}let t=n?Ce(n):null,r=Ce(e);return t&&t!=="/"&&r.startsWith(`${t}/`)?r.slice(t.length+1):null}function Ca(e,n){if(!e)return!1;let t=Aa(e,n);return t!==null&&_a.test(t)}function Ra(e,n,t,r=[]){if(!e||!n)return!0;let o=Ce(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 l=o.slice(0,s)||"/";if(r.some(a=>`${l}/.git`===Ce(a)))return!0;let i=Ce(n)||"/";return i===l||l==="/"||i.startsWith(`${l}/`)}function us(e){if(e.decision.verdict==="allow")return null;let n=Mr(e.baseline.ruleId,e);return n?Re(n):e.service==="git.worktree"?Re("keep-work"):e.service==="fs.outside"?Re("stay-in-project"):e.action===Pt?Re("keep-anvil-on"):e.action==="claude.bash.secrets.expose"||Sa.has(e.action)&&Ca(e.target,e.home)?Re("keep-keys-in"):e.prod?Re("stay-out-of-prod"):e.service==="secrets.shown"?Re("keep-env-out"):null}function ds(e,n,t){return e.id==="keep-keys-in"&&n!=="claude.bash.secrets.expose"?"credentials":e.slugs.includes(t)?t:e.slugs[0]}function Ea(e){let n=new Set(e.policies.filter(t=>t.origin==="baseline").flatMap(t=>t.rules.map(r=>r.id)));return Object.keys(cs).filter(t=>!n.has(t))}var Wt=new Set(["claude.bash.prod.target"]),ps={"claude.bash.deps.add":{says:/\b(?:new|unknown|unfamiliar|undeclared|unlisted|introduc[a-z]*|(?:pull|bring)(?:s|ing)? in)\b|(?<!\b(?:npm|pnpm|yarn|bun|deno|poetry|uv|pdm|pipenv|cargo|composer|dotnet|go|gem|bundle|conda)\s+)\badd(?:s|ed|ing)?\b/i,more:/\b(?:new|add(?:s|ed|ing)?) (?:or|and) |\bor (?:new|add)|\bnot (?:only|just) (?:new|add)|\b(?:updat|upgrad|downgrad|bump|version|chang|remov|uninstall)/i}},Xe=J({"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:"throw away git 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.bash.deps.add":{slug:"new-dependency",text:"add a new dependency"},"claude.bash.prod.target":{slug:"production",text:"use a production account"},"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.file.outside_project":{slug:"outside-project",text:"change files outside the project"},"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 gs(e){if(!Ot(e))return null;let n="cluster, cloud and database destroys";return{what:n,context:`It also holds ${n}, cloud-credential prints and packages the project doesn't declare, until the user sets a mode for their kinds.`}}var fs=J({"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 jt(e,n){return e&&fs[e]?fs[e].slug:!e||e==="hold-risky-actions"?Xe[n]?.slug??n:e.replace(/@.*$/,"")}function Fr(e,n,t,r){return r&&n==="baseline"?ds(Re(r),t,jt(e,t)):!r&&e==="block-protected-targets"?Xe[t]?.slug??t:jt(e,t)}function Tt(e){return Xe[e]?.text??e}function Hr(e){let n=new Set(as);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(jt(null,o));else n.add(jt(r.id,""));return n.size}function zr(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 Ur(e,n){let t=zr(e).filter(o=>Xe[o]),r=t.filter(o=>Nt(n,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===t.length?"enforce":`${r.length} enforced, rest ghost`}}var Br="anvil-claude";function D(e){let n=e.trim();return n===Br||n.endsWith(` ${Br}`)||n.endsWith(`/${Br}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var ms="\u{1F539}",B=e=>`${ms} ${e} ${ms}`;var Qe=e=>`
|
|
2
|
+
${Me.next} ${e}`;function Oa(e,n,t){return`${Qe(`To ${e}, run this in a terminal (not in this chat):`)}
|
|
3
|
+
${n}${t?Qe(`Then ${t}.`):""}`}var Pa=72;function Le(e,n){let t=`To ${e}, run in a terminal: ${n}`;return t.length+5<=Pa?Qe(t):`${Qe(`To ${e}, run in a terminal:`)}
|
|
4
|
+
${n}`}var Na=(e,n)=>`they run \`${D(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 hs="blocking unsafe actions automatically",ys="checking every action";var De="anvil";function In(e){De=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}function yn(){return De}var he=e=>`${D(De)} ${e}`;function Ia(e,n=De,t){return`${B("Anvil isn't working")} ${e}.
|
|
5
|
+
Every command waits until it's fixed, so nothing runs unchecked.${t?Qe(t):""}${Le("fix it",`${D(n)} on`)}${Le("turn Anvil off instead",`${D(n)} off`)}`}function ja(e,n=De,t){return`${B("Anvil isn't working")} ${e}, so Claude Code holds every tool call until the user fixes it${t?` (${t})`:""} by running \`${D(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 ws(e){return`${B("Held by Anvil")} ${e}${Qe("Claude can do it in smaller steps, each one checked")}`}function bs(e){return`${B("Held by Anvil")} ${e}, so nothing ran. Do it in smaller steps, each under that size.`}function ks(e){return`${B("Held by Anvil")} ${e} \xB7 held for more than one OK can show, so none is offered${Qe("Claude can do it in smaller steps, each one asked about")}`}function vs(e){return`${B("Held by Anvil")} ${e}. It is held for more than one OK can show, so nothing ran and no OK is offered. Do it in smaller steps, each held for less.`}function Fe(e,n,t=De,r){let o=ja(n,t,r);return{systemMessage:Ia(n,t,r),hookSpecificOutput:e==="SessionStart"?{hookEventName:e,additionalContext:o}:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:o}}}function xs(e,n,t=De){let r=Wa(e.replace(/^Anvil:? /,""),t);return`${B("Anvil")} ${r.said}${n>0?` (and ${n} more)`:""}${r.fix??Le("see details",`${D(t)} report`)}`}function Wa(e,n){let t=e.lastIndexOf(` run ${D(n)} on`),r=t>0?e[t-1]:"";if(t<=0||r!==":"&&r!==";")return{said:e,fix:null};let o=e.slice(t+` run ${D(n)} on`.length);return o!==""&&!/^ to [a-z][a-z ]*$/.test(o)?{said:e,fix:null}:{said:e.slice(0,t-1),fix:Le("fix it",`${D(n)} on`)}}function $s(e,n,t=null){return`${B(`Anvil would've ${e==="block"?"blocked this":"held this for review"}`)} ${n} \xB7 it ran${t?Le("hold these for your OK",`${D(De)} enforce ${t}`):""}`}function Ss(e,n,t,r,o=!1){let s=`${B("Held by Anvil for your OK")} ${o?`${e} \xB7 on by default`:e}`;return t?`${s}${Oa("allow it once",`${D(n)} allow ${t}`,"tell Claude to go on")}`:`${s}${Qe(`it can't be allowed right now: ${r}`)}`}function _s(e,n,t=De,r=null){let o=r?` If its names are enough, \`${r}\` lists them without the values, and runs.`:"",s=r?"Do not try another way to see the values.":"Do not try another way.";return n?`${B("Held by Anvil")} ${e}. Nothing ran.${o} Tell the user: to allow it once, ${Na(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). ${s}`:`${B("Held by Anvil")} ${e}. Nothing ran, and it can't be allowed right now; the user has been told how to fix that.${o} ${s}`}function As(e,n=!1){return`${B("Held by Anvil for your OK")} ${e} \xB7 Yes ${n?"lets it go on":"runs it once"}`}function Cs(e,n){return`${B("Blocked by Anvil")} ${e}${Le("change the rule",`${D(n)} rules edit`)}`}function Rs(e){return`${B("Blocked by Anvil")} ${e}. Nothing ran, and it can't be allowed once. Do not try another way.`}function Kr(e){return`${B("Allowed once, with your OK")} ${e}`}import{createHash as Cc}from"crypto";import{appendFileSync as ti,closeSync as ri,constants as Xs,fstatSync as oi,mkdirSync as Rc,openSync as si,readdirSync as Ec,readFileSync as Oc,readSync as ii,renameSync as Pc,statSync as Qr,unlinkSync as Qs,writeFileSync as Nc}from"fs";import{homedir as Ic}from"os";import{dirname as jc,join as re}from"path";var it,Ta,Es="its file (claude-conditions.js) is missing or won't load";function Os(){return Ta??=import(new URL("claude-conditions.js",import.meta.url).href).then(e=>{it=typeof e.matchCondition=="function"&&typeof e.capMoved=="function"?e:void 0},()=>{})}function Ps(e,n,t){return it?it.matchCondition(e,n,t):{hit:"unknown",why:`Anvil can't check this rule's condition: ${Es}`}}function Ns(e,n){return it?it.capMoved(e,n):`Anvil can't read amounts: ${Es}`}var Is=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,Ma=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,La=/(?:^|[^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]|$)/,js=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),Ws=(e,n)=>e.split("+").every(t=>t[0]==="="?n.split(/[^a-z0-9]+/).includes(t.slice(1)):n.includes(t));function Da(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 Fa(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("."),l=a=>r===a||r.endsWith(`.${a}`)||a.includes("*")&&a.split(".").every((c,u,d)=>d.length===s.length&&(c==="*"||c===s[u])),i=!1;return e.hosts.some(a=>{let c=a.indexOf("/");return c<0?l(a):(i||=l(a.slice(0,c))&&/^(?:\/batch\/?|\u0000)$/.test(t),l(a.slice(0,c))&&t.includes(a.slice(c)))})?"this":o&&!i?"other":"?"}function Ha(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 wn(e,n,t,r){let o=js(t);return e.toolWords.length===0||e.toolWords.some(s=>Ws(s,o))?{hit:"match",part:n,why:e.said}:r===3||/\u0000|%00/.test(o)||La.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 za(e,n,t){let r=d=>({hit:"unknown",part:n,why:`Anvil can't tell ${d}, so it holds it (your rule: ${e.said})`});if(n.action==="claude.mcp.side_effect"){let d=n.host;if(!d)return r("which app this tool belongs to");let f=`mcp.${d}.`,h=js(t.tool?.startsWith("mcp__")?t.tool.split("__").slice(2).join("__"):n.target?.startsWith(f)?n.target.slice(f.length):"");if(Da(e,d))return wn(e,n,h,1);let m=(e.anywhere??[]).some(E=>Ws(E,h))?{hit:"match",part:n,why:e.said}:null;if(!Is.test(d)&&!Ma.test(d))return m;let k=e.toolPrefixes.find(E=>h.startsWith(E));return k?wn(e,n,h.slice(k.length),1):e.servers.some(E=>E.length>2&&`_${h}_`.includes(`_${E}_`))?wn(e,n,h,1):m||(e.others??[]).includes(d)?m:r(`which app ${Is.test(d)?`the connector ${d.slice(0,8)}\u2026`:d} acts on`)}let o=n.target??"",s=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(o)?`https://${o}`:o,l=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),i="";try{l&&(i=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{i="\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:[],Ha(s)].filter(d=>typeof d=="string"&&d!==""),c=a.map(d=>Fa(e,d,i)),u=[o,...a].some(d=>/^smtps?[:.]/i.test(d));if(c.includes("this")||u&&e.hosts.includes("smtp:")){let d=a.find((h,m)=>c[m]==="this"&&!h.includes(".")),f=o.includes("/")?3:2;return d?wn(e,n,`cli:${d.toLowerCase()} ${o}`,f):u?wn(e,n,"send mail",2):l?wn(e,n,i,3):wn(e,n,o,f)}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 jn(e,n,t){let r=null;for(let o of n){let s=za(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{createHash as Xp}from"crypto";import{existsSync as Lt,readdirSync as qa,statSync as Ls}from"fs";import{dirname as Vr,isAbsolute as Va,join as pe,posix as Za,resolve as lt}from"path";import{posix as Ms}from"path";var Ua=null;function Q(){return Ua??process.platform==="win32"}var Ts=/^([A-Za-z]):(.*)$/s,Ba=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function qr(e,n){let t=Ms.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function Wn(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 be(e){if(!Q())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(Ts.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/${Wn(o[1],t).toLowerCase()}${o[2]?`/${Wn(o[2],t).toLowerCase()}`:""}`;return qr(a,Wn(o[3]??"",t).toLowerCase())}let s=Ts.exec(n);if(s){let a=s[2];return a===""?`/${s[1].toLowerCase()}`:a.startsWith("/")?qr(`/${s[1].toLowerCase()}`,Wn(a,t).toLowerCase()):null}let l=Ba.exec(n);if(l)return qr(`/${l[1].toLowerCase()}`,Wn(l[2]??"",t).toLowerCase());let i=Wn(n,t).toLowerCase();if(i.startsWith("/")){let a=Ms.normalize(i);return a.length>1&&a.endsWith("/")?a.slice(0,-1):a}return i}function Ka(e){return be(e)??e}function Mt(e){if(!Q())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 G(e){return Q()?Mt(e)??e:e}function bn(e){return!Q()||typeof e!="string"||e===""?e:Ka(e)}var Ga="claude.file.outside_project";var Ja=(e,n)=>{let t=n.endsWith("/")?n.slice(0,-1):n;return e===t||e.startsWith(`${t}/`)},Ya=J({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 Fs(e,n,t){if(n.length===0)return null;let r=null,o=(s,l)=>{let i=s.action.endsWith(".deploy")&&s.host?Ya[s.host]:void 0;r??={hit:"unknown",part:s,why:`Anvil can't tell ${l}, so it holds it (your rule: ${e.said})${i?`. Say where it goes (${i}) and a deploy that isn't production runs`:""}`}};for(let s of n){let l=s.attributes;if(e.field==="outside_project"&&s.action===Ga){let i=l.op;if(i==="write")continue;if((i==="delete"||i==="move")&&(l.lands==="outside"||l.lands==="whole"))return{hit:"match",part:s,why:`${e.said} (${s.target??"outside"})`};o(s,i==="move"?"where this moves from":"where this deletes")}else if(e.field==="outside_project"){let i=s.target,a=t.projectDir?[i,...t.touched?.full??[]].find(c=>c?.startsWith("/")&&!Ja(c,t.projectDir)):null;if(a)return{hit:"match",part:s,why:`${e.said} (${a})`};(!i||!i.startsWith("/")||!t.projectDir)&&o(s,"where this deletes")}else if(e.field==="environment"){if(l.environment==="production")return{hit:"match",part:s,why:`${e.said}${typeof l.environment_said=="string"?` (${l.environment_said})`:""}`};l.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 i=Hs(l,t.home),a=i?.find(c=>(e.value.includes("/")?c:c.split("/").pop())===e.value.toLowerCase().replace(/\.git$/,""));if(a!==void 0){let c=[...new Set(i)].filter(d=>d!==a),u=c.length>3?` and ${c.splice(2).length} more`:"";return{hit:"match",part:s,why:`${e.said} (${a})`,detail:[a,...c].join(", ")+u,steady:a}}i||o(s,"which repository this pushes to")}}return r}function Hs(e,n){try{let t=typeof e.repo_dir=="string"?G(e.repo_dir):e.repo_dir,r=n===null?null:G(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"||!Va(t)||!Lt(t)||o!=="git"&&o!=="gh"||/[$`]/.test(s??""))return null;if(o==="gh"&&s!==null)return Ds([s],t);let l=Xa(t,r);if(l===null)return null;let i=new Map;for(let u of l)u.section==="remote"&&u.sub!==null&&(u.key==="url"||(o==="git"?u.key==="pushurl":u.key==="gh-resolved"&&u.value!=="base"))&&i.set(u.sub,[...i.get(u.sub)??[],u.value]);if(s!==null&&!i.has(s)&&!/^[./]|[/:]/.test(s))return null;let a=s!==null?i.get(s)??[s]:[...i.values()].flat();if(s===null)for(let u of l)(u.section==="branch"&&/^(push)?remote$/.test(u.key)||u.section==="remote"&&u.sub===null&&u.key==="pushdefault")&&u.value!=="."&&!i.has(u.value)&&a.push(u.value);let c=new Set(a);for(let u of a)for(let d of l)d.section==="url"&&d.sub!==null&&/^(push)?insteadof$/.test(d.key)&&d.value&&u.startsWith(d.value)&&c.add(d.sub+u.slice(d.value.length));return c.size>0?Ds([...c],t):null}catch{return null}}function Ds(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),i=(s?Za.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(o)&&!o.startsWith(".")?o:lt(n,o)).replace(/[?#].*$/,"").split(/[\\/]/).filter(f=>f&&f!=="."),a=i.findIndex((f,h)=>h>=2&&/^pulls?$/.test(f));a>=2&&(i=i.slice(0,a));let[c,u]=i.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),d=u??c;if(!d||d==="..")return null;t.push(u!==void 0&&c!==".."?`${c}/${u}`:d)}return t}function Xa(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=nc(e);return r&&ec(r,n)}function Qa(e,n){let t=process.env,r=process.platform==="win32"?[pe(t.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),pe(t.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(s=>`${s}/gitconfig`),o=t.GIT_CONFIG_NOSYSTEM?[]:t.GIT_CONFIG_SYSTEM?[t.GIT_CONFIG_SYSTEM]:r;return t.GIT_CONFIG_GLOBAL?o.push(t.GIT_CONFIG_GLOBAL):n&&o.push(pe(t.XDG_CONFIG_HOME||pe(n,".config"),"git","config"),pe(n,".gitconfig")),o.push(pe(e.common,"config"),pe(e.gitDir,"config.worktree")),o.filter(s=>s!=="/dev/null")}function ec(e,n,t=[]){let r=[],o=24,s=(i,a)=>{t.push(i);let c=--o<0||a>5?void 0:ge(i,1024*1024);if(c===void 0)return!1;for(let u of tc(c?.toString("utf8")??""))if(r.push(u),u.key==="path"&&/^include(if)?$/.test(u.section)){let d=u.value.startsWith("~/")?n&&pe(n,u.value.slice(2)):!/^[~%]/.test(u.value)&<(Vr(i),u.value);if(!d||!s(d,a+1))return!1}return!0},l=!0;for(let i of Qa(e,n))l=s(i,0)&&l;return l?r:null}function nc(e,n=!1){let t=r=>/^(ref: refs\/|[0-9a-f]{40})/.test(ge(pe(r,"HEAD"),4096)?.toString("utf8")??"");for(let r=lt(e),o=0;o<64;o++,r=Vr(r)){let s=pe(r,".git"),l=["objects","refs"].every(i=>Lt(pe(r,i)))&&t(r)?r:null;if(Lt(s)){let i=Ls(s);if(i.isDirectory())t(s)&&(l=s);else if(l=i.isFile()?/^gitdir:\s*(.+)$/m.exec(ge(s,65536)?.toString("utf8")??"")?.[1]?.trim():null,!l)return null}if(l){let i=lt(r,l),a=ge(pe(i,"commondir"),65536),c=a===null?i:lt(i,a.toString("utf8").trim());for(let u of n?[]:["remotes","branches"]){let d=pe(c,u);if(Lt(d)&&(!Ls(d).isDirectory()||qa(d).length>0))return null}return{gitDir:i,common:c,top:r}}if(Vr(r)===r)return null}return null}function tc(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[i,...a]=s[1].toLowerCase().split(".");t=i,r=s[2]?.replace(/\\(.)/g,"$1")??(a.length>0?a.join("."):null),o=o.slice(s[0].length).trim()}let l=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(o);l&&n.push({section:t,sub:r,key:l[1].toLowerCase(),value:l[2]===void 0?"true":l[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(i,a,c)=>a??c??"").trim()})}return n}import{domainToASCII as ag}from"url";var hg="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as oc,readdirSync as sc,realpathSync as qs}from"fs";import{basename as ic,dirname as lc,join as ac}from"path";function en(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||Q()?n.normalize("NFC").toLowerCase():n}function at(e){if(!/[*?[]/.test(e))return null;let n=[...e],t=[],r=!1;for(let o=0;o<n.length;o++){let s=n[o],l=s==="["?n.indexOf("]",o+2):-1;if(s==="*")(t[t.length-1]!==null||t.length===0)&&t.push(null);else if(s==="?")t.push(i=>i!=="/");else if(l>0){let i=n.slice(o+1,l),a=i[0]==="!"||i[0]==="^",c=a?i.slice(1):i,u=[];for(let d=0;d<c.length;d++){let f=c[d].codePointAt(0);if(c[d+1]==="-"&&d+2<c.length){let h=c[d+2].codePointAt(0);f>h&&(r=!0),u.push([f,h]),d+=2}else u.push([f,f])}t.push(d=>d!=="/"&&u.some(([f,h])=>d.codePointAt(0)>=f&&d.codePointAt(0)<=h)!==a),o=l}else t.push(i=>i===s)}return r?{source:"(?!)",test:()=>!1}:{source:e,test(o){let s=[...o],l=0,i=0,a=-1,c=0;for(;i<s.length;){let u=t[l];if(u!=null&&u(s[i]))l++,i++;else if(u===null)a=l++,c=i;else if(a>=0&&s[c]!=="/")l=a+1,i=++c;else return!1}for(;t[l]===null;)l++;return l===t.length}}}var rc=e=>e==="**"||/^[*?]+(?:\.[*?]+)*$/.test(e.replace(/\[[^\]]+\]/g,"?"));function Zr(e){let n=Q()?be(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,l=[],i=0;for(let c of o.split("/"))c===""||c==="."||(c!==".."?l.push(c):l.length>0&&l[l.length-1]!=="**"?l.pop():s!==1&&l.length===0&&i++);if(l.length===0||l.every(rc))return null;let a=[];for(let c of l){if(c==="**"){a[a.length-1]!==null&&a.push(null);continue}let u=en(c),d=at(u);if(d&&d.source==="(?!)")return null;a.push(d??u)}for(;a[a.length-1]===null;)a.pop();return{segs:a,at:i>0&&s===3?2:s,up:i}}var zs=["Write","Edit","MultiEdit","NotebookEdit"],cc=["Read","Grep","NotebookRead","Glob","LS"],uc=["claude.bash.fs.delete_recursive","claude.bash.fs.delete_disposable"],dc=[".git",".anvil/rules.md",".anvil/rules.json"],Us=new Set(["node_modules",".git"]),fc=1e4,pc=/^(?:https?|ftps?|wss?|git|ssh|s3|gs|file):$/;var Bs=new WeakMap,nn=e=>en(e).split("/").filter(Boolean);function gc(e,n,t){let r=new Map,o=(s,l)=>{if(s===e.length)return 2;if(l===n.length)return 1;let i=s*(n.length+1)+l,a=r.get(i);if(a!==void 0)return a;let c=e[s],u=n[l],d=0;if(c===null)for(let f=l;f<=n.length&&d<2;f++)d=Math.max(d,o(s+1,f));else if(u==="**")d=2;else{let f=at(u);d=(f?typeof c!="string"||f.test(c):typeof c=="string"?c===u:c.test(u))?o(s+1,l+1):0}return r.set(i,d),d};return o(0,t)}function Gr(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,l=0,i=!1;for(let a of s)if(!(a.length>=n.length||a.some((c,u)=>c!==n[u]))){i=!0;for(let c=a.length;c<n.length&&l<2;c+=o===3?1:n.length)l=Math.max(l,gc(e.segs,n,c))}return l===2?2:o===3?i?3:0:l===1&&e.segs.includes(null)?3:l}function Vs(e){if(Q())return mc(e);let n="";for(let t=e;t.length>1;)try{return qs.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}function mc(e){let n=Mt(e);if(n===null||process.platform!=="win32")return e;let t=[];for(let r=n;;)try{return be(ac(qs.native(r),...t))??e}catch{let o=lc(r);if(o===r)return e;t.unshift(ic(r)),r=o}}function hc(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 l=`${o}/${e.segs.slice(0,s).join("/")}`,i=Vs(l);return en(i)===en(l)?null:{segs:[...nn(i),...e.segs.slice(s)],at:1,up:0}}function yc(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((i,a)=>t[a]===i));s--){let l=`/${t.slice(0,s).join("/")}`;dc.some(i=>oc(G(`${l}/${i}`)))&&o.push(l)}return o}function wc(e,n){if(Us.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=sc(G(r[o]),{withFileTypes:!0})}catch{continue}for(let l of s){if(++t>fc)return"unsure";let i=`${r[o]}/${l.name}`;if(n(nn(i)))return"yes";l.isDirectory()&&!Us.has(l.name)&&r.push(i)}}return"no"}var Ks=new WeakMap;function bc(e,n){if(!n)return!1;let t=Ks.get(e);t||(t=e.paths.map(o=>{let s=en(o.split("/").filter(c=>c!==""&&!/^[*?]+$/.test(c)).pop()??""),l=/^[*?]+[^*?[]+$/.test(s),i=s.replace(/^[*?]+/,"");if(i===""||/[*?[]/.test(i))return!0;let a=i.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&");return new RegExp(`${l?"":"(?:^|[\\s'\"`=:(/])"}${a}(?=$|[\\s'"\`/;|&)<>])`)}),Ks.set(e,t));let r=en(n);return t.some(o=>o===!0||o.test(r))}function Zs(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),l=o.attributes.path,i=s!==null?zs.includes(s)||cc.includes(s):l!==void 0;if(i&&(s!==null?!zs.includes(s):o.action==="claude.file.read_secret"))return null;let a=r.touched,c=new Set(a?.written??[]),u=new Set(a?.read??[]),d=i?[...typeof l=="string"?[l]:[],...a?.full??[]]:[...c,...(a?.full??[]).filter(y=>!u.has(y)||c.has(y))],f=i?[]:a?.unknown??[],h=`(your rule: ${e.said})`;if(i&&d.length===0)return{hit:"unknown",part:o,why:`Anvil can't tell which file this writes, so it holds it ${h}`};if(d.length===0&&f.length===0)return null;let m=Bs.get(e);if(m||Bs.set(e,m=e.paths.map(Zr)),m.includes(null))return{hit:"unknown",part:o,why:`Anvil can't read this rule's paths, so it holds every write ${h}`};let k=y=>r.projectDir&&y.startsWith(`${r.projectDir}/`)?y.slice(r.projectDir.length+1):r.home&&y.startsWith(`${r.home}/`)?`~${y.slice(r.home.length)}`:y,E=(y,S)=>({hit:"unknown",part:{...o,target:S},why:`${y}, so Anvil holds it ${h}`}),q=typeof r.root=="string"?r.root:null,W=q??r.projectDir,oe=r.home?nn(r.home):null,Pe=y=>[...new Map([...y,...y.map(Vs)].map(S=>[nn(S).join("/"),nn(S)])).values()],se=Pe(W?.startsWith("/")?[W]:[]),w=new Map,Se=y=>{if(q!==null)return se;let S=w.get(y);if(S===void 0){let _=Pe(yc(y,r.home)).filter(ne=>!se.some(we=>we.join("/")===ne.join("/")));S=_.length===0?se:[...se,..._],w.set(y,S)}return S},N=[...new Set(d)].filter(y=>y.startsWith("/")).map(y=>({p:y,w:nn(y)})).filter(y=>!y.w.some(S=>pc.test(S))),Ne=[...se,...[r.projectDir,r.home].filter(y=>typeof y=="string"&&y.startsWith("/")).map(nn)],Ie=(y,S)=>[...Ne,...Se(y)].some(_=>_.length>=S.length&&S.every((ne,we)=>_[we]===ne)),me=y=>a?.written===void 0||c.has(y)||i?`changes ${k(y)}`:`may change ${k(y)}`,z=[],M=[],ye=(y,S)=>{for(let _ of N){let ne=S(_.p);for(let we of y){let fe=Gr(we,_.w,oe,ne);if(fe===2)return{hit:"match",part:{...o,target:k(_.p)},why:me(_.p)};fe===1&&!Ie(_.p,_.w)&&z.push({p:_.p,sure:!0}),fe===3&&!Ie(_.p,_.w)&&M.push(_.p)}}return null},g=m,x=ye(g,Se)??ye(g.map(y=>hc(y,r.home,W)).filter(y=>y!==null),()=>[]);if(x)return x;let C=y=>en(y).replace(/(?<!^)\/+$/,""),O=y=>n.some(S=>uc.includes(S.action)&&typeof S.target=="string"&&C(S.target)===C(y));for(let y of new Set(M)){if(z.some(_=>_.p===y)||!(O(y)||c.has(y)))continue;let S=wc(y,_=>g.some(ne=>Gr(ne,_,oe,Se(y))===2));S!=="no"&&z.push({p:y,sure:S==="yes"})}let L=z.find(y=>y.sure&&O(y.p));if(L)return{hit:"match",part:{...o,target:k(L.p)},why:`deletes ${k(L.p)}, which holds ${e.paths.join(", ")}`};let R=z[0];if(R!==void 0)return E(`it changes ${k(R.p)}, a folder that ${R.sure?"holds":"may hold"} ${e.paths.join(", ")}, and Anvil can't tell what changes in it`,k(R.p));for(let y of f){let S=y.includes("\0")?y.slice(0,y.indexOf("\0")):y,_=S.slice(0,S.lastIndexOf("/"));if(_.startsWith("/")&&g.some(ne=>Gr(ne,nn(_),oe,Se(_))===2))return E(`Anvil can't read the whole path this writes (${k(y.replace(/[\u0000\u0001]/g,""))})`,k(_))}return f.length>0&&bc(e,r.command)?E(`it writes where Anvil can't read, and it names ${e.paths.join(", ")}`,o.target):null}function Gs(e,n,t){switch(e.type){case"app":return jn(e,n,t);case"paths":return Zs(e,n,t);case"target":return Fs(e,n,t);case"kind":return n[0]?{hit:"match",part:n[0],why:e.said}:null}}function Js(e,n,t=Ps){let r=e.kinds?n.parts.filter(i=>e.kinds.includes(i.action)):n.parts;if(e.kinds&&r.length===0)return null;if(!e.when||e.when.length===0)return Gs(e.narrowing,r,n);let o=null,s=n.parts.length>15,l=i=>`${i}, so it holds it (your rule: ${e.text})`;for(let i of r){let a=Gs(e.narrowing,[i],n);if(!a)continue;let c=e.when.map(d=>t(d,a.part,n));if(c.some(d=>d===null)){s&&(o??={hit:"unknown",part:a.part,why:l("Anvil can't read everything this line does")});continue}let u=c.find(d=>d!==null&&d.hit==="unknown");if(a.hit==="match"&&!u){let d=k=>k?a.detail:a.steady??a.detail,f=k=>[...d(k)?[d(k)]:[],...c.flatMap((E,q)=>E?.hit==="match"&&E.detail&&(k||e.when[q].type!=="when")?[E.detail]:[])].join(", "),[h,m]=[f(!0),f(!1)];return{hit:"match",part:a.part,why:a.why,...h?{detail:h}:{},...h===m?{}:{steady:m}}}o??=a.hit==="unknown"?a:{hit:"unknown",part:a.part,why:l(u.why)}}return o}var Jr="anvil-claude-compiled/1";function Yr(e,n){return`mut:${e}:${n}`}var Dt={verdict:"allow",policy:null,origin:null,ruleId:null,blockedBy:null,source:null};function vc(e){return typeof e!="string"?"":e.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/g,"").trim().toLowerCase()}function xc(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 $c(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 Xr(e,n){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(n)}function Sc(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 _c(e,n,t,r,o){let s=(l,i,a,c)=>({verdict:a??(i==="confirmation_required"?"hold":"block"),policy:e.name,origin:e.origin,ruleId:l,blockedBy:i,source:c});if(!e.allowed_actions.includes(n.action))return e.deny_unlisted?s(null,"allowlist",null,null):Dt;for(let l of e.rules)if(!(!Xr(l,n.action)||o?.(l.id)))switch(l.primitive){case"confirmation_gate":{if(l.all_actions===!0||Sc(l.trigger_verbs??[],n.action))return s(l.id,"confirmation_required",l.intent,l.source??null);break}case"service_blocklist":{let i=l.blocked??[];if(i.length===0)break;let a=vc(n.service);if(a&&xc(a,i))return s(l.id,"service_in_blocklist",l.intent,l.source??null);break}case"resource_mutation_rate":{let i=l.rate;if(!i||i.count<=0||i.per_ms<=0||!Number.isFinite(i.count)||!Number.isFinite(i.per_ms))break;let a=$c(n.metadata,l.resource_field?.trim()||"resource_id");if(!a)break;if(t.recordAndCount(Yr(n.action,a),i.per_ms,r)>i.count)return s(l.id,"resource_mutation_rate_exceeded",l.intent,l.source??null);break}case"durable_key_dedup":break}return Dt}var Tn={allow:0,hold:1,block:2};function Ft(e,n,t,r,o,s){let l=Dt,i=Dt;for(let a of e.policies){if(!ie(a,o))continue;let c=_c(a,n,t,r,a.origin==="baseline"?s:void 0);a.origin==="baseline"&&Tn[c.verdict]>Tn[i.verdict]&&(i=c);let u=Tn[c.verdict]>Tn[l.verdict],d=c.verdict!=="allow"&&Tn[c.verdict]===Tn[l.verdict]&&a.origin!=="baseline";(u||d)&&(l=c)}return{decision:l,baseline:i}}function ie(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&Ac(n,e.project_dir))}function ct(e,n,t){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!ie(o,t))){for(let s of o.rules)s.mode&&Xr(s,n)&&(r=ot(r,s.mode));o.off?.includes(n)&&(r=ot(r,"off"))}return r}function Ys(e,n,t,r){let o=!1;for(let s of e.policies)if(!(s.origin==="baseline"||!ie(s,t))){if(s.off?.includes(n))return!1;for(let l of s.rules)if(Xr(l,n)){if(l.mode!=="enforce"||!r.says.test(l.note??"")||r.more.test(l.note??""))return!1;o=!0}}return o}function Ac(e,n){let t=bn(e),r=bn(n),o=r.endsWith("/")?r.slice(0,-1):r;return t===o||t.startsWith(o+"/")}function kn(e=Ic()){return tn(re(e,".anvil","claude"))}function tn(e){return{dir:e,bin:re(e,"bin"),compiled:re(e,"compiled.json"),modes:re(e,"modes.json"),decisions:re(e,"decisions.jsonl"),install:re(e,"install.json"),state:re(e,"state"),approvals:re(e,"approvals"),counts:re(e,"counts"),backups:re(e,"backups")}}var Wc=3500;function j(e,n=8*1024*1024){try{let t=Qr(e);return t.isFile()&&t.size<=n}catch(t){return t.code==="ENOENT"?null:!1}}function ge(e,n=8*1024*1024){let t;try{t=si(e,Xs.O_RDONLY|Xs.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=oi(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 l=ii(t,o,s,r.size-s,s);if(l===0)break;s+=l}return o.subarray(0,s)}finally{ri(t)}}function rn(e,n){let t=n.endsWith(`
|
|
6
6
|
`)?n:`${n}
|
|
7
|
-
`;if(Buffer.byteLength(t)>
|
|
8
|
-
`);
|
|
9
|
-
`)){let c=a.indexOf(" ");if(c<=0||a.slice(c+1)!==n)continue;let
|
|
10
|
-
`))if(s)try{let
|
|
11
|
-
`,o.index)+1;(r.get(s)??r.set(s,new Set).get(s)).add(o[1])}for(let[o,s]of[...r].sort((i
|
|
12
|
-
`,o);try{let
|
|
7
|
+
`;if(Buffer.byteLength(t)>Wc)throw new Error(`refusing to append a ${Buffer.byteLength(t)}-byte line`);if(j(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);ti(e,t,{mode:384})}function U(e){Rc(e,{recursive:!0,mode:448})}function ee(e,n){if(j(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let t;try{t=si(e,"r")}catch{return""}try{let r=oi(t).size,o=Math.max(0,r-n),s=r-o;if(s<=0)return"";let l=Buffer.alloc(s);ii(t,l,0,s,o);let i=l.toString("utf8");if(o>0){let a=i.indexOf(`
|
|
8
|
+
`);i=a<0?"":i.slice(a+1)}return i}finally{ri(t)}}function le(e,n,t=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Nc(r,n,{mode:t}),ut(r,e)}function ut(e,n){for(let t=0;;t++)try{Pc(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 dt(e){if(j(e)!==!0)return null;try{return JSON.parse(Oc(e,"utf8"))}catch{return null}}var ei=256*1024,Tc=1024*1024,Ht=class{constructor(n,t=()=>null){this.file=n;this.answer=t}recordAndCount(n,t,r){let o=r-t,s=this.restartedAt(n,r),l=1,i=ee(this.file,ei);for(let a of i.split(`
|
|
9
|
+
`)){let c=a.indexOf(" ");if(c<=0||a.slice(c+1)!==n)continue;let u=Number(a.slice(0,c));Number.isFinite(u)&&u>=o&&u<=r&&u>s&&l++}return this.rotateIfLarge(),rn(this.file,`${r} ${n.replace(/[\r\n]/g," ")}`),l}restart(n,t,r){let o=this.restartDir();U(o),le(re(o,`${ni(n)}.json`),JSON.stringify({v:1,at:t,...r?{tr:r.transcript,call:r.call}:{}}));try{for(let s of Ec(o)){let l=re(o,s);Qr(l).mtimeMs<t-864e5&&Qs(l)}}catch{}}restartedAt(n,t){let r=re(this.restartDir(),`${ni(n)}.json`),o=ge(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 l=this.answer(s.tr,s.call);if(l===null)return-1/0;if(l==="no")return Qs(r),-1/0;le(r,JSON.stringify({v:1,at:s.at}))}return s.at}catch{return-1/0}}restartDir(){return re(jc(this.file),"rate-ok")}rotateIfLarge(){try{if(Qr(this.file).size>Tc){let n=ee(this.file,ei);le(this.file,n)}}catch{}}},ni=e=>Cc("sha256").update(e).digest("hex").slice(0,16);function li(e,n){let t=re(e,n.toISOString().slice(0,10));j(t,Number.MAX_SAFE_INTEGER)!==!1&&ti(t,".",{mode:384})}var ci="/.anvil/claude/bin/claude-hook.js",zc=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var Mn=class extends Error{constructor(n){super(n),this.name="SettingsRefused"}};var ui=["UserPromptSubmit","SubagentStart","SubagentStop","PreModelSwitch"],Ln=e=>typeof e=="string"&&ui.includes(e);function di(e){let n=new Set;for(let t of e)try{let r=pi(no(t)),o=r===null?null:eo(r.toString("utf8"),t).hooks;for(let s of ui)JSON.stringify(o?.[s]??null).includes(ci)&&n.add(s)}catch{}return n}function eo(e,n){let t=e.startsWith("\uFEFF")?e.slice(1):e;if(t.trim()==="")return{};let r;try{r=JSON.parse(t)}catch(o){throw new Mn(`${n} is not valid JSON (${o instanceof Error?o.message:String(o)}). Anvil changed nothing; fix the file and run this again.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Mn(`${n} is not a JSON object. Anvil changed nothing.`);return r}function Uc(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 Bc=e=>{let n=Uc(e);return n!==null&&(n.includes(ci)||zc.test(n))};function Kc(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 fi(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function pi(e){return ge(e,64*1024*1024)}function no(e){try{if(!Mc(e).isSymbolicLink())return e}catch{return e}try{return ai(e)}catch(n){let t=n.code;throw t==="ENOENT"?new Mn(`${e} is a link to ${qc(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new Mn(`${e} is a link Anvil cannot follow (${t??String(n)}). Anvil changed nothing.`)}}function qc(e){let n=Fc(e);try{n=ai(n)}catch{}return Hc(n,Dc(e))}function to(e){try{let n=no(e),t=zt(n);if(!t.isFile()||t.size>4*1024*1024)return!1;let r=pi(n);if(r===null)return!1;let o=eo(r.toString("utf8"),e).hooks?.PreToolUse;return Array.isArray(o)&&o.some(s=>{let l=s&&typeof s=="object"?s:null,i=l?.matcher;return(i===void 0||i===""||i==="*")&&Array.isArray(l?.hooks)&&l.hooks.some(a=>Bc(a)&&Gc(a))})}catch{return!1}}function gi(e,n){let t;try{t=no(e)}catch{return"unreadable"}let r;try{r=zt(t)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=eo(Lc(t,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let s=o.hooks?.PreToolUse;return Array.isArray(s)&&s.some(i=>{let a=i&&typeof i=="object"?i:null,c=a?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(a?.hooks)&&a.hooks.some(u=>Kc(u,n))})?"present":"missing"}function Vc(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")?/^\d{2,3}$/.test(n[r+4]??"")?2:1:0;if(n&&r>=0&&n[r+3+o]==="||"){let s=r>0&&r%5===0;for(let l=0;s&&l<r;l+=5)s=n[l]==="["&&(n[l+1]==="-s"||n[l+1]==="-f")&&n[l+3]==="]"&&n[l+4]==="&&"&&t(n[l+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 Zc(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 Vc(n)}function Gc(e){let n=Zc(e);if(!n)return!1;try{return zt(n[0]).isFile()&&zt(n[1]).isFile()}catch{return!1}}import{spawnSync as sf}from"child_process";import{createHash as bt}from"crypto";import{lstatSync as lf,readdirSync as gr,readFileSync as dr,realpathSync as Wl,statSync as jo}from"fs";import{basename as cn,dirname as kt,isAbsolute as xt,join as v,resolve as Vn}from"path";import{createHash as Jc}from"crypto";import{closeSync as Yc,constants as mi,fstatSync as Xc,openSync as Qc,readdirSync as hi,readFileSync as eu,readSync as nu,statSync as tu,unlinkSync as ro,writeFileSync as ru}from"fs";import{join as vn}from"path";var ou=9,yi=4*1024*1024,oo=6*36e5,so="waiting",su=4,wi=16;function iu(e){let n;try{n=Qc(e,mi.O_RDONLY|mi.O_NONBLOCK)}catch(t){if(t.code==="ENOENT")return"";throw t}try{let t=Xc(n);if(!t.isFile())throw new Error("the day's cap count is not a regular file");if(t.size>yi)throw new Error(`the day's cap count is over ${yi/1024/1024} MB`);let r=Buffer.alloc(t.size),o=0;for(;o<t.size;){let s=nu(n,r,o,t.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{Yc(n)}}function Ut(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 bi=e=>{let n=new Date(e);return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`};function xi(e,n,t,r=null){let o=[];for(let s of e.policies)if(ie(s,t)){for(let l of s.caps??[])if(l.kinds.some(i=>n.includes(i))){if(l.match&&r){let i=r.parts.filter(a=>l.kinds.includes(a.action));if(i.length>0&&jn(l.match,i,r)===null)continue}o.push(l)}}return o}var Ee=class extends Error{constructor(t,r){super(t);this.cap=r}};function lu(e,n){return n.parts.filter(t=>e.kinds.includes(t.action)&&(!e.match||jn(e.match,[t],n)!==null))}function au(e,n){if(!n)return 1;if(n.parts.length>=wi)throw new Ee(`this call has more actions than Anvil counts in one line (${wi})`,e);let t=n.tool?.startsWith("mcp__")===!0,r=n.command??(t?cu(n.input):null);if(r!==null&&$i(r))throw new Ee("this line repeats what it runs a number of times Anvil can't read",e);if(t&&r!==null&&/[;&|\n]/.test(r))throw new Ee("an MCP tool runs this line of several commands, which Anvil can't count one by one",e);return Math.max(1,lu(e,n).length)}function cu(e){for(let n of["command","cmd","script","input","code","cli_command"])if(typeof e?.[n]=="string")return e[n];return null}function uu(e){let n="",t=[],r=/(?:\b(?:ba|z|da|k|fi)?sh(?:\s+-\S+)*\s+-\w*c\w*|\beval|\bssh\b[^;&|\n]*|\bsu\b[^;&|\n]*-c)\s*$/;for(let o=0;o<e.length;o++){let s=e[o];if(s==="\\"){n+=" ",o++;continue}if(s!=="'"&&s!=='"'){n+=s;continue}let l=o+1,i="";for(;l<e.length&&e[l]!==s;l++)s==='"'&&e[l]==="\\"?i+=e[++l]??"":i+=e[l];t.push({text:i,code:r.test(n)}),n+=" Q ",o=l}return{bare:n,quoted:t}}function $i(e,n=0){let{bare:t,quoted:r}=uu(e);if(n<3&&r.some(i=>i.code&&$i(i.text,n+1)))return!0;let o=String.raw`(?:^|[;&|(){}\n!]|\b(?:do|then|else|elif|time|coproc)\b)\s*`,s=String.raw`(?:[A-Za-z_]\w*=\S*\s+|(?:sudo|nohup|time|command|builtin|env|exec|nice|ionice|timeout|stdbuf|caffeinate)(?:\s+-\S+)*(?:\s+\d+(?:\.\d+)?[smhd]?)?\s+)*`;if(new RegExp(String.raw`${o}${s}(?:while|until|select|repeat)\b`).test(t)||new RegExp(String.raw`${o}${s}(?:xargs|parallel|watch)\b`).test(t)||/\bfind\b[^;&|\n]*\s-(?:exec|execdir|ok|okdir)\b/.test(t))return!0;for(let i of t.matchAll(/(?<![\w-])([A-Za-z_][\w-]*)\s*\(\s*\)\s*\{([^}]*)/g))if(new RegExp(String.raw`(?:^|[;&|\s{(])${i[1].replace(/-/g,"\\-")}(?:$|[;&|\s)}])`).test(i[2]))return!0;let l=0;for(let i of t.matchAll(new RegExp(String.raw`${o}${s}for\b([^;\n]*)`,"g"))){let a=/^\s*[A-Za-z_]\w*\s+in\s+(.*)$/.exec(i[1]),c=a?a[1].trim().split(/\s+/).filter(Boolean):[];if(!a||c.length===0||c.length>16||c.some(u=>/[$`*?[\]{}~]/.test(u)))return!0;l+=c.length}return l>64}function Si(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 Kt(e,n,t=null){if(e.unit==="money"){let l=Ns(e,t);if(typeof l=="string")throw new Ee(l,e);return l}let r=au(e,t);if(e.unit==="calls")return r;let o=n?.machines??1,s=(n?.hours??1)*o;return e.unit==="machines"?o*r:e.unit==="hours"?s*r:(e.price?.per==="hour"?s:o)*(e.price?.usd??0)*r}function du(e,n,t){try{return Kt(e,n,t)}catch(r){if(r instanceof Ee)return e.limit;throw r}}var ft=class{constructor(n){this.dir=n}file(n){return vn(this.dir,`${bi(n)}.log`)}write(n){U(this.dir),rn(this.file(n.t),JSON.stringify(n)),n.tr&&n.call&&(U(vn(this.dir,so)),ru(vn(this.dir,so,vi(n.cap,n.key)),n.cap,{mode:384}))}settle(n,t,r=null){let o=vn(this.dir,so),s;try{s=hi(o)}catch{return}if(s.length===0)return;let l=new Set;for(let c of s)try{let u=vn(o,c);t-tu(u).mtimeMs>oo+36e5?ro(u):l.add(eu(u,"utf8"))}catch{}let i=n.filter(c=>l.has(c.id)),a=i.length>0?this.resolve(i,t,r).done:[];for(let c of a)try{ro(vn(o,c))}catch{}}read(n,t){let r=[],o=new Date(n);for(o.setHours(0,0,0,0);o.getTime()<=t;o.setDate(o.getDate()+1))for(let s of iu(this.file(o.getTime())).split(`
|
|
10
|
+
`))if(s)try{let l=JSON.parse(s);typeof l.t=="number"&&typeof l.cap=="string"&&typeof l.key=="string"&&r.push(l)}catch{}return r}usedIn(n,t,r,o=n.length,s=!1){let l=Ut(t,r),i=new Map;for(let c=0;c<o;c++){let u=n[c];u.cap===t.id&&i.set(u.key,u.op==="x"||!i.has(u.key)||i.get(u.key).op==="x"?u:{...i.get(u.key),op:u.op})}let a=0;for(let c of i.values())c.op!=="x"&&c.t>=l&&(s||c.t<=r)&&(a+=c.n);return a}used(n,t,r=null){return this.resolve([n],t,r),this.usedIn(this.read(Ut(n,t),t),n,t)}resolve(n,t,r=null){let o=new Set(n.map(m=>m.id)),s=Math.min(...n.map(m=>Ut(m,t))),l=new Map;for(let m of this.read(s,t))o.has(m.cap)&&l.set(`${m.cap}\0${m.key}`,m);let i=[...l.values()].filter(m=>m.tr&&m.call&&(m.op==="x"?typeof m.seen=="number":m.op==="ask"||t-m.t<=oo)),a=[];if(i.length===0)return{left:0,done:a};let c=i.length;i.sort((m,k)=>+(k.op==="x")-+(m.op==="x")||k.t-m.t);let u=new Set(r?.s?i.filter(m=>m.s===r.s).map(m=>m.tr):[]),d=m=>[...new Set(m.map(k=>k.tr))].filter(k=>!u.has(k)).slice(0,su),f=[...new Set([...u,...d(i.filter(m=>m.op==="x")),...d(i.filter(m=>m.op!=="x"))])],h=new Map(f.map(m=>[m,_i(ee(m,4*1024*1024),new Set(i.filter(k=>k.tr===m).map(k=>k.call)))]));for(let m of i){let k=h.get(m.tr);if(!k)continue;let E=k.get(m.call)??[],q=W=>(this.write(W),c--,void a.push(vi(m.cap,m.key)));m.op==="x"?E.length>1||E.length===1&&!E[0].refused?q({t:m.t,op:"ran",cap:m.cap,key:m.key,n:typeof m.was=="number"&&Number.isFinite(m.was)?m.was:0}):t-m.seen>=oo&&q({t:m.t,op:"x",cap:m.cap,key:m.key,n:0}):E.length===1&&E[0].refused?r&&m.s!==void 0&&r.s===m.s&&(r.a??"")===(m.a??"")&&this.write({t:m.t,op:"x",cap:m.cap,key:m.key,n:0,tr:m.tr,call:m.call,seen:t,was:m.n,s:m.s,a:m.a??""}):E.length>0&&q({t:m.t,op:"ran",cap:m.cap,key:m.key,n:m.n})}return{left:c,done:a}}prune(n){try{let t=bi(n-ou*864e5);for(let r of hi(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<t&&ro(vn(this.dir,r))}catch{}}},Bt=class extends ft{admit(n,t,r,o,s,l=null,i=null,a=null){if(n.length===0)return null;let c=n.map(h=>Kt(h,r,l));this.resolve(n,o,a),n.forEach((h,m)=>this.write({t:o,op:"ran",cap:h.id,key:t,n:c[m],...ki(i)})),s?.();let u=Math.min(...n.map(h=>Ut(h,o))),d=this.read(u,o+6e4),f=[];if(n.forEach((h,m)=>{let k=d.findIndex(E=>E.cap===h.id&&E.key===t&&E.op==="ran"&&E.t===o);if(k<0)f.push({cap:h,used:h.limit,n:c[m]});else{let E=this.usedIn(d,h,o,k+1,!0);E>h.limit&&f.push({cap:h,used:E-d[k].n,n:c[m]})}}),f.length>0)for(let h of n)this.write({t:o,op:"x",cap:h.id,key:t,n:0});return this.prune(o),f.length>0?{...f[0],...f.length>1?{also:f.slice(1)}:{}}:null}count(n,t,r,o,s="ran",l,i=null){for(let a of n)this.write({t:o,op:s,cap:a.id,key:t,n:du(a,r,i),...ki(l)})}},ki=e=>e?.tr&&e.call?{tr:e.tr,call:e.call,...e.s?{s:e.s,a:e.a??""}:{}}:{},vi=(e,n)=>Jc("sha256").update(`${e}\0${n}`).digest("hex").slice(0,32),fu=new Set(["user-rejected","permission-rule","automode-blocked","automode-unavailable","cancelled"]);function pu(e,n){return _i(e,new Set([n])).get(n)??[]}function _i(e,n){let t=new Map,r=new Map;for(let o of e.matchAll(/"tool_use_id":\s?"([^"\\]{1,200})"/g)){if(!n.has(o[1]))continue;let s=e.lastIndexOf(`
|
|
11
|
+
`,o.index)+1;(r.get(s)??r.set(s,new Set).get(s)).add(o[1])}for(let[o,s]of[...r].sort((l,i)=>l[0]-i[0])){let l=e.indexOf(`
|
|
12
|
+
`,o);try{let i=JSON.parse(e.slice(o,l<0?void 0:l));if(i.type!==void 0&&i.type!=="user")continue;let a=Array.isArray(i.message?.content)?i.message.content:[],c=i.toolDenialKind;for(let u of s){let d=a.find(h=>h&&h.type==="tool_result"&&h.tool_use_id===u);if(!d)continue;(t.get(u)??t.set(u,[]).get(u)).push({refused:d.is_error===!0&&(typeof c=="string"?fu.has(c):i.toolUseResult==="User rejected tool use")})}}catch{for(let i of s)(t.get(i)??t.set(i,[]).get(i)).push({refused:!1})}}return t}function Ai(e,n){return!e||!n?null:gu(ee(e,4*1024*1024),n)}function gu(e,n){let t=e.indexOf(`"tool_use_id":"${n}"`);if(t<0)return null;let r=e.slice(e.lastIndexOf(`
|
|
13
13
|
`,t)+1,e.indexOf(`
|
|
14
14
|
`,t)<0?void 0:e.indexOf(`
|
|
15
|
-
`,t));try{let o=JSON.parse(r),
|
|
16
|
-
`){let
|
|
17
|
-
`}),s=
|
|
18
|
-
`?t[++a]=
|
|
19
|
-
`,a);if(
|
|
20
|
-
`||c===";"?
|
|
21
|
-
`&&(i=s,r.length>0&&(o=r.shift())))}return n.push({start:s,end:e.length,op:""}),{segments:n,quotes:t}}var ht=(e,n,t)=>n[t]>0&&n[t]<on&&e[t]===ze[n[t]];function Ln(e,n,t){if(hr.lastIndex=n,!hr.exec(e))return n;let r=hr.lastIndex;if((t[n]&~on)===0)return r;for(let o=n;o<r;o++)if(ht(e,t,o))return o;return r}function Re(e,n,t=()=>!0,r=()=>!0){let{quotes:o}=bn(e),s="",i=0;n.lastIndex=0;for(let l=n.exec(e);l;l=n.exec(e)){let a=l.index+l[0].length;if(!t(l))continue;let c=Ln(e,a,o);c===a||!r(e.slice(a,c))||(s+=e.slice(i,a)+ne,i=n.lastIndex=c)}return s+e.slice(i)}var ee=e=>new RegExp(`(?:^|\\s)(?:${e})(?:=|${mt})(?=[^\\s-])`,"g"),fe=e=>new RegExp(`(?:^|[\\s"'(/])(?:${e})(?=$|[\\s"';)])`),yn=(e,n=0,t="(?!)")=>{let r=`(?:${$}(?:(?:${t})${$}[^\\s-][^\\s]*|(?!(?:${t})${$})-[\\w-]+(?:=[^\\s]*)?))*`;return new RegExp(`(?:^|[\\s"'(/])(?:${e})${r}(?:${$}[^\\s-][^\\s]*${r}){${n}}${$}(?=[^\\s-])`,"g")},Ws=new RegExp(`(?:^|[\\s(])(?:http|https|xh|xhs)${$}`),mc=[{when:fe("mysql\\w*|mariadb[\\w-]*"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:fe("redis-cli|keydb-cli|valkey-cli"),flag:ee("-a")},{when:fe("curl"),flag:ee("-[A-Za-z]*[uUb]|--user|--proxy-user")},{when:Ws,flag:ee("-a")},{when:new RegExp(`${fe("sshpass|mongo|mongosh|mongodump|mongorestore|mongoexport|mongoimport|twine|cqlsh").source}|(?:^|\\s)login(?=$|\\s)`),flag:ee("-p")},{when:/\bgh\s+secret\s+set\b/,flag:ee("-b|--body")},{when:/\bsecurity\s+add-(?:generic|internet)-password\b/,flag:ee("-w")},{when:/\bsecurity\s+(?:unlock-keychain|create-keychain|set-keychain-password)\b/,flag:ee("-p|-o")},{when:/\bsecurity\s+import\b/,flag:ee("-P")},{when:fe("sqlcmd|bcp|osql|isql"),flag:ee("-P")},{when:fe("zip|zipcloak|unzip"),flag:ee("-P|--password")},{when:fe("7z|7za|7zr|7zz"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:fe("ldap\\w+"),flag:ee("-w|-s")},{when:fe("openssl"),flag:ee("-k|-K")},{when:fe("ssh-keygen"),flag:ee("-N|-P")},{when:fe("smbclient|rpcclient|smbmap|smbget|smbcacls|net"),flag:new RegExp(`(?:^|\\s)(?:-U|--user(?:name)?)(?:=|${mt})[^\\s%"']+%(?=[^\\s])`,"g")},{when:/\bvault\s+login\b/,flag:new RegExp(`\\bvault${$}login(?:${$}-[\\w-]+(?:=[^\\s]*)?)*${$}(?=[^\\s=-][^\\s=]*(?:\\s|$))`,"g")},{when:/\bnetlify\s+env:set\b/,flag:yn(`netlify${$}env:set`,1)},{when:/\bconvex\s+env\s+set\b/,flag:yn(`convex${$}env${$}set`,1)},{when:/\bcargo\s+login\b/,flag:yn(`cargo${$}login`,0,"--registry")},{when:/\bpoetry\s+config\b/,flag:yn(`poetry${$}config(?:${$}-[\\w-]+)*${$}pypi-token\\.[\\w.-]+`)},{when:/\bpoetry\s+config\b/,flag:yn(`poetry${$}config(?:${$}-[\\w-]+)*${$}http-basic\\.[\\w.-]+`,1)},{when:/\bngrok\b/,flag:yn(`ngrok${$}(?:config${$}add-(?:authtoken|api-key)|authtoken)`)}],hc=new RegExp(`(?:^|[\\s"'(/])htpasswd((?:${$}-(?:[A-Za-z]*[Cr]${$}\\d+|[A-Za-z]+))+)${$}(?:[^\\s]+)${$}(?:[^\\s]+)${$}(?=[^\\s])`,"g"),Rs=/\b(?:gh\s+secret\s+set|wrangler\s+(?:pages\s+)?secret\s+put|vercel\s+env\s+add|docker\s+secret\s+create|modal\s+secret\s+create|firebase\s+functions:secrets:set|fly(?:ctl)?\s+secrets\s+(?:set|import)|supabase\s+secrets\s+set|heroku\s+config:set|railway\s+variables\b[^\n]*?\s--set|security\s+add-(?:generic|internet)-password|op\s+item\s+create|vault\s+(?:kv\s+)?put|aws\s+ssm\s+put-parameter|az\s+keyvault\s+secret\s+set|gcloud\s+secrets\s+(?:create|versions\s+add)|netlify\s+env:set|convex\s+env\s+set|eas\s+(?:secret|env):create)\b/,yc=ee("--value"),wc=/^(\s*(?:echo|printf)(?:\s+-[A-Za-z]+)*\s+)\S(?:[\s\S]*\S)?/,Es=new RegExp(`<<<${mt}(?=[^\\s-])`,"g"),Ps=e=>/--password-stdin\b|\bchg?passwd\b|\bcargo\s+login\b/.test(e)||/\bsudo\b/.test(e)&&/\s(?:-(?=[A-Za-z]*S)[A-Za-z]+|--stdin)(?=\s|$)/.test(e)||/\bpasswd\b/.test(e)&&/\s--stdin\b/.test(e)||/\bgh\s+auth\s+login\b/.test(e)&&/\s--with-token\b/.test(e),dt=/(?:^|\s)(["']?)([A-Za-z][\w-]*)(==|:(?![=:/]))/g;function bc(e){let{quotes:n}=bn(e),t="",r=0;dt.lastIndex=0;for(let o=dt.exec(e);o;o=dt.exec(e)){let s=o[3]!=="==";if(!(s?js.test(o[2]):wn(o[2])))continue;let i=o.index+o[0].length,l=ze.indexOf(o[1]),a;if(l>0&&(n[i]&~on)===l)for(a=i;a<e.length&&!ht(e,n,a);)a++;else a=Ln(e,i,n);let c=i;for(;c<a&&(e[c]===" "||e[c]===" ");)c++;c===a||s&&/^\d{1,5}(?:[/?#]|$)/.test(e.slice(c,a))||(t+=e.slice(r,c)+ne,r=dt.lastIndex=a)}return t+e.slice(r)}function kc(e){let{segments:n}=bn(e),t="";for(let r=0;r<n.length;r++){let o=n[r],s=e.slice(o.start,o.end);for(let a of mc)a.when.test(s)&&(s=Re(s,a.flag));s=Re(s,hc,a=>/b/.test(a[1].replace(/\d+/g,""))),Ws.test(s)&&(s=bc(s)),Rs.test(s)?s=Ls(Re(Re(s,Es),yc),()=>!0):Ps(s)&&(s=Re(s,Es));let i=n[r+1],l=o.op==="|"&&i?e.slice(i.start,i.end):"";l&&(Rs.test(l)||Ps(l))&&(s=s.replace(wc,`$1${ne}`)),t+=s+e.slice(o.end,i?i.start:o.end)}return t}var xc=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#"'`<>]*@/gi,vc=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#:@[\]"'`<>]*:(?!\d{1,5}(?:[/?#]|$))[^\s@"'`<>]{1,256}@/gi,Sc=[/(\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],$c=e=>Sc.reduce((n,t)=>n.replace(t,`$1${ne}`),e),_c=new RegExp(`\\bmachine${$}[^\\s]+(?:${$}login${$}[^\\s]+)?${$}password${$}(?=[^\\s])`,"g"),Cc=/[._]netrc\b/,Ac=new RegExp(`(?:^|\\n|\\\\n|["'])[ \\t]*(?:login${$}[^\\s]+${$})?password${$}(?=[^\\s])`,"g"),Rc=[/\bhv[sbr]\.[A-Za-z0-9_-]{20,}/g,/\banv_(?:live|test)_[A-Za-z0-9_-]{8,}/g,/\bpypi-AgE[A-Za-z0-9_-]{16,}/g,/\bhf_[A-Za-z0-9]{30,}\b/g,/\bdo[opr]_v1_[A-Za-z0-9]{32,}\b/g],Ts=e=>{let n=e.replace(/^["'\\]+|["'\\]+$/g,"");return n.length>=8&&!/\s/.test(n)&&/\d/.test(n)&&/[A-Za-z]/.test(n)},Ms=/^(?:key|apikey|api_key_id|k)$/i,Ec=new RegExp(`(?:^|[\\s("'])--?(?!no-|noauth\\b|anyauth\\b|bypass\\b|askpass\\b)(?=[A-Za-z])[\\w-]*?(?:token|api[-_]?key|secret|secret[-_]?string|access[-_]?key|secret[-_]?key|passw(?:or)?d|passphrase|pass(?:in|out)?|otp|auth|cookie|bearer|credentials?)(?:=|${$}(?=[^\\s-]))`,"gi"),ft=new RegExp(`(?:^|\\s)(?:-H|--header)(?:=|${mt})(?=[^\\s-])`,"g");function Pc(e){let{quotes:n}=bn(e),t="",r=0;ft.lastIndex=0;for(let o=ft.exec(e);o;o=ft.exec(e)){let s=o.index+o[0].length,i=Ln(e,s,n),l=e.slice(s,i),a=l[0]==='"'||l[0]==="'"?l[0]:"",c=/^([ \t]*([\w-]+)[ \t]*:[ \t]*)\S/.exec(a?l.slice(1):l);!c||!js.test(c[2])||(t+=`${e.slice(r,s)}${a}${c[1]}${ne}${a}`,r=ft.lastIndex=i)}return t+e.slice(r)}var pt=/(?:(?<![\w.$-])|(?<=(?:^|\s)-e))([A-Za-z_][\w.-]*)(?:=(?!=)|[ \t]*=[ \t]*(?=["']))/g;function Ls(e,n=wn){let{quotes:t}=bn(e),r="",o=0;pt.lastIndex=0;for(let s=pt.exec(e);s;s=pt.exec(e)){let i=s.index+s[0].length;if(!n(s[1])&&!(Ms.test(s[1])&&Ts(e.slice(i,Ln(e,i,t)))))continue;let l=ze.indexOf(e[s.index-1]??""),a;if(l>0&&(t[s.index]&~on)===l)for(a=i;a<e.length&&!ht(e,t,a);)a++;else a=Ln(e,i,t);a!==i&&(r+=e.slice(o,i)+ne,o=pt.lastIndex=a)}return r+e.slice(o)}var gt=/(?:(\\?["'])([A-Za-z_][\w.-]*)\1|(?<![\w.$:/"'-])([A-Za-z_][\w.-]*))[ \t]*:[ \t]*/g,yr=/[^\s,}\]"'\\{[]+/y;function Oc(e){let{quotes:n}=bn(e),t="",r=0;gt.lastIndex=0;for(let o=gt.exec(e);o;o=gt.exec(e)){let s=o[2]??o[3],i=!wn(s)&&Ms.test(s);if(!wn(s)&&!i)continue;let l=o.index+o[0].length,a=/^[rRbBuUfF]{1,2}(?=["'])/.exec(e.slice(l,l+3));a&&(l+=a[0].length);let c=e[l],d="",u=-1;if(e.startsWith('\\"',l))d='\\"',u=e.indexOf('\\"',l+2);else if((c==='"'||c==="'")&&!ht(e,n,l)){d=c;let g=l+1;for(;g<e.length&&e[g]!==c;)g+=c==='"'&&e[g]==="\\"?2:1;u=g<e.length?g:-1}else(o[1]!==void 0||i)&&c!=='"'&&c!=="'"&&(yr.lastIndex=l,yr.exec(e)&&(u=yr.lastIndex));u<=l+d.length||i&&!Ts(e.slice(l+d.length,u))||(t+=e.slice(r,l)+d+ne,r=gt.lastIndex=u)}return t+e.slice(r)}var Nc=/(^|\n)([ \t]*(?:-[ \t]+)?)([A-Za-z_][\w.-]*)([ \t]*:[ \t]+)([^\s"'`#][^\n"'`]*)/g,Ic=e=>e.replace(Nc,(n,t,r,o,s)=>wn(o)?`${t}${r}${o}${s}${ne}`:n),jc=new RegExp(`\\b(?:config|configure)${$}set${$}(?:-{1,2}\\w[\\w-]*(?:=\\S*)?${$})*((?!-)[^\\s=]+)${$}(?=[^\\s-])`,"g"),Wc=/\b(?:redis|keydb|valkey)-cli\b/,Os=/(?:"[^"\n]*"|'[^'\n]*'|[^\s"'\\;&|]+)/.source,Tc=new RegExp(`\\bAUTH[ \\t]+${Os}(?:[ \\t]+${Os})?`,"g"),Ns=/^(?:to|the|a|an|is|are|for|and|or|of|in|on|it|be|as|at|by|from|with|this|that|flag|option|instead|here|there|if|when|you|your)$/i,Mc=/\b(Bearer|Basic)([ \t]+)([A-Za-z0-9\-._~+/]+=*)/gi,wr="\uE000";function Lc(e){return e.includes(wr)?e:e.replace(Mc,(n,t,r,o)=>o.length>=8&&(/[0-9+/=_~]/.test(o)||/[a-z][A-Z]|[A-Z]{2}/.test(o.slice(1)))?`${t}${r}${ne}`:`${t}${wr}${r}${o}`)}function Is(e){let n=kc(e);return n=n.replace(xc,`$1${ne}@`).replace(vc,`$1${ne}@`),n=$c(n),n=Pc(n),n=Re(n,Ec,()=>!0,t=>!Ns.test(t)),n=Re(n,_c),Cc.test(n)&&(n=Re(n,Ac,()=>!0,t=>!Ns.test(t))),n=Rc.reduce((t,r)=>t.replace(r,ne),n),n=Ls(n),n=Oc(n),n=Ic(n),n=Re(n,jc,t=>wn(t[1])),Wc.test(n)&&(n=n.replace(Tc,`AUTH ${ne}`)),$s(Lc(n)).split(wr).join("")}function Ds(e,n=8192){if(e.length<=n)return Is(e);let t=e.slice(0,n),r=t.search(/-----BEGIN [A-Z0-9 ]*-----/);return r>=0&&!/-----END [A-Z0-9 ]*-----/.test(t.slice(r))&&(t=`${t.slice(0,r)}-----BEGIN ${ne}`),Is(t)}var Fs="held by default",Dc={recordAndCount:()=>1},yt={allow:0,hold:1,block:2};function Hs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function br(e){let n={action:e.action,service:e.service,target:e.attributes.target??null,host:e.attributes.host??null,attributes:e.attributes},t=(e.findings??[]).slice(1).map(s=>{let i=s;return{action:s.action,service:s.service,target:s.target,host:typeof i.host=="string"?i.host:null,attributes:i}}),r=new Set([n,...t].map(s=>s.action)),o=e.also.filter(s=>!r.has(s)).map(s=>({action:s,service:null,target:null,host:null,attributes:{}}));return[n,...t,...o]}function kr(e,n,t,r,o,s,i,l=null,a=[]){let c=i?{session_id:i}:{},d=[n.action,...n.also.filter(p=>p!==n.action)],u=(p,A,b)=>A?"enforce":no(t,p,lr(e,p,s),b),g=(p,A,b)=>!A&&b&&to(t,p,lr(e,p,s)),h=p=>{if(p===n.action&&n.catastrophic)return{why:n.why};let A=(n.findings??[]).find(b=>b.action===p&&b.catastrophic);return A?{why:A.why}:null},m=[];d.forEach((p,A)=>{let b=A===0,{decision:I,baseline:Y}=ir(e,b?{action:p,service:n.service,metadata:{...n.attributes,...c}}:{action:p,service:null,metadata:c},r,o,s),M=Zt({action:p,decision:I,baseline:Y,service:b?n.service:null,target:b?n.attributes.target??null:null,projectDir:s,home:l,histories:a}),W=h(p),R=u(p,M,W!==null);R!=="off"&&(W&&I.verdict!=="allow"&&g(p,M,!0)?m.push({action:p,decision:I,mode:R,floor:M?.id??null,why:`${W.why} \xB7 ${Fs}`}):m.push({action:p,decision:I,mode:R,floor:M?.id??null}))});let x=new Set;for(let p of(n.findings??[]).slice(1)){if(!p.service&&!p.target)continue;let A=`${p.action}\0${p.service??""}\0${p.target??""}`;if(x.has(A))continue;x.add(A);let{decision:b,baseline:I}=ir(e,{action:p.action,service:p.service,metadata:{target:p.target,...c}},Dc,o,s);if(b.verdict==="allow")continue;let Y=Zt({action:p.action,decision:b,baseline:I,service:p.service,target:p.target,projectDir:s,home:l,histories:a}),M=p.catastrophic===!0,W=u(p.action,Y,M);W!=="off"&&m.push({action:p.action,decision:b,mode:W,floor:Y?.id??null,why:M&&g(p.action,Y,!0)?`${p.why} \xB7 ${Fs}`:p.why,target:p.target})}if(e.policies.some(p=>p.narrowed&&p.narrowed.length>0)){let p={tool:n.tool??null,parts:br(n),touched:n.touched??null,projectDir:s,home:l,command:n.command??null,input:n.input??null,...o>0?{now:o}:{}};for(let A of e.policies)if(!(!A.narrowed||!de(A,s)))for(let b of A.narrowed){let I=Ko(b,{...p,root:A.origin==="project"?A.project_dir??null:null});if(!I)continue;let Y=/^(.*):(\d+) · /.exec(b.source),M=`your rule "${b.text}"${Y?` (${Y[1]} line ${Y[2]})`:""}`,W=I.part===p.parts[0]?n.why:(n.findings??[]).find(R=>R.action===I.part.action&&R.target===I.part.target)?.why??null;m.push({action:I.part.action,decision:{verdict:I.hit==="unknown"?"hold":b.intent,policy:A.name,origin:A.origin,ruleId:b.id,blockedBy:"narrowed_rule",source:b.source},mode:t?.kill_switch===!0?"ghost":b.mode,floor:null,why:I.hit==="unknown"?`${W?`${W}: `:""}${I.why}`:`${W??I.why}${I.detail?` (${I.detail})`:""} \xB7 ${M}`,target:I.part.target})}}let _=m.filter(p=>p.decision.verdict!=="allow");if(_.length===0)return{lead:null,stops:[],mode:"ghost"};let z=_.filter(p=>p.mode==="enforce"),J=(z.length>0?z:_).reduce((p,A)=>yt[A.decision.verdict]>yt[p.decision.verdict]||yt[A.decision.verdict]===yt[p.decision.verdict]&&A.floor&&!p.floor?A:p);return{lead:J,stops:[J,..._.filter(p=>p!==J)],mode:z.length>0?"enforce":"ghost"}}var Fc=["command","cmd","script","input","code"];function Us(e,n){let t=n&&typeof n=="object"?n:{};if(e==="Bash")return zs(typeof t.command=="string"?t.command:"");if(Fc.some(o=>typeof t[o]=="string"&&zs(t[o])))return!0;let r=0;try{r=JSON.stringify(n??null)?.length??0}catch{return!0}return r>16384}function zs(e){if(e.length>2048)return!0;let n=0,t=0;for(let o=0;o<e.length;o++){let s=e[o];s===";"||s==="|"||s==="&"||s===`
|
|
22
|
-
`?(n++,(s==="|"||s==="&")&&e[o+1]===s&&o++):(s==="`"||(s==="$"||s==="<"||s===">")&&e[o+1]==="(")&&t++}return n>16||t>8||(e.match(/\{[^{}\s]*,[^{}\s]*\}/g)?.length??0)>4?!0:(e.match(/(?:^|[\s;&|(){}`])(?:cd|pushd|popd)(?=$|[\s;&|()])/g)?.length??0)>8}import{createHash as
|
|
23
|
-
`,"wx");let o=!1;try{n?
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
`)}catch{}}var
|
|
28
|
-
`))if(o)try{let s=JSON.parse(o);typeof s.p=="string"&&s.p.startsWith("/")?t.push(s.p):typeof s.l=="string"&&r.push(s.l)}catch{}return{made:t,launched:r}}function
|
|
29
|
-
`))if(
|
|
30
|
-
`)){
|
|
31
|
-
`,exitCode:0});function It(e,n){let t=v(e.env.CLAUDE_CONFIG_DIR),r=k(t?$n(t):k(e.home,".claude"),"settings.json"),o=v(e.env.CLAUDE_PROJECT_DIR)??v(n.cwd);return o?[r,k(o,".claude","settings.local.json"),k(o,".claude","settings.json")]:[r]}function Xu(e,n,t){if(e!=="Bash"||!t)return null;let r=n&&typeof n=="object"?n.command:null,o=typeof r=="string"?r.slice(0,65536):"";if(!/\bgit\b/.test(o)||!/\b(clean|stash)\b/.test(o))return null;let s=[".claude/settings.local.json",".anvil/rules.json"].filter(a=>C(k(t,a))===!0);if(s.length===0)return[];let i=ju("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","status","--porcelain=v1","--ignored","--untracked-files=all","-z","--",...s],{cwd:t,encoding:"utf8",timeout:500,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}});if(i.status!==0||typeof i.stdout!="string")return s.map(a=>({path:k(t,a),ignored:!1}));let l=[];for(let a of i.stdout.split("\0")){let c=a.slice(0,2),d=s.find(u=>a.slice(3)===u||a.slice(3).endsWith(`/${u}`));(c==="??"||c==="!!")&&d!==void 0?l.push({path:k(t,d),ignored:c==="!!"}):(c[0]==="A"||c.includes("M"))&&d!==void 0&&l.push({path:k(t,d),ignored:!1,staged:!0})}return l}function Qu(e,n,t,r){if(["Read","Glob","Grep","LS","WebFetch","WebSearch","TodoWrite"].includes(e))return null;let o=k(n,".claude"),s=k(n,".anvil"),l=[...[".zshrc",".zshenv",".zprofile",".bashrc",".bash_profile",".bash_aliases",".profile",k(".config","fish","config.fish"),...process.platform==="win32"?[k("Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),k("Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")]:[]].map(c=>k(n,c)),o,k(o,"settings.json"),k(o,"settings.local.json"),k(o,"hooks"),k(o,"plugins"),k(n,".claude.json"),s,k(s,"claude"),k(s,"claude","modes.json"),k(s,"claude","compiled.json"),k(s,"rules.json"),k(s,"workspace-keys.json")];t&&l.push(t,k(t,"settings.json"),k(t,"hooks")),r&&l.push(k(r,".claude"),k(r,".claude","settings.json"),k(r,".claude","settings.local.json"),k(r,".mcp.json"));let a={};for(let c of l){let d=Bn(c,n,!0);d!==c&&(a[d]=c)}return Object.keys(a).length>0?a:null}function Ti(e,n){return k(e.state,"covered",An(v(n.session_id)))}function ed(e,n,t){try{let r=Ti(e,t);if(C(r)!==null||!It(n,t).some(o=>dr(o)))return;D(k(e.state,"covered")),Q(r,String(n.now()))}catch{}}async function Ai(e,n,t,r){let o=()=>It(n,t).some(i=>dr(i)),s=Ti(e,t);if(C(s)===!0)return o();if(r!=="SessionStart"||!o())return!1;for(let i=0;i<300;i+=25)if(await new Promise(l=>setTimeout(l,25)),C(s)===!0)return!0;return!1}function nd(e,n){try{D(e.state),Q(k(e.state,"plugin-seen"),String(n))}catch{}}var jt=!1;async function Mi(e,n){ae=Pt=null;let t=n.now(),r=n.anvilDir?Fe(n.anvilDir):De(n.home),o=Tn(r.install)?.cli??n.cli;Nn(o),jt=typeof o=="string";let s=null,i=v(n.entry),l=Buffer.byteLength(e)/1048576,a=`(${l.toFixed(1)} MB; Anvil reads up to 8 MB)`;if(l>Uu)return hn(i)?Ue:i==="SessionStart"?G(Ae("SessionStart",`it can't read what Claude Code sent ${a}`)):td(r,e,`this call is too large to check ${a}`,t,n);try{if(s=JSON.parse(e),!s||typeof s!="object"||i&&!v(s.hook_event_name))throw new Error("hook input is not a hook event");let c=v(s.hook_event_name),d=()=>{let g=Di(r,v(s.session_id));return g?`${JSON.stringify({systemMessage:g})}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
${
|
|
35
|
-
`);if(!e.stdout)return G({systemMessage:l});try{let a=JSON.parse(e.stdout),c=typeof a.systemMessage=="string"?a.systemMessage:null;return G({...a,systemMessage:c?`${c}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
`))
|
|
39
|
-
`)
|
|
40
|
-
|
|
15
|
+
`,t));try{let o=JSON.parse(r),l=(Array.isArray(o.message?.content)?o.message.content:[]).find(c=>c.type==="tool_result"&&c.tool_use_id===n);if(!l)return null;let i=typeof l.content=="string"?l.content:JSON.stringify(l.content??"");return pu(r,n)[0]?.refused===!0||l.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(i)?"no":"yes"}catch{return null}}var io="[-.\\s\\u2010-\\u2015]",zm=new RegExp(`(?:\\+?1${io}?)?(?:\\(?\\d{3}\\)?${io}?\\d{3}${io}?\\d{4})`,"g"),mu="[-.\\s()\\u2010-\\u2015]",Um=new RegExp(`\\+[2-9]\\d(?:${mu}{0,2}\\d){5,13}\\b`,"g");var hu=/\b(?:Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi,yu=/\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b/g,wu=/\b(?:sk|pk|api|key|token|secret)[-_=][A-Za-z0-9]{20,}\b/gi,Ci=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,bu=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,ku=/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16}\b/g,vu=/\bgh[opusr]_[A-Za-z0-9]{36,}\b/g,xu=/\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,$u=/\bglpat-[A-Za-z0-9_\-]{20,}\b/g,Su=/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,_u=/\bhttps:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+/g,Au=/\bAIza[A-Za-z0-9_\-]{35}\b/g,Cu=/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,Ru=/\bSK[0-9a-f]{32}\b/g,Eu=/\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\b/g,Ou=/\bnpm_[A-Za-z0-9]{36}\b/g,Pu=/\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}\b/g,Nu=[hu,yu,wu,ku,vu,xu,$u,Su,_u,Au,Cu,Ru,Eu,Ou,Pu];function Ri(e){let n=e;n=n.replace(bu,"");for(let r of Nu)r.lastIndex=0,n=n.replace(r,"");Ci.lastIndex=0;let t=Ci.exec(n);return t&&(n=n.slice(0,t.index)),n}var ce="***",Ei=/"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?/.source,Oi=/\$\([^)]*\)?|\$\{[^}]*\}?|\\[\s\S]|[^\s"'`;&|<>()\\]/.source,lo=new RegExp(`(?:${Ei}|${Oi})(?:${Oi}|(?=["'](?![\\s;&|)<>]|$))(?:${Ei}))*`,"y"),P=/(?:[ \t]|\\\r?\n)+/.source,Jt=/(?:[ \t]|\\\r?\n)*/.source,Iu=/token|secret|passw(?:or)?d|passphrase|pwd|api[-_]?key|access[-_]?key|private[-_]?key|credentials?|auth|(?:^|[_.:-])(?:pass|pw|sig|signature)$|[_.:-]key$/i,ju=/[a-z0-9](?:Pass|Key|Sig)$/,Wu=/tokens$|tokeniz|author(?!i[sz]ation)|no_?auth$/i,Fn=e=>(Iu.test(e)||ju.test(e))&&!Wu.test(e),Li=/key|token|secret|auth|passw|cookie|session|credential|signature/i,on=["",'"',"'","`"],xn=128,Pi=/<<-?[ \t]*(["']?)([\w.@-]+)\1/y;function Hn(e){let n=[],t=new Uint8Array(e.length+1),r=[],o=null,s=0,l=0,i=0;for(let a=0;a<e.length;a++){let c=e[a];if(o!==null){if(c===`
|
|
16
|
+
`){let f=e.slice(l,a).trim();n.push({start:s,end:a,op:`
|
|
17
|
+
`}),s=l=a+1,i=0,f===o&&(o=r.shift()??null);continue}t[a]=i,c==="\\"&&i!==2&&e[a+1]!==`
|
|
18
|
+
`?t[++a]=i|xn:i?c===on[i]&&(i=0):on.indexOf(c)>0&&(i=on.indexOf(c));continue}if(t[a]=i,i){c==="\\"&&i!==2?t[++a]=i|xn:c===on[i]&&(i=0);continue}if(c==="\\"){t[++a]=xn;continue}let u=on.indexOf(c);if(u>0){i=u;continue}if(c==="#"&&(a===s||/\s/.test(e[a-1]))){let f=e.indexOf(`
|
|
19
|
+
`,a);if(f<0)break;a=f-1;continue}if(c==="<"&&e[a+1]==="<"&&e[a+2]!=="<"){Pi.lastIndex=a;let f=Pi.exec(e);if(f){r.push(f[2]),a+=f[0].length-1;continue}}let d="";c===`
|
|
20
|
+
`||c===";"?d=c:c==="&"?d=e[a+1]==="&"?"&&":e[a-1]===">"||e[a-1]==="<"||e[a+1]===">"?"":"&":c==="|"&&(d=e[a+1]==="|"?"||":e[a+1]==="&"?"|&":"|"),d&&(n.push({start:s,end:a,op:d}),a+=d.length-1,s=a+1,d===`
|
|
21
|
+
`&&(l=s,r.length>0&&(o=r.shift())))}return n.push({start:s,end:e.length,op:""}),{segments:n,quotes:t}}var Yt=(e,n,t)=>n[t]>0&&n[t]<xn&&e[t]===on[n[t]];function pt(e,n,t){if(lo.lastIndex=n,!lo.exec(e))return n;let r=lo.lastIndex;if((t[n]&~xn)===0)return r;for(let o=n;o<r;o++)if(Yt(e,t,o))return o;return r}function He(e,n,t=()=>!0,r=()=>!0){let{quotes:o}=Hn(e),s="",l=0;n.lastIndex=0;for(let i=n.exec(e);i;i=n.exec(e)){let a=i.index+i[0].length;if(!t(i))continue;let c=pt(e,a,o);c===a||!r(e.slice(a,c))||(s+=e.slice(l,a)+ce,l=n.lastIndex=c)}return s+e.slice(l)}var ae=e=>new RegExp(`(?:^|\\s)(?:${e})(?:=|${Jt})(?=[^\\s-])`,"g"),ke=e=>new RegExp(`(?:^|[\\s"'(/])(?:${e})(?=$|[\\s"';)])`),Dn=(e,n=0,t="(?!)")=>{let r=`(?:${P}(?:(?:${t})${P}[^\\s-][^\\s]*|(?!(?:${t})${P})-[\\w-]+(?:=[^\\s]*)?))*`;return new RegExp(`(?:^|[\\s"'(/])(?:${e})${r}(?:${P}[^\\s-][^\\s]*${r}){${n}}${P}(?=[^\\s-])`,"g")},Di=new RegExp(`(?:^|[\\s(])(?:http|https|xh|xhs)${P}`),Tu=[{when:ke("mysql\\w*|mariadb[\\w-]*"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:ke("redis-cli|keydb-cli|valkey-cli"),flag:ae("-a")},{when:ke("curl"),flag:ae("-[A-Za-z]*[uUb]|--user|--proxy-user")},{when:Di,flag:ae("-a")},{when:new RegExp(`${ke("sshpass|mongo|mongosh|mongodump|mongorestore|mongoexport|mongoimport|twine|cqlsh").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:/\bsecurity\s+(?:unlock-keychain|create-keychain|set-keychain-password)\b/,flag:ae("-p|-o")},{when:/\bsecurity\s+import\b/,flag:ae("-P")},{when:ke("sqlcmd|bcp|osql|isql"),flag:ae("-P")},{when:ke("zip|zipcloak|unzip"),flag:ae("-P|--password")},{when:ke("7z|7za|7zr|7zz"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:ke("ldap\\w+"),flag:ae("-w|-s")},{when:ke("openssl"),flag:ae("-k|-K")},{when:ke("ssh-keygen"),flag:ae("-N|-P")},{when:ke("smbclient|rpcclient|smbmap|smbget|smbcacls|net"),flag:new RegExp(`(?:^|\\s)(?:-U|--user(?:name)?)(?:=|${Jt})[^\\s%"']+%(?=[^\\s])`,"g")},{when:/\bvault\s+login\b/,flag:new RegExp(`\\bvault${P}login(?:${P}-[\\w-]+(?:=[^\\s]*)?)*${P}(?=[^\\s=-][^\\s=]*(?:\\s|$))`,"g")},{when:/\bnetlify\s+env:set\b/,flag:Dn(`netlify${P}env:set`,1)},{when:/\bconvex\s+env\s+set\b/,flag:Dn(`convex${P}env${P}set`,1)},{when:/\bcargo\s+login\b/,flag:Dn(`cargo${P}login`,0,"--registry")},{when:/\bpoetry\s+config\b/,flag:Dn(`poetry${P}config(?:${P}-[\\w-]+)*${P}pypi-token\\.[\\w.-]+`)},{when:/\bpoetry\s+config\b/,flag:Dn(`poetry${P}config(?:${P}-[\\w-]+)*${P}http-basic\\.[\\w.-]+`,1)},{when:/\bngrok\b/,flag:Dn(`ngrok${P}(?:config${P}add-(?:authtoken|api-key)|authtoken)`)}],Mu=new RegExp(`(?:^|[\\s"'(/])htpasswd((?:${P}-(?:[A-Za-z]*[Cr]${P}\\d+|[A-Za-z]+))+)${P}(?:[^\\s]+)${P}(?:[^\\s]+)${P}(?=[^\\s])`,"g"),Ni=/\b(?:gh\s+secret\s+set|wrangler\s+(?:pages\s+)?secret\s+put|vercel\s+env\s+add|docker\s+secret\s+create|modal\s+secret\s+create|firebase\s+functions:secrets:set|fly(?:ctl)?\s+secrets\s+(?:set|import)|supabase\s+secrets\s+set|heroku\s+config:set|railway\s+variables\b[^\n]*?\s--set|security\s+add-(?:generic|internet)-password|op\s+item\s+create|vault\s+(?:kv\s+)?put|aws\s+ssm\s+put-parameter|az\s+keyvault\s+secret\s+set|gcloud\s+secrets\s+(?:create|versions\s+add)|netlify\s+env:set|convex\s+env\s+set|eas\s+(?:secret|env):create)\b/,Lu=ae("--value"),Du=/^(\s*(?:echo|printf)(?:\s+-[A-Za-z]+)*\s+)\S(?:[\s\S]*\S)?/,Ii=new RegExp(`<<<${Jt}(?=[^\\s-])`,"g"),ji=e=>/--password-stdin\b|\bchg?passwd\b|\bcargo\s+login\b/.test(e)||/\bsudo\b/.test(e)&&/\s(?:-(?=[A-Za-z]*S)[A-Za-z]+|--stdin)(?=\s|$)/.test(e)||/\bpasswd\b/.test(e)&&/\s--stdin\b/.test(e)||/\bgh\s+auth\s+login\b/.test(e)&&/\s--with-token\b/.test(e),qt=/(?:^|\s)(["']?)([A-Za-z][\w-]*)(==|:(?![=:/]))/g;function Fu(e){let{quotes:n}=Hn(e),t="",r=0;qt.lastIndex=0;for(let o=qt.exec(e);o;o=qt.exec(e)){let s=o[3]!=="==";if(!(s?Li.test(o[2]):Fn(o[2])))continue;let l=o.index+o[0].length,i=on.indexOf(o[1]),a;if(i>0&&(n[l]&~xn)===i)for(a=l;a<e.length&&!Yt(e,n,a);)a++;else a=pt(e,l,n);let c=l;for(;c<a&&(e[c]===" "||e[c]===" ");)c++;c===a||s&&/^\d{1,5}(?:[/?#]|$)/.test(e.slice(c,a))||(t+=e.slice(r,c)+ce,r=qt.lastIndex=a)}return t+e.slice(r)}function Hu(e){let{segments:n}=Hn(e),t="";for(let r=0;r<n.length;r++){let o=n[r],s=e.slice(o.start,o.end);for(let a of Tu)a.when.test(s)&&(s=He(s,a.flag));s=He(s,Mu,a=>/b/.test(a[1].replace(/\d+/g,""))),Di.test(s)&&(s=Fu(s)),Ni.test(s)?s=zi(He(He(s,Ii),Lu),()=>!0):ji(s)&&(s=He(s,Ii));let l=n[r+1],i=o.op==="|"&&l?e.slice(l.start,l.end):"";i&&(Ni.test(i)||ji(i))&&(s=s.replace(Du,`$1${ce}`)),t+=s+e.slice(o.end,l?l.start:o.end)}return t}var zu=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#"'`<>]*@/gi,Uu=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#:@[\]"'`<>]*:(?!\d{1,5}(?:[/?#]|$))[^\s@"'`<>]{1,256}@/gi,Bu=[/(\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],Ku=e=>Bu.reduce((n,t)=>n.replace(t,`$1${ce}`),e),qu=new RegExp(`\\bmachine${P}[^\\s]+(?:${P}login${P}[^\\s]+)?${P}password${P}(?=[^\\s])`,"g"),Vu=/[._]netrc\b/,Zu=new RegExp(`(?:^|\\n|\\\\n|["'])[ \\t]*(?:login${P}[^\\s]+${P})?password${P}(?=[^\\s])`,"g"),Gu=[/\bhv[sbr]\.[A-Za-z0-9_-]{20,}/g,/\banv_(?:live|test)_[A-Za-z0-9_-]{8,}/g,/\bpypi-AgE[A-Za-z0-9_-]{16,}/g,/\bhf_[A-Za-z0-9]{30,}\b/g,/\bdo[opr]_v1_[A-Za-z0-9]{32,}\b/g],Fi=e=>{let n=e.replace(/^["'\\]+|["'\\]+$/g,"");return n.length>=8&&!/\s/.test(n)&&/\d/.test(n)&&/[A-Za-z]/.test(n)},Hi=/^(?:key|apikey|api_key_id|k)$/i,Ju=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?)(?:=|${P}(?=[^\\s-]))`,"gi"),Vt=new RegExp(`(?:^|\\s)(?:-H|--header)(?:=|${Jt})(?=[^\\s-])`,"g");function Yu(e){let{quotes:n}=Hn(e),t="",r=0;Vt.lastIndex=0;for(let o=Vt.exec(e);o;o=Vt.exec(e)){let s=o.index+o[0].length,l=pt(e,s,n),i=e.slice(s,l),a=i[0]==='"'||i[0]==="'"?i[0]:"",c=/^([ \t]*([\w-]+)[ \t]*:[ \t]*)\S/.exec(a?i.slice(1):i);!c||!Li.test(c[2])||(t+=`${e.slice(r,s)}${a}${c[1]}${ce}${a}`,r=Vt.lastIndex=l)}return t+e.slice(r)}var Zt=/(?:(?<![\w.$-])|(?<=(?:^|\s)-e))([A-Za-z_][\w.-]*)(?:=(?!=)|[ \t]*=[ \t]*(?=["']))/g;function zi(e,n=Fn){let{quotes:t}=Hn(e),r="",o=0;Zt.lastIndex=0;for(let s=Zt.exec(e);s;s=Zt.exec(e)){let l=s.index+s[0].length;if(!n(s[1])&&!(Hi.test(s[1])&&Fi(e.slice(l,pt(e,l,t)))))continue;let i=on.indexOf(e[s.index-1]??""),a;if(i>0&&(t[s.index]&~xn)===i)for(a=l;a<e.length&&!Yt(e,t,a);)a++;else a=pt(e,l,t);a!==l&&(r+=e.slice(o,l)+ce,o=Zt.lastIndex=a)}return r+e.slice(o)}var Gt=/(?:(\\?["'])([A-Za-z_][\w.-]*)\1|(?<![\w.$:/"'-])([A-Za-z_][\w.-]*))[ \t]*:[ \t]*/g,ao=/[^\s,}\]"'\\{[]+/y;function Xu(e){let{quotes:n}=Hn(e),t="",r=0;Gt.lastIndex=0;for(let o=Gt.exec(e);o;o=Gt.exec(e)){let s=o[2]??o[3],l=!Fn(s)&&Hi.test(s);if(!Fn(s)&&!l)continue;let i=o.index+o[0].length,a=/^[rRbBuUfF]{1,2}(?=["'])/.exec(e.slice(i,i+3));a&&(i+=a[0].length);let c=e[i],u="",d=-1;if(e.startsWith('\\"',i))u='\\"',d=e.indexOf('\\"',i+2);else if((c==='"'||c==="'")&&!Yt(e,n,i)){u=c;let f=i+1;for(;f<e.length&&e[f]!==c;)f+=c==='"'&&e[f]==="\\"?2:1;d=f<e.length?f:-1}else(o[1]!==void 0||l)&&c!=='"'&&c!=="'"&&(ao.lastIndex=i,ao.exec(e)&&(d=ao.lastIndex));d<=i+u.length||l&&!Fi(e.slice(i+u.length,d))||(t+=e.slice(r,i)+u+ce,r=Gt.lastIndex=d)}return t+e.slice(r)}var Qu=/(^|\n)([ \t]*(?:-[ \t]+)?)([A-Za-z_][\w.-]*)([ \t]*:[ \t]+)([^\s"'`#][^\n"'`]*)/g,ed=e=>e.replace(Qu,(n,t,r,o,s)=>Fn(o)?`${t}${r}${o}${s}${ce}`:n),nd=new RegExp(`\\b(?:config|configure)${P}set${P}(?:-{1,2}\\w[\\w-]*(?:=\\S*)?${P})*((?!-)[^\\s=]+)${P}(?=[^\\s-])`,"g"),td=/\b(?:redis|keydb|valkey)-cli\b/,Wi=/(?:"[^"\n]*"|'[^'\n]*'|[^\s"'\\;&|]+)/.source,rd=new RegExp(`\\bAUTH[ \\t]+${Wi}(?:[ \\t]+${Wi})?`,"g"),Ti=/^(?: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,od=/\b(Bearer|Basic)([ \t]+)([A-Za-z0-9\-._~+/]+=*)/gi,co="\uE000";function sd(e){return e.includes(co)?e:e.replace(od,(n,t,r,o)=>o.length>=8&&(/[0-9+/=_~]/.test(o)||/[a-z][A-Z]|[A-Z]{2}/.test(o.slice(1)))?`${t}${r}${ce}`:`${t}${co}${r}${o}`)}function Mi(e){let n=Hu(e);return n=n.replace(zu,`$1${ce}@`).replace(Uu,`$1${ce}@`),n=Ku(n),n=Yu(n),n=He(n,Ju,()=>!0,t=>!Ti.test(t)),n=He(n,qu),Vu.test(n)&&(n=He(n,Zu,()=>!0,t=>!Ti.test(t))),n=Gu.reduce((t,r)=>t.replace(r,ce),n),n=zi(n),n=Xu(n),n=ed(n),n=He(n,nd,t=>Fn(t[1])),td.test(n)&&(n=n.replace(rd,`AUTH ${ce}`)),Ri(sd(n)).split(co).join("")}function Ui(e,n=8192){if(e.length<=n)return Mi(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 ${ce}`),Mi(t)}var Bi="held by default",Ki={recordAndCount:()=>1},Xt={allow:0,hold:1,block:2};function Vi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function uo(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 l=s;return{action:s.action,service:s.service,target:s.target,host:typeof l.host=="string"?l.host:null,attributes:l}}),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]}var qi="claude.bash.git.push_main",gt="claude.bash.prod.target";function fo(e,n){return Ye(n).includes("protect-main")&&![e.action,...e.also].includes(qi)&&[e,...e.findings??[]].some(t=>t.service==="git.main")?{...e,also:[...e.also,qi]}:e}function po(e,n,t,r,o,s,l,i=null,a=[]){let c=fo(n,t),u=l?{session_id:l}:{},d=[c.action,...c.also.filter(g=>g!==c.action)],f=Ye(t),h=(g,x)=>C=>{let O=Mr(C,{service:g,target:x,projectDir:s,home:i,histories:a});return O!==void 0&&f.includes(O)},m=g=>{let x=us(g);return x&&f.includes(x.id)?null:x},k=(g,x,C)=>{if(x)return"enforce";let O=ct(e,g,s);return O===null&&st.has(g)?C&&Tr(t,g,null)?"enforce":"off":It(t,g,O,C)},E=(g,x,C,O)=>O==="enforce"&&!C&&!x&&Wt.has(g)?"ghost":O,q=(g,x,C)=>!x&&C&&Tr(t,g,ct(e,g,s)),W=g=>{let x=(c.findings??[]).filter(C=>C.action===g);return(g===c.action?c.copy===!0:x.length>0)&&x.every(C=>C.copy===!0)&&ct(e,g,s)===null},oe=g=>{let x=ps[g];return x!==void 0&&Ys(e,g,s,x)},Pe=g=>g.catastrophic===!0&&!(g.described&&f.includes(os)),se=g=>{if(g===c.action&&Pe(c))return{why:c.why};let x=(c.findings??[]).find(C=>C.action===g&&Pe(C));return x?{why:x.why}:null},w=[],Se=(g,x,C,O,L)=>{if(g===gt)return;let{decision:R,baseline:y}=Ft(e,{action:gt,service:C,metadata:L},Ki,o,s,h(C,O));if(R.verdict==="allow"||R.origin==="baseline")return;let S=m({action:gt,decision:R,baseline:y,service:C,target:O,projectDir:s,home:i,histories:a,prod:x}),_=k(gt,S,!1);_!=="off"&&w.push({action:gt,decision:R,mode:_,floor:S?.id??null,why:x,target:O})};d.forEach((g,x)=>{let C=x===0,O=C?c.service:null,L=C?c.attributes.target??null:null,{decision:R,baseline:y}=Ft(e,C?{action:g,service:c.service,metadata:{...c.attributes,...u}}:{action:g,service:null,metadata:u},r,o,s,h(O,L)),S=m({action:g,decision:R,baseline:y,service:O,target:L,projectDir:s,home:i,histories:a,prod:C&&c.prod});if(!S&&W(g))return;let _=se(g),ne=oe(g),we=ne&&!S&&_===null,fe=we?y:R,Ve=we?It(t,g,null,!1):E(g,C?c.prod:c.findings?.some(Rn=>Rn.action===g&&Rn.prod),S,k(g,S,_!==null));Ve!=="off"&&_&&fe.verdict!=="allow"&&q(g,S,!0)?w.push({action:g,decision:fe,mode:Ve,floor:S?.id??null,why:`${_.why} \xB7 ${Bi}`}):Ve!=="off"&&w.push({action:g,decision:fe,mode:Ve,floor:S?.id??null,...S?.id==="stay-out-of-prod"?{why:c.prod}:_&&ne?{why:_.why}:{}}),C&&c.prod&&Se(g,c.prod,O,L,{...c.attributes,...u})});let N=new Set;for(let g of(c.findings??[]).slice(1)){if(!g.service&&!g.target&&!g.prod)continue;let x=`${g.action}\0${g.service??""}\0${g.target??""}${g.prod?"\0p":""}`;if(N.has(x))continue;N.add(x);let{decision:C,baseline:O}=Ft(e,{action:g.action,service:g.service,metadata:{target:g.target,...u}},Ki,o,s,h(g.service,g.target));if(C.verdict==="allow")continue;let L=m({action:g.action,decision:C,baseline:O,service:g.service,target:g.target,projectDir:s,home:i,histories:a,prod:g.prod});if(!L&&g.copy===!0&&ct(e,g.action,s)===null)continue;let R=Pe(g),y=!L&&!R&&oe(g.action),S=y?O:C;if(S.verdict==="allow")continue;let _=y?It(t,g.action,null,!1):E(g.action,g.prod,L,k(g.action,L,R));_!=="off"&&w.push({action:g.action,decision:S,mode:_,floor:L?.id??null,why:L?.id==="stay-out-of-prod"?g.prod:R&&q(g.action,L,!0)?`${g.why} \xB7 ${Bi}`:g.why,target:g.target}),g.prod&&Se(g.action,g.prod,g.service,g.target,{target:g.target,...u})}if(e.policies.some(g=>g.narrowed&&g.narrowed.length>0)){let g={tool:c.tool??null,parts:uo(c),touched:c.touched??null,projectDir:s,home:i,command:c.command??null,input:c.input??null,...o>0?{now:o}:{}};for(let x of e.policies)if(!(!x.narrowed||!ie(x,s)))for(let C of x.narrowed){let O=Js(C,{...g,root:x.origin==="project"?x.project_dir??null:null});if(!O)continue;let L=/^(.*):(\d+) · /.exec(C.source),R=`your rule "${C.text}"${L?` (${L[1]} line ${L[2]})`:""}`,y=O.part===g.parts[0]?c.why:(c.findings??[]).find(_=>_.action===O.part.action&&_.target===O.part.target)?.why??null,S=_=>`${y??O.why}${_?` (${_})`:""} \xB7 ${R}`;w.push({action:O.part.action,decision:{verdict:O.hit==="unknown"?"hold":C.intent,policy:x.name,origin:x.origin,ruleId:C.id,blockedBy:"narrowed_rule",source:C.source},mode:t?.kill_switch===!0?"ghost":C.mode,floor:null,why:O.hit==="unknown"?`${y?`${y}: `:""}${O.why}`:S(O.detail),...O.steady!==void 0?{same:S(O.steady)}:{},target:O.part.target})}}let Ne=w.filter(g=>g.decision.verdict!=="allow");if(Ne.length===0)return{lead:null,stops:[],mode:"ghost"};let Ie=Ne.filter(g=>g.mode==="enforce"),me=Ie.length>0?Ie:Ne,z=g=>g.floor?g.floor==="keep-env-out"?1:0:2,M=(g,x)=>g.action===x.action&&x.action!==c.action&&x.why===void 0&&g.why!==void 0,ye=me.reduce((g,x)=>Xt[x.decision.verdict]>Xt[g.decision.verdict]||Xt[x.decision.verdict]===Xt[g.decision.verdict]&&(z(x)<z(g)||z(x)===z(g)&&M(x,g))?x:g);return{lead:ye,stops:[ye,...Ne.filter(g=>g!==ye)],mode:Ie.length>0?"enforce":"ghost"}}var id=["command","cmd","script","input","code"];function Gi(e,n){let t=n&&typeof n=="object"?n:{};if(e==="Bash")return Zi(typeof t.command=="string"?t.command:"");if(id.some(o=>typeof t[o]=="string"&&Zi(t[o])))return!0;let r=0;try{r=JSON.stringify(n??null)?.length??0}catch{return!0}return r>16384}function Zi(e){if(e.length>2048)return!0;let n=0,t=0;for(let o=0;o<e.length;o++){let s=e[o];s===";"||s==="|"||s==="&"||s===`
|
|
22
|
+
`?(n++,(s==="|"||s==="&")&&e[o+1]===s&&o++):(s==="`"||(s==="$"||s==="<"||s===">")&&e[o+1]==="(")&&t++}return n>16||t>8||(e.match(/\{[^{}\s]*,[^{}\s]*\}/g)?.length??0)>4?!0:(e.match(/(?:^|[\s;&|(){}`])(?:cd|pushd|popd)(?=$|[\s;&|()])/g)?.length??0)>8}import{createHash as pl,randomBytes as gl}from"crypto";import{readdirSync as wd,renameSync as bd,unlinkSync as ph}from"fs";import{join as lr}from"path";import{createHmac as ld,randomBytes as go,timingSafeEqual as ad}from"crypto";import{closeSync as Qi,existsSync as mo,fsyncSync as el,linkSync as cd,mkdirSync as nl,openSync as tl,readdirSync as ud,readFileSync as Un,unlinkSync as rl,writeSync as ol}from"fs";import{basename as dd,dirname as nr,join as ve}from"path";var ze="_seal";function or(e){return ve(e.dir,"seal.key")}function zn(e,n){return ve(e.state,"lkg",n)}function Oe(e){let n=or(e);if(j(n,1024)!==!0)return null;try{let t=Un(n,"utf8").trim();return/^[0-9a-f]{64}$/.test(t)?Buffer.from(t,"hex"):null}catch{return null}}function wo(e){return Oe(e)?"ok":j(or(e),1024)===null?"missing":"damaged"}var tr=class extends Error{};function sr(e,n){return`Anvil's seal key (${or(e)}) is ${n==="damaged"?"damaged":"missing"}`}function fd(e){let n=Oe(e);if(n)return n;let t=wo(e);if(t==="damaged"||bo(e))throw new tr(`${sr(e,t)}; run ${he("on")} to restore it`);let{key:r,created:o}=pd(e,!1);return o&&gd(e,r),r}function Ji(e,n,t){let r=tl(e,t,384);try{ol(r,n),el(r)}finally{Qi(r)}}function pd(e,n){nl(e.dir,{recursive:!0,mode:448});let t=or(e),r=ve(e.dir,`.seal.key.${process.pid}.${go(4).toString("hex")}.tmp`);Ji(r,`${go(32).toString("hex")}
|
|
23
|
+
`,"wx");let o=!1;try{n?ut(r,t):cd(r,t),o=!0}catch(l){let i=l.code??"";if(i!=="EEXIST"){if(n||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(i))throw l;try{Ji(t,Un(r,"utf8"),"wx"),o=!0}catch(a){if(a.code!=="EEXIST")throw a}}}finally{try{rl(r)}catch{}}let s=Oe(e);if(!s)throw new tr(`${sr(e,"damaged")}; run ${he("on")} to restore it`);return{key:s,created:o}}function gd(e,n){let t=[[e.modes,er],[e.compiled,ll],[e.install,void 0]];for(let[r,o]of t)if(j(r,8*1024*1024)===!0)try{let s=Un(r,"utf8");if(s.includes(`"${ze}"`))continue;let l=JSON.parse(s);if(!l||typeof l!="object"||Array.isArray(l))continue;r===e.modes&&delete l.turned_off;let i=`${JSON.stringify(yo(n,l),null,2)}
|
|
24
|
+
`;$n(r,i),o&&$n(zn(e,o),i)}catch{}if(j(e.modes)===null&&j(zn(e,er))===null){let r=`${JSON.stringify(yo(n,Wr()),null,2)}
|
|
25
|
+
`;$n(e.modes,r),$n(zn(e,er),r)}}function ho(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>ho(t===void 0?null:t,n+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(n===0&&r===ze)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${ho(e[r],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function sl(e,n){return ld("sha256",e).update(ho(n)).digest("hex")}function Qt(e){if(!(ze in e))return e;let n={...e};return delete n[ze],n}function yo(e,n){let t=Qt(n);return{...t,[ze]:sl(e,t)}}function md(e,n){let t=n[ze];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let r;try{r=sl(e,n)}catch{return!1}return ad(Buffer.from(t,"hex"),Buffer.from(r,"hex"))}function $n(e,n,t=384){nl(nr(e),{recursive:!0,mode:448});let r=ve(nr(e),`.${dd(e)}.${process.pid}.${Date.now().toString(36)}.${go(3).toString("hex")}.tmp`);try{let o=tl(r,"w",t);try{ol(o,n),el(o)}finally{Qi(o)}ut(r,e)}catch(o){try{rl(r)}catch{}throw o}}function xe(e,n,t=8*1024*1024){let r=j(e,t);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(Un(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:n?ze in o?md(n,o)?{status:"ok",value:Qt(o)}:{status:"changed",value:Qt(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:Qt(o)}}function il(e,n,t,r){let o=fd(e),s=`${JSON.stringify(yo(o,t),null,2)}
|
|
26
|
+
`;$n(n,s),r&&$n(zn(e,r),s)}var er="modes.json",ll="compiled.json";function bo(e){return mo(ve(e.bin,"claude-hook.sh"))||hd(e)}function hd(e){let n=t=>{try{return ud(t).slice(0,200).some(r=>r.endsWith(".json")&&j(ve(t,r),65536)===!0&&Un(ve(t,r),"utf8").includes(`"${ze}"`))}catch{return!1}};if(n(ve(e.state,"lkg"))||n(ve(e.state,"pending"))||n(e.approvals))return!0;for(let t of[e.modes,e.compiled,e.install])if(j(t,8*1024*1024)===!0)try{if(Un(t,"utf8").includes(`"${ze}"`))return!0}catch{}return!1}var rr=J({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function Yi(e=new Date){return is(null,"enforce","all",e)}function al(e,n=Oe(e),t={}){if(!n){let l=wo(e);if(t.installed===!0||l==="damaged"||bo(e))return{value:Yi(),source:"strict",problem:`${sr(e,l)}, so every rule is enforced until \`${he("on")}\` restores it`};let i=xe(e.modes,null);if(i.status!=="unkeyed")return{value:null,source:"unkeyed",problem:null};let{turned_off:a,...c}=i.value;return{value:c,source:"unkeyed",problem:null}}let r=xe(e.modes,n);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${rr[r.status]??"cannot be used"}`,s=xe(zn(e,er),n);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:Yi(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${he("on")}\` resets it`}}function cl(e,n,t=Oe(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===Jr&&Array.isArray(c.policies),s=()=>{if(!n)return null;let c=xe(n,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!t){let c=wo(e),u=r.installed===!0||c==="damaged"||bo(e),d=xe(e.compiled,null),f=d.status==="unkeyed"&&o(d.value)?d.value:null;return u?{value:null,source:"strict",problem:`${sr(e,c)}: \`${he("on")}\` restores it`}:{value:f??s(),source:"unkeyed",problem:null}}let l=xe(e.compiled,t);if(l.status==="ok"&&o(l.value))return{value:l.value,source:"file",problem:null};let i=`compiled.json ${l.status==="ok"?"is not a rules table":rr[l.status]??"cannot be used"}`,a=xe(zn(e,ll),t);return a.status==="ok"&&o(a.value)?{value:a.value,source:"last-good",problem:`${i}; Anvil keeps the rules it last compiled`}:l.status==="missing"&&a.status==="missing"&&j(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${i}, and so is Anvil's own copy: \`${he("on")}\` recompiles them`}}function Xi(e,n){return n&&(e===n||e.startsWith(`${n}/`))?`~${e.slice(n.length)}`:e}function ir(e,n,t,r=!0){let o=xe(e.install,n,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${rr.unreadable}`];if(n&&o.status!=="ok")return[`install.json ${rr[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):[],l=[];for(let d of s.slice(0,64)){if(!d||typeof d.real_path!="string"||typeof d.command!="string")continue;let f=gi(d.settings_path??d.real_path,fi(d)),h=Xi(d.settings_path??d.real_path,t);f!=="present"&&(f==="no-file"&&d.scope==="project"&&!mo(nr(nr(d.real_path)))||(f==="disabled"?r&&l.push(`${h} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):f==="missing"||f==="no-file"?l.push(`Anvil's hook was taken out of ${h} outside \`${he("off")}\`, so new sessions are not checked`):l.push(`${h} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let i=o.status==="ok"||o.status==="unkeyed"?o.value:null,a=[...Array.isArray(i?.package_dirs)?i.package_dirs:[],...typeof i?.package_dir=="string"?[i.package_dir]:[]].filter(d=>typeof d=="string"&&d.startsWith("/")).slice(0,16),c=a[a.length-1]??"",u=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return s.length>0&&a.length>0&&a.every(d=>!mo(ve(d,"package.json")))&&l.push(`the Anvil package that installed this hook is gone (${Xi(c,t)}): keep Anvil with ${D(u)} on, or remove it with ${D(u)} off --purge`),l}function yd(e){return ve(e.state,"health.json")}function ul(e,n,t){try{let r=yd(e),o=xe(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;$n(r,`${JSON.stringify({v:1,at:new Date(t).toISOString(),...n})}
|
|
27
|
+
`)}catch{}}var yh=600*1e3,kd=1440*60*1e3,dl="23456789abcdefghjkmnpqrstuvwxyz",fl=8;function ar(e){return lr(e.state,"pending")}function vd(){let e=gl(fl),n="";for(let t=0;t<fl;t++)n+=dl[e[t]%dl.length];return n}function xd(e){return pl("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var $d=()=>gl(8).toString("hex"),ko=e=>`${pl("sha256").update(e??"").digest("hex").slice(0,12)}.`;function ml(e,n,t){let r=vd(),o=$d();U(ar(e));let s={v:2,id:o,code_sha256:xd(r),...n,created_at:new Date(t).toISOString(),expires_at:new Date(t+kd).toISOString()};return il(e,lr(ar(e),`${ko(n.session)}${o}.json`),s),{code:r,id:o}}function Sd(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function hl(e,n,t,r,o,s,l=!0){let i=[];try{i=wd(e.approvals).filter(c=>c.endsWith(".json")&&!c.includes(".used-")).slice(0,2e3)}catch{return{approved:!1,forged:0}}let a=0;for(let c of i){let u=lr(e.approvals,c),d=xe(u,n,64*1024);if(d.status==="missing")continue;if(d.status!=="ok"||d.value.v!==2||!Array.isArray(d.value.stops)){a++;continue}let f=d.value;if(Date.parse(f.expires_at)>=s&&!((f.session??null)!==(t??null)||(f.project??null)!==(r??null))&&o.every(h=>f.stops.some(m=>Sd(m,h)))){if(!l)return{approved:!0,forged:a};try{return bd(u,lr(e.approvals,`${c.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:a}}catch{}}}return{approved:!1,forged:a}}import{lstatSync as Ad,readdirSync as Cd,statSync as Rd,utimesSync as Ed}from"fs";import{join as mt}from"path";import{posix as ey}from"path";import{posix as zh}from"path";var _d=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});var Eh=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});var Oh=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"});var Ph=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"}),Nh=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 Ih=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 Th}from"module";var vo=10080*60*1e3;function yl(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 xo(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 $o=3600*1e3;var Od=600,Pd=256*1024;function So(e,n){return mt(e.state,"sessions",`${n}.jsonl`)}function wl(e,n){if(!n)return{made:[],launched:[]};let t=[],r=[];for(let o of ee(So(e,n),Pd).split(`
|
|
28
|
+
`))if(o)try{let s=JSON.parse(o);typeof s.p=="string"&&s.p.startsWith("/")?t.push(s.p):typeof s.l=="string"&&r.push(s.l)}catch{}return{made:t,launched:r}}function Nd(e){try{return Ad(e),!0}catch{return!1}}function bl(e,n,t,r,o=null,s=Date.now()){if(!(!n||t.paths.length===0&&t.launched.length===0))try{U(mt(e.state,"sessions"));let l=So(e,n),i=[...r.made];for(let a of t.paths)i.some(c=>a===c||a.startsWith(`${c}/`))||Nd(a)||(rn(l,JSON.stringify(o?{p:a,t:s,d:o}:{p:a})),i.push(a));for(let a of t.launched)r.launched.includes(a)||rn(l,JSON.stringify({l:a.slice(0,Od)}))}catch{}}function kl(e,n,t=Date.now()){if(n)try{let r=new Date(t);Ed(So(e,n),r,r)}catch{}}function vl(e,n,t,r,o=Date.now()){if(!n||!t)return[];let s=Date.now(),l=new Set,i=0;try{let a=mt(e.state,"sessions"),c=Cd(a).filter(u=>u.endsWith(".jsonl")&&u!==`${n}.jsonl`).map(u=>({f:u,at:Rd(mt(a,u)).mtimeMs})).filter(u=>o-u.at>=$o&&o-u.at<=vo+$o).sort((u,d)=>d.at-u.at).slice(0,200);for(let{f:u}of c){if(i>4*1024*1024||l.size>=5e3||Date.now()-s>150)break;let d=ee(mt(a,u),64*1024);i+=d.length;for(let f of d.split(`
|
|
29
|
+
`))if(f.includes('"d"'))try{let h=JSON.parse(f);if(typeof h.p!="string"||typeof h.t!="number"||h.d!==t||o-h.t>vo||h.t>o)continue;if(yl(h.p,t,r)&&l.add(h.p),l.size>=5e3)break}catch{}}}catch{}return[...l]}import{spawnSync as Id}from"child_process";import{lstatSync as jd,realpathSync as _o,statSync as Wd}from"fs";import{dirname as Td}from"path";var Bn=["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null"];function xl(e){let n=[];for(let t of e.split("\0")){let[r="",o="true"]=t.split(`
|
|
30
|
+
`);if(r==="submodule.recurse"){if(!/^(false|no|off|0)$/i.test(o))return null}else if(r!==""){let s=r.slice(7,r.lastIndexOf("."));if(!/^[\w.-]+$/.test(s))return null;n.push("-c",`filter.${s}.clean=`,"-c",`filter.${s}.process=`,"-c",`filter.${s}.required=false`)}}return n}function Ue(e,n,t,r=!1,o=400,s=1024*1024){let l=Id(e,n,{cwd:t?G(t):void 0,encoding:"utf8",timeout:o,maxBuffer:s,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}});return l.error||l.signal?null:(l.status===0||r)&&typeof l.stdout=="string"?l.stdout:null}function Md(e,n){let t=Date.now()+300,r=Ue("git",[...Bn,"config","-z","--get-regexp","^(filter\\.|submodule\\.recurse$)"],n,!0,300),o=r===null?null:xl(r);if(o===null)return null;let s=e.slice(1).split("\0").filter(i=>i!=="");if(e[0]==="s"){let i=t-Date.now(),a=i>0?Ue("git",[...Bn,"ls-files","-z","--stage","--",...s],n,!1,i,32*1024*1024):null;if(a===null||/(^|\0)160000 /.test(a))return null}let l=t-Date.now();return l>0?Ue("git",[...Bn,...o,"status","--porcelain=v1","-uall","--ignore-submodules=dirty",...e[0]==="x"?["--ignored=matching"]:[],"--",...s],n,!1,l):null}function Ao(e){try{let n=typeof e=="string"&&e!==""?Wd(e):null;return n&&n.birthtimeMs>0&&n.birthtimeMs!==n.ctimeMs?n.birthtimeMs:null}catch{return null}}function $l(e){let n=e.arg??"";try{switch(e.kind){case"ps":return Ue("ps",["-A","-ww","-o","pid=,ppid=,command="]);case"port":return/^\d{1,5}$/.test(n)?Ue("lsof",["-nP","-t","-i",`:${n}`],null,!0):null;case"branch":return Ue("git",["reflog","show","--date=unix","--format=%gd %gs",`refs/heads/${n}`,"--"],e.cwd);case"ignored":return Ue("git",[...Bn,"check-ignore","-q","--",n],e.cwd);case"status":return Md(n,e.cwd);case"stashes":return Ue("git",[...Bn,"-c","log.showSignature=false","stash","list","--format=%gs"],e.cwd,!1,300);case"cwd":{if(!/^\d+$/.test(n))return null;if(process.platform==="linux")return _o(`/proc/${n}/cwd`);let t=/^n(\/.*)$/m.exec(Ue("lsof",["-a","-p",n,"-d","cwd","-Fn"],null,!0)??"")?.[1];return t?_o(t):null}case"file":{let t=_o(G(n));return`${Q()?be(t)??t:t} ${Ao(G(n))??""}`}case"owner":{if(Q()||!n.startsWith("/"))return null;for(let t=n;;t=Td(t))try{return String(jd(t).uid)}catch{if(t==="/")return null}}}}catch{}return null}var cr=e=>`${e.kind}\0${e.cwd??""}\0${e.arg??""}`;import{existsSync as Ld,readFileSync as Co,statSync as Dd}from"fs";import{dirname as Fd,isAbsolute as Sl,join as Ro,resolve as Eo}from"path";function _l(e){return!!e&&e.length<65536&&/\bgh\s+pr\s+(create|edit)\b/.test(e)}function Hd(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(Sl(s)?s:Eo(r[r.length-1]??n??t,s)))}return[...new Set(r)].slice(0,8)}function zd(e){let n=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(e.trim());return n?`${n[1]}/${n[2]}`.toLowerCase():null}function Ud(e){let n=e;for(let t=0;t<12&&n.length>1;t++,n=Fd(n)){let r=Ro(n,".git");if(!Ld(r))continue;let o=r;if(Dd(r).isFile()){if(j(r,64*1024)!==!0)return[];let u=/^gitdir:\s*(.+)$/m.exec(Co(r,"utf8"))?.[1]?.trim();if(!u)return[];o=Sl(u)?u:Eo(n,u);let d=Ro(o,"commondir");j(d,64*1024)===!0&&(o=Eo(o,Co(d,"utf8").trim()))}let s=Ro(o,"config");if(j(s,1024*1024)!==!0)return[];let l=Co(s,"utf8").slice(0,65536),i="",a=[],c=null;for(let u of l.split(`
|
|
31
|
+
`)){let d=/^\s*\[(\w+)(?:\s+"([^"]*)")?\]/.exec(u);if(d){c=d[1]==="remote"?d[2]??null:null;continue}let f=/^\s*url\s*=\s*(.+)$/.exec(u),h=c!==null&&f?zd(f[1]):null;h&&(c==="origin"&&!i?i=h:a.includes(h)||a.push(h))}return[i,...a.filter(u=>u!==i)]}return[]}function Al(e,n,t){let r={};try{for(let o of Hd(e,n,t))r[o]=Ud(o)}catch{}return r}import{readdirSync as Bd,realpathSync as Kd,statSync as qd}from"fs";import{dirname as Sn,isAbsolute as El,join as Be,resolve as Kn,sep as Cl}from"path";function ur(e,n){try{return ge(e,n)?.toString("utf8")??null}catch{return null}}function Rl(e){for(let n=e,t=0;t<64&&Sn(n)!==n;t++,n=Sn(n)){let r=Be(n,".git"),o;try{o=qd(r).isDirectory()}catch{continue}if(o)return{top:n,common:r};let s=ur(r,4096),l=s===null?null:/^gitdir:\s*(.+?)\s*$/m.exec(s);if(!l)return null;let i=Kn(n,l[1]),a=/^(.*[\\/]\.git)[\\/]worktrees[\\/][^\\/]+[\\/]?$/.exec(i)?.[1];if(!a)return null;let c=ur(Be(i,"gitdir"),4096);if(c===null)return null;let u=d=>{try{return Kd.native(d)}catch{return d}};return u(Kn(i,c.trim()))===u(r)?{top:n,common:a}:null}return null}function Vd(e,n){let t=[];for(let r of[Be(n,"settings.json"),Be(e,".claude","settings.json"),Be(e,".claude","settings.local.json")])try{let o=ur(r,1048576);if(o===null)continue;let s=JSON.parse(o).permissions?.additionalDirectories;Array.isArray(s)&&t.push(...s.filter(l=>typeof l=="string"))}catch{}return t}function Ol(e,n,t,r,o){let s=[],l=(d,f)=>d==="~"||d.startsWith("~/")||d.startsWith("~\\")?Be(n,d.slice(1)):El(d)?d:Kn(f,d),i=d=>process.platform==="linux"?d:d.toLowerCase(),a=d=>i(d.endsWith(Cl)?d:d+Cl),c=d=>{let f=Kn(d);Sn(Sn(f))!==Sn(f)&&!a(Kn(n)).startsWith(a(f))&&i(f)!==i(e)&&s.push(f)},u=Date.now()+200;for(let d of Vd(e,t??Be(n,".claude")))c(l(d,e));for(let[d,f]of r)c(l(d,f));try{let d=Rl(e);if(d)if(c(d.top),/[\\/]\.git$/.test(d.common)&&c(Sn(d.common)),o)for(let f of o.slice(0,16)){if(Date.now()>u)break;let h=Rl(f);h&&h.common===d.common&&c(h.top)}else{let f=Be(d.common,"worktrees");for(let h of Bd(f).slice(0,512)){let m=ur(Be(f,h,"gitdir"),4096);m!==null&&c(Sn(Kn(f,h,m.trim())))}}}catch{}return[...new Set(s)]}function Pl(e,n){if(e===null||!e.includes("$"))return null;let t={},r=0;for(let o of e.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)){if(r>=16)break;let s=o[1],l=n[s];Object.hasOwn(t,s)||s==="PWD"||s==="OLDPWD"||typeof l!="string"||l.length>4096||!(El(l)||/^[A-Za-z]:[\\/]/.test(l))||[...l].some(i=>i<" ")||(t[s]=l,r++)}return r>0?t:null}import{closeSync as Zd,constants as Nl,fstatSync as Gd,openSync as Jd,readSync as Yd,statSync as Xd}from"fs";var Qd=64*1024,ef=8;function Il(e,n){let t={},r=[];for(let o of e.slice(0,ef)){let s=null,l=null,i=!0;try{Xd(G(o)).isFile()&&(s=Jd(G(o),Nl.O_RDONLY|Nl.O_NONBLOCK));let a=s!==null?Gd(s):null;if(s!==null&&a!==null&&a.isFile()&&a.size<=Qd){let c=Buffer.alloc(a.size),u=Yd(s,c,0,a.size,0),d=c.subarray(0,u).toString("utf8");d.includes("\0")||(l=d)}}catch(a){a.code==="ENOENT"&&(i=!1)}finally{s!==null&&Zd(s)}l!==null?t[o]=l:i&&n.includes(o)&&r.push(o)}return{scripts:t,unreadable:r}}var nf=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g;function jl(e){return e.replace(nf,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}import{createHash as Oy}from"crypto";import{readdirSync as Ny,readFileSync as Iy,renameSync as jy,statSync as Wy,unlinkSync as Ty}from"fs";import{join as Ly}from"path";var tf=1440*60*1e3;var rf=64*1024*1024,of=14*tf;var af=1e3,cf=3e3,Kl=6e4,uf=new Set(["default","acceptEdits","plan"]),df=new Set(["default","acceptEdits","plan","auto","dontAsk"]),ff="cli",pf=[2,1,153],gf=[2,1,322];function mf(e){if(!e)return null;for(let n of[64*1024,2*1024*1024]){let t="";try{t=ee(e,n)}catch{return null}let r=[...t.matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)].pop();if(r)return[Number(r[1]),Number(r[2]),Number(r[3])]}return null}function hf(e,n){return e.CLAUDE_CODE_ENTRYPOINT===ff&&ql(n,pf)}function ql(e,n){let t=mf(e);if(!t)return!1;for(let r=0;r<n.length;r++)if(t[r]!==n[r])return t[r]>n[r];return!0}function yf(e,n,t){return/^(cli|claude-desktop)$/.test(e.CLAUDE_CODE_ENTRYPOINT??"")&&t!=="SubagentHandback"&&ql(n,gf)}var wf=8,Zn=class extends Error{constructor(n){super(n),this.name="CoreUnavailable"}},Gn=class extends Error{constructor(){super("out of time"),this.name="ClassifyTimeout"}},wt=(e,n,t,r)=>({paths:e,payload:t,table:r,env:n.env,home:n.home,now:n.now(),cli:yn(),fallbackTable:n.fallbackTable,installed:n.anvilDir!==void 0,...n.planProbe?{probe:n.planProbe}:{}});function Oo(e,n){try{return ge(e.compiled,64*1024*1024)?.includes(`"${n}"`)===!0}catch{return!1}}function No(e,n){let t=A(e.env.CLAUDE_PROJECT_DIR)??n;return t&&t.startsWith("/")?Ce(t):t}var bf="AnvilSelfCheck",kf=3,Tl=4e3,A=e=>typeof e=="string"&&e.length>0?e:null;function sn(e,n=160){let t=jl(Ui(e,4096).replace(/\s+/g," ").trim());return t.length>n?`${t.slice(0,n-1)}\u2026`:t}function vf(e){if(!e||!xt(e))return null;let n=e;for(let t=0;t<64;t++){let r=v(n,".git"),o=!1,s=!1;try{let i=jo(r);s=!0,o=i.isFile()}catch{}if(s)try{let i=r;if(o){if(j(r,64*1024)!==!0)return null;let u=/^gitdir:\s*(.+?)\s*$/m.exec(dr(r,"utf8"));if(!u)return null;i=Vn(n,u[1])}if(j(v(i,"HEAD"),64*1024)!==!0)return null;let a=dr(v(i,"HEAD"),"utf8").trim(),c=/^ref:\s*refs\/heads\/(.+)$/.exec(a);return c?c[1]:null}catch{return null}let l=kt(n);if(l===n)return null;n=l}return null}function Ml(e){if(!e||!xt(e))return[];let n=v(e,".git");try{if(j(n,64*1024)!==!0)return[];let t=/^gitdir:\s*(.+?)\s*$/m.exec(dr(n,"utf8"));if(!t)return[];let r=/^(.*[\\/]\.git)[\\/]worktrees[\\/][^\\/]+[\\/]?$/.exec(Vn(e,t[1]));return r?[bn(r[1])]:[]}catch{return[]}}function xf(e,n){return(e==="Bash"||e==="PowerShell")&&n&&typeof n=="object"?n.command??null:Io(n)}function Io(e,n=0){return n>64?"[nested too deep]":Array.isArray(e)?e.map(t=>Io(t,n+1)):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Io(e[t],n+1)])):e}var ln=e=>process.platform==="win32"?Wl.native(e):Wl(e);function $f(e,n){let t=r=>{try{return ln(r)}catch{return null}};return[...new Set([...n,...[e,...n].map(t).filter(r=>r!==null&&r!==e)])]}function Sf(e,n){if(!n)return e;let t;try{t=ln(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 Ll="claude.file.outside_project",an="\0a link loop",Vl=J({Write:"file_path",Edit:"file_path",MultiEdit:"file_path",Read:"file_path",NotebookEdit:"notebook_path"}),_n=(e,n)=>[...new Set([...e,...n??[]])];function _f(e,n,t){let r=Vl[e];if(!r||!n||typeof n!="object")return n;let o=n[r];if(typeof o!="string")return n;let s=mr(o,t,!0);return s===o?n:{...n,[r]:s}}var qn=(e,n)=>Sf(e.replace(/^\/private(?=\/(?:tmp|var|etc)(?:\/|$))/,""),n);function mr(e,n,t){if(!xt(e)||e.length>4096)return e;let r=Vn(e);if(!t){let l=kt(e);if(l===e)return e;let i=mr(l,n,!0);return i===l?e:v(i,cn(e))}let o=[],s=e;for(;;)try{let l=qn(v(ln(s),...o.reverse()),n);return l===r||`/private${l}`===r?r:l}catch(l){if(l.code==="ELOOP")return an;o.push(cn(s));let i=kt(s);if(i===s)return e;s=i}}var Zl=/^\.env(\.|rc$|$)|^\.dev\.vars$/;function Gl(e,n){return e?xt(e)?e:n?v(n,e):null:null}function Af(e,n){let t=Gl(e,n);if(!t||!Zl.test(cn(t)))return null;try{let r=ge(t,1048576);return r===null?null:(r.toString("utf8").match(/^[ \t]*(?:export[ \t]+)?[A-Za-z_][\w.]*[ \t]*=/gm)??[]).length}catch{return null}}function Cf(e,n){if(n===null)return e;let t=`${n} ${n===1?"key":"keys"}`,r=e.indexOf("a secrets file ("),o=r<0?-1:e.indexOf(")",r);return o>0?`${e.slice(0,o)}, ${t}${e.slice(o)}`:e.endsWith(")")?`${e.slice(0,-1)}, ${t})`:`${e} (${t})`}function Rf(e,n){let t=Gl(e,n);if(!t)return null;let r=n?Ce(n):null,o=r&&t.startsWith(`${r}/`)?t.slice(r.length+1):t;return/^[\w./@+-]{1,120}$/.test(o)?Zl.test(cn(t))?`grep -oE '^(export )?[A-Z][A-Z0-9_]*=' ${o}`:/\.json$/.test(t)?`jq keys ${o}`:null:null}function Ef(e,n,t){let r={full:{},parent:{}},o=!1,s=(i,a)=>Q()&&!i.startsWith(an)?be(i)??a:i;for(let i of["full","parent"])for(let a of e[i]){if(Date.now()>t)return"out-of-time";let c=s(mr(G(a),n,i==="full"),a);c!==a&&(r[i][a]=c,o=!0)}let l=Math.min(t,Date.now()+Of);for(let i of["glob","deep"])for(let a of e[i]??[]){let c=new Set,u=a.endsWith("/");i==="deep"?Nf(G(a),n,l,c):Pf(G(u?a.slice(0,-1):a),u,n,l,c);let d=[...c].slice(0,fr).map(f=>s(f,f));c.size>fr&&d.push(an),d.length>0&&((r[i]??={})[a]=d,o=!0)}return o?r:null}var fr=64,Of=200;function Jl(e,n){let t=e.split(/[\\/]/),r=[t[0]?`${t[0]}\\`:"/"];for(let o of t.slice(1)){if(o==="")continue;let s=at(o),l=[];for(let i of r){if(Date.now()>n)return"late";if(!s)l.push(v(i,o));else{let a=[];try{a=gr(i)}catch{}for(let c of a)(!c.startsWith(".")||o.startsWith("."))&&s.test(c)&&l.push(v(i,c))}}r=l}return r}var Yl=(e,n)=>e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`);function Pf(e,n,t,r,o){let s=e.split(/[\\/]/),l=s[s.length-1],i=s.findIndex(u=>/[*?[]/.test(u)),a;try{a=qn(ln(s.slice(0,i).join(e.includes("\\")?"\\":"/")||"/"),t)}catch{return}let c=i<0?[]:Jl(e,r);if(c==="late")return void o.add(an);for(let u of c){if(Date.now()>r)return void o.add(an);let d;try{if(n){let f=ln(u);if(!jo(f).isDirectory())continue;d=qn(f,t)}else lf(u),d=v(qn(ln(kt(u)),t),cn(u))}catch{continue}if(Yl(d,a)||o.add(!n&&/[*?[]/.test(l)?v(kt(d),l):d),o.size>fr)return}}function Nf(e,n,t,r){let o=/[*?[]/.test(e)?Jl(e,t):[e];if(o==="late")return void r.add(an);let s=l=>{l.code==="ELOOP"&&r.add(an)};for(let l of o){let i;try{i=ln(l)}catch(d){s(d);continue}let a=qn(i,n),c=new Set([i]),u=[i];for(let d=0;d<u.length;d++){if(Date.now()>t)return void r.add(an);let f=[];try{f=gr(u[d],{withFileTypes:!0})}catch{}for(let h of f){let m=v(u[d],h.name);if(h.isDirectory()&&u.push(m),!h.isSymbolicLink())continue;let k;try{if(k=ln(m),c.has(k)||!jo(k).isDirectory())continue}catch(q){s(q);continue}c.add(k);let E=qn(k,n);if(!Yl(E,a)&&(r.add(E),u.push(k),r.size>fr))return}}}}async function Dl(e,n,t,r){if(!n)return{classification:await t.classifyInline(e,r),failure:null};let o=await t.classifyInWorker(e,r);return o.kind==="ok"?{classification:o.classification,failure:null}:{classification:null,failure:o.kind==="timeout"?{rule:"too-long-to-check"}:{rule:"could-not-check",error:o.error}}}var If=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function jf(e,n,t,r){return bt("sha256").update(JSON.stringify([e??"",n,xf(n,t),r??""])).digest("hex").slice(0,10)}function Jn(e){return e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:bt("sha256").update(e).digest("hex").slice(0,24):"none"}function qe(e,n){try{U(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)})),rn(e.decisions,t)}catch{}}function Fl(e,n,t,r,o,s){qe(e,{v:1,ts:new Date(o).toISOString(),session:A(s?.session_id),tool:A(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:sn(t instanceof Error?t.message:String(t),200)})}var An={stdout:"",exitCode:0},K=e=>({stdout:`${JSON.stringify(e)}
|
|
32
|
+
`,exitCode:0});function hr(e,n){let t=A(e.env.CLAUDE_CONFIG_DIR),r=v(t?Vn(t):v(e.home,".claude"),"settings.json"),o=A(e.env.CLAUDE_PROJECT_DIR)??A(n.cwd);return o?[r,v(o,".claude","settings.local.json"),v(o,".claude","settings.json")]:[r]}function Wf(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=>j(v(t,a))===!0);if(s.length===0)return[];let l=sf("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","status","--porcelain=v1","--ignored","--untracked-files=all","-z","--",...s],{cwd:t,encoding:"utf8",timeout:500,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}});if(l.status!==0||typeof l.stdout!="string")return s.map(a=>({path:v(t,a),ignored:!1}));let i=[];for(let a of l.stdout.split("\0")){let c=a.slice(0,2),u=s.find(d=>a.slice(3)===d||a.slice(3).endsWith(`/${d}`));(c==="??"||c==="!!")&&u!==void 0?i.push({path:v(t,u),ignored:c==="!!"}):(c[0]==="A"||c.includes("M"))&&u!==void 0&&i.push({path:v(t,u),ignored:!1,staged:!0})}return i}function Tf(e,n,t,r){if(["Read","Glob","Grep","LS","WebFetch","WebSearch","TodoWrite"].includes(e))return null;let o=v(n,".claude"),s=v(n,".anvil"),i=[...[".zshrc",".zshenv",".zprofile",".bashrc",".bash_profile",".bash_aliases",".profile",v(".config","fish","config.fish"),...process.platform==="win32"?[v("Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),v("Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")]:[]].map(c=>v(n,c)),o,v(o,"settings.json"),v(o,"settings.local.json"),v(o,"hooks"),v(o,"plugins"),v(n,".claude.json"),s,v(s,"claude"),v(s,"claude","modes.json"),v(s,"claude","compiled.json"),v(s,"rules.json"),v(s,"workspace-keys.json")];t&&i.push(t,v(t,"settings.json"),v(t,"hooks")),r&&i.push(v(r,".claude"),v(r,".claude","settings.json"),v(r,".claude","settings.local.json"),v(r,".mcp.json"));let a={};for(let c of i){let u=mr(c,n,!0);u!==c&&(a[u]=c)}return Object.keys(a).length>0?a:null}function Xl(e,n){return v(e.state,"covered",Jn(A(n.session_id)))}function Mf(e,n,t){try{let r=Xl(e,t);if(j(r)!==null||!hr(n,t).some(o=>to(o)))return;U(v(e.state,"covered")),le(r,String(n.now()))}catch{}}async function Hl(e,n,t,r){let o=()=>hr(n,t).some(l=>to(l)),s=Xl(e,t);if(j(s)===!0)return o();if(r!=="SessionStart"||!o())return!1;for(let l=0;l<300;l+=25)if(await new Promise(i=>setTimeout(i,25)),j(s)===!0)return!0;return!1}function Lf(e,n){try{U(e.state),le(v(e.state,"plugin-seen"),String(n))}catch{}}var vt=!1;async function Ql(e,n){ue=yt=pr=null;let t=n.now(),r=n.anvilDir?tn(n.anvilDir):kn(n.home),o=dt(r.install)?.cli??n.cli;In(o),vt=typeof o=="string";let s=null,l=A(n.entry),i=Buffer.byteLength(e)/1048576,a=`(${i.toFixed(1)} MB; Anvil reads up to 8 MB)`;if(i>wf)return Ln(l)?An:l==="SessionStart"?K(Fe("SessionStart",`it can't read what Claude Code sent ${a}`)):Df(r,e,`this call is too large to check ${a}`,t,n);try{if(s=JSON.parse(e),!s||typeof s!="object"||l&&!A(s.hook_event_name))throw new Error("hook input is not a hook event");let c=A(s.hook_event_name),u=()=>{let f=na(r,A(s.session_id));return f?`${JSON.stringify({systemMessage:f})}
|
|
33
|
+
`:null};if(n.plugin&&Ln(c)&&di(hr(n,s)).has(c)&&await Hl(r,n,s,c))return An;if(c==="UserPromptSubmit"&&n.modelAtPrompt&&Oo(r,"never")){let f=await n.modelAtPrompt({...wt(r,n,s,null),projectDir:No(n,A(s.cwd))}).catch(u);if(f)return{stdout:f,exitCode:0}}if(c==="UserPromptSubmit"&&n.budgetAtPrompt&&Oo(r,"budgets")){let f=await n.budgetAtPrompt(wt(r,n,s,null)).catch(u);if(f)return{stdout:f,exitCode:0}}if(c==="PreModelSwitch"&&n.modelAtSwitch&&Oo(r,"model_rules")){let f=await n.modelAtSwitch({...wt(r,n,s,null),projectDir:No(n,A(s.cwd))}).catch(u);if(f)return{stdout:f,exitCode:0}}if(n.helpers&&(c?.startsWith("Subagent")||s.source==="resume")&&j(v(r.dir,"helpers","live"))!==null&&await n.helpers().then(f=>f.onEvent(s,r,n.now()),()=>0),Ln(c))return An;if(n.plugin){if(await Hl(r,n,s,c))return An;c==="SessionStart"&&Lf(r,n.now())}else n.anvilDir!==void 0&&Mf(r,n,s);if(c==="SessionStart")return await Kf(r,n,s);if(c===bf)return await Bf(r,n);if(c!=="PreToolUse")return An;let d=pr={oks:[],yes:0,why:null,noted:!1,counts:new Map,notes:[]};for(let f=t;;f=n.now()){let h=await Ff(s,r,{...n,round:d},f),m=yt?.(h)??h;if(!h.again)return m;let k=JSON.parse(m.stdout).systemMessage;d.notes.push(...[ue,k].filter(E=>!!E)),ue=yt=null}}catch(c){let u=(s&&A(s.hook_event_name))??l??(/"hook_event_name"\s*:\s*"SessionStart"/.test(e.slice(0,4096))?"SessionStart":null),d=s&&A(s.hook_event_name)?"its check crashed":"it can't read what Claude Code sent";if(u==="SessionStart")return K(Fe("SessionStart",d));if(u&&u!=="PreToolUse")return An;let f=ht(r,s??{},d,t,n.now(),c);return yt?.(f)??f}}function ea(e,n,t,r,o,s,l){let i=n("cwd");qe(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:i?cn(i):null,path:"none",ms:Math.max(0,s-o),...l?{error:sn(String(l),200)}:{}})}function ht(e,n,t,r,o,s){return ea(e,l=>A(n[l]),"could-not-check",`Anvil isn't working: ${t}`,r,o,s),K(Fe("PreToolUse",t))}function Df(e,n,t,r,o){let s=n.slice(0,4096);return ea(e,l=>new RegExp(`"${l}"\\s*:\\s*"([^"\\\\]{1,200})"`).exec(s)?.[1]??null,"too-long-to-check",t,r,o.now()),K({systemMessage:ws(t),...Cn("deny",bs(t))})}async function Ff(e,n,t,r){let o=t.now(),s=t.round,l=A(e.tool_name)??"unknown",i=A(e.session_id),a=A(e.cwd);try{U(n.counts),s.counted||(s.counted=!0,li(n.counts,new Date(o)))}catch{}let c=Wo(n,t,o),u=c.table;if(!u)return ht(n,e,ta(c),r,t.now());let d=c.modes;if(t.coreProblem)return ht(n,e,t.coreProblem,r,t.now());try{let p=u.policies.flatMap(b=>b.caps??[]);p.length>0&&new ft(v(n.dir,"caps")).settle(p,o,{s:i,a:A(e.agent_id)??""})}catch{}let f=No(t,a);try{vt||In(u.cli),ue=Hf(n,u,f,i,yn())}catch{ue=null}let h=wl(n,i),m=Vi(e.tool_input),k=(l==="Bash"||l==="PowerShell")&&typeof m?.command=="string"?m.command:null;kl(n,i,o);let E=xo(k)?vl(n,i,f,{tmpdir:t.tmpdir},o):[],q=E.length>0?{...h,made:[...h.made,...E.filter(p=>!h.made.includes(p))]}:h,W=null,oe=()=>{w?.makings&&bl(n,i,w.makings,h,f,o),W?.ran()},Pe=Pl(k,t.env),se={tool_name:l,tool_input:e.tool_input??null,cwd:a,git_branch:vf(a),project_dir:f,session_id:i,home:t.home,tmpdir:t.tmpdir,claude_config_dir:A(t.env.CLAUDE_CONFIG_DIR),project_controls:Wf(l,e.tool_input,f),control_links:Tf(l,t.home,A(t.env.CLAUDE_CONFIG_DIR),f),session_facts:{...q,startedAt:Ao(e.transcript_path),..._l(k)?{repoRemotes:Al(k,a,t.home)}:{},...Pe?{env:Pe}:{}},want_makings:!0,production:u.policies.flatMap(p=>ie(p,f)&&p.production||[])},w=null,Se="inline",N=null,Ne=t.timeLimitMs??af,Ie=Date.now()+(t.totalLimitMs??cf),me=()=>Math.min(Ne,Ie-Date.now()),z=null,M=null,ye=()=>{z=w??z,w=null,N={rule:"too-long-to-check"}},g={},x={},C=[],O=!1,L=async(p,b)=>{let $=w;({classification:w,failure:N}=await Dl(p,b,t,me())),!w&&$&&(z=$);let I=w?.touched;I&&M&&(M={full:_n(M.full,I.full),parent:_n(M.parent,I.parent),read:_n(M.read,I.read),written:_n(M.written,I.written),unknown:_n(M.unknown,I.unknown)})};try{let p=Gi(l,e.tool_input);p&&(Se="worker");let b={...se,tool_input:_f(l,se.tool_input,t.home),on_disk:"collect"};({classification:w,failure:N}=await Dl(b,p,t,me()));let $=w?.touched;$&&(M={full:[...$.full],parent:[...$.parent],read:[...$.read??[]],written:[...$.written??[]],unknown:[...$.unknown??[]]});let I=Vl[l],te=I&&se.tool_input&&typeof se.tool_input=="object"?se.tool_input[I]:void 0;if(typeof te=="string"&&xt(te)&&te.length<=4096){let V=[Q()?be(te)??Vn(te):Vn(te)];M=M?{...M,full:_n(M.full,V),written:_n(M.written,V)}:{full:V,parent:[],read:[],written:V,unknown:[]}}let H=$&&($.full.length>0||$.parent.length>0)?Ef($,t.home,Math.min(Date.now()+Ne,Ie)):null,Et=(V,Z)=>[...new Set([...V,...V.flatMap(X=>[Z.full[X],Z.parent[X]].filter(F=>typeof F=="string"))])];if(H&&H!=="out-of-time"&&M&&(M={full:[...new Set([...M.full,...Object.values(H.full)])],parent:[...new Set([...M.parent,...Object.values(H.parent)])],read:Et(M.read,H),written:Et(M.written,H),unknown:M.unknown}),H==="out-of-time")ye();else{let V=w?[w.action===Ll?w.attributes.target:null,...(w.findings??[]).map(Ae=>Ae.action===Ll?Ae.target:null)]:[],Z=[...V,...Object.values(H?.full??{}),...Object.values(H?.parent??{}),...Object.values(H?.glob??{}).flat(),...Object.values(H?.deep??{}).flat()].filter(Ae=>!!Ae&&Ae.startsWith("/")).map(G),X=f!==null&&f!==""&&(H!==null||V.some(Boolean)),F=X?Ol(f,t.home,A(t.env.CLAUDE_CONFIG_DIR),u.policies.filter(Ae=>ie(Ae,f)).flatMap(Ae=>(Ae.project_folders??[]).map(ha=>[ha,Ae.project_dir??f])),Z):[],jr=X?$f(f,F):[];jr.length>0&&(b={...b,session_facts:{...b.session_facts??{made:[],launched:[]},roots:jr}}),(H!==null||jr.length>0)&&(H!==null&&(b={...b,on_disk:H}),me()<=0?ye():await L(b,p))}x={...se.session_facts?.scripts??{}};for(let V=0;V<2&&w?.scriptsWanted&&w.scriptsWanted.length>0;V++){let Z=w.scriptsWanted.filter(F=>!(F in x)&&!C.includes(F));if(Z.length===0)break;if(me()<=0){ye();break}let X=Il(Z,q.made);if(Object.keys(X.scripts).length===0&&X.unreadable.length===0)break;if(Object.assign(x,X.scripts),C.push(...X.unreadable),b={...b,session_facts:{...b.session_facts??{made:[],launched:[]},scripts:{...x},...C.length>0?{unreadableScripts:[...C]}:{}}},me()<=0){ye();break}await L(b,p)}for(let V=0;V<3&&w?.probesWanted;V++){let Z=w.probesWanted.filter(F=>!(cr(F)in g));for(let F of Z)me()>400&&(g[cr(F)]=F.kind==="changes"||F.kind==="deps"||F.kind==="reach"?await t.answerChanges?.(F)??null:$l(F));if(Z.length===0||me()<=400){O=me()<=400&&Z.some(F=>F.kind==="changes");break}b={...b,session_facts:{...b.session_facts??{made:[],launched:[]},probed:{...g}}};let X={classification:w,failure:N};try{await L(b,p)}catch(F){if(!(F instanceof Gn))throw F;w=null,N={rule:"too-long-to-check"}}if(!w&&N?.rule==="too-long-to-check"&&X.classification&&!Z.some(F=>F.kind==="changes")){({classification:w,failure:N}=X);break}}}catch(p){if(w&&(z=w,w=null),p instanceof Zn)return ht(n,e,"its checker can't load",r,t.now(),p);N=p instanceof Gn?{rule:"too-long-to-check"}:{rule:"could-not-check",error:p instanceof Error?p.message:String(p)}}(O||w?.probesWanted?.some(p=>p.kind==="changes"&&!(cr(p)in g)))&&(z=w,w=null,N={rule:"too-long-to-check"}),w?.action===Bl&&(u.policies.some(p=>p.allowed_actions.includes(Bl))?!N&&u.policies.some(p=>p.helpers&&ie(p,f))&&(yt=(W=(await t.helpers()).launchStep({paths:n,table:u,projectDir:f,payload:e,deps:t,modes:d,now:o,cli:yn()})).finish):w={...w,action:"claude.tool.other"}),w&&u.policies.some(p=>p.narrowed?.some(b=>(b.when?.length??0)>0)||p.caps?.some(b=>b.unit==="money"))&&await Os(),w&&k!==null&&m?.dangerouslyDisableSandbox===!0&&t.lockHold&&(w=await t.lockHold(w,{anvilDir:n.dir,transcript:A(e.transcript_path)}).catch(()=>null)??w);let R=[],y="ghost",S=Ye(d).includes("hold-unchecked"),_=null,ne=t.rates??new Ht(v(n.state,"rate.jsonl"),Ai),we=new Map,fe={recordAndCount(p,b,$){let I=`${b} ${p}`,te=we.get(I)??0;we.set(I,te+1);let H=s.counts.get(I)??[];return s.counts.set(I,H),H[te]??=ne.recordAndCount(p,b,$)},restart:(p,b,$)=>ne.restart?.(p,b,$)},Ve=bn(f),Rn=bn(t.home);if(w)try{U(n.state),{stops:R,mode:y}=po(u,{...w,tool:l,touched:M,command:k,input:m},d,fe,o,Ve,i,Rn,Ml(f))}catch(p){S=!1,N={rule:"could-not-check",error:p instanceof Error?p.message:String(p)}}else if(N&&z)try{let p=po(u,{...z,tool:l,touched:M,command:k,input:m},d,fe,o,Ve,i,Rn,Ml(f));p.mode==="enforce"&&p.lead?.decision.verdict==="block"?({stops:R,mode:y}=p,w=z,N=null):_=p}catch{S=!1}!S&&w?.parse==="limited"&&!N&&!(y==="enforce"&&R[0]?.decision.verdict==="block")&&(N={rule:"could-not-check",why:"too long or nested too deep to read in full"});let Lo=N?.error!==void 0?await To(t):null;if(Lo)return ht(n,e,Lo,r,t.now());let Do=S&&N!==null;if(Do&&(N=null,_&&({stops:R,mode:y}=_,w=z)),w&&(w=fo(w,d)),N){let p={verdict:"hold",policy:null,origin:null,ruleId:N.rule,blockedBy:"time_limit",source:null};y="enforce",R=[{action:"claude.bash.unclassified",decision:p,mode:y,floor:"hold-unchecked"}]}W?.stop&&!R.some(p=>p.mode==="enforce"&&p.decision.verdict==="block")&&(R=[W.stop,...R],y="enforce");let Fo=w?[w.action,...w.also]:[],Ho=()=>({note:na(n,i)??void 0});if(t.modelAtAction&&w&&!N&&d?.kill_switch!==!0&&u.policies.some(p=>ie(p,f)&&(p.model_rules?.never?.length||[...p.model_rules?.guards??[],...p.model_rules?.second??[]].some(b=>b.kinds.some($=>Fo.includes($)))))&&!(y==="enforce"&&R[0]?.decision.verdict==="block")){let p=await t.modelAtAction({...wt(n,t,e,u),kinds:Fo,projectDir:f}).catch(Ho);p?.note&&(ue=ue?`${ue}
|
|
34
|
+
${p.note}`:p.note),p?.stop&&(R=p.stop.action==="claude.budget"?[p.stop]:[p.stop,...R],y="enforce")}if(t.budgetAtAction&&(w||Do)&&!N&&d?.kill_switch!==!0&&u.policies.some(p=>p.budgets?.length)&&!(y==="enforce"&&R[0]?.decision.verdict==="block")){let p=await t.budgetAtAction(wt(n,t,e,u)).catch(Ho);p?.note&&(ue=ue?`${ue}
|
|
35
|
+
${p.note}`:p.note),p?.stop&&(y="enforce",R=[p.stop])}let nt=w?.units??null,En=w?{tool:l,parts:uo({...w,tool:l,touched:M,command:k}),touched:M,projectDir:Ve,home:Rn??null,command:k,input:m,now:o}:null,je=w&&!N?xi(u,[w.action,...w.also],f,En):[],On=[],kr=(p,b,$)=>({cap:JSON.stringify([p.id,p.text,p.limit,$]),used:b}),$t=null,tt=[],vr=(p,b)=>b instanceof Ee?`${b.message}, so your cap ${p.text} can't count it`:`couldn't check your cap ${p.text} (${b?.code??(b instanceof Error?b.message.slice(0,60):"unreadable")})`,dn=je.length>0?new Bt(v(n.dir,"caps")):null,St=A(e.tool_use_id)??`${Jn(i)}-${o}-${process.pid}`,zo=A(e.permission_mode),xr={s:i,a:A(e.agent_id)??""},$r=zo!==null&&df.has(zo)?{tr:zl(A(e.transcript_path),A(e.agent_id)),call:A(e.tool_use_id),...xr}:void 0;if(dn&&y!=="enforce"){let p;try{p=d?.kill_switch===!0?(dn.count(je,St,nt,o,"ran",$r,En),null):dn.admit(je,St,nt,o,void 0,En,$r??null,xr)}catch(b){if(p=null,d?.kill_switch!==!0){let $=b instanceof Ee?b.cap??je.find(te=>te.unit==="money")??je[0]:je[0],I={verdict:"hold",policy:"caps",origin:null,ruleId:$.id,blockedBy:"cap_unreadable",source:$.source};y="enforce",R=[{action:w.action,decision:I,mode:y,floor:null,why:vr($,b)},...R]}}if(p){let b={verdict:"hold",policy:"caps",origin:null,ruleId:p.cap.id,blockedBy:"cap_reached",source:p.cap.source};y="enforce";let $=[p,...p.also??[]];On=$.map(I=>kr(I.cap,I.used,I.n)),$t={action:w.action,decision:b,mode:y,floor:null,why:$.map(I=>Ul(I.cap,I.used,I.n)).join("; and ")},R=[$t,...R]}}if(dn&&y==="enforce"&&R[0]&&w&&!N&&!$t&&R[0].action!=="claude.budget"){for(let p of je)if(!(R[0].decision.blockedBy==="cap_unreadable"&&R[0].decision.ruleId===p.id))try{let b=Kt(p,nt,En),$=dn.used(p,o,xr);if($+b<=p.limit)continue;On.push(kr(p,$,b)),tt.push(Ul(p,$,b))}catch(b){On.push(kr(p,0,vr(p,b))),tt.push(vr(p,b))}}let Sr=async()=>{try{w&&i&&t.moot&&gr(ar(n)).some(p=>p.startsWith(ko(i))||/^[0-9a-f]{16}\.json$/.test(p))&&await t.moot({anvilDir:n.dir,session:i,project:f,stops:[w.action,...w.also].map((p,b)=>({kind:p,target:b?null:w.attributes.target??null})),now:o})}catch{}},T=R[0],Uo={command:k,input:e.tool_input,cwd:a,home:t.home,scripts:x,unread:[...C,...w?.scriptsWanted??[]],classification:w,touched:M?{...M}:null,model:W?.model??null},_r=s.oks.length>0&&T&&await t.asRead?.(Uo,s.oks.map(p=>p.read)).catch(()=>null)||null;T&&W?.starts&&W.stop!==T&&tt.push(W.starts),_r?.said&&tt.push(_r.said);let Bo=s.why===null?An:K({systemMessage:Kr(s.why)});if(!T)return oe(),await Sr(),Ke(Bo,n,i,c.problems,o);let Ze=y==="enforce"?R.filter(p=>p.mode==="enforce"):R,Ko=p=>N?N.why??(N.rule==="too-long-to-check"?"too long to check in time":"could not be checked"):p.why?p.why:w&&p.action===w.action?w.why:Tt(p.action),Pn=p=>p.target!==void 0?p.target:w&&p.action===w.action?w.attributes.target??null:null,aa=p=>p.replace(/ ?\((?:a command with no rule of its own, )?read by its (?:words|name)\)/g,"").trim(),Ar=p=>(p===T?[qo(p),...tt]:[qo(p)]).join("; and "),qo=p=>{let b=aa(Ko(p));if(p.decision.ruleId==="hold-delete-bursts")return`more than 20 recursive deletes in a minute (this one ${b})`;if(p.decision.ruleId==="hold-helper-bursts")return"more than 20 helper agent launches in 10 minutes";if(p.decision.ruleId==="hold-repeated-side-effect")return`the same app change again within 10 minutes (${b})`;let $=Pn(p);return p.decision.ruleId==="block-protected-targets"&&!p.floor&&$&&/\/\.git(\/|$)/.test($)?`deletes the .git of another repository inside the project (${f&&$.startsWith(`${f}/`)?$.slice(f.length+1):$})`:p.floor==="keep-env-out"?Cf(b,Af($,a)):b},Vo=p=>{let b=[...new Set(p)];return b.filter($=>!b.some(I=>I!==$&&I.startsWith(`${$} \xB7 `))).join("; ")},Cr=Vo((T.decision.verdict==="block"?[T]:Ze).map(Ar)),_e=sn(Cr),fn=sn(Cr,1/0),Zo=T.decision.verdict==="block"?"block":"hold",Go=N?null:Pn(T),pn={v:1,ts:new Date(o).toISOString(),session:i,agent_id:A(e.agent_id),agent_type:A(e.agent_type),tool:l,action:T.action,verdict:Zo,mode:y,rule:T.decision.ruleId,slug:Fr(T.decision.ruleId,T.decision.origin,T.action,T.floor),...T.floor?{floor:T.floor}:{},policy:T.decision.policy,blocked_by:T.decision.blockedBy,why:_e,target:Go?sn(Go,200):null,project:f?cn(f):null,path:Se,...N?.error?{error:sn(N.error,200)}:{},...R.length>1?{also:R.slice(1).map(p=>({action:p.action,verdict:p.decision.verdict,mode:p.mode,rule:p.decision.ruleId,...p.floor?{floor:p.floor}:{}}))}:{},...w?.housekeeping&&T.action===w.action?{housekeeping:!0}:{}};if(y==="ghost"){oe(),await Sr();let p=R.filter(Z=>!Wt.has(Z.action)||Z.decision.blockedBy==="narrowed_rule"||[w,...w?.findings??[]].some(X=>X?.action===Z.action&&X.prod)),b=s.why===null&&p.length>0&&Uf(n,i,o),$={...pn,delivered:b?"note":"none",ms:t.now()-r,...p.length===0?{scoped:!0}:{}};if(qe(n,$),!b)return Ke(Bo,n,i,c.problems,o);let I=p.find(Z=>Z.decision.verdict==="block")??p[0],te=I.decision.verdict==="block",H=Fr(I.decision.ruleId,I.decision.origin,I.action,I.floor),Et=p.length<R.length?sn(Vo((te?[I]:p).map(Ar))):_e,V=!te&&!w?.housekeeping&&I.decision.blockedBy!=="narrowed_rule"&&Xe[I.action]?.slug===H?H:null;return Ke(K({systemMessage:$s(te?"block":"hold",Et,V)}),n,i,c.problems,o)}let We=yn();if(Zo==="block"){qe(n,{...pn,delivered:T.action==="claude.advisor.second"?"pause":"deny",ms:t.now()-r});let p=T.said,b=p?.user??Cs(_e,We),$=p?.agent??Rs(_e);return Ke(K({systemMessage:b,...Cn("deny",$)}),n,i,c.problems,o)}let ca=N!==null||If.has(l)||l.startsWith("mcp__"),_t=jf(i,l,e.tool_input,a),Rr=ca?`input:${_t}`:null,gn=T.action==="claude.budget",At=Ze.map(p=>({kind:p.action,target:gn?Pn(p):N?Rr:Rr?`${Pn(p)??""}#${Rr}`:Pn(p)})),ua=Oe(n),Er=Ze.flatMap((p,b)=>p===$t?[]:[JSON.stringify([At[b],p.decision.ruleId,p.decision.blockedBy,p.floor,p.same??Ko(p)])]),Jo=s.oks.filter((p,b)=>_r?.changed[b]?.length===0),Or=!gn&&Er.length+On.length>0&&Er.every(p=>Jo.some(b=>b.seen.has(p)))&&On.every(p=>Jo.some(b=>p.used<=(b.used.get(p.cap)??-1))),mn={approved:Or,forged:0};try{!Or&&!gn&&(mn=hl(n,ua,i,f,At,o))}catch{mn={approved:!1,forged:0}}let rt=mn.forged>0?[...c.problems,`${mn.forged===1?"an approval was":`${mn.forged} approvals were`} written outside \`${D(We)} allow\`; ${mn.forged===1?"it releases":"they release"} nothing`]:c.problems;if(mn.approved){oe(),await Sr();try{dn?.count(je,St,nt,o,"ran",$r,En)}catch(p){Fl(n,"caps",p instanceof Error?p:new Error(String(p)),r,t.now(),e)}return Or||(Po(fe,Ze,i,o),qe(n,{...pn,delivered:"approved",ms:t.now()-r})),Ke(K({systemMessage:Kr(_e)}),n,i,rt,o)}if(Cr.length>Tl||fn.length>Tl)return qe(n,{...pn,delivered:"deny",ms:t.now()-r}),Ke(K({systemMessage:ks(_e),...Cn("deny",vs(_e))}),n,i,rt,o);let Yo=Ze.some(p=>Lr.has(p.decision.ruleId??"")),Ct=A(e.permission_mode),da=!/^sdk-/.test(A(t.env.CLAUDE_CODE_ENTRYPOINT)??"");if(Ct!==null&&da&&!gn&&(uf.has(Ct)||Ct==="bypassPermissions"&&hf(t.env,A(e.transcript_path))||Ct==="auto"&&yf(t.env,A(e.transcript_path),l))){N||oe();try{dn?.count(je,St,nt,o,"ask",{tr:zl(A(e.transcript_path),A(e.agent_id)),call:A(e.tool_use_id),s:i,a:A(e.agent_id)??""},En)}catch($){Fl(n,"caps",$ instanceof Error?$:new Error(String($)),r,t.now(),e)}qe(n,{...pn,delivered:"ask",call:A(e.tool_use_id),transcript:A(e.transcript_path),ms:t.now()-r});let p=A(e.transcript_path),b=A(e.tool_use_id);return p&&b&&Po(fe,Ze,i,o,{transcript:p,call:b}),Ke(K(Cn("ask",As(T.floor?`${fn} \xB7 on by default`:fn,Yo))),n,i,rt,o)}let Xo=p=>t.notify?.({session:i,transcript:A(e.transcript_path),why:_e,cli:We,call:_t,cwd:a,again:p}),Qo=()=>{let p=k??(/^(Agent|Task)$/.test(l)?w?.why??l:e.tool_input&&typeof e.tool_input=="object"?JSON.stringify(e.tool_input):null);return ml(n,{session:i,project:f,stops:At,why:fn,project_name:f?cn(f):null,call:_t,...p?{command:`${l}: ${sn(p,240)}`}:{}},t.now())},es=t.now()-r,Pr=p=>qe(n,{...pn,ts:new Date(t.now()).toISOString(),delivered:p,ms:es}),fa=()=>{s.noted||(s.noted=!0,Pr("deny"))},Nr=null,pa=async()=>(Nr=(await t.asRead?.(Uo,[]).catch(()=>null))?.read??null)!==null,Te=t.ask&&s.yes<kf&&!(W?.stop&&W.stop===T)?await t.ask({look:pa,payload:e,session:i,transcript:A(e.transcript_path),project:f,stops:At,why:fn,reasons:[...new Set(Ze.map(Ar))],always:!!T.floor,burst:Yo,budget:gn,cli:We,call:_t,keep:()=>Qo().id,opening:fa}).catch(()=>null):null;if(Te?.did==="allowed"&&(gn||(Nr&&s.oks.push({read:Nr,seen:new Set(Er),used:new Map(On.map(p=>[p.cap,p.used]))}),Po(fe,Ze,i,t.now()),Pr("approved")),s.yes++,s.noted=!1,gn||(s.why=_e)),Te&&!("agent"in Te))return{...K(Cn("deny","")),again:!0};if(Te)return Te.did==="declined"&&Pr("declined"),Te.notify&&Xo(!0),Ke(K({...Te.user?{systemMessage:Te.user}:{},...Cn("deny",Te.agent)}),n,i,rt,o);let Ge=null,Ir,ns=null;try{({code:Ge,id:Ir}=Qo())}catch(p){Ge=null;let b=p.code;ns=b==="ENOSPC"||b==="EDQUOT"?"the disk is full, so the hold could not be recorded: free some space, then ask Claude to try again":b==="EACCES"||b==="EPERM"||b==="EROFS"?`Anvil's folder (${n.dir}) cannot be written: fix that, then ask Claude to try again`:null}s.noted||qe(n,{...pn,delivered:"deny",...Ir?{hold:Ir}:{},ms:es}),Ge&&!(W?.stop&&W.stop===T)&&Xo(!1);let Rt=Ge?T.said:void 0,ga=Rt?Rt.user.replace("{why}",()=>fn).replace("{code}",Ge):Ss(fn,We,Ge,ns??(T.floor?`to repair Anvil, run in a terminal: ${D(We)} on`:`to repair Anvil, run in a terminal: ${D(We)} on (or change the rule: ${D(We)} rules edit)`),T.floor!==void 0&&T.floor!==null),ma=Rt?Rt.agent:W?.stop===T?W.agent(Ge!==null):_s(_e,Ge!==null,We,T.floor==="keep-env-out"?Rf(Pn(T),a):null);return Ke(K({systemMessage:ga,...Cn("deny",ma)}),n,i,rt,o)}function Po(e,n,t,r,o){if(!(!t||!e.restart)){for(let s of n)if(!(!s.decision.ruleId||!Lr.has(s.decision.ruleId)))try{e.restart(Yr(s.action,t),r,o)}catch{}}}function Cn(e,n){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:e,permissionDecisionReason:n}}}function Wo(e,n,t){let r=Oe(e),o=n.anvilDir!==void 0,s=cl(e,n.fallbackTable,r,{installed:o}),l=al(e,r,{installed:o}),i=[];try{i=o?ir(e,r,n.home):[]}catch{i=[]}let a=A(n.env.ANVIL_HOOK_NODE_FALLBACK),c=o&&a?`the Node Anvil was set up with ${A(n.env.ANVIL_HOOK_NODE_WHY)==="broken"?"could not start":"is gone"}, so it runs under ${a}; run ${he("on")} to set it up again`:null,u=s.value?Dr(s.value):Nn,d=Nn.filter(k=>!u.includes(k));if(i.some(k=>k.startsWith("install.json "))){let k=s.value?.cli??n.cli;In(k),vt=typeof k=="string"}else vt||In(s.value?.cli);let f=yn(),h=d.length>0?`its own rules for ${d.map(k=>k.short).join("; ")} are missing from the rules it judges with, so it may not stop those calls; run ${D(f)} on`:null,m=[s.problem,l.problem,...i,c,h].filter(k=>typeof k=="string"&&k.length>0);return ul(e,{problems:m,modes_source:l.source,rules_source:s.source},t),{table:s.value,modes:l.value,problems:m}}function Ke(e,n,t,r,o,s=!1){let l=[];if(r.length>0&&(s||zf(n,t,r,o))){let a=r[0];l.push(a.includes("Anvil is not checking")?a:xs(a,r.length-1))}if(l.push(...new Set([...pr?.notes??[],...ue?[ue]:[]])),ue=pr=null,l.length===0)return e;let i=l.join(`
|
|
36
|
+
`);if(!e.stdout)return K({systemMessage:i});try{let a=JSON.parse(e.stdout),c=typeof a.systemMessage=="string"?a.systemMessage:null;return K({...a,systemMessage:c?`${c}
|
|
37
|
+
${i}`:i})}catch{return e}}function zl(e,n){if(!e||n===null)return e;if(!/^[A-Za-z0-9_-]{1,80}$/.test(n)||!e.endsWith(".jsonl"))return null;let t=v(e.slice(0,-6),"subagents"),r=`agent-${n}.jsonl`;if(j(v(t,r),Number.MAX_SAFE_INTEGER)===!0)return v(t,r);try{for(let o of gr(v(t,"workflows")).slice(0,64))if(j(v(t,"workflows",o,r),Number.MAX_SAFE_INTEGER)===!0)return v(t,"workflows",o,r)}catch{}return null}function Ul(e,n,t){let r=a=>String(Math.round(a*100)/100),o=a=>e.unit==="money"&&e.money?Si(a,e.money):e.unit==="usd"?`$${r(a)}`:r(a),s={minute:"in the last minute",hour:"in the last hour",day:"today",week:"this week"}[e.window],l=n<e.limit?` + ${o(t)} in this call`:"",i=e.window==="day"?"; resets at midnight":e.window==="week"?"; resets Monday":"";return`cap reached: ${e.text} (${o(n)} used ${s}${l}${i})`}function na(e,n){try{let t=v(e.state,`note-${Jn(n)}.meter`);if(j(t)!==null)return null;U(e.state),le(t,"")}catch{}return`${B("Anvil")} budgets and model rules can't be checked${Le("fix it",he("on"))}`}var ue=null,pr=null,yt=null,Bl="claude.agent.helper";function Hf(e,n,t,r,o){let s=[],l=new Set,i=u=>{try{let d=j(u,262144);return d===null?"gone":d===!1?"unreadable":bt("sha256").update(dr(u,"utf8")).digest("hex")}catch{return"unreadable"}};for(let u of n.policies){if(!u.from||!ie(u,t))continue;l.add(u.from.file);let d=i(u.from.file);d!==u.from.sha256&&s.push(`${u.origin==="project"?".anvil/rules.md":"~/.anvil/rules.md"} ${d==="gone"?"was removed":d==="unreadable"?"can't be read":"changed"}`)}let a=s.length>0,c=t?v(t,".anvil","rules.md"):null;if(c&&!l.has(c)&&i(c)!=="gone"&&s.push(".anvil/rules.md isn't applied yet in this folder"),s.length===0)return null;try{U(e.state);let u=v(e.state,`rules-${Jn(r)}`),d=bt("sha256").update(s.join("|")).digest("hex").slice(0,16);if(ee(u,64).trim()===d)return null;le(u,d)}catch{}return`${B("Anvil")} ${s.join(" \xB7 ")}${a?" \xB7 the rules applied before still hold":""}${Le("apply it",`${D(o)} sync`)}`}function zf(e,n,t,r){try{U(e.state);let o=v(e.state,`problem-${Jn(n)}`),s=bt("sha256").update(t.join(`
|
|
38
|
+
`)).digest("hex").slice(0,16),[l,i]=ee(o,128).trim().split(" ");return l===s&&Number.isFinite(Number(i))&&r-Number(i)<Kl&&r>=Number(i)?!1:(le(o,`${s} ${r}`),!0)}catch{return!0}}function Uf(e,n,t){try{U(e.state);let r=v(e.state,`note-${Jn(n)}`),o=Number(ee(r,64).trim());return Number.isFinite(o)&&t-o<Kl&&t>=o?!1:(le(r,String(t)),!0)}catch{return!1}}async function To(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 Bf(e,n){let t=n.now(),r=Wo(e,n,t),o=await To(n),s=[...r.table?[]:["no rules are compiled"],...o?[o]:[],...r.problems],l=Oe(e),i=n.anvilDir!==void 0?ir(e,l,n.home).filter(u=>!ir(e,l,n.home,!1).includes(u)):[],a=s.filter(u=>!i.includes(u)),c={checking:!!r.table&&o===null,ok:a.length===0,problems:s,mode:r.table?Ur(r.table,r.modes).text:"none",rules:r.table?Hr(r.table):0};return K({anvil_self_check:c})}async function Kf(e,n,t){let r=n.now();try{await n.sessionChores?.(e.dir,r)}catch{}let o=Wo(e,n,r),s=await To(n),l=o.table;if(!l)return K(Fe("SessionStart",ta(o)));if(s)return K(Fe("SessionStart",s));let{enforced:i}=Ur(l,o.modes);vt||In(l.cli);let a=yn(),c=[...o.problems],u=[];try{u=n.anvilDir!==void 0&&n.startProblems?await n.startProblems({anvilDir:e.dir,home:n.home,files:hr(n,t),cli:a}):[]}catch{u=[]}for(let W of u)c.some(oe=>oe.includes(W)||W.includes(oe))||c.push(W);let d=gs(o.modes),f=Ye(o.modes),h=Dr(l,f),m=h.some(W=>W.verdict==="block")?hs:ys,k=null;try{k=await n.sessionWords?.()??null}catch{k=null}let E=k?k.sessionLine(i,f.length>0?1/0:zr(l).filter(W=>Xe[W]).length,c,a,d?.what??null,m):`${B("Anvil is on")} ${m}`,q=k?k.sessionContext(h.map(W=>W.id),i.filter(W=>!st.has(W)).map(Tt),a,d?.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 K({systemMessage:E,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:q}})}function ta(e){return e.problems.join(" ").includes("seal key")?"its seal key is missing or damaged":/^compiled\.json .*changed outside/m.test(e.problems.join(`
|
|
39
|
+
`))?"its rules were changed outside Anvil":"its rules are missing"}import{spawn as qf}from"child_process";import{readFileSync as Vf,statSync as Zf}from"fs";import{join as Yn}from"path";function Gf(e){try{let n=JSON.parse(Vf(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 Jf="sync-next",Yf="sync-pulled",Xf="claude-sync.js",Qf=6e4,ep=5*6e4;function oa(e,n){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||Yn(n,".anvil","workspace-keys.json")}function np(e,n){if(e.ANVIL_API_KEY?.trim())return!0;try{return Zf(oa(e,n)).isFile()}catch{return!1}}var tp=10*6e4;function sa(e){try{let n=e.env.ANVIL_CLAUDE_SYNC?.trim().toLowerCase();if(n==="off"||n==="0"||n==="false")return!1;if(!np(e.env,e.home))return j(Yn(e.paths.state,"sync-active.json"))===!0&&ra(e.paths,e.now),!1;let t=Yn(e.binDir,Xf);if(j(t)!==!0)return!1;let r=Yn(e.paths.state,Jf),o=Number(ee(r,64).trim());if(Number.isFinite(o)&&o>e.now&&o-e.now<=1440*6e4&&!(e.sessionStart===!0&&rp(e.paths,e.now)))return!1;U(e.paths.state);let s=oa(e.env,e.home);return!e.env.ANVIL_API_KEY?.trim()&&(j(s,1024*1024)!==!0||!Gf(s))?(ra(e.paths,e.now),le(r,String(e.now+tp)),!1):(le(r,String(e.now+Qf)),(e.start??op)(e.execPath,t,e.paths.dir),!0)}catch{return!1}}function rp(e,n){let t=Number(ee(Yn(e.state,Yf),64).trim());return!(Number.isFinite(t)&&t>0&&t<=n+6e4&&n-t<=ep)}function ra(e,n){let t=Yn(e.state,"signed-out.json"),r=dt(t);typeof r?.open!="string"&&le(t,`${JSON.stringify({open:new Date(n).toISOString(),windows:Array.isArray(r?.windows)?r.windows:[]})}
|
|
40
|
+
`)}function op(e,n,t){let r=qf(e,[n],{detached:!0,stdio:"ignore",cwd:t,env:process.env,windowsHide:!0});r.on("error",()=>{}),r.unref()}var Y=et(ap(import.meta.url)),ia=Date.now(),Mo=$e(Y,"claude-hook-core.js"),de=wr(Y)==="bin"&&wr(et(Y))==="claude"&&wr(et(et(Y)))===".anvil"?et(Y):void 0,dp=!de&&wr(Y)==="bin"&&yr($e(et(Y),".claude-plugin","plugin.json")),la=null;async function fp(e){try{(await import("module")).enableCompileCache?.($e(de??kn(e).dir,"cache"))}catch{}}function Qn(){return la??=import(br(Mo).href),la}var pp=null,un=()=>pp??=import(br($e(Y,"claude-meter.js")).href),gp=new cp.Script("globalThis.__anvilClassify()");async function mp(e,n){let t;try{t=await Qn()}catch(s){throw new Zn(s instanceof Error?s.message:String(s))}let{classifyRequest:r}=t;if(typeof r!="function")throw new Zn("no classifier in its file");let o=globalThis;o.__anvilClassify=()=>r(e);try{return gp.runInThisContext({timeout:n})}catch(s){throw s.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new Gn:s}finally{delete o.__anvilClassify}}function hp(e,n){return new Promise(t=>{let r=!1,o=(i,a)=>{r||(r=!0,clearTimeout(l),a&&a.terminate().catch(()=>{}),t(i))},s;try{s=new up(Mo,{workerData:{anvilClaudeHook:!0,request:e}})}catch(i){t({kind:"error",error:i instanceof Error?i.message:String(i)});return}let l=setTimeout(()=>o({kind:"timeout"},s),n);s.once("message",i=>{o(i.ok&&i.classification?{kind:"ok",classification:i.classification}:{kind:"error",error:i.error??"worker failed"},s)}),s.once("error",i=>o({kind:"error",error:i.message},s)),s.once("exit",i=>o({kind:"error",error:`worker exited (${i}) without an answer`}))})}async function yp(){try{let e=await un(),n=e.probeAccount?.(process.env)??null;if(!n||!e.runPlanProbe)return;e.runPlanProbe({paths:de?tn(de):kn(Xn()),env:process.env,now:()=>Date.now(),account:n})}catch{}}async function wp(){process.argv[2]==="--plan-probe"&&(await yp(),process.exit(0));let e="",n=()=>setTimeout(()=>process.exit(1),5e3),t=process.ppid,r=n(),o=()=>import(br($e(Y,"claude-approve.js")).href),s=async u=>{clearTimeout(r);try{return await(await o()).askPerson({...u,anvilDir:de,now:()=>Date.now()},{bin:Y,env:process.env,home:Xn(),started:ia})}finally{r=n()}},l=null,i=!1,a="";try{let u=Xn();await fp(u);try{a=sp(0,"utf8")}catch{a=""}if(a.length<64*1024&&a.includes("SessionStart"))try{i=JSON.parse(a).hook_event_name==="SessionStart"}catch{i=!1}e=(await Ql(a,{home:u,...de?{anvilDir:de}:{},tmpdir:lp(),env:process.env,now:()=>Date.now(),classifyInline:mp,classifyInWorker:hp,...dp?{plugin:!0,fallbackTable:$e(Y,"baseline.json")}:{},...de&&yr($e(Y,"baseline.json"))?{fallbackTable:$e(Y,"baseline.json")}:{},coreProblem:yr(Mo)?null:"its checker file is missing",entry:process.env.ANVIL_HOOK_EVENT,cli:process.env.ANVIL_HOOK_CLI,startProblems:async f=>(await Qn()).startProblems?.(f)??[],sessionChores:async(f,h)=>(await Qn()).sessionChores?.(f,h),answerChanges:async f=>(await Qn()).answerChanges?.(f)??null,sessionWords:async()=>{let f=await Qn();if(!f.sessionLine||!f.sessionContext)throw new Error("an older classifier file");return{sessionLine:f.sessionLine,sessionContext:f.sessionContext}},...de&&process.env.ANVIL_HOOK_WAIT?{ask:s,asRead:async(...f)=>(await o()).asRead(...f)}:{},notify:f=>{l=f},planProbe:{hookFile:$e(Y,"claude-hook.js"),node:process.execPath},budgetAtPrompt:async f=>(await un()).budgetAtPrompt(f),budgetAtAction:async f=>(await un()).budgetAtAction(f),modelAtAction:async f=>{let h=await un();return h.modelRulesAt?h.modelRulesAt(f):h.modelAtAction(f)},modelAtSwitch:async f=>(await un()).modelAtSwitch(f),modelAtPrompt:async f=>(await un()).modelAtPrompt(f),helpers:()=>import(br($e(Y,"claude-helpers.js")).href),moot:async f=>(await Qn()).mootHolds?.(f),lockHold:async(f,h)=>(await un()).lockHold?.(f,h)??null})).stdout}catch{let u=null;try{u=i?"SessionStart":JSON.parse(a).hook_event_name??null}catch{u=null}e=u==="SessionStart"||u==="PreToolUse"||u===null?`${JSON.stringify(Fe(u??"PreToolUse","its check crashed"))}
|
|
41
|
+
`:""}clearTimeout(r);try{e&&process.ppid===t&&ip(1,e)}catch{}if(globalThis.__anvilHookAnswered=!0,l&&de)try{await(await o()).heldNotice({...l,anvilDir:de,bin:Y,home:Xn(),now:Date.now(),env:process.env})}catch{}(Ln(process.env.ANVIL_HOOK_EVENT)||/"hook_event_name"\s*:\s*"(?:UserPromptSubmit|SubagentStart|SubagentStop|PreModelSwitch)"/.test(a.slice(0,4096)))&&process.exit(0);let c=de??kn(Xn()).dir;yr($e(c,"locks.json"))&&await un().then(u=>u.lockRun?.({anvilDir:c,input:a,sessionStart:i,now:Date.now()}),()=>0);try{let u=Xn();sa({paths:de?tn(de):kn(u),binDir:Y,home:u,env:process.env,now:ia,execPath:process.execPath,sessionStart:i})}catch{}process.exit(0)}wp();
|