@useanvil/claude-code 0.0.0-stage → 0.8.1
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 +2027 -0
- package/LICENSE +111 -0
- package/README.md +214 -2
- package/TELEMETRY.md +60 -0
- package/dist/claude-conditions.js +12 -0
- package/dist/claude-helpers.js +12 -0
- package/dist/claude-hook-core.js +87 -0
- package/dist/claude-hook.js +38 -0
- package/dist/claude-meter.js +35 -0
- package/dist/claude-powershell.cjs +37 -0
- package/dist/claude-sync.js +28 -0
- package/dist/cli/claude-main.js +23716 -0
- package/dist/cli.js +18 -0
- package/docs/coding-agents/YOUR-RULES.md +701 -0
- package/package.json +34 -4
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import{existsSync as Wr,readFileSync as Yu,writeSync as Xu}from"fs";import{homedir as Nt,tmpdir as Qu}from"os";import{basename as Ot,dirname as Cn,join as Re}from"path";import{fileURLToPath as ed,pathToFileURL as jr}from"url";import nd from"vm";import{Worker as td}from"worker_threads";import{spawnSync as Jf}from"child_process";import{createHash as Xf}from"crypto";import{chmodSync as ep,existsSync as np,lstatSync as Jl,mkdirSync as tp,readdirSync as rp,readFileSync as Yl,readlinkSync as Xl,realpathSync as Go,rmdirSync as op,statSync as ot,unlinkSync as sp,writeFileSync as ip}from"fs";import{dirname as Ql,join as ap,resolve as ea}from"path";var ve={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Ii(e){if(!e){let l=c=>c;return{on:!1,bold:l,dim:l,blue:l,grey:l,amber:l,mark:l,field:l}}let n=e==="truecolor",t=l=>c=>`\x1B[${l}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"),a={[ve.on]:r,[ve.blocked]:r,[ve.held]:r,[ve.next]:r,[ve.watching]:o,[ve.problem]:s,[ve.ok]:i};return{on:!0,bold:t("1"),dim:t("2"),blue:r,grey:o,amber:s,mark:l=>(a[l]??(c=>c))(l),field:l=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${ji(l)}\x1B[0m`}}var gd=Ii(!1),Wi=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function ji(e){return e.replace(Wi,"")}var je="claude";function Ze(e){return e==="ghost"||e==="enforce"?e:null}function zr(e,n){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let t=Ze(e.services?.[je]?.actions?.[n]?.mode);return t||(Ze(e.default_mode)??"ghost")}function Dt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[je]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function Gn(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function Ur(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:Dt(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[je]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[je]?.actions??{}};for(let i of t)s[i]={mode:n};return{version:1,kill_switch:o.kill_switch===!0,default_mode:Ze(o.default_mode)??"ghost",services:{...o.services??{},[je]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function Ti(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:Ze(e.default_mode)==="enforce"?!0:Object.values(e.services?.[je]?.actions??{}).some(n=>Ze(n?.mode)==="enforce")}var Jn="claude.agent.controls";function Yn(e,n){return n===Jn&&Ti(e)?"enforce":zr(e,n)}var Hr={off:0,ghost:1,enforce:2};function Rn(e,n){return e===null?n:n===null?e:Hr[n]>Hr[e]?n:e}function Br(e,n){return!e||typeof e!="object"?null:Ze(e.services?.[je]?.actions?.[n]?.mode)??(Ze(e.default_mode)==="enforce"?"enforce":null)}function qr(e,n,t,r=!1){let s=Rn(Br(e,n),t)??(r&&Gn(e)?"enforce":Yn(e,n));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function Zr(e,n,t){return Rn(Br(e,n),t)===null&&Gn(e)&&Yn(e,n)!=="enforce"}function xe(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function z(e){return Object.assign(Object.create(null),e)}var cn=[{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)"}}],Mi="home and project wipes and force-pushes to main",xd=`always blocking ${Mi}`,Li=new Map(cn.map(e=>[e.id,e]));function Ve(e){return Li.get(e)}var Di=z({"block-protected-targets":"protect","hold-delete-bursts":"stop-loops","hold-repeated-side-effect":"stop-loops","hold-helper-bursts":"stop-helper-bursts"}),Vr=new Set(["hold-delete-bursts","hold-helper-bursts"]),Kr=new Set(cn.flatMap(e=>Object.keys(e.slugs)));var Gr=z({"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 Ft(e){let n=new Set(qi(e));return cn.filter(t=>!Object.entries(Gr).some(([r,o])=>o.includes(t.id)&&n.has(r)))}var Ht=new Set([Jn,"claude.bash.secrets.expose"]),Fi=new Set(["claude.file.read_secret","claude.file.write_secret","claude.bash.secrets.print"]),Hi=/^(?:\.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 zi(e,n){if(e.startsWith("~/")){let o=xe(e.slice(2));return o.startsWith("/")?o.slice(1):o}let t=n?xe(n):null,r=xe(e);return t&&t!=="/"&&r.startsWith(`${t}/`)?r.slice(t.length+1):null}function Ui(e,n){if(!e)return!1;let t=zi(e,n);return t!==null&&Hi.test(t)}function Bi(e,n,t,r=[]){if(!e||!n)return!0;let o=xe(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(l=>`${i}/.git`===xe(l)))return!0;let a=xe(n)||"/";return a===i||i==="/"||a.startsWith(`${i}/`)}function zt(e){if(e.decision.verdict==="allow")return null;let n=e.baseline.ruleId?Di[e.baseline.ruleId]:void 0;if(n==="protect"){if(!(e.service==="fs.git_dir"&&!Bi(e.target,e.projectDir,e.home,e.histories)))return Ve("protect")}else if(n)return Ve(n);return e.action===Jn?Ve("keep-anvil-on"):e.action==="claude.bash.secrets.expose"||Fi.has(e.action)&&Ui(e.target,e.home)?Ve("keep-keys-in"):null}function Jr(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 qi(e){let n=new Set(e.policies.filter(t=>t.origin==="baseline").flatMap(t=>t.rules.map(r=>r.id)));return Object.keys(Gr).filter(t=>!n.has(t))}var Ke=z({"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 Xr(e){if(!Gn(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 Yr=z({"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 Xn(e,n){return e&&Yr[e]?Yr[e].slug:!e||e==="hold-risky-actions"?Ke[n]?.slug??n:e.replace(/@.*$/,"")}function Qr(e,n,t,r){return r&&n==="baseline"?Jr(Ve(r),t,Xn(e,t)):!r&&e==="block-protected-targets"?Ke[t]?.slug??t:Xn(e,t)}function Qn(e){return Ke[e]?.text??e}function Ut(e){let n=new Set(Kr);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(Xn(null,o));else n.add(Xn(r.id,""));return n.size}function Bt(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 qt(e,n){let t=Bt(e).filter(o=>Ke[o]),r=t.filter(o=>Yn(n,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===t.length?"enforce":`${r.length} enforced, rest ghost`}}var Zt="anvil-claude";function I(e){let n=e.trim();return n===Zt||n.endsWith(` ${Zt}`)||n.endsWith(`/${Zt}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var eo="\u{1F539}",F=e=>`${eo} ${e} ${eo}`;var Ge=e=>`
|
|
2
|
+
${ve.next} ${e}`;function Zi(e,n,t){return`${Ge(`To ${e}, run this in a terminal (not in this chat):`)}
|
|
3
|
+
${n}${t?Ge(`Then ${t}.`):""}`}var Vi=72;function $e(e,n){let t=`To ${e}, run in a terminal: ${n}`;return t.length+5<=Vi?Ge(t):`${Ge(`To ${e}, run in a terminal:`)}
|
|
4
|
+
${n}`}var Ki=(e,n)=>`they run \`${I(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 no="blocking unsafe actions automatically";var Se="anvil";function En(e){Se=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}function Je(){return Se}var le=e=>`${I(Se)} ${e}`;function Gi(e,n=Se,t){return`${F("Anvil isn't working")} ${e}.
|
|
5
|
+
Every command waits until it's fixed, so nothing runs unchecked.${t?Ge(t):""}${$e("fix it",`${I(n)} on`)}${$e("turn Anvil off instead",`${I(n)} off`)}`}function Ji(e,n=Se,t){return`${F("Anvil isn't working")} ${e}, so Claude Code holds every tool call until the user fixes it${t?` (${t})`:""} by running \`${I(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 to(e){return`${F("Held by Anvil")} ${e}${Ge("Claude can do it in smaller steps, each one checked")}`}function ro(e){return`${F("Held by Anvil")} ${e}, so nothing ran. Do it in smaller steps, each under that size.`}function _e(e,n,t=Se,r){let o=Ji(n,t,r);return{systemMessage:Gi(n,t,r),hookSpecificOutput:e==="SessionStart"?{hookEventName:e,additionalContext:o}:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:o}}}function oo(e,n,t=Se){let r=Yi(e.replace(/^Anvil:? /,""),t);return`${F("Anvil")} ${r.said}${n>0?` (and ${n} more)`:""}${r.fix??$e("see details",`${I(t)} report`)}`}function Yi(e,n){let t=e.lastIndexOf(` run ${I(n)} on`),r=t>0?e[t-1]:"";if(t<=0||r!==":"&&r!==";")return{said:e,fix:null};let o=e.slice(t+` run ${I(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",`${I(n)} on`)}}function so(e,n,t=null){return`${F(`Anvil would've ${e==="block"?"blocked this":"held this for review"}`)} ${n} \xB7 it ran${t?$e("hold these for your OK",`${I(Se)} enforce ${t}`):""}`}function io(e,n,t,r,o=!1){let s=`${F("Held by Anvil for your OK")} ${o?`${e} \xB7 always on`:e}`;return t?`${s}${Zi("allow it once",`${I(n)} allow ${t}`,"tell Claude to go on")}`:`${s}${Ge(`it can't be allowed right now: ${r}`)}`}function lo(e,n,t=Se){return n?`${F("Held by Anvil")} ${e}. Nothing ran. Tell the user: to allow it once, ${Ki(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.`:`${F("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 ao(e){return`${F("Held by Anvil for your OK")} ${e}`}function co(e,n){return`${F("Blocked by Anvil")} ${e}${$e("change the rule",`${I(n)} rules edit`)}`}function uo(e){return`${F("Blocked by Anvil")} ${e}. Nothing ran, and it can't be allowed once. Do not try another way.`}function fo(e){return`${F("Blocked by Anvil")} ${e} \xB7 can't be overridden`}function po(e){return`${F("Blocked by Anvil")} ${e}. Nothing ran, and this can't be overridden. Do not try another way.`}function go(e){return`${F("Allowed once, with your OK")} ${e}`}import{createHash as Fl}from"crypto";import{appendFileSync as Uo,closeSync as Bo,constants as Do,fstatSync as qo,mkdirSync as Hl,openSync as Zo,readdirSync as zl,readFileSync as Ul,readSync as Vo,renameSync as Bl,statSync as nr,unlinkSync as Fo,writeFileSync as ql}from"fs";import{homedir as Zl}from"os";import{dirname as Vl,join as Z}from"path";var Pn,Xi,mo="its file (claude-conditions.js) is missing or won't load";function ho(){return Xi??=import(new URL("claude-conditions.js",import.meta.url).href).then(e=>{Pn=typeof e.matchCondition=="function"&&typeof e.capMoved=="function"?e:void 0},()=>{})}function yo(e,n,t){return Pn?Pn.matchCondition(e,n,t):{hit:"unknown",why:`Anvil can't check this rule's condition: ${mo}`}}function wo(e,n){return Pn?Pn.capMoved(e,n):`Anvil can't read amounts: ${mo}`}var bo=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,Qi=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,el=/(?:^|[^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]|$)/,ko=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),vo=(e,n)=>e.split("+").every(t=>t[0]==="="?n.split(/[^a-z0-9]+/).includes(t.slice(1)):n.includes(t));function nl(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 tl(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=l=>r===l||r.endsWith(`.${l}`)||l.includes("*")&&l.split(".").every((c,d,u)=>u.length===s.length&&(c==="*"||c===s[d])),a=!1;return e.hosts.some(l=>{let c=l.indexOf("/");return c<0?i(l):(a||=i(l.slice(0,c))&&/^(?:\/batch\/?|\u0000)$/.test(t),i(l.slice(0,c))&&t.includes(l.slice(c)))})?"this":o&&!a?"other":"?"}function rl(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 Ye(e,n,t,r){let o=ko(t);return e.toolWords.length===0||e.toolWords.some(s=>vo(s,o))?{hit:"match",part:n,why:e.said}:r===3||/\u0000|%00/.test(o)||el.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 ol(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=ko(t.tool?.startsWith("mcp__")?t.tool.split("__").slice(2).join("__"):n.target?.startsWith(g)?n.target.slice(g.length):"");if(nl(e,u))return Ye(e,n,h,1);let x=(e.anywhere??[]).some(T=>vo(T,h))?{hit:"match",part:n,why:e.said}:null;if(!bo.test(u)&&!Qi.test(u))return x;let $=e.toolPrefixes.find(T=>h.startsWith(T));return $?Ye(e,n,h.slice($.length),1):e.servers.some(T=>T.length>2&&`_${h}_`.includes(`_${T}_`))?Ye(e,n,h,1):x||(e.others??[]).includes(u)?x:r(`which app ${bo.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),a="";try{i&&(a=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{a="\0"}if(!n.host&&!n.service)return r("where this writes");let l=[n.host,n.service,...Array.isArray(n.attributes.hosts)?n.attributes.hosts:[],rl(s)].filter(u=>typeof u=="string"&&u!==""),c=l.map(u=>tl(e,u,a)),d=[o,...l].some(u=>/^smtps?[:.]/i.test(u));if(c.includes("this")||d&&e.hosts.includes("smtp:")){let u=l.find((h,x)=>c[x]==="this"&&!h.includes(".")),g=o.includes("/")?3:2;return u?Ye(e,n,`cli:${u.toLowerCase()} ${o}`,g):d?Ye(e,n,"send mail",2):i?Ye(e,n,a,3):Ye(e,n,o,g)}return c.includes("?")?r(`where this writes (${l[0].replace(/[\u0000-\u001f]/g,"")})`):t.tool?.startsWith("mcp__")?r("what else this tool's command writes"):null}function Nn(e,n,t){let r=null;for(let o of n){let s=ol(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 nt,readdirSync as al,statSync as So}from"fs";import{dirname as Kt,isAbsolute as cl,join as oe,posix as ul,resolve as On}from"path";import{posix as $o}from"path";var sl=null;function U(){return sl??process.platform==="win32"}var xo=/^([A-Za-z]):(.*)$/s,il=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function Vt(e,n){let t=$o.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function un(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 ce(e){if(!U())return e;let n=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),t=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(n);if(r){let l=r[2];if(r[1]===".")return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(l))n=`\\\\${l.slice(4)}`;else if(xo.test(l))n=l;else return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;t=!0}n=n.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(n);if(o){let l=`/unc/${un(o[1],t).toLowerCase()}${o[2]?`/${un(o[2],t).toLowerCase()}`:""}`;return Vt(l,un(o[3]??"",t).toLowerCase())}let s=xo.exec(n);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?Vt(`/${s[1].toLowerCase()}`,un(l,t).toLowerCase()):null}let i=il.exec(n);if(i)return Vt(`/${i[1].toLowerCase()}`,un(i[2]??"",t).toLowerCase());let a=un(n,t).toLowerCase();if(a.startsWith("/")){let l=$o.normalize(a);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return a}function ll(e){return ce(e)??e}function et(e){if(!U())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 q(e){return U()?et(e)??e:e}function Xe(e){return!U()||typeof e!="string"||e===""?e:ll(e)}var dl=(e,n)=>{let t=n.endsWith("/")?n.slice(0,-1):n;return e===t||e.startsWith(`${t}/`)},fl=z({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 Co(e,n,t){if(n.length===0)return null;let r=null,o=(s,i)=>{let a=s.action.endsWith(".deploy")&&s.host?fl[s.host]:void 0;r??={hit:"unknown",part:s,why:`Anvil can't tell ${i}, so it holds it (your rule: ${e.said})${a?`. Say where it goes (${a}) and a deploy that isn't production runs`:""}`}};for(let s of n){let i=s.attributes;if(e.field==="outside_project"){let a=s.target,l=t.projectDir?[a,...t.touched?.full??[]].find(c=>c?.startsWith("/")&&!dl(c,t.projectDir)):null;if(l)return{hit:"match",part:s,why:`${e.said} (${l})`};(!a||!a.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 a=Ao(i,t.home),l=a?.find(c=>(e.value.includes("/")?c:c.split("/").pop())===e.value.toLowerCase().replace(/\.git$/,""));if(l!==void 0)return{hit:"match",part:s,why:`${e.said} (${l})`};a||o(s,"which repository this pushes to")}}return r}function Ao(e,n){try{let t=typeof e.repo_dir=="string"?q(e.repo_dir):e.repo_dir,r=n===null?null:q(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"||!cl(t)||!nt(t)||o!=="git"&&o!=="gh"||/[$`]/.test(s??""))return null;if(o==="gh"&&s!==null)return _o([s],t);let i=pl(t,r);if(i===null)return null;let a=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"))&&a.set(d.sub,[...a.get(d.sub)??[],d.value]);if(s!==null&&!a.has(s)&&!/^[./]|[/:]/.test(s))return null;let l=s!==null?a.get(s)??[s]:[...a.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!=="."&&!a.has(d.value)&&l.push(d.value);let c=new Set(l);for(let d of l)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?_o([...c],t):null}catch{return null}}function _o(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),a=(s?ul.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(o)&&!o.startsWith(".")?o:On(n,o)).replace(/[?#].*$/,"").split(/[\\/]/).filter(g=>g&&g!=="."),l=a.findIndex((g,h)=>h>=2&&/^pulls?$/.test(g));l>=2&&(a=a.slice(0,l));let[c,d]=a.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 pl(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=gl(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=[],a=24,l=(c,d)=>{let u=--a<0||d>5?void 0:he(c,1048576);if(u===void 0)return!1;for(let g of ml(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)&&On(Kt(c),g.value);if(!h||!l(h,d+1))return!1}return!0};return s.every(c=>l(c,0))?i:null}function gl(e){let n=t=>/^(ref: refs\/|[0-9a-f]{40})/.test(he(oe(t,"HEAD"),4096)?.toString("utf8")??"");for(let t=On(e),r=0;r<64;r++,t=Kt(t)){let o=oe(t,".git"),s=["objects","refs"].every(i=>nt(oe(t,i)))&&n(t)?t:null;if(nt(o)){let i=So(o);if(i.isDirectory())n(o)&&(s=o);else if(s=i.isFile()?/^gitdir:\s*(.+)$/m.exec(he(o,65536)?.toString("utf8")??"")?.[1]?.trim():null,!s)return null}if(s){let i=On(t,s),a=he(oe(i,"commondir"),65536),l=a===null?i:On(i,a.toString("utf8").trim());for(let c of["remotes","branches"]){let d=oe(l,c);if(nt(d)&&(!So(d).isDirectory()||al(d).length>0))return null}return{gitDir:i,common:l}}if(Kt(t)===t)return null}return null}function ml(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[a,...l]=s[1].toLowerCase().split(".");t=a,r=s[2]?.replace(/\\(.)/g,"$1")??(l.length>0?l.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,(a,l,c)=>l??c??"").trim()})}return n}import{domainToASCII as ef}from"url";var cf="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as yl,readdirSync as wl,realpathSync as Io}from"fs";import{basename as bl,dirname as kl,join as vl}from"path";function Te(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||U()?n.normalize("NFC").toLowerCase():n}function Gt(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(a=>a!=="/");else if(i>0){let a=n.slice(o+1,i),l=a[0]==="!"||a[0]==="^",c=l?a.slice(1):a,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)!==l),o=i}else t.push(a=>a===s)}return r?{source:"(?!)",test:()=>!1}:{source:e,test(o){let s=[...o],i=0,a=0,l=-1,c=0;for(;a<s.length;){let d=t[i];if(d!=null&&d(s[a]))i++,a++;else if(d===null)l=i++,c=a;else if(l>=0&&s[c]!=="/")i=l+1,a=++c;else return!1}for(;t[i]===null;)i++;return i===t.length}}}var hl=e=>e==="**"||/^[*?]+(?:\.[*?]+)*$/.test(e.replace(/\[[^\]]+\]/g,"?"));function Ro(e){let n=U()?ce(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=[],a=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&&a++);if(i.length===0||i.every(hl))return null;let l=[];for(let c of i){if(c==="**"){l[l.length-1]!==null&&l.push(null);continue}let d=Te(c),u=Gt(d);if(u&&u.source==="(?!)")return null;l.push(u??d)}for(;l[l.length-1]===null;)l.pop();return{segs:l,at:a>0&&s===3?2:s,up:a}}var Eo=["Write","Edit","MultiEdit","NotebookEdit"],xl=["Read","Grep","NotebookRead","Glob","LS"],$l=["claude.bash.fs.delete_recursive","claude.bash.fs.delete_disposable"],Sl=[".git",".anvil/rules.md",".anvil/rules.json"],Po=new Set(["node_modules",".git"]),_l=1e4,Cl=/^(?:https?|ftps?|wss?|git|ssh|s3|gs|file):$/;var No=new WeakMap,Me=e=>Te(e).split("/").filter(Boolean);function Al(e,n,t){let r=new Map,o=(s,i)=>{if(s===e.length)return 2;if(i===n.length)return 1;let a=s*(n.length+1)+i,l=r.get(a);if(l!==void 0)return l;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=Gt(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(a,u),u};return o(0,t)}function Jt(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(l=>l.slice(0,Math.max(0,l.length-e.up))):r.length===0?[[]]:r,i=0,a=!1;for(let l of s)if(!(l.length>=n.length||l.some((c,d)=>c!==n[d]))){a=!0;for(let c=l.length;c<n.length&&i<2;c+=o===3?1:n.length)i=Math.max(i,Al(e.segs,n,c))}return i===2?2:o===3?a?3:0:i===1&&e.segs.includes(null)?3:i}function Wo(e){if(U())return Rl(e);let n="";for(let t=e;t.length>1;)try{return Io.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}function Rl(e){let n=et(e);if(n===null||process.platform!=="win32")return e;let t=[];for(let r=n;;)try{return ce(vl(Io.native(r),...t))??e}catch{let o=kl(r);if(o===r)return e;t.unshift(bl(r)),r=o}}function El(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("/")}`,a=Wo(i);return Te(a)===Te(i)?null:{segs:[...Me(a),...e.segs.slice(s)],at:1,up:0}}function Pl(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((a,l)=>t[l]===a));s--){let i=`/${t.slice(0,s).join("/")}`;Sl.some(a=>yl(q(`${i}/${a}`)))&&o.push(i)}return o}function Nl(e,n){if(Po.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=wl(q(r[o]),{withFileTypes:!0})}catch{continue}for(let i of s){if(++t>_l)return"unsure";let a=`${r[o]}/${i.name}`;if(n(Me(a)))return"yes";i.isDirectory()&&!Po.has(i.name)&&r.push(a)}}return"no"}var Oo=new WeakMap;function Ol(e,n){if(!n)return!1;let t=Oo.get(e);t||(t=e.paths.map(o=>{let s=Te(o.split("/").filter(c=>c!==""&&!/^[*?]+$/.test(c)).pop()??""),i=/^[*?]+[^*?[]+$/.test(s),a=s.replace(/^[*?]+/,"");if(a===""||/[*?[]/.test(a))return!0;let l=a.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&");return new RegExp(`${i?"":"(?:^|[\\s'\"`=:(/])"}${l}(?=$|[\\s'"\`/;|&)<>])`)}),Oo.set(e,t));let r=Te(n);return t.some(o=>o===!0||o.test(r))}function jo(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,a=s!==null?Eo.includes(s)||xl.includes(s):i!==void 0;if(a&&(s!==null?!Eo.includes(s):o.action==="claude.file.read_secret"))return null;let l=r.touched,c=new Set(l?.written??[]),d=new Set(l?.read??[]),u=a?[...typeof i=="string"?[i]:[],...l?.full??[]]:[...c,...(l?.full??[]).filter(m=>!d.has(m)||c.has(m))],g=a?[]:l?.unknown??[],h=`(your rule: ${e.said})`;if(a&&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 x=No.get(e);if(x||No.set(e,x=e.paths.map(Ro)),x.includes(null))return{hit:"unknown",part:o,why:`Anvil can't read this rule's paths, so it holds every write ${h}`};let $=m=>r.projectDir&&m.startsWith(`${r.projectDir}/`)?m.slice(r.projectDir.length+1):r.home&&m.startsWith(`${r.home}/`)?`~${m.slice(r.home.length)}`:m,T=(m,E)=>({hit:"unknown",part:{...o,target:E},why:`${m}, so Anvil holds it ${h}`}),te=typeof r.root=="string"?r.root:null,ke=te??r.projectDir,G=r.home?Me(r.home):null,p=m=>[...new Map([...m,...m.map(Wo)].map(E=>[Me(E).join("/"),Me(E)])).values()],_=p(ke?.startsWith("/")?[ke]:[]),y=new Map,N=m=>{if(te!==null)return _;let E=y.get(m);if(E===void 0){let P=p(Pl(m,r.home)).filter(B=>!_.some(se=>se.join("/")===B.join("/")));E=P.length===0?_:[..._,...P],y.set(m,E)}return E},J=[...new Set(u)].filter(m=>m.startsWith("/")).map(m=>({p:m,w:Me(m)})).filter(m=>!m.w.some(E=>Cl.test(E))),M=[..._,...[r.projectDir,r.home].filter(m=>typeof m=="string"&&m.startsWith("/")).map(Me)],W=(m,E)=>[...M,...N(m)].some(P=>P.length>=E.length&&E.every((B,se)=>P[se]===B)),C=m=>l?.written===void 0||c.has(m)||a?`changes ${$(m)}`:`may change ${$(m)}`,pe=[],He=[],An=(m,E)=>{for(let P of J){let B=E(P.p);for(let se of m){let re=Jt(se,P.w,G,B);if(re===2)return{hit:"match",part:{...o,target:$(P.p)},why:C(P.p)};re===1&&!W(P.p,P.w)&&pe.push({p:P.p,sure:!0}),re===3&&!W(P.p,P.w)&&He.push(P.p)}}return null},Ee=x,A=An(Ee,N)??An(Ee.map(m=>El(m,r.home,ke)).filter(m=>m!==null),()=>[]);if(A)return A;let j=m=>Te(m).replace(/(?<!^)\/+$/,""),ze=m=>n.some(E=>$l.includes(E.action)&&typeof E.target=="string"&&j(E.target)===j(m));for(let m of new Set(He)){if(pe.some(P=>P.p===m)||!(ze(m)||c.has(m)))continue;let E=Nl(m,P=>Ee.some(B=>Jt(B,P,G,N(m))===2));E!=="no"&&pe.push({p:m,sure:E==="yes"})}let Ue=pe.find(m=>m.sure&&ze(m.p));if(Ue)return{hit:"match",part:{...o,target:$(Ue.p)},why:`deletes ${$(Ue.p)}, which holds ${e.paths.join(", ")}`};let Pe=pe[0];if(Pe!==void 0)return T(`it changes ${$(Pe.p)}, a folder that ${Pe.sure?"holds":"may hold"} ${e.paths.join(", ")}, and Anvil can't tell what changes in it`,$(Pe.p));for(let m of g){let E=m.includes("\0")?m.slice(0,m.indexOf("\0")):m,P=E.slice(0,E.lastIndexOf("/"));if(P.startsWith("/")&&Ee.some(B=>Jt(B,Me(P),G,N(P))===2))return T(`Anvil can't read the whole path this writes (${$(m.replace(/[\u0000\u0001]/g,""))})`,$(P))}return g.length>0&&Ol(e,r.command)?T(`it writes where Anvil can't read, and it names ${e.paths.join(", ")}`,o.target):null}function To(e,n,t){switch(e.type){case"app":return Nn(e,n,t);case"paths":return jo(e,n,t);case"target":return Co(e,n,t);case"kind":return n[0]?{hit:"match",part:n[0],why:e.said}:null}}function Mo(e,n,t=yo){let r=e.kinds?n.parts.filter(a=>e.kinds.includes(a.action)):n.parts;if(e.kinds&&r.length===0)return null;if(!e.when||e.when.length===0)return To(e.narrowing,r,n);let o=null,s=n.parts.length>15,i=a=>`${a}, so it holds it (your rule: ${e.text})`;for(let a of r){let l=To(e.narrowing,[a],n);if(!l)continue;let c=e.when.map(u=>t(u,l.part,n));if(c.some(u=>u===null)){s&&(o??={hit:"unknown",part:l.part,why:i("Anvil can't read everything this line does")});continue}let d=c.find(u=>u!==null&&u.hit==="unknown");if(l.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:l.part,why:l.why,...u.length>0?{detail:u.join(", ")}:{}}}o??=l.hit==="unknown"?l:{hit:"unknown",part:l.part,why:i(d.why)}}return o}var Yt="anvil-claude-compiled/1";function Xt(e,n){return`mut:${e}:${n}`}var tt={verdict:"allow",policy:null,origin:null,ruleId:null,blockedBy:null,source:null};function Wl(e){return typeof e!="string"?"":e.normalize("NFKC").replace(/[\u0000-\u001f\u007f]/g,"").trim().toLowerCase()}function jl(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 Tl(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 Lo(e,n){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(n)}function Ml(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 Ll(e,n,t,r){let o=(s,i,a,l)=>({verdict:a??(i==="confirmation_required"?"hold":"block"),policy:e.name,origin:e.origin,ruleId:s,blockedBy:i,source:l});if(!e.allowed_actions.includes(n.action))return e.deny_unlisted?o(null,"allowlist",null,null):tt;for(let s of e.rules)if(Lo(s,n.action))switch(s.primitive){case"confirmation_gate":{if(s.all_actions===!0||Ml(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 a=Wl(n.service);if(a&&jl(a,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 a=Tl(n.metadata,s.resource_field?.trim()||"resource_id");if(!a)break;if(t.recordAndCount(Xt(n.action,a),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 tt}var dn={allow:0,hold:1,block:2};function Qt(e,n,t,r,o){let s=tt,i=tt;for(let a of e.policies){if(!ye(a,o))continue;let l=Ll(a,n,t,r);a.origin==="baseline"&&dn[l.verdict]>dn[i.verdict]&&(i=l);let c=dn[l.verdict]>dn[s.verdict],d=l.verdict!=="allow"&&dn[l.verdict]===dn[s.verdict]&&a.origin!=="baseline";(c||d)&&(s=l)}return{decision:s,baseline:i}}function ye(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&Dl(n,e.project_dir))}function er(e,n,t){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!ye(o,t))){for(let s of o.rules)s.mode&&Lo(s,n)&&(r=Rn(r,s.mode));o.off?.includes(n)&&(r=Rn(r,"off"))}return r}function Dl(e,n){let t=Xe(e),r=Xe(n),o=r.endsWith("/")?r.slice(0,-1):r;return t===o||t.startsWith(o+"/")}function Qe(e=Zl()){return Le(Z(e,".anvil","claude"))}function Le(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 Kl=3500;function S(e,n=8*1024*1024){try{let t=nr(e);return t.isFile()&&t.size<=n}catch(t){return t.code==="ENOENT"?null:!1}}function he(e,n=8*1024*1024){let t;try{t=Zo(e,Do.O_RDONLY|Do.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=qo(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=Vo(t,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Bo(t)}}function De(e,n){let t=n.endsWith(`
|
|
6
|
+
`)?n:`${n}
|
|
7
|
+
`;if(Buffer.byteLength(t)>Kl)throw new Error(`refusing to append a ${Buffer.byteLength(t)}-byte line`);if(S(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);Uo(e,t,{mode:384})}function H(e){Hl(e,{recursive:!0,mode:448})}function V(e,n){if(S(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let t;try{t=Zo(e,"r")}catch{return""}try{let r=qo(t).size,o=Math.max(0,r-n),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);Vo(t,i,0,s,o);let a=i.toString("utf8");if(o>0){let l=a.indexOf(`
|
|
8
|
+
`);a=l<0?"":a.slice(l+1)}return a}finally{Bo(t)}}function X(e,n,t=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;ql(r,n,{mode:t}),In(r,e)}function In(e,n){for(let t=0;;t++)try{Bl(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 Wn(e){if(S(e)!==!0)return null;try{return JSON.parse(Ul(e,"utf8"))}catch{return null}}var Ho=256*1024,Gl=1024*1024,rt=class{constructor(n,t=()=>null){this.file=n;this.answer=t}recordAndCount(n,t,r){let o=r-t,s=this.restartedAt(n,r),i=1,a=V(this.file,Ho);for(let l of a.split(`
|
|
9
|
+
`)){let c=l.indexOf(" ");if(c<=0||l.slice(c+1)!==n)continue;let d=Number(l.slice(0,c));Number.isFinite(d)&&d>=o&&d<=r&&d>s&&i++}return this.rotateIfLarge(),De(this.file,`${r} ${n.replace(/[\r\n]/g," ")}`),i}restart(n,t,r){let o=this.restartDir();H(o),X(Z(o,`${zo(n)}.json`),JSON.stringify({v:1,at:t,...r?{tr:r.transcript,call:r.call}:{}}));try{for(let s of zl(o)){let i=Z(o,s);nr(i).mtimeMs<t-864e5&&Fo(i)}}catch{}}restartedAt(n,t){let r=Z(this.restartDir(),`${zo(n)}.json`),o=he(r,4096);if(!o)return-1/0;try{let s=JSON.parse(o.toString("utf8"));if(typeof s.at!="number"||!Number.isFinite(s.at)||s.at>t)return-1/0;if(typeof s.tr=="string"&&typeof s.call=="string"){let i=this.answer(s.tr,s.call);if(i===null)return-1/0;if(i==="no")return Fo(r),-1/0;X(r,JSON.stringify({v:1,at:s.at}))}return s.at}catch{return-1/0}}restartDir(){return Z(Vl(this.file),"rate-ok")}rotateIfLarge(){try{if(nr(this.file).size>Gl){let n=V(this.file,Ho);X(this.file,n)}}catch{}}},zo=e=>Fl("sha256").update(e).digest("hex").slice(0,16);function Ko(e,n){let t=Z(e,n.toISOString().slice(0,10));S(t,Number.MAX_SAFE_INTEGER)!==!1&&Uo(t,".",{mode:384})}var na="/.anvil/claude/bin/claude-hook.js",ta=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var fn=class extends Error{constructor(n){super(n),this.name="SettingsRefused"}};var ra=["UserPromptSubmit","SubagentStart","SubagentStop","PreModelSwitch"],jn=e=>typeof e=="string"&&ra.includes(e);function Jo(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 fn(`${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 fn(`${n} is not a JSON object. Anvil changed nothing.`);return r}function oa(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 sa=e=>{let n=oa(e);return n!==null&&(n.includes(na)||ta.test(n))};function ia(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 Yo(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function la(e){return he(e,64*1024*1024)}function Xo(e){try{if(!Jl(e).isSymbolicLink())return e}catch{return e}try{return Go(e)}catch(n){let t=n.code;throw t==="ENOENT"?new fn(`${e} is a link to ${aa(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new fn(`${e} is a link Anvil cannot follow (${t??String(n)}). Anvil changed nothing.`)}}function aa(e){let n=Ql(e);try{n=Go(n)}catch{}return ea(n,Xl(e))}function tr(e){try{let n=Xo(e),t=ot(n);if(!t.isFile()||t.size>4*1024*1024)return!1;let r=la(n);if(r===null)return!1;let o=Jo(r.toString("utf8"),e).hooks?.PreToolUse;return Array.isArray(o)&&o.some(s=>{let i=s&&typeof s=="object"?s:null,a=i?.matcher;return(a===void 0||a===""||a==="*")&&Array.isArray(i?.hooks)&&i.hooks.some(l=>sa(l)&&da(l))})}catch{return!1}}function Qo(e,n){let t;try{t=Xo(e)}catch{return"unreadable"}let r;try{r=ot(t)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=Jo(Yl(t,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let s=o.hooks?.PreToolUse;return Array.isArray(s)&&s.some(a=>{let l=a&&typeof a=="object"?a:null,c=l?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(l?.hooks)&&l.hooks.some(d=>ia(d,n))})?"present":"missing"}function ca(e){let n=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),t=s=>s.startsWith("'")?s.slice(1,-1).replace(/'\\''/g,"'"):s,r=n?n.findIndex(s=>s==="/bin/sh"||s==="sh"):-1,o=n&&r>=0&&(n[r+3]==="PreToolUse"||n[r+3]==="SessionStart")?1:0;if(n&&r>=0&&n[r+3+o]==="||"){let s=r>0&&r%5===0;for(let i=0;s&&i<r;i+=5)s=n[i]==="["&&(n[i+1]==="-s"||n[i+1]==="-f")&&n[i+3]==="]"&&n[i+4]==="&&"&&t(n[i+2])===t(n[r+1]);if(r===0||s)return[t(n[r+1]),t(n[r+2])]}return!n||n.length!==2?null:[t(n[0]),t(n[1])]}function ua(e){if(!e||typeof e!="object")return null;let{command:n,args:t}=e;if(typeof n!="string")return null;if(Array.isArray(t)){let r=t.find(o=>typeof o=="string"&&/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js$/i.test(o));return r?[n,r]:null}return ca(n)}function da(e){let n=ua(e);if(!n)return!1;try{return ot(n[0]).isFile()&&ot(n[1]).isFile()}catch{return!1}}import{spawnSync as au}from"child_process";import{createHash as Fn}from"crypto";import{readdirSync as cu,readFileSync as Rt,realpathSync as ii,statSync as uu}from"fs";import{basename as Hn,dirname as Rr,isAbsolute as Et,join as b,resolve as kn}from"path";import{closeSync as fa,constants as es,fstatSync as pa,openSync as ga,readdirSync as ma,readSync as ha,unlinkSync as ya}from"fs";import{join as ns}from"path";var wa=9,ts=4*1024*1024;function ba(e){let n;try{n=ga(e,es.O_RDONLY|es.O_NONBLOCK)}catch(t){if(t.code==="ENOENT")return"";throw t}try{let t=pa(n);if(!t.isFile())throw new Error("the day's cap count is not a regular file");if(t.size>ts)throw new Error(`the day's cap count is over ${ts/1024/1024} MB`);let r=Buffer.alloc(t.size),o=0;for(;o<t.size;){let s=ha(n,r,o,t.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{fa(n)}}function st(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 rs=e=>{let n=new Date(e);return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`};function os(e,n,t,r=null){let o=[];for(let s of e.policies)if(ye(s,t)){for(let i of s.caps??[])if(i.kinds.some(a=>n.includes(a))){if(i.match&&r){let a=r.parts.filter(l=>i.kinds.includes(l.action));if(a.length>0&&Nn(i.match,a,r)===null)continue}o.push(i)}}return o}var en=class extends Error{};function ss(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 lt(e,n,t=null){if(e.unit==="money"){let s=wo(e,t);if(typeof s=="string")throw new en(s);return s}if(e.unit==="calls")return 1;let r=n?.machines??1,o=(n?.hours??1)*r;return e.unit==="machines"?r:e.unit==="hours"?o:(e.price?.per==="hour"?o:r)*(e.price?.usd??0)}function ka(e,n,t){try{return lt(e,n,t)}catch(r){if(r instanceof en)return e.limit;throw r}}var it=class{constructor(n){this.dir=n}file(n){return ns(this.dir,`${rs(n)}.log`)}write(n){H(this.dir),De(this.file(n.t),JSON.stringify(n))}read(n,t){let r=[],o=new Date(n);for(o.setHours(0,0,0,0);o.getTime()<=t;o.setDate(o.getDate()+1))for(let s of ba(this.file(o.getTime())).split(`
|
|
10
|
+
`))if(s)try{let i=JSON.parse(s);typeof i.t=="number"&&typeof i.cap=="string"&&typeof i.key=="string"&&r.push(i)}catch{}return r}usedIn(n,t,r,o=n.length,s=!1){let i=st(t,r),a=new Map;for(let c=0;c<o;c++){let d=n[c];d.cap===t.id&&a.set(d.key,d.op==="x"||!a.has(d.key)||a.get(d.key).op==="x"?d:{...a.get(d.key),op:d.op})}let l=0;for(let c of a.values())c.op!=="x"&&c.t>=i&&(s||c.t<=r)&&(l+=c.n);return l}admit(n,t,r,o,s,i=null){if(n.length===0)return null;let a=n.map(u=>lt(u,r,i));this.resolve(n,o),n.forEach((u,g)=>this.write({t:o,op:"ran",cap:u.id,key:t,n:a[g]})),s?.();let l=Math.min(...n.map(u=>st(u,o))),c=this.read(l,o+6e4),d=null;for(let u of n){let g=c.findIndex(x=>x.cap===u.id&&x.key===t&&x.op==="ran"&&x.t===o);if(g<0){d={cap:u,used:u.limit};break}let h=this.usedIn(c,u,o,g+1,!0);if(h>u.limit){d={cap:u,used:h-c[g].n};break}}if(d)for(let u of n)this.write({t:o,op:"x",cap:u.id,key:t,n:0});return this.prune(o),d}count(n,t,r,o,s="ran",i,a=null){for(let l of n)this.write({t:o,op:s,cap:l.id,key:t,n:ka(l,r,a),...s==="ask"&&i?.tr&&i.call?{tr:i.tr,call:i.call}:{}})}used(n,t){return this.resolve([n],t),this.usedIn(this.read(st(n,t),t),n,t)}resolve(n,t){let r=new Set(n.map(a=>a.id)),o=Math.min(...n.map(a=>st(a,t))),s=new Map;for(let a of this.read(o,t)){if(!r.has(a.cap))continue;let l=`${a.cap}\0${a.key}`;a.op==="ask"?s.set(l,a):s.delete(l)}let i=0;for(let a of s.values()){if(i>=4||t-a.t<1e3)continue;i++;let l=rr(a.tr,a.call);l==="no"?this.write({t:a.t,op:"x",cap:a.cap,key:a.key,n:0}):l==="yes"&&this.write({t:a.t,op:"ran",cap:a.cap,key:a.key,n:a.n})}}prune(n){try{let t=rs(n-wa*864e5);for(let r of ma(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<t&&ya(ns(this.dir,r))}catch{}}};function rr(e,n){return!e||!n?null:va(V(e,4*1024*1024),n)}function va(e,n){let t=e.indexOf(`"tool_use_id":"${n}"`);if(t<0)return null;let r=e.slice(e.lastIndexOf(`
|
|
11
|
+
`,t)+1,e.indexOf(`
|
|
12
|
+
`,t)<0?void 0:e.indexOf(`
|
|
13
|
+
`,t));try{let o=JSON.parse(r),i=(Array.isArray(o.message?.content)?o.message.content:[]).find(l=>l.type==="tool_result"&&l.tool_use_id===n);if(!i)return null;let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??"");return i.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(a)?"no":"yes"}catch{return null}}var or="[-.\\s\\u2010-\\u2015]",kp=new RegExp(`(?:\\+?1${or}?)?(?:\\(?\\d{3}\\)?${or}?\\d{3}${or}?\\d{4})`,"g"),xa="[-.\\s()\\u2010-\\u2015]",vp=new RegExp(`\\+[2-9]\\d(?:${xa}{0,2}\\d){5,13}\\b`,"g");var $a=/\b(?:Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi,Sa=/\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b/g,_a=/\b(?:sk|pk|api|key|token|secret)[-_=][A-Za-z0-9]{20,}\b/gi,is=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,Ca=/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/g,Aa=/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASCA)[A-Z0-9]{16}\b/g,Ra=/\bgh[opusr]_[A-Za-z0-9]{36,}\b/g,Ea=/\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,Pa=/\bglpat-[A-Za-z0-9_\-]{20,}\b/g,Na=/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,Oa=/\bhttps:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9]+\/B[A-Za-z0-9]+\/[A-Za-z0-9]+/g,Ia=/\bAIza[A-Za-z0-9_\-]{35}\b/g,Wa=/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,ja=/\bSK[0-9a-f]{32}\b/g,Ta=/\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\b/g,Ma=/\bnpm_[A-Za-z0-9]{36}\b/g,La=/\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}\b/g,Da=[$a,Sa,_a,Aa,Ra,Ea,Pa,Na,Oa,Ia,Wa,ja,Ta,Ma,La];function ls(e){let n=e;n=n.replace(Ca,"");for(let r of Da)r.lastIndex=0,n=n.replace(r,"");is.lastIndex=0;let t=is.exec(n);return t&&(n=n.slice(0,t.index)),n}var ee="***",as=/"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?/.source,cs=/\$\([^)]*\)?|\$\{[^}]*\}?|\\[\s\S]|[^\s"'`;&|<>()\\]/.source,sr=new RegExp(`(?:${as}|${cs})(?:${cs}|(?=["'](?![\\s;&|)<>]|$))(?:${as}))*`,"y"),k=/(?:[ \t]|\\\r?\n)+/.source,ft=/(?:[ \t]|\\\r?\n)*/.source,Fa=/token|secret|passw(?:or)?d|passphrase|pwd|api[-_]?key|access[-_]?key|private[-_]?key|credentials?|auth|(?:^|[_.:-])(?:pass|pw|sig|signature)$|[_.:-]key$/i,Ha=/[a-z0-9](?:Pass|Key|Sig)$/,za=/tokens$|tokeniz|author(?!i[sz]ation)|no_?auth$/i,gn=e=>(Fa.test(e)||Ha.test(e))&&!za.test(e),ys=/key|token|secret|auth|passw|cookie|session|credential|signature/i,Fe=["",'"',"'","`"],nn=128,us=/<<-?[ \t]*(["']?)([\w.@-]+)\1/y;function mn(e){let n=[],t=new Uint8Array(e.length+1),r=[],o=null,s=0,i=0,a=0;for(let l=0;l<e.length;l++){let c=e[l];if(o!==null){if(c===`
|
|
14
|
+
`){let g=e.slice(i,l).trim();n.push({start:s,end:l,op:`
|
|
15
|
+
`}),s=i=l+1,a=0,g===o&&(o=r.shift()??null);continue}t[l]=a,c==="\\"&&a!==2&&e[l+1]!==`
|
|
16
|
+
`?t[++l]=a|nn:a?c===Fe[a]&&(a=0):Fe.indexOf(c)>0&&(a=Fe.indexOf(c));continue}if(t[l]=a,a){c==="\\"&&a!==2?t[++l]=a|nn:c===Fe[a]&&(a=0);continue}if(c==="\\"){t[++l]=nn;continue}let d=Fe.indexOf(c);if(d>0){a=d;continue}if(c==="#"&&(l===s||/\s/.test(e[l-1]))){let g=e.indexOf(`
|
|
17
|
+
`,l);if(g<0)break;l=g-1;continue}if(c==="<"&&e[l+1]==="<"&&e[l+2]!=="<"){us.lastIndex=l;let g=us.exec(e);if(g){r.push(g[2]),l+=g[0].length-1;continue}}let u="";c===`
|
|
18
|
+
`||c===";"?u=c:c==="&"?u=e[l+1]==="&"?"&&":e[l-1]===">"||e[l-1]==="<"||e[l+1]===">"?"":"&":c==="|"&&(u=e[l+1]==="|"?"||":e[l+1]==="&"?"|&":"|"),u&&(n.push({start:s,end:l,op:u}),l+=u.length-1,s=l+1,u===`
|
|
19
|
+
`&&(i=s,r.length>0&&(o=r.shift())))}return n.push({start:s,end:e.length,op:""}),{segments:n,quotes:t}}var pt=(e,n,t)=>n[t]>0&&n[t]<nn&&e[t]===Fe[n[t]];function Tn(e,n,t){if(sr.lastIndex=n,!sr.exec(e))return n;let r=sr.lastIndex;if((t[n]&~nn)===0)return r;for(let o=n;o<r;o++)if(pt(e,t,o))return o;return r}function Ce(e,n,t=()=>!0,r=()=>!0){let{quotes:o}=mn(e),s="",i=0;n.lastIndex=0;for(let a=n.exec(e);a;a=n.exec(e)){let l=a.index+a[0].length;if(!t(a))continue;let c=Tn(e,l,o);c===l||!r(e.slice(l,c))||(s+=e.slice(i,l)+ee,i=n.lastIndex=c)}return s+e.slice(i)}var Q=e=>new RegExp(`(?:^|\\s)(?:${e})(?:=|${ft})(?=[^\\s-])`,"g"),ue=e=>new RegExp(`(?:^|[\\s"'(/])(?:${e})(?=$|[\\s"';)])`),pn=(e,n=0,t="(?!)")=>{let r=`(?:${k}(?:(?:${t})${k}[^\\s-][^\\s]*|(?!(?:${t})${k})-[\\w-]+(?:=[^\\s]*)?))*`;return new RegExp(`(?:^|[\\s"'(/])(?:${e})${r}(?:${k}[^\\s-][^\\s]*${r}){${n}}${k}(?=[^\\s-])`,"g")},ws=new RegExp(`(?:^|[\\s(])(?:http|https|xh|xhs)${k}`),Ua=[{when:ue("mysql\\w*|mariadb[\\w-]*"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:ue("redis-cli|keydb-cli|valkey-cli"),flag:Q("-a")},{when:ue("curl"),flag:Q("-[A-Za-z]*[uUb]|--user|--proxy-user")},{when:ws,flag:Q("-a")},{when:new RegExp(`${ue("sshpass|mongo|mongosh|mongodump|mongorestore|mongoexport|mongoimport|twine|cqlsh").source}|(?:^|\\s)login(?=$|\\s)`),flag:Q("-p")},{when:/\bgh\s+secret\s+set\b/,flag:Q("-b|--body")},{when:/\bsecurity\s+add-(?:generic|internet)-password\b/,flag:Q("-w")},{when:/\bsecurity\s+(?:unlock-keychain|create-keychain|set-keychain-password)\b/,flag:Q("-p|-o")},{when:/\bsecurity\s+import\b/,flag:Q("-P")},{when:ue("sqlcmd|bcp|osql|isql"),flag:Q("-P")},{when:ue("zip|zipcloak|unzip"),flag:Q("-P|--password")},{when:ue("7z|7za|7zr|7zz"),flag:/(?:^|\s)-p(?=[^\s-])/g},{when:ue("ldap\\w+"),flag:Q("-w|-s")},{when:ue("openssl"),flag:Q("-k|-K")},{when:ue("ssh-keygen"),flag:Q("-N|-P")},{when:ue("smbclient|rpcclient|smbmap|smbget|smbcacls|net"),flag:new RegExp(`(?:^|\\s)(?:-U|--user(?:name)?)(?:=|${ft})[^\\s%"']+%(?=[^\\s])`,"g")},{when:/\bvault\s+login\b/,flag:new RegExp(`\\bvault${k}login(?:${k}-[\\w-]+(?:=[^\\s]*)?)*${k}(?=[^\\s=-][^\\s=]*(?:\\s|$))`,"g")},{when:/\bnetlify\s+env:set\b/,flag:pn(`netlify${k}env:set`,1)},{when:/\bconvex\s+env\s+set\b/,flag:pn(`convex${k}env${k}set`,1)},{when:/\bcargo\s+login\b/,flag:pn(`cargo${k}login`,0,"--registry")},{when:/\bpoetry\s+config\b/,flag:pn(`poetry${k}config(?:${k}-[\\w-]+)*${k}pypi-token\\.[\\w.-]+`)},{when:/\bpoetry\s+config\b/,flag:pn(`poetry${k}config(?:${k}-[\\w-]+)*${k}http-basic\\.[\\w.-]+`,1)},{when:/\bngrok\b/,flag:pn(`ngrok${k}(?:config${k}add-(?:authtoken|api-key)|authtoken)`)}],Ba=new RegExp(`(?:^|[\\s"'(/])htpasswd((?:${k}-(?:[A-Za-z]*[Cr]${k}\\d+|[A-Za-z]+))+)${k}(?:[^\\s]+)${k}(?:[^\\s]+)${k}(?=[^\\s])`,"g"),ds=/\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/,qa=Q("--value"),Za=/^(\s*(?:echo|printf)(?:\s+-[A-Za-z]+)*\s+)\S(?:[\s\S]*\S)?/,fs=new RegExp(`<<<${ft}(?=[^\\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),at=/(?:^|\s)(["']?)([A-Za-z][\w-]*)(==|:(?![=:/]))/g;function Va(e){let{quotes:n}=mn(e),t="",r=0;at.lastIndex=0;for(let o=at.exec(e);o;o=at.exec(e)){let s=o[3]!=="==";if(!(s?ys.test(o[2]):gn(o[2])))continue;let i=o.index+o[0].length,a=Fe.indexOf(o[1]),l;if(a>0&&(n[i]&~nn)===a)for(l=i;l<e.length&&!pt(e,n,l);)l++;else l=Tn(e,i,n);let c=i;for(;c<l&&(e[c]===" "||e[c]===" ");)c++;c===l||s&&/^\d{1,5}(?:[/?#]|$)/.test(e.slice(c,l))||(t+=e.slice(r,c)+ee,r=at.lastIndex=l)}return t+e.slice(r)}function Ka(e){let{segments:n}=mn(e),t="";for(let r=0;r<n.length;r++){let o=n[r],s=e.slice(o.start,o.end);for(let l of Ua)l.when.test(s)&&(s=Ce(s,l.flag));s=Ce(s,Ba,l=>/b/.test(l[1].replace(/\d+/g,""))),ws.test(s)&&(s=Va(s)),ds.test(s)?s=vs(Ce(Ce(s,fs),qa),()=>!0):ps(s)&&(s=Ce(s,fs));let i=n[r+1],a=o.op==="|"&&i?e.slice(i.start,i.end):"";a&&(ds.test(a)||ps(a))&&(s=s.replace(Za,`$1${ee}`)),t+=s+e.slice(o.end,i?i.start:o.end)}return t}var Ga=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#"'`<>]*@/gi,Ja=/(?<![\w+.-])([a-z][\w+.-]*:\/\/)[^\s/?#:@[\]"'`<>]*:(?!\d{1,5}(?:[/?#]|$))[^\s@"'`<>]{1,256}@/gi,Ya=[/(\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],Xa=e=>Ya.reduce((n,t)=>n.replace(t,`$1${ee}`),e),Qa=new RegExp(`\\bmachine${k}[^\\s]+(?:${k}login${k}[^\\s]+)?${k}password${k}(?=[^\\s])`,"g"),ec=/[._]netrc\b/,nc=new RegExp(`(?:^|\\n|\\\\n|["'])[ \\t]*(?:login${k}[^\\s]+${k})?password${k}(?=[^\\s])`,"g"),tc=[/\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],bs=e=>{let n=e.replace(/^["'\\]+|["'\\]+$/g,"");return n.length>=8&&!/\s/.test(n)&&/\d/.test(n)&&/[A-Za-z]/.test(n)},ks=/^(?:key|apikey|api_key_id|k)$/i,rc=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?)(?:=|${k}(?=[^\\s-]))`,"gi"),ct=new RegExp(`(?:^|\\s)(?:-H|--header)(?:=|${ft})(?=[^\\s-])`,"g");function oc(e){let{quotes:n}=mn(e),t="",r=0;ct.lastIndex=0;for(let o=ct.exec(e);o;o=ct.exec(e)){let s=o.index+o[0].length,i=Tn(e,s,n),a=e.slice(s,i),l=a[0]==='"'||a[0]==="'"?a[0]:"",c=/^([ \t]*([\w-]+)[ \t]*:[ \t]*)\S/.exec(l?a.slice(1):a);!c||!ys.test(c[2])||(t+=`${e.slice(r,s)}${l}${c[1]}${ee}${l}`,r=ct.lastIndex=i)}return t+e.slice(r)}var ut=/(?:(?<![\w.$-])|(?<=(?:^|\s)-e))([A-Za-z_][\w.-]*)(?:=(?!=)|[ \t]*=[ \t]*(?=["']))/g;function vs(e,n=gn){let{quotes:t}=mn(e),r="",o=0;ut.lastIndex=0;for(let s=ut.exec(e);s;s=ut.exec(e)){let i=s.index+s[0].length;if(!n(s[1])&&!(ks.test(s[1])&&bs(e.slice(i,Tn(e,i,t)))))continue;let a=Fe.indexOf(e[s.index-1]??""),l;if(a>0&&(t[s.index]&~nn)===a)for(l=i;l<e.length&&!pt(e,t,l);)l++;else l=Tn(e,i,t);l!==i&&(r+=e.slice(o,i)+ee,o=ut.lastIndex=l)}return r+e.slice(o)}var dt=/(?:(\\?["'])([A-Za-z_][\w.-]*)\1|(?<![\w.$:/"'-])([A-Za-z_][\w.-]*))[ \t]*:[ \t]*/g,ir=/[^\s,}\]"'\\{[]+/y;function sc(e){let{quotes:n}=mn(e),t="",r=0;dt.lastIndex=0;for(let o=dt.exec(e);o;o=dt.exec(e)){let s=o[2]??o[3],i=!gn(s)&&ks.test(s);if(!gn(s)&&!i)continue;let a=o.index+o[0].length,l=/^[rRbBuUfF]{1,2}(?=["'])/.exec(e.slice(a,a+3));l&&(a+=l[0].length);let c=e[a],d="",u=-1;if(e.startsWith('\\"',a))d='\\"',u=e.indexOf('\\"',a+2);else if((c==='"'||c==="'")&&!pt(e,n,a)){d=c;let g=a+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!=="'"&&(ir.lastIndex=a,ir.exec(e)&&(u=ir.lastIndex));u<=a+d.length||i&&!bs(e.slice(a+d.length,u))||(t+=e.slice(r,a)+d+ee,r=dt.lastIndex=u)}return t+e.slice(r)}var ic=/(^|\n)([ \t]*(?:-[ \t]+)?)([A-Za-z_][\w.-]*)([ \t]*:[ \t]+)([^\s"'`#][^\n"'`]*)/g,lc=e=>e.replace(ic,(n,t,r,o,s)=>gn(o)?`${t}${r}${o}${s}${ee}`:n),ac=new RegExp(`\\b(?:config|configure)${k}set${k}(?:-{1,2}\\w[\\w-]*(?:=\\S*)?${k})*((?!-)[^\\s=]+)${k}(?=[^\\s-])`,"g"),cc=/\b(?:redis|keydb|valkey)-cli\b/,gs=/(?:"[^"\n]*"|'[^'\n]*'|[^\s"'\\;&|]+)/.source,uc=new RegExp(`\\bAUTH[ \\t]+${gs}(?:[ \\t]+${gs})?`,"g"),ms=/^(?: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,dc=/\b(Bearer|Basic)([ \t]+)([A-Za-z0-9\-._~+/]+=*)/gi,lr="\uE000";function fc(e){return e.includes(lr)?e:e.replace(dc,(n,t,r,o)=>o.length>=8&&(/[0-9+/=_~]/.test(o)||/[a-z][A-Z]|[A-Z]{2}/.test(o.slice(1)))?`${t}${r}${ee}`:`${t}${lr}${r}${o}`)}function hs(e){let n=Ka(e);return n=n.replace(Ga,`$1${ee}@`).replace(Ja,`$1${ee}@`),n=Xa(n),n=oc(n),n=Ce(n,rc,()=>!0,t=>!ms.test(t)),n=Ce(n,Qa),ec.test(n)&&(n=Ce(n,nc,()=>!0,t=>!ms.test(t))),n=tc.reduce((t,r)=>t.replace(r,ee),n),n=vs(n),n=sc(n),n=lc(n),n=Ce(n,ac,t=>gn(t[1])),cc.test(n)&&(n=n.replace(uc,`AUTH ${ee}`)),ls(fc(n)).split(lr).join("")}function xs(e,n=8192){if(e.length<=n)return hs(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 ${ee}`),hs(t)}var $s="held by default",pc={recordAndCount:()=>1},gt={allow:0,hold:1,block:2};function Ss(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ar(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 cr(e,n,t,r,o,s,i,a=null,l=[]){let c=i?{session_id:i}:{},d=[n.action,...n.also.filter(p=>p!==n.action)],u=(p,_,y)=>_?"enforce":qr(t,p,er(e,p,s),y),g=(p,_,y)=>!_&&y&&Zr(t,p,er(e,p,s)),h=p=>{if(p===n.action&&n.catastrophic)return{why:n.why};let _=(n.findings??[]).find(y=>y.action===p&&y.catastrophic);return _?{why:_.why}:null},x=[];d.forEach((p,_)=>{let y=_===0,{decision:N,baseline:J}=Qt(e,y?{action:p,service:n.service,metadata:{...n.attributes,...c}}:{action:p,service:null,metadata:c},r,o,s),M=zt({action:p,decision:N,baseline:J,service:y?n.service:null,target:y?n.attributes.target??null:null,projectDir:s,home:a,histories:l}),W=h(p),C=u(p,M,W!==null);C!=="off"&&(W&&N.verdict!=="allow"&&g(p,M,!0)?x.push({action:p,decision:N,mode:C,floor:M?.id??null,why:`${W.why} \xB7 ${$s}`}):x.push({action:p,decision:N,mode:C,floor:M?.id??null}))});let $=new Set;for(let p of(n.findings??[]).slice(1)){if(!p.service&&!p.target)continue;let _=`${p.action}\0${p.service??""}\0${p.target??""}`;if($.has(_))continue;$.add(_);let{decision:y,baseline:N}=Qt(e,{action:p.action,service:p.service,metadata:{target:p.target,...c}},pc,o,s);if(y.verdict==="allow")continue;let J=zt({action:p.action,decision:y,baseline:N,service:p.service,target:p.target,projectDir:s,home:a,histories:l}),M=p.catastrophic===!0,W=u(p.action,J,M);W!=="off"&&x.push({action:p.action,decision:y,mode:W,floor:J?.id??null,why:M&&g(p.action,J,!0)?`${p.why} \xB7 ${$s}`:p.why,target:p.target})}if(e.policies.some(p=>p.narrowed&&p.narrowed.length>0)){let p={tool:n.tool??null,parts:ar(n),touched:n.touched??null,projectDir:s,home:a,command:n.command??null,input:n.input??null,...o>0?{now:o}:{}};for(let _ of e.policies)if(!(!_.narrowed||!ye(_,s)))for(let y of _.narrowed){let N=Mo(y,{...p,root:_.origin==="project"?_.project_dir??null:null});if(!N)continue;let J=/^(.*):(\d+) · /.exec(y.source),M=`your rule "${y.text}"${J?` (${J[1]} line ${J[2]})`:""}`,W=N.part===p.parts[0]?n.why:(n.findings??[]).find(C=>C.action===N.part.action&&C.target===N.part.target)?.why??null;x.push({action:N.part.action,decision:{verdict:N.hit==="unknown"?"hold":y.intent,policy:_.name,origin:_.origin,ruleId:y.id,blockedBy:"narrowed_rule",source:y.source},mode:t?.kill_switch===!0?"ghost":y.mode,floor:null,why:N.hit==="unknown"?`${W?`${W}: `:""}${N.why}`:`${W??N.why}${N.detail?` (${N.detail})`:""} \xB7 ${M}`,target:N.part.target})}}let T=x.filter(p=>p.decision.verdict!=="allow");if(T.length===0)return{lead:null,stops:[],mode:"ghost"};let te=T.filter(p=>p.mode==="enforce"),G=(te.length>0?te:T).reduce((p,_)=>gt[_.decision.verdict]>gt[p.decision.verdict]||gt[_.decision.verdict]===gt[p.decision.verdict]&&_.floor&&!p.floor?_:p);return{lead:G,stops:[G,...T.filter(p=>p!==G)],mode:te.length>0?"enforce":"ghost"}}var gc=["command","cmd","script","input","code"];function Cs(e,n){let t=n&&typeof n=="object"?n:{};if(e==="Bash")return _s(typeof t.command=="string"?t.command:"");if(gc.some(o=>typeof t[o]=="string"&&_s(t[o])))return!0;let r=0;try{r=JSON.stringify(n??null)?.length??0}catch{return!0}return r>16384}function _s(e){if(e.length>2048)return!0;let n=0,t=0;for(let o=0;o<e.length;o++){let s=e[o];s===";"||s==="|"||s==="&"||s===`
|
|
20
|
+
`?(n++,(s==="|"||s==="&")&&e[o+1]===s&&o++):(s==="`"||(s==="$"||s==="<"||s===">")&&e[o+1]==="(")&&t++}return n>16||t>8||(e.match(/\{[^{}\s]*,[^{}\s]*\}/g)?.length??0)>4?!0:(e.match(/(?:^|[\s;&|(){}`])(?:cd|pushd|popd)(?=$|[\s;&|()])/g)?.length??0)>8}import{createHash as Bs,randomBytes as qs}from"crypto";import{readdirSync as Cc,renameSync as Ac,unlinkSync as Bp}from"fs";import{join as $t}from"path";import{createHmac as mc,randomBytes as ur,timingSafeEqual as hc}from"crypto";import{closeSync as Ps,existsSync as dr,fsyncSync as Ns,linkSync as yc,mkdirSync as Os,openSync as Is,readdirSync as wc,readFileSync as yn,unlinkSync as Ws,writeSync as js}from"fs";import{basename as bc,dirname as yt,join as de}from"path";var Ae="_seal";function kt(e){return de(e.dir,"seal.key")}function hn(e,n){return de(e.state,"lkg",n)}function we(e){let n=kt(e);if(S(n,1024)!==!0)return null;try{let t=yn(n,"utf8").trim();return/^[0-9a-f]{64}$/.test(t)?Buffer.from(t,"hex"):null}catch{return null}}function gr(e){return we(e)?"ok":S(kt(e),1024)===null?"missing":"damaged"}var wt=class extends Error{};function vt(e,n){return`Anvil's seal key (${kt(e)}) is ${n==="damaged"?"damaged":"missing"}`}function kc(e){let n=we(e);if(n)return n;let t=gr(e);if(t==="damaged"||mr(e))throw new wt(`${vt(e,t)}; run ${le("on")} to restore it`);let{key:r,created:o}=vc(e,!1);return o&&xc(e,r),r}function As(e,n,t){let r=Is(e,t,384);try{js(r,n),Ns(r)}finally{Ps(r)}}function vc(e,n){Os(e.dir,{recursive:!0,mode:448});let t=kt(e),r=de(e.dir,`.seal.key.${process.pid}.${ur(4).toString("hex")}.tmp`);As(r,`${ur(32).toString("hex")}
|
|
21
|
+
`,"wx");let o=!1;try{n?In(r,t):yc(r,t),o=!0}catch(i){let a=i.code??"";if(a!=="EEXIST"){if(n||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(a))throw i;try{As(t,yn(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{Ws(r)}catch{}}let s=we(e);if(!s)throw new wt(`${vt(e,"damaged")}; run ${le("on")} to restore it`);return{key:s,created:o}}function xc(e,n){let t=[[e.modes,ht],[e.compiled,Ls],[e.install,void 0]];for(let[r,o]of t)if(S(r,8*1024*1024)===!0)try{let s=yn(r,"utf8");if(s.includes(`"${Ae}"`))continue;let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=`${JSON.stringify(pr(n,i),null,2)}
|
|
22
|
+
`;tn(r,a),o&&tn(hn(e,o),a)}catch{}if(S(e.modes)===null&&S(hn(e,ht))===null){let r=`${JSON.stringify(pr(n,Dt()),null,2)}
|
|
23
|
+
`;tn(e.modes,r),tn(hn(e,ht),r)}}function fr(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>fr(t===void 0?null:t,n+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(n===0&&r===Ae)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${fr(e[r],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function Ts(e,n){return mc("sha256",e).update(fr(n)).digest("hex")}function mt(e){if(!(Ae in e))return e;let n={...e};return delete n[Ae],n}function pr(e,n){let t=mt(n);return{...t,[Ae]:Ts(e,t)}}function $c(e,n){let t=n[Ae];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let r;try{r=Ts(e,n)}catch{return!1}return hc(Buffer.from(t,"hex"),Buffer.from(r,"hex"))}function tn(e,n,t=384){Os(yt(e),{recursive:!0,mode:448});let r=de(yt(e),`.${bc(e)}.${process.pid}.${Date.now().toString(36)}.${ur(3).toString("hex")}.tmp`);try{let o=Is(r,"w",t);try{js(o,n),Ns(o)}finally{Ps(o)}In(r,e)}catch(o){try{Ws(r)}catch{}throw o}}function fe(e,n,t=8*1024*1024){let r=S(e,t);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(yn(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:n?Ae in o?$c(n,o)?{status:"ok",value:mt(o)}:{status:"changed",value:mt(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:mt(o)}}function Ms(e,n,t,r){let o=kc(e),s=`${JSON.stringify(pr(o,t),null,2)}
|
|
24
|
+
`;tn(n,s),r&&tn(hn(e,r),s)}var ht="modes.json",Ls="compiled.json";function mr(e){return dr(de(e.bin,"claude-hook.sh"))||Sc(e)}function Sc(e){let n=t=>{try{return wc(t).slice(0,200).some(r=>r.endsWith(".json")&&S(de(t,r),65536)===!0&&yn(de(t,r),"utf8").includes(`"${Ae}"`))}catch{return!1}};if(n(de(e.state,"lkg"))||n(de(e.state,"pending"))||n(e.approvals))return!0;for(let t of[e.modes,e.compiled,e.install])if(S(t,8*1024*1024)===!0)try{if(yn(t,"utf8").includes(`"${Ae}"`))return!0}catch{}return!1}var bt=z({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function Rs(e=new Date){return Ur(null,"enforce","all",e)}function Ds(e,n=we(e),t={}){if(!n){let i=gr(e);if(t.installed===!0||i==="damaged"||mr(e))return{value:Rs(),source:"strict",problem:`${vt(e,i)}, so every rule is enforced until \`${le("on")}\` restores it`};let a=fe(e.modes,null);return{value:a.status==="unkeyed"?a.value:null,source:"unkeyed",problem:null}}let r=fe(e.modes,n);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${bt[r.status]??"cannot be used"}`,s=fe(hn(e,ht),n);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:Rs(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${le("on")}\` resets it`}}function Fs(e,n,t=we(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===Yt&&Array.isArray(c.policies),s=()=>{if(!n)return null;let c=fe(n,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!t){let c=gr(e),d=r.installed===!0||c==="damaged"||mr(e),u=fe(e.compiled,null),g=u.status==="unkeyed"&&o(u.value)?u.value:null;return d?{value:null,source:"strict",problem:`${vt(e,c)}: \`${le("on")}\` restores it`}:{value:g??s(),source:"unkeyed",problem:null}}let i=fe(e.compiled,t);if(i.status==="ok"&&o(i.value))return{value:i.value,source:"file",problem:null};let a=`compiled.json ${i.status==="ok"?"is not a rules table":bt[i.status]??"cannot be used"}`,l=fe(hn(e,Ls),t);return l.status==="ok"&&o(l.value)?{value:l.value,source:"last-good",problem:`${a}; Anvil keeps the rules it last compiled`}:i.status==="missing"&&l.status==="missing"&&S(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${a}, and so is Anvil's own copy: \`${le("on")}\` recompiles them`}}function Es(e,n){return n&&(e===n||e.startsWith(`${n}/`))?`~${e.slice(n.length)}`:e}function xt(e,n,t,r=!0){let o=fe(e.install,n,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${bt.unreadable}`];if(n&&o.status!=="ok")return[`install.json ${bt[o.status]??"cannot be used"}`];let s=(o.status==="ok"||o.status==="unkeyed")&&o.value.installs&&typeof o.value.installs=="object"?Object.values(o.value.installs):[],i=[];for(let u of s.slice(0,64)){if(!u||typeof u.real_path!="string"||typeof u.command!="string")continue;let g=Qo(u.settings_path??u.real_path,Yo(u)),h=Es(u.settings_path??u.real_path,t);g!=="present"&&(g==="no-file"&&u.scope==="project"&&!dr(yt(yt(u.real_path)))||(g==="disabled"?r&&i.push(`${h} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):g==="missing"||g==="no-file"?i.push(`Anvil's hook was taken out of ${h} outside \`${le("off")}\`, so new sessions are not checked`):i.push(`${h} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let a=o.status==="ok"||o.status==="unkeyed"?o.value:null,l=[...Array.isArray(a?.package_dirs)?a.package_dirs:[],...typeof a?.package_dir=="string"?[a.package_dir]:[]].filter(u=>typeof u=="string"&&u.startsWith("/")).slice(0,16),c=l[l.length-1]??"",d=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return s.length>0&&l.length>0&&l.every(u=>!dr(de(u,"package.json")))&&i.push(`the Anvil package that installed this hook is gone (${Es(c,t)}): keep Anvil with ${I(d)} on, or remove it with ${I(d)} off --purge`),i}function _c(e){return de(e.state,"health.json")}function Hs(e,n,t){try{let r=_c(e),o=fe(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;tn(r,`${JSON.stringify({v:1,at:new Date(t).toISOString(),...n})}
|
|
25
|
+
`)}catch{}}var Kp=600*1e3,Rc=1440*60*1e3,zs="23456789abcdefghjkmnpqrstuvwxyz",Us=8;function St(e){return $t(e.state,"pending")}function Ec(){let e=qs(Us),n="";for(let t=0;t<Us;t++)n+=zs[e[t]%zs.length];return n}function Pc(e){return Bs("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var Nc=()=>qs(8).toString("hex"),hr=e=>`${Bs("sha256").update(e??"").digest("hex").slice(0,12)}.`;function Zs(e,n,t){let r=Ec(),o=Nc();H(St(e));let s={v:2,id:o,code_sha256:Pc(r),...n,created_at:new Date(t).toISOString(),expires_at:new Date(t+Rc).toISOString()};return Ms(e,$t(St(e),`${hr(n.session)}${o}.json`),s),{code:r,id:o}}function Oc(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function Vs(e,n,t,r,o,s){let i=[];try{i=Cc(e.approvals).filter(l=>l.endsWith(".json")&&!l.includes(".used-")).slice(0,2e3)}catch{return{approved:!1,forged:0}}let a=0;for(let l of i){let c=$t(e.approvals,l),d=fe(c,n,64*1024);if(d.status==="missing")continue;if(d.status!=="ok"||d.value.v!==2||!Array.isArray(d.value.stops)){a++;continue}let u=d.value;if(Date.parse(u.expires_at)>=s&&!((u.session??null)!==(t??null)||(u.project??null)!==(r??null))&&o.every(g=>u.stops.some(h=>Oc(h,g))))try{return Ac(c,$t(e.approvals,`${l.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:a}}catch{}}return{approved:!1,forged:a}}import{lstatSync as Wc,readdirSync as jc,statSync as Tc,utimesSync as Mc}from"fs";import{join as Mn}from"path";import{posix as Ng}from"path";import{posix as bg}from"path";var Ic=Object.freeze({maxInputLength:131072,maxWords:16384,maxDepth:64});var ig=Object.freeze({code:"unsupported-function-substitution",message:"${ list; } function substitutions run in the current shell and cannot be analyzed"});var lg=Object.freeze({code:"unclosed-parameter-expansion",message:"${ parameter expansion is not closed"});var ag=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"}),cg=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 ug=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 pg}from"module";var yr=10080*60*1e3;function Ks(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 wr(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 br=3600*1e3;var Lc=600,Dc=256*1024;function kr(e,n){return Mn(e.state,"sessions",`${n}.jsonl`)}function Gs(e,n){if(!n)return{made:[],launched:[]};let t=[],r=[];for(let o of V(kr(e,n),Dc).split(`
|
|
26
|
+
`))if(o)try{let s=JSON.parse(o);typeof s.p=="string"&&s.p.startsWith("/")?t.push(s.p):typeof s.l=="string"&&r.push(s.l)}catch{}return{made:t,launched:r}}function Fc(e){try{return Wc(e),!0}catch{return!1}}function Js(e,n,t,r,o=null,s=Date.now()){if(!(!n||t.paths.length===0&&t.launched.length===0))try{H(Mn(e.state,"sessions"));let i=kr(e,n),a=[...r.made];for(let l of t.paths)a.some(c=>l===c||l.startsWith(`${c}/`))||Fc(l)||(De(i,JSON.stringify(o?{p:l,t:s,d:o}:{p:l})),a.push(l));for(let l of t.launched)r.launched.includes(l)||De(i,JSON.stringify({l:l.slice(0,Lc)}))}catch{}}function Ys(e,n,t=Date.now()){if(n)try{let r=new Date(t);Mc(kr(e,n),r,r)}catch{}}function Xs(e,n,t,r,o=Date.now()){if(!n||!t)return[];let s=Date.now(),i=new Set,a=0;try{let l=Mn(e.state,"sessions"),c=jc(l).filter(d=>d.endsWith(".jsonl")&&d!==`${n}.jsonl`).map(d=>({f:d,at:Tc(Mn(l,d)).mtimeMs})).filter(d=>o-d.at>=br&&o-d.at<=yr+br).sort((d,u)=>u.at-d.at).slice(0,200);for(let{f:d}of c){if(a>4*1024*1024||i.size>=5e3||Date.now()-s>150)break;let u=V(Mn(l,d),64*1024);a+=u.length;for(let g of u.split(`
|
|
27
|
+
`))if(g.includes('"d"'))try{let h=JSON.parse(g);if(typeof h.p!="string"||typeof h.t!="number"||h.d!==t||o-h.t>yr||h.t>o)continue;if(Ks(h.p,t,r)&&i.add(h.p),i.size>=5e3)break}catch{}}}catch{}return[...i]}import{spawnSync as Hc}from"child_process";import{lstatSync as zc,realpathSync as vr,statSync as Uc}from"fs";import{dirname as Bc}from"path";function wn(e,n,t,r=!1){let o=Hc(e,n,{cwd:t?q(t):void 0,encoding:"utf8",timeout:400,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}});return o.error||o.signal?null:(o.status===0||r)&&typeof o.stdout=="string"?o.stdout:null}function xr(e){try{let n=typeof e=="string"&&e!==""?Uc(e):null;return n&&n.birthtimeMs>0&&n.birthtimeMs!==n.ctimeMs?n.birthtimeMs:null}catch{return null}}function Qs(e){let n=e.arg??"";try{switch(e.kind){case"ps":return wn("ps",["-A","-ww","-o","pid=,ppid=,command="]);case"port":return/^\d{1,5}$/.test(n)?wn("lsof",["-nP","-t","-i",`:${n}`],null,!0):null;case"stashes":return wn("git",["stash","list","--date=unix","--format=%gd"],e.cwd);case"branch":return wn("git",["reflog","show","--date=unix","--format=%gd %gs",`refs/heads/${n}`,"--"],e.cwd);case"ignored":return wn("git",["-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null","check-ignore","-q","--",n],e.cwd);case"cwd":{if(!/^\d+$/.test(n))return null;if(process.platform==="linux")return vr(`/proc/${n}/cwd`);let t=/^n(\/.*)$/m.exec(wn("lsof",["-a","-p",n,"-d","cwd","-Fn"],null,!0)??"")?.[1];return t?vr(t):null}case"file":{let t=vr(q(n));return`${U()?ce(t)??t:t} ${xr(q(n))??""}`}case"owner":{if(U()||!n.startsWith("/"))return null;for(let t=n;;t=Bc(t))try{return String(zc(t).uid)}catch{if(t==="/")return null}}}}catch{}return null}var _t=e=>`${e.kind}\0${e.cwd??""}\0${e.arg??""}`;import{existsSync as qc,readFileSync as $r,statSync as Zc}from"fs";import{dirname as Vc,isAbsolute as ei,join as Sr,resolve as _r}from"path";function ni(e){return!!e&&e.length<65536&&/\bgh\s+pr\s+(create|edit)\b/.test(e)}function Kc(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(ei(s)?s:_r(r[r.length-1]??n??t,s)))}return[...new Set(r)].slice(0,8)}function Gc(e){let n=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(e.trim());return n?`${n[1]}/${n[2]}`.toLowerCase():null}function Jc(e){let n=e;for(let t=0;t<12&&n.length>1;t++,n=Vc(n)){let r=Sr(n,".git");if(!qc(r))continue;let o=r;if(Zc(r).isFile()){if(S(r,64*1024)!==!0)return[];let d=/^gitdir:\s*(.+)$/m.exec($r(r,"utf8"))?.[1]?.trim();if(!d)return[];o=ei(d)?d:_r(n,d);let u=Sr(o,"commondir");S(u,64*1024)===!0&&(o=_r(o,$r(u,"utf8").trim()))}let s=Sr(o,"config");if(S(s,1024*1024)!==!0)return[];let i=$r(s,"utf8").slice(0,65536),a="",l=[],c=null;for(let d of i.split(`
|
|
28
|
+
`)){let u=/^\s*\[(\w+)(?:\s+"([^"]*)")?\]/.exec(d);if(u){c=u[1]==="remote"?u[2]??null:null;continue}let g=/^\s*url\s*=\s*(.+)$/.exec(d),h=c!==null&&g?Gc(g[1]):null;h&&(c==="origin"&&!a?a=h:l.includes(h)||l.push(h))}return[a,...l.filter(d=>d!==a)]}return[]}function ti(e,n,t){let r={};try{for(let o of Kc(e,n,t))r[o]=Jc(o)}catch{}return r}import{closeSync as Yc,constants as ri,fstatSync as Xc,openSync as Qc,readSync as eu,statSync as nu}from"fs";var tu=64*1024,ru=8;function oi(e,n){let t={},r=[];for(let o of e.slice(0,ru)){let s=null,i=null,a=!0;try{nu(q(o)).isFile()&&(s=Qc(q(o),ri.O_RDONLY|ri.O_NONBLOCK));let l=s!==null?Xc(s):null;if(s!==null&&l!==null&&l.isFile()&&l.size<=tu){let c=Buffer.alloc(l.size),d=eu(s,c,0,l.size,0),u=c.subarray(0,d).toString("utf8");u.includes("\0")||(i=u)}}catch(l){l.code==="ENOENT"&&(a=!1)}finally{s!==null&&Yc(s)}i!==null?t[o]=i:a&&n.includes(o)&&r.push(o)}return{scripts:t,unreadable:r}}var ou=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g;function si(e){return e.replace(ou,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}import{createHash as nm}from"crypto";import{readdirSync as rm,readFileSync as om,renameSync as sm,statSync as im,unlinkSync as lm}from"fs";import{join as cm}from"path";var su=1440*60*1e3;var iu=64*1024*1024,lu=14*su;var du=1e3,fu=3e3,pi=6e4,pu=new Set(["default","acceptEdits","plan"]),gu="cli",Cr=[2,1,153];function mu(e){if(!e)return null;let n="";try{n=V(e,64*1024)}catch{return null}let t=[...n.matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)],r=t[t.length-1];return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function hu(e,n){if(e.CLAUDE_CODE_ENTRYPOINT!==gu)return!1;let t=mu(n);if(!t)return!1;for(let r=0;r<Cr.length;r++)if(t[r]!==Cr[r])return t[r]>Cr[r];return!0}var yu=8,vn=class extends Error{constructor(n){super(n),this.name="CoreUnavailable"}},xn=class extends Error{constructor(){super("out of time"),this.name="ClassifyTimeout"}},Dn=(e,n,t,r)=>({paths:e,payload:t,table:r,env:n.env,home:n.home,now:n.now(),cli:Je(),fallbackTable:n.fallbackTable,installed:n.anvilDir!==void 0,...n.planProbe?{probe:n.planProbe}:{}});function Ar(e,n){try{return he(e.compiled,64*1024*1024)?.includes(`"${n}"`)===!0}catch{return!1}}function Er(e,n){let t=v(e.env.CLAUDE_PROJECT_DIR)??n;return t&&t.startsWith("/")?xe(t):t}var wu="AnvilSelfCheck",v=e=>typeof e=="string"&&e.length>0?e:null;function bn(e,n=160){let t=si(xs(e,4096).replace(/\s+/g," ").trim());return t.length>n?`${t.slice(0,n-1)}\u2026`:t}function bu(e){if(!e||!Et(e))return null;let n=e;for(let t=0;t<64;t++){let r=b(n,".git"),o=!1,s=!1;try{let a=uu(r);s=!0,o=a.isFile()}catch{}if(s)try{let a=r;if(o){if(S(r,64*1024)!==!0)return null;let d=/^gitdir:\s*(.+?)\s*$/m.exec(Rt(r,"utf8"));if(!d)return null;a=kn(n,d[1])}if(S(b(a,"HEAD"),64*1024)!==!0)return null;let l=Rt(b(a,"HEAD"),"utf8").trim(),c=/^ref:\s*refs\/heads\/(.+)$/.exec(l);return c?c[1]:null}catch{return null}let i=Rr(n);if(i===n)return null;n=i}return null}function li(e){if(!e||!Et(e))return[];let n=b(e,".git");try{if(S(n,64*1024)!==!0)return[];let t=/^gitdir:\s*(.+?)\s*$/m.exec(Rt(n,"utf8"));if(!t)return[];let r=/^(.*[\\/]\.git)[\\/]worktrees[\\/][^\\/]+[\\/]?$/.exec(kn(e,t[1]));return r?[Xe(r[1])]:[]}catch{return[]}}function ku(e,n){return(e==="Bash"||e==="PowerShell")&&n&&typeof n=="object"?n.command??null:Pr(n)}function Pr(e,n=0){return n>64?"[nested too deep]":Array.isArray(e)?e.map(t=>Pr(t,n+1)):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Pr(e[t],n+1)])):e}var gi=e=>process.platform==="win32"?ii.native(e):ii(e);function vu(e,n){if(!n)return e;let t;try{t=gi(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 mi=z({Write:"file_path",Edit:"file_path",MultiEdit:"file_path",Read:"file_path",NotebookEdit:"notebook_path"}),rn=(e,n)=>[...new Set([...e,...n??[]])];function xu(e,n,t){let r=mi[e];if(!r||!n||typeof n!="object")return n;let o=n[r];if(typeof o!="string")return n;let s=zn(o,t,!0);return s===o?n:{...n,[r]:s}}function zn(e,n,t){if(!Et(e)||e.length>4096)return e;let r=kn(e);if(!t){let i=Rr(e);if(i===e)return e;let a=zn(i,n,!0);return a===i?e:b(a,Hn(e))}let o=[],s=e;for(;;)try{let i=vu(b(gi(s),...o.reverse()).replace(/^\/private(?=\/(?:tmp|var|etc)(?:\/|$))/,""),n);return i===r||`/private${i}`===r?r:i}catch{o.push(Hn(s));let i=Rr(s);if(i===s)return e;s=i}}function $u(e,n,t){let r={full:{},parent:{}},o=!1;for(let s of["full","parent"])for(let i of e[s]){if(Date.now()>t)return"out-of-time";let a=U()?ce(zn(q(i),n,s==="full"))??i:zn(i,n,s==="full");a!==i&&(r[s][i]=a,o=!0)}return o?r:null}async function ai(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 Su=new Set(["Write","Edit","MultiEdit","NotebookEdit"]);function _u(e,n,t,r){return Fn("sha256").update(JSON.stringify([e??"",n,ku(n,t),r??""])).digest("hex").slice(0,10)}function $n(e){return e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Fn("sha256").update(e).digest("hex").slice(0,24):"none"}function sn(e,n){try{H(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)})),De(e.decisions,t)}catch{}}function ci(e,n,t,r,o,s){sn(e,{v:1,ts:new Date(o).toISOString(),session:v(s?.session_id),tool:v(s?.tool_name)??"unknown",action:"none",verdict:"error",mode:null,delivered:"none",rule:null,slug:null,policy:null,why:`hook error at ${n}`,target:null,project:null,path:"none",ms:Math.max(0,o-r),error:bn(t instanceof Error?t.message:String(t),200)})}var ln={stdout:"",exitCode:0},K=e=>({stdout:`${JSON.stringify(e)}
|
|
29
|
+
`,exitCode:0});function Nr(e,n){let t=v(e.env.CLAUDE_CONFIG_DIR),r=b(t?kn(t):b(e.home,".claude"),"settings.json"),o=v(e.env.CLAUDE_PROJECT_DIR)??v(n.cwd);return o?[r,b(o,".claude","settings.local.json"),b(o,".claude","settings.json")]:[r]}function Cu(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(l=>S(b(t,l))===!0);if(s.length===0)return[];let i=au("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(l=>({path:b(t,l),ignored:!1}));let a=[];for(let l of i.stdout.split("\0")){let c=l.slice(0,2),d=s.find(u=>l.slice(3)===u||l.slice(3).endsWith(`/${u}`));(c==="??"||c==="!!")&&d!==void 0?a.push({path:b(t,d),ignored:c==="!!"}):(c[0]==="A"||c.includes("M"))&&d!==void 0&&a.push({path:b(t,d),ignored:!1,staged:!0})}return a}function Au(e,n,t,r){if(["Read","Glob","Grep","LS","WebFetch","WebSearch","TodoWrite"].includes(e))return null;let o=b(n,".claude"),s=b(n,".anvil"),a=[...[".zshrc",".zshenv",".zprofile",".bashrc",".bash_profile",".bash_aliases",".profile",b(".config","fish","config.fish"),...process.platform==="win32"?[b("Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),b("Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")]:[]].map(c=>b(n,c)),o,b(o,"settings.json"),b(o,"settings.local.json"),b(o,"hooks"),b(o,"plugins"),b(n,".claude.json"),s,b(s,"claude"),b(s,"claude","modes.json"),b(s,"claude","compiled.json"),b(s,"rules.json"),b(s,"workspace-keys.json")];t&&a.push(t,b(t,"settings.json"),b(t,"hooks")),r&&a.push(b(r,".claude"),b(r,".claude","settings.json"),b(r,".claude","settings.local.json"),b(r,".mcp.json"));let l={};for(let c of a){let d=zn(c,n,!0);d!==c&&(l[d]=c)}return Object.keys(l).length>0?l:null}function hi(e,n){return b(e.state,"covered",$n(v(n.session_id)))}function Ru(e,n,t){try{let r=hi(e,t);if(S(r)!==null||!Nr(n,t).some(o=>tr(o)))return;H(b(e.state,"covered")),X(r,String(n.now()))}catch{}}async function Eu(e,n,t,r){let o=()=>Nr(n,t).some(i=>tr(i)),s=hi(e,t);if(S(s)===!0)return o();if(r!=="SessionStart"||!o())return!1;for(let i=0;i<300;i+=25)if(await new Promise(a=>setTimeout(a,25)),S(s)===!0)return!0;return!1}function Pu(e,n){try{H(e.state),X(b(e.state,"plugin-seen"),String(n))}catch{}}var Pt=!1;async function yi(e,n){ae=At=null;let t=n.now(),r=n.anvilDir?Le(n.anvilDir):Qe(n.home),o=Wn(r.install)?.cli??n.cli;En(o),Pt=typeof o=="string";let s=null,i=v(n.entry),a=Buffer.byteLength(e)/1048576,l=`(${a.toFixed(1)} MB; Anvil reads up to 8 MB)`;if(a>yu)return jn(i)?ln:i==="SessionStart"?K(_e("SessionStart",`it can't read what Claude Code sent ${l}`)):Nu(r,e,`this call is too large to check ${l}`,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=bi(r,v(s.session_id));return g?`${JSON.stringify({systemMessage:g})}
|
|
30
|
+
`:null};if(c==="UserPromptSubmit"&&n.modelAtPrompt&&Ar(r,"never")){let g=await n.modelAtPrompt({...Dn(r,n,s,null),projectDir:Er(n,v(s.cwd))}).catch(d);if(g)return{stdout:g,exitCode:0}}if(c==="UserPromptSubmit"&&n.budgetAtPrompt&&Ar(r,"budgets")){let g=await n.budgetAtPrompt(Dn(r,n,s,null)).catch(d);if(g)return{stdout:g,exitCode:0}}if(c==="PreModelSwitch"&&n.modelAtSwitch&&Ar(r,"model_rules")){let g=await n.modelAtSwitch({...Dn(r,n,s,null),projectDir:Er(n,v(s.cwd))}).catch(d);if(g)return{stdout:g,exitCode:0}}if(n.helpers&&(c?.startsWith("Subagent")||s.source==="resume")&&S(b(r.dir,"helpers","live"))!==null&&await n.helpers().then(g=>g.onEvent(s,r,n.now()),()=>0),jn(c))return ln;if(n.plugin){if(await Eu(r,n,s,c))return ln;c==="SessionStart"&&Pu(r,n.now())}else n.anvilDir!==void 0&&Ru(r,n,s);if(c==="SessionStart")return await Mu(r,n,s);if(c===wu)return await Tu(r,n);if(c!=="PreToolUse")return ln;let u=await Ou(s,r,n,t);return At?.(u)??u}catch(c){let d=(s&&v(s.hook_event_name))??i??(/"hook_event_name"\s*:\s*"SessionStart"/.test(e.slice(0,4096))?"SessionStart":null),u=s&&v(s.hook_event_name)?"its check crashed":"it can't read what Claude Code sent";if(d==="SessionStart")return K(_e("SessionStart",u));if(d&&d!=="PreToolUse")return ln;let g=Ln(r,s??{},u,t,n.now(),c);return At?.(g)??g}}function wi(e,n,t,r,o,s,i){let a=n("cwd");sn(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:a?Hn(a):null,path:"none",ms:Math.max(0,s-o),...i?{error:bn(String(i),200)}:{}})}function Ln(e,n,t,r,o,s){return wi(e,i=>v(n[i]),"could-not-check",`Anvil isn't working: ${t}`,r,o,s),K(_e("PreToolUse",t))}function Nu(e,n,t,r,o){let s=n.slice(0,4096);return wi(e,i=>new RegExp(`"${i}"\\s*:\\s*"([^"\\\\]{1,200})"`).exec(s)?.[1]??null,"too-long-to-check",t,r,o.now()),K({systemMessage:to(t),...Ct("deny",ro(t))})}async function Ou(e,n,t,r){let o=t.now(),s=v(e.tool_name)??"unknown",i=v(e.session_id),a=v(e.cwd);try{H(n.counts),Ko(n.counts,new Date(o))}catch{}let l=Or(n,t,o),c=l.table;if(!c)return Ln(n,e,ki(l),r,t.now());let d=l.modes;if(t.coreProblem)return Ln(n,e,t.coreProblem,r,t.now());let u=Er(t,a);try{Pt||En(c.cli),ae=Iu(n,c,u,i,Je())}catch{ae=null}let g=Gs(n,i),h=Ss(e.tool_input),x=(s==="Bash"||s==="PowerShell")&&typeof h?.command=="string"?h.command:null;Ys(n,i,o);let $=wr(x)?Xs(n,i,u,{tmpdir:t.tmpdir},o):[],T=$.length>0?{...g,made:[...g.made,...$.filter(f=>!g.made.includes(f))]}:g,te=null,ke=()=>{p?.makings&&Js(n,i,p.makings,g,u,o),te?.ran()},G={tool_name:s,tool_input:e.tool_input??null,cwd:a,git_branch:bu(a),project_dir:u,session_id:i,home:t.home,tmpdir:t.tmpdir,claude_config_dir:v(t.env.CLAUDE_CONFIG_DIR),project_controls:Cu(s,e.tool_input,u),control_links:Au(s,t.home,v(t.env.CLAUDE_CONFIG_DIR),u),session_facts:{...T,startedAt:xr(e.transcript_path),...ni(x)?{repoRemotes:ti(x,a,t.home)}:{}},want_makings:!0},p=null,_="inline",y=null,N=t.timeLimitMs??du,J=Date.now()+(t.totalLimitMs??fu),M=()=>Math.min(N,J-Date.now()),W=null,C=null,pe=()=>{W=p??W,p=null,y={rule:"too-long-to-check"}},He={},An=!1,Ee=async(f,w)=>{let R=p;({classification:p,failure:y}=await ai(f,w,t,M())),!p&&R&&(W=R);let ie=p?.touched;ie&&C&&(C={full:rn(C.full,ie.full),parent:rn(C.parent,ie.parent),read:rn(C.read,ie.read),written:rn(C.written,ie.written),unknown:rn(C.unknown,ie.unknown)})};try{let f=Cs(s,e.tool_input);f&&(_="worker");let w={...G,tool_input:xu(s,G.tool_input,t.home),on_disk:"collect"};({classification:p,failure:y}=await ai(w,f,t,M()));let R=p?.touched;R&&(C={full:[...R.full],parent:[...R.parent],read:[...R.read??[]],written:[...R.written??[]],unknown:[...R.unknown??[]]});let ie=mi[s],We=ie&&G.tool_input&&typeof G.tool_input=="object"?G.tool_input[ie]:void 0;if(typeof We=="string"&&Et(We)&&We.length<=4096){let L=[U()?ce(We)??kn(We):kn(We)];C=C?{...C,full:rn(C.full,L),written:rn(C.written,L)}:{full:L,parent:[],read:[],written:L,unknown:[]}}if(R&&(R.full.length>0||R.parent.length>0)){let L=$u(R,t.home,Math.min(Date.now()+N,J)),ge=(me,D)=>[...new Set([...me,...me.flatMap(Fr=>[D.full[Fr],D.parent[Fr]].filter(Oi=>typeof Oi=="string"))])];L&&L!=="out-of-time"&&C&&(C={full:[...new Set([...C.full,...Object.values(L.full)])],parent:[...new Set([...C.parent,...Object.values(L.parent)])],read:ge(C.read,L),written:ge(C.written,L),unknown:C.unknown}),L==="out-of-time"?pe():L!==null&&(w={...w,on_disk:L},M()<=0?pe():await Ee(w,f))}let Lt={...G.session_facts?.scripts??{}},Kn=[];for(let L=0;L<2&&p?.scriptsWanted&&p.scriptsWanted.length>0;L++){let ge=p.scriptsWanted.filter(D=>!(D in Lt)&&!Kn.includes(D));if(ge.length===0)break;if(M()<=0){pe();break}let me=oi(ge,T.made);if(Object.keys(me.scripts).length===0&&me.unreadable.length===0)break;if(Object.assign(Lt,me.scripts),Kn.push(...me.unreadable),w={...w,session_facts:{...w.session_facts??{made:[],launched:[]},scripts:{...Lt},...Kn.length>0?{unreadableScripts:[...Kn]}:{}}},M()<=0){pe();break}await Ee(w,f)}for(let L=0;L<3&&p?.probesWanted;L++){let ge=p.probesWanted.filter(D=>!(_t(D)in He));for(let D of ge)M()>400&&(He[_t(D)]=D.kind==="changes"?await t.answerChanges?.(D)??null:Qs(D));if(ge.length===0||M()<=400){An=M()<=400&&ge.some(D=>D.kind==="changes");break}w={...w,session_facts:{...w.session_facts??{made:[],launched:[]},probed:{...He}}};let me={classification:p,failure:y};try{await Ee(w,f)}catch(D){if(!(D instanceof xn))throw D;p=null,y={rule:"too-long-to-check"}}if(!p&&y?.rule==="too-long-to-check"&&me.classification&&!ge.some(D=>D.kind==="changes")){({classification:p,failure:y}=me);break}}}catch(f){if(p&&(W=p,p=null),f instanceof vn)return Ln(n,e,"its checker can't load",r,t.now(),f);y=f instanceof xn?{rule:"too-long-to-check"}:{rule:"could-not-check",error:f instanceof Error?f.message:String(f)}}(An||p?.probesWanted?.some(f=>f.kind==="changes"&&!(_t(f)in He)))&&(W=p,p=null,y={rule:"too-long-to-check"}),p?.action===fi&&(c.policies.some(f=>f.allowed_actions.includes(fi))?!y&&c.policies.some(f=>f.helpers&&ye(f,u))&&(At=(te=(await t.helpers()).launchStep({paths:n,table:c,projectDir:u,payload:e,deps:t,modes:d,now:o,cli:Je()})).finish):p={...p,action:"claude.tool.other"}),p&&c.policies.some(f=>f.narrowed?.some(w=>(w.when?.length??0)>0)||f.caps?.some(w=>w.unit==="money"))&&await ho();let A=[],j="ghost",ze=t.rates??new rt(b(n.state,"rate.jsonl"),rr),Ue=Xe(u),Pe=Xe(t.home);if(p)try{H(n.state),{stops:A,mode:j}=cr(c,{...p,tool:s,touched:C,command:x,input:h},d,ze,o,Ue,i,Pe,li(u))}catch(f){y={rule:"could-not-check",error:f instanceof Error?f.message:String(f)}}else if(y&&W)try{let f=cr(c,{...W,tool:s,touched:C,command:x,input:h},d,ze,o,Ue,i,Pe,li(u));f.mode==="enforce"&&f.lead?.decision.verdict==="block"&&({stops:A,mode:j}=f,p=W,y=null)}catch{}p?.parse==="limited"&&!y&&!(j==="enforce"&&A[0]?.decision.verdict==="block")&&(y={rule:"could-not-check",why:"too long or nested too deep to read in full"});let m=y?.error!==void 0?await Ir(t):null;if(m)return Ln(n,e,m,r,t.now());if(y){let f={verdict:"hold",policy:null,origin:null,ruleId:y.rule,blockedBy:"time_limit",source:null};j="enforce",A=[{action:"claude.bash.unclassified",decision:f,mode:j,floor:"hold-unchecked"}]}te?.stop&&!A.some(f=>f.mode==="enforce"&&f.decision.verdict==="block")&&(A=[te.stop,...A],j="enforce");let E=p?[p.action,...p.also]:[],P=()=>({note:bi(n,i)??void 0});if(t.modelAtAction&&p&&!y&&d?.kill_switch!==!0&&c.policies.some(f=>ye(f,u)&&(f.model_rules?.never?.length||f.model_rules?.guards?.some(w=>w.kinds.some(R=>E.includes(R)))))&&!(j==="enforce"&&A[0]?.decision.verdict==="block")){let f=await t.modelAtAction({...Dn(n,t,e,c),kinds:E,projectDir:u}).catch(P);f?.note&&(ae=ae?`${ae}
|
|
31
|
+
${f.note}`:f.note),f?.stop&&(A=[f.stop,...A],j="enforce")}if(t.budgetAtAction&&p&&!y&&d?.kill_switch!==!0&&c.policies.some(f=>f.budgets?.length)&&!(j==="enforce"&&A[0]?.decision.verdict==="block")){let f=await t.budgetAtAction(Dn(n,t,e,c)).catch(P);f?.note&&(ae=ae?`${ae}
|
|
32
|
+
${f.note}`:f.note),f?.stop&&(j="enforce",A=[f.stop])}let B=p?.units??null,se=p?{tool:s,parts:ar({...p,tool:s,touched:C,command:x}),touched:C,projectDir:Ue,home:Pe??null,command:x,input:h,now:o}:null,re=p&&!y?os(c,[p.action,...p.also],u,se):[],Ne=re.length>0?new it(b(n.dir,"caps")):null,Un=v(e.tool_use_id)??`${$n(i)}-${o}-${process.pid}`;if(Ne&&j!=="enforce"){let f;try{f=d?.kill_switch===!0?(Ne.count(re,Un,B,o,"ran",void 0,se),null):Ne.admit(re,Un,B,o,void 0,se)}catch(w){if(f=null,d?.kill_switch!==!0){let R=w instanceof en?re.find(We=>We.unit==="money")??re[0]:re[0],ie={verdict:"hold",policy:"caps",origin:null,ruleId:R.id,blockedBy:"cap_unreadable",source:R.source};j="enforce",A=[{action:p.action,decision:ie,mode:j,floor:null,why:w instanceof en?`${w.message}, so your cap ${R.text} can't count it`:`couldn't check your cap ${R.text} (${w?.code??(w instanceof Error?w.message.slice(0,60):"unreadable")})`},...A]}}if(f){let w={verdict:"hold",policy:"caps",origin:null,ruleId:f.cap.id,blockedBy:"cap_reached",source:f.cap.source};j="enforce",A=[{action:p.action,decision:w,mode:j,floor:null,why:di(f.cap,f.used)},...A]}}if(Ne&&j==="enforce"&&A[0]&&p&&!y&&A[0].decision.blockedBy!=="cap_reached"&&A[0].action!=="claude.budget")try{let f=re.find(w=>Ne.used(w,o)+lt(w,B,se)>w.limit);f&&(A=[{...A[0],why:`${A[0].why??p.why}; and ${di(f,Ne.used(f,o))}`},...A.slice(1)])}catch{}let It=async()=>{try{p&&i&&t.moot&&cu(St(n)).some(f=>f.startsWith(hr(i))||/^[0-9a-f]{16}\.json$/.test(f))&&await t.moot({anvilDir:n.dir,session:i,project:u,stops:[p.action,...p.also].map((f,w)=>({kind:f,target:w?null:p.attributes.target??null})),now:o})}catch{}},O=A[0];if(!O)return ke(),await It(),on(ln,n,i,l.problems,o);let Bn=j==="enforce"?A.filter(f=>f.mode==="enforce"):A,_i=f=>y?y.why??(y.rule==="too-long-to-check"?"too long to check in time":"could not be checked"):f.why?f.why:p&&f.action===p.action?p.why:Qn(f.action),qn=f=>f.target!==void 0?f.target:p&&f.action===p.action?p.attributes.target??null:null,Ci=f=>f.replace(/ ?\((?:a command with no rule of its own, )?read by its (?:words|name)\)/g,"").trim(),Ai=f=>{let w=Ci(_i(f));if(f.decision.ruleId==="hold-delete-bursts")return`more than 20 recursive deletes in a minute (this one ${w})`;if(f.decision.ruleId==="hold-helper-bursts")return"more than 20 helper agent launches in 10 minutes";if(f.decision.ruleId==="hold-repeated-side-effect")return`the same app change again within 10 minutes (${w})`;let R=qn(f);return f.decision.ruleId==="block-protected-targets"&&!f.floor&&R&&/\/\.git(\/|$)/.test(R)?`deletes the .git of another repository inside the project (${u&&R.startsWith(`${u}/`)?R.slice(u.length+1):R})`:w},Y=bn((O.decision.verdict==="block"?[O]:Bn).map(Ai).join("; ")),Zn=O.decision.verdict==="block"?"block":"hold",Mr=y?null:qn(O),Be={v:1,ts:new Date(o).toISOString(),session:i,agent_id:v(e.agent_id),agent_type:v(e.agent_type),tool:s,action:O.action,verdict:Zn,mode:j,rule:O.decision.ruleId,slug:Qr(O.decision.ruleId,O.decision.origin,O.action,O.floor),...O.floor?{floor:O.floor}:{},policy:O.decision.policy,blocked_by:O.decision.blockedBy,why:Y,target:Mr?bn(Mr,200):null,project:u?Hn(u):null,path:_,...y?.error?{error:bn(y.error,200)}:{},...A.length>1?{also:A.slice(1).map(f=>({action:f.action,verdict:f.decision.verdict,mode:f.mode,rule:f.decision.ruleId,...f.floor?{floor:f.floor}:{}}))}:{},...p?.housekeeping&&O.action===p.action?{housekeeping:!0}:{}};if(j==="ghost"){ke(),await It();let f=ju(n,i,o);if(sn(n,{...Be,delivered:f?"note":"none",ms:t.now()-r}),!f)return on(ln,n,i,l.problems,o);let w=Zn==="hold"&&!p?.housekeeping&&O.decision.blockedBy!=="narrowed_rule"&&Ke[O.action]?.slug===Be.slug?Be.slug:null;return on(K({systemMessage:so(Zn,Y,w)}),n,i,l.problems,o)}let Oe=Je();if(Zn==="block"){sn(n,{...Be,delivered:"deny",ms:t.now()-r});let f=O.floor?fo(Y):co(Y,Oe),w=O.floor?po(Y):uo(Y);return on(K({systemMessage:f,...Ct("deny",w)}),n,i,l.problems,o)}let Wt=y!==null||Su.has(s)||s.startsWith("mcp__")?`input:${_u(i,s,e.tool_input,a)}`:null,Lr=Bn.map(f=>({kind:f.action,target:y?Wt:Wt?`${qn(f)??""}#${Wt}`:qn(f)})),Ri=we(n),qe={approved:!1,forged:0};try{qe=Vs(n,Ri,i,u,Lr,o)}catch{qe={approved:!1,forged:0}}let jt=qe.forged>0?[...l.problems,`${qe.forged===1?"an approval was":`${qe.forged} approvals were`} written outside \`${I(Oe)} allow\`; ${qe.forged===1?"it releases":"they release"} nothing`]:l.problems;if(qe.approved){ke(),await It();try{Ne?.count(re,Un,B,o,"ran",void 0,se)}catch(f){ci(n,"caps",f instanceof Error?f:new Error(String(f)),r,t.now(),e)}return ui(ze,Bn,i,o),sn(n,{...Be,delivered:"approved",ms:t.now()-r}),on(K({systemMessage:go(Y)}),n,i,jt,o)}let Tt=v(e.permission_mode),Ei=!/^sdk-/.test(v(t.env.CLAUDE_CODE_ENTRYPOINT)??"");if(Tt!==null&&Ei&&O.action!=="claude.budget"&&(pu.has(Tt)||Tt==="bypassPermissions"&&hu(t.env,v(e.transcript_path)))){y||ke();try{Ne?.count(re,Un,B,o,"ask",{tr:v(e.transcript_path),call:v(e.tool_use_id)},se)}catch(R){ci(n,"caps",R instanceof Error?R:new Error(String(R)),r,t.now(),e)}sn(n,{...Be,delivered:"ask",call:v(e.tool_use_id),transcript:v(e.transcript_path),ms:t.now()-r});let f=v(e.transcript_path),w=v(e.tool_use_id);return f&&w&&ui(ze,Bn,i,o,{transcript:f,call:w}),on(K(Ct("ask",ao(O.floor?`${Y} \xB7 always on`:Y))),n,i,jt,o)}let Ie=null,Mt,Dr=null;try{let f=x??(/^(Agent|Task)$/.test(s)?p?.why??s:e.tool_input&&typeof e.tool_input=="object"?JSON.stringify(e.tool_input):null);({code:Ie,id:Mt}=Zs(n,{session:i,project:u,stops:Lr,why:Y,project_name:u?Hn(u):null,...f?{command:`${s}: ${bn(f,240)}`}:{}},o))}catch(f){Ie=null;let w=f.code;Dr=w==="ENOSPC"||w==="EDQUOT"?"the disk is full, so the hold could not be recorded: free some space, then ask Claude to try again":w==="EACCES"||w==="EPERM"||w==="EROFS"?`Anvil's folder (${n.dir}) cannot be written: fix that, then ask Claude to try again`:null}sn(n,{...Be,delivered:"deny",...Mt?{hold:Mt}:{},ms:t.now()-r}),Ie&&t.notify?.({session:i,transcript:v(e.transcript_path),why:Y,cli:Oe});let Vn=Ie?O.said:void 0,Pi=Vn?Vn.user.replace("{why}",()=>Y).replace("{code}",Ie):io(Y,Oe,Ie,Dr??(O.floor?`to repair Anvil, run in a terminal: ${I(Oe)} on`:`to repair Anvil, run in a terminal: ${I(Oe)} on (or change the rule: ${I(Oe)} rules edit)`),O.floor!==void 0&&O.floor!==null),Ni=Vn?Vn.agent:te?.stop===O?te.agent(Ie!==null):lo(Y,Ie!==null,Oe);return on(K({systemMessage:Pi,...Ct("deny",Ni)}),n,i,jt,o)}function ui(e,n,t,r,o){if(!(!t||!e.restart)){for(let s of n)if(!(!s.decision.ruleId||!Vr.has(s.decision.ruleId)))try{e.restart(Xt(s.action,t),r,o)}catch{}}}function Ct(e,n){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:e,permissionDecisionReason:n}}}function Or(e,n,t){let r=we(e),o=n.anvilDir!==void 0,s=Fs(e,n.fallbackTable,r,{installed:o}),i=Ds(e,r,{installed:o}),a=[];try{a=o?xt(e,r,n.home):[]}catch{a=[]}let l=v(n.env.ANVIL_HOOK_NODE_FALLBACK),c=o&&l?`the Node Anvil was set up with ${v(n.env.ANVIL_HOOK_NODE_WHY)==="broken"?"could not start":"is gone"}, so it runs under ${l}; run ${le("on")} to set it up again`:null,d=s.value?Ft(s.value):cn,u=cn.filter($=>!d.includes($));Pt||En(s.value?.cli);let g=Je(),h=u.length>0?`its always-on stops for ${u.map($=>$.short).join("; ")} are missing from the rules it judges with, so it may not stop those calls; run ${I(g)} on`:null,x=[s.problem,i.problem,...a,c,h].filter($=>typeof $=="string"&&$.length>0);return Hs(e,{problems:x,modes_source:i.source,rules_source:s.source},t),{table:s.value,modes:i.value,problems:x}}function on(e,n,t,r,o,s=!1){let i=[];if(r.length>0&&(s||Wu(n,t,r,o))){let l=r[0];i.push(l.includes("Anvil is not checking")?l:oo(l,r.length-1))}if(ae&&i.push(ae),ae=null,i.length===0)return e;let a=i.join(`
|
|
33
|
+
`);if(!e.stdout)return K({systemMessage:a});try{let l=JSON.parse(e.stdout),c=typeof l.systemMessage=="string"?l.systemMessage:null;return K({...l,systemMessage:c?`${c}
|
|
34
|
+
${a}`:a})}catch{return e}}function di(e,n){let t=i=>String(Math.round(i*100)/100),r=e.unit==="money"&&e.money?ss(n,e.money):e.unit==="usd"?`$${t(n)}`:t(n),o={minute:"in the last minute",hour:"in the last hour",day:"today",week:"this week"}[e.window],s=e.window==="day"?"; resets at midnight":e.window==="week"?"; resets Monday":"";return`cap reached: ${e.text} (${r} used ${o}${s})`}function bi(e,n){try{let t=b(e.state,`note-${$n(n)}.meter`);if(S(t)!==null)return null;H(e.state),X(t,"")}catch{}return`${F("Anvil")} budgets and model rules can't be checked${$e("fix it",le("on"))}`}var ae=null,At=null,fi="claude.agent.helper";function Iu(e,n,t,r,o){let s=[],i=new Set,a=d=>{try{let u=S(d,262144);return u===null?"gone":u===!1?"unreadable":Fn("sha256").update(Rt(d,"utf8")).digest("hex")}catch{return"unreadable"}};for(let d of n.policies){if(!d.from||!ye(d,t))continue;i.add(d.from.file);let u=a(d.from.file);u!==d.from.sha256&&s.push(`${d.origin==="project"?".anvil/rules.md":"~/.anvil/rules.md"} ${u==="gone"?"was removed":u==="unreadable"?"can't be read":"changed"}`)}let l=s.length>0,c=t?b(t,".anvil","rules.md"):null;if(c&&!i.has(c)&&a(c)!=="gone"&&s.push(".anvil/rules.md isn't applied yet in this folder"),s.length===0)return null;try{H(e.state);let d=b(e.state,`rules-${$n(r)}`),u=Fn("sha256").update(s.join("|")).digest("hex").slice(0,16);if(V(d,64).trim()===u)return null;X(d,u)}catch{}return`${F("Anvil")} ${s.join(" \xB7 ")}${l?" \xB7 the rules applied before still hold":""}${$e("apply it",`${I(o)} sync`)}`}function Wu(e,n,t,r){try{H(e.state);let o=b(e.state,`problem-${$n(n)}`),s=Fn("sha256").update(t.join(`
|
|
35
|
+
`)).digest("hex").slice(0,16),[i,a]=V(o,128).trim().split(" ");return i===s&&Number.isFinite(Number(a))&&r-Number(a)<pi&&r>=Number(a)?!1:(X(o,`${s} ${r}`),!0)}catch{return!0}}function ju(e,n,t){try{H(e.state);let r=b(e.state,`note-${$n(n)}`),o=Number(V(r,64).trim());return Number.isFinite(o)&&t-o<pi&&t>=o?!1:(X(r,String(t)),!0)}catch{return!1}}async function Ir(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 Tu(e,n){let t=n.now(),r=Or(e,n,t),o=await Ir(n),s=[...r.table?[]:["no rules are compiled"],...o?[o]:[],...r.problems],i=we(e),a=n.anvilDir!==void 0?xt(e,i,n.home).filter(d=>!xt(e,i,n.home,!1).includes(d)):[],l=s.filter(d=>!a.includes(d)),c={checking:!!r.table&&o===null,ok:l.length===0,problems:s,mode:r.table?qt(r.table,r.modes).text:"none",rules:r.table?Ut(r.table):0};return K({anvil_self_check:c})}async function Mu(e,n,t){let r=n.now();try{await n.sessionChores?.(e.dir,r)}catch{}let o=Or(e,n,r),s=await Ir(n),i=o.table;if(!i)return K(_e("SessionStart",ki(o)));if(s)return K(_e("SessionStart",s));let{enforced:a}=qt(i,o.modes);Pt||En(i.cli);let l=Je(),c=[...o.problems],d=[];try{d=n.anvilDir!==void 0&&n.startProblems?await n.startProblems({anvilDir:e.dir,home:n.home,files:Nr(n,t),cli:l}):[]}catch{d=[]}for(let $ of d)c.some(T=>T.includes($)||$.includes(T))||c.push($);let u=Xr(o.modes),g=null;try{g=await n.sessionWords?.()??null}catch{g=null}let h=g?g.sessionLine(a,Bt(i).filter($=>Ke[$]).length,c,l,u?.what??null):`${F("Anvil is on")} ${no}`,x=g?g.sessionContext(Ft(i).map($=>$.context),a.filter($=>!Ht.has($)).map(Qn),l,u?.context??null):"Anvil (anvilcontrol.ai) checks every tool call in this session before it runs. Changing Anvil is the user's to do, in their own terminal.";return K({systemMessage:h,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:x}})}function ki(e){return e.problems.join(" ").includes("seal key")?"its seal key is missing or damaged":/^compiled\.json .*changed outside/m.test(e.problems.join(`
|
|
36
|
+
`))?"its rules were changed outside Anvil":"its rules are missing"}import{spawn as Lu}from"child_process";import{readFileSync as Du,statSync as Fu}from"fs";import{join as Sn}from"path";function Hu(e){try{let n=JSON.parse(Du(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 zu="sync-next",Uu="sync-pulled",Bu="claude-sync.js",qu=6e4,Zu=5*6e4;function xi(e,n){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||Sn(n,".anvil","workspace-keys.json")}function Vu(e,n){if(e.ANVIL_API_KEY?.trim())return!0;try{return Fu(xi(e,n)).isFile()}catch{return!1}}var Ku=10*6e4;function $i(e){try{let n=e.env.ANVIL_CLAUDE_SYNC?.trim().toLowerCase();if(n==="off"||n==="0"||n==="false")return!1;if(!Vu(e.env,e.home))return S(Sn(e.paths.state,"sync-active.json"))===!0&&vi(e.paths,e.now),!1;let t=Sn(e.binDir,Bu);if(S(t)!==!0)return!1;let r=Sn(e.paths.state,zu),o=Number(V(r,64).trim());if(Number.isFinite(o)&&o>e.now&&o-e.now<=1440*6e4&&!(e.sessionStart===!0&&Gu(e.paths,e.now)))return!1;H(e.paths.state);let s=xi(e.env,e.home);return!e.env.ANVIL_API_KEY?.trim()&&(S(s,1024*1024)!==!0||!Hu(s))?(vi(e.paths,e.now),X(r,String(e.now+Ku)),!1):(X(r,String(e.now+qu)),(e.start??Ju)(e.execPath,t,e.paths.dir),!0)}catch{return!1}}function Gu(e,n){let t=Number(V(Sn(e.state,Uu),64).trim());return!(Number.isFinite(t)&&t>0&&t<=n+6e4&&n-t<=Zu)}function vi(e,n){let t=Sn(e.state,"signed-out.json"),r=Wn(t);typeof r?.open!="string"&&X(t,`${JSON.stringify({open:new Date(n).toISOString(),windows:Array.isArray(r?.windows)?r.windows:[]})}
|
|
37
|
+
`)}function Ju(e,n,t){let r=Lu(e,[n],{detached:!0,stdio:"ignore",cwd:t,env:process.env,windowsHide:!0});r.on("error",()=>{}),r.unref()}var ne=Cn(ed(import.meta.url)),rd=Date.now(),Tr=Re(ne,"claude-hook-core.js"),be=Ot(ne)==="bin"&&Ot(Cn(ne))==="claude"&&Ot(Cn(Cn(ne)))===".anvil"?Cn(ne):void 0,od=!be&&Ot(ne)==="bin"&&Wr(Re(Cn(ne),".claude-plugin","plugin.json")),Si=null;async function sd(e){try{(await import("module")).enableCompileCache?.(Re(be??Qe(e).dir,"cache"))}catch{}}function an(){return Si??=import(jr(Tr).href),Si}var id=null,_n=()=>id??=import(jr(Re(ne,"claude-meter.js")).href),ld=new nd.Script("globalThis.__anvilClassify()");async function ad(e,n){let t;try{t=await an()}catch(s){throw new vn(s instanceof Error?s.message:String(s))}let{classifyRequest:r}=t;if(typeof r!="function")throw new vn("no classifier in its file");let o=globalThis;o.__anvilClassify=()=>r(e);try{return ld.runInThisContext({timeout:n})}catch(s){throw s.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new xn:s}finally{delete o.__anvilClassify}}function cd(e,n){return new Promise(t=>{let r=!1,o=(a,l)=>{r||(r=!0,clearTimeout(i),l&&l.terminate().catch(()=>{}),t(a))},s;try{s=new td(Tr,{workerData:{anvilClaudeHook:!0,request:e}})}catch(a){t({kind:"error",error:a instanceof Error?a.message:String(a)});return}let i=setTimeout(()=>o({kind:"timeout"},s),n);s.once("message",a=>{o(a.ok&&a.classification?{kind:"ok",classification:a.classification}:{kind:"error",error:a.error??"worker failed"},s)}),s.once("error",a=>o({kind:"error",error:a.message},s)),s.once("exit",a=>o({kind:"error",error:`worker exited (${a}) without an answer`}))})}async function ud(){try{let e=await _n(),n=e.probeAccount?.(process.env)??null;if(!n||!e.runPlanProbe)return;e.runPlanProbe({paths:be?Le(be):Qe(Nt()),env:process.env,now:()=>Date.now(),account:n})}catch{}}async function dd(){process.argv[2]==="--plan-probe"&&(await ud(),process.exit(0));let e="",n=null,t=!1,r="";try{let o=Nt();await sd(o);try{r=Yu(0,"utf8")}catch{r=""}if(r.length<64*1024&&r.includes("SessionStart"))try{t=JSON.parse(r).hook_event_name==="SessionStart"}catch{t=!1}e=(await yi(r,{home:o,...be?{anvilDir:be}:{},tmpdir:Qu(),env:process.env,now:()=>Date.now(),classifyInline:ad,classifyInWorker:cd,...od?{plugin:!0,fallbackTable:Re(ne,"baseline.json")}:{},...be&&Wr(Re(ne,"baseline.json"))?{fallbackTable:Re(ne,"baseline.json")}:{},coreProblem:Wr(Tr)?null:"its checker file is missing",entry:process.env.ANVIL_HOOK_EVENT,cli:process.env.ANVIL_HOOK_CLI,startProblems:async i=>(await an()).startProblems?.(i)??[],sessionChores:async(i,a)=>(await an()).sessionChores?.(i,a),answerChanges:async i=>(await an()).answerChanges?.(i)??null,sessionWords:async()=>{let i=await an();if(!i.sessionLine||!i.sessionContext)throw new Error("an older classifier file");return{sessionLine:i.sessionLine,sessionContext:i.sessionContext}},notify:i=>{n=i},planProbe:{hookFile:Re(ne,"claude-hook.js"),node:process.execPath},budgetAtPrompt:async i=>(await _n()).budgetAtPrompt(i),budgetAtAction:async i=>(await _n()).budgetAtAction(i),modelAtAction:async i=>(await _n()).modelAtAction(i),modelAtSwitch:async i=>(await _n()).modelAtSwitch(i),modelAtPrompt:async i=>(await _n()).modelAtPrompt(i),helpers:()=>import(jr(Re(ne,"claude-helpers.js")).href),moot:async i=>(await an()).mootHolds?.(i)})).stdout}catch{let o=null;try{o=t?"SessionStart":JSON.parse(r).hook_event_name??null}catch{o=null}e=o==="SessionStart"||o==="PreToolUse"||o===null?`${JSON.stringify(_e(o??"PreToolUse","its check crashed"))}
|
|
38
|
+
`:""}try{e&&Xu(1,e)}catch{}if(globalThis.__anvilHookAnswered=!0,n)try{(await an()).heldNotice?.({...n,anvilDir:be??Qe(Nt()).dir,now:Date.now(),env:process.env})}catch{}(jn(process.env.ANVIL_HOOK_EVENT)||/"hook_event_name"\s*:\s*"(?:UserPromptSubmit|SubagentStart|SubagentStop|PreModelSwitch)"/.test(r.slice(0,4096)))&&process.exit(0);try{let o=Nt();$i({paths:be?Le(be):Qe(o),binDir:ne,home:o,env:process.env,now:rd,execPath:process.execPath,sessionStart:t})}catch{}process.exit(0)}dd();
|