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