@useanvil/claude-code 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +727 -0
- package/README.md +128 -38
- package/dist/Anvil +0 -0
- package/dist/claude-approve.js +23 -0
- package/dist/claude-conditions.js +19 -12
- package/dist/claude-helpers.js +9 -9
- package/dist/claude-hook-core.js +88 -80
- package/dist/claude-hook.js +38 -37
- package/dist/claude-meter.js +52 -48
- package/dist/claude-powershell.cjs +17 -17
- package/dist/claude-sync.js +26 -26
- package/dist/cli/claude-main.js +5409 -2519
- package/docs/coding-agents/YOUR-RULES.md +507 -654
- package/package.json +1 -1
package/dist/claude-sync.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{existsSync as Bi,linkSync as Ki,readFileSync as zi,renameSync as Ji,statSync as zt,unlinkSync as Bt,writeFileSync as qi}from"fs";import{homedir as Ae,hostname as po}from"os";import{basename as qe,dirname as ee,join as E}from"path";import{fileURLToPath as Vi,pathToFileURL as go}from"url";import{createHmac as ts,randomBytes as mt,timingSafeEqual as ns}from"crypto";import{closeSync as Bn,existsSync as yt,fsyncSync as Kn,linkSync as rs,mkdirSync as zn,openSync as Jn,readdirSync as os,readFileSync as ue,unlinkSync as qn,writeSync as Vn}from"fs";import{basename as ss,dirname as Te,join as I}from"path";var v={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"},yo="Anvil. Claude Code",q=80,wo=11;function U(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 t=e==="truecolor",n=a=>c=>`\x1B[${a}m${c}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),i=n(t?"38;2;245;165;36":"38;5;214"),l=n(t?"38;2;34;197;94":"32"),s={[v.on]:r,[v.blocked]:r,[v.held]:r,[v.next]:r,[v.watching]:o,[v.problem]:i,[v.ok]:l};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:i,mark:a=>(s[a]??(c=>c))(a),field:a=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Xe(a)}\x1B[0m`}}var V=U(!1),bo=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Xe(e){return e.replace(bo,"")}function Xt(e){return Xe(e).length}function Qt(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function en(e,t){let n=[],r="";for(let o of e.split(/\s+/).filter(Boolean))r&&r.length+1+o.length>t?(n.push(r),r=o):r=r?`${r} ${o}`:o;return r&&n.push(r),n.length>0?n:[""]}function ko(e,t){let n=[],r="";for(let o of e){if(r&&r.length+3+o.length<=t){r=`${r} \xB7 ${o}`;continue}r&&n.push(r);let i=o.length>t?en(o,t):[o];n.push(...i.slice(0,-1)),r=i[i.length-1]}return r&&n.push(r),n.length>0?n:[""]}function Ce(e,t,n=V){return` ${n.mark(e)} ${t}`}function R(e,t,n=V){return` ${n.dim(e.padEnd(wo))}${t}`}function Qe(e,t,n=V,r=q){let o=` ${yo} \xB7 ${e}`,i=r-o.length-3,l=i>=8&&t?`${t.length>i?`\u2026${t.slice(t.length-i+1)}`:t} `:"",s=`${o}${" ".repeat(Math.max(2,r-o.length-l.length))}${l}`.slice(0,r);return n.on?n.field(s):s.trimEnd()}function et(e=q){return e-7}function tn(e,t,n=V,r=q,o={}){let i=r-3,l=i-4,s=o.tone??n.grey,a=o.mark?`${n.mark(o.mark)} `:"",c=(o.mark?2:0)+e.length,u=o.note?` ${o.note}`:"",f=Math.max(1,i-4-c-1-u.length-(u?2:1)),p=` ${s("\u256D\u2500 ")}${a}${n.bold(e)} ${s("\u2500".repeat(f))}${u?`${n.dim(u)}${s(" \u2500\u256E")}`:s("\u2500\u256E")}`,g=t.map(d=>{let N=Xt(d)>l?Qt(Xe(d),l):d;return` ${s("\u2502")} ${N}${" ".repeat(Math.max(0,l-Xt(N)))} ${s("\u2502")}`});return[p,...g,` ${s(`\u2570${"\u2500".repeat(i-2)}\u256F`)}`]}function te(e,t,n,r=V,o=q-7,i=9,l=s=>s){let s=e===null?0:2,a=Math.max(10,o-s-i);return(typeof n=="string"?en(n,a):ko(n,a)).map((u,f)=>f===0?`${e===null?"":`${r.mark(e)} `}${r.bold(t.padEnd(i))}${l(u)}`:`${" ".repeat(s+i)}${l(u)}`)}function vo(e,t,n,r=V,o="blue",i=q){let s=` ${(o==="blue"?r.blue:o==="amber"?r.amber:r.grey)("\u258C")} ${r.dim(e.padEnd(9))}`,a=t?`${r.blue(r.bold(t))}${n?" ":""}`:"",c=i-3-9-(t?t.length+(n?3:0):0);return`${s}${a}${n?r.dim(Qt(n,Math.max(0,c))):""}`}function tt(e,t,n=V,r=0,o="Next"){return vo(o,e.padEnd(t?r:0),t??"",n,"blue")}var P="claude";function G(e){return e==="ghost"||e==="enforce"?e:null}function ne(e,t){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let n=G(e.services?.[P]?.actions?.[t]?.mode);return n||(G(e.default_mode)??"ghost")}function nt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[P]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function re(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function rn(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:nt(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[P]:{actions:{}}},updated_at:r.toISOString()};let i={...o.services?.[P]?.actions??{}};for(let l of n)i[l]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:G(o.default_mode)??"ghost",services:{...o.services??{},[P]:{actions:i}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function xo(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:G(e.default_mode)==="enforce"?!0:Object.values(e.services?.[P]?.actions??{}).some(t=>G(t?.mode)==="enforce")}var rt="claude.agent.controls";function oe(e,t){return t===rt&&xo(e)?"enforce":ne(e,t)}var nn={off:0,ghost:1,enforce:2};function me(e,t){return e===null?t:t===null?e:nn[t]>nn[e]?t:e}function on(e,t){return!e||typeof e!="object"?null:G(e.services?.[P]?.actions?.[t]?.mode)??(G(e.default_mode)==="enforce"?"enforce":null)}function ot(e,t,n,r=!1){let i=me(on(e,t),n)??(r&&re(e)?"enforce":oe(e,t));return e?.kill_switch===!0&&i==="enforce"?"ghost":i}function sn(e,t,n){return me(on(e,t),n)===null&&re(e)&&oe(e,t)!=="enforce"}function _(e){return Object.assign(Object.create(null),e)}var Re=[{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)"}}],_o="home and project wipes and force-pushes to main",$o=`always blocking ${_o}`,ml=new Map(Re.map(e=>[e.id,e]));var ln=new Set(Re.flatMap(e=>Object.keys(e.slugs)));var an=_({"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 cn(e){let t=new Set(So(e));return Re.filter(n=>!Object.entries(an).some(([r,o])=>o.includes(n.id)&&t.has(r)))}var ye=new Set([rt,"claude.bash.secrets.expose"]);function So(e){let t=new Set(e.policies.filter(n=>n.origin==="baseline").flatMap(n=>n.rules.map(r=>r.id)));return Object.keys(an).filter(n=>!t.has(n))}var M=_({"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"}}),un={slug:"catastrophic",text:"cluster, cloud and database destroys, and cloud-credential prints"};function dn(e){if(!re(e))return null;let t="cluster, cloud and database destroys";return{what:t,context:`It also holds ${t} and cloud-credential prints, until the user sets a mode for their kinds.`}}var Oe=_({"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 Ee(e,t){return e&&Oe[e]?Oe[e].slug:!e||e==="hold-risky-actions"?M[t]?.slug??t:e.replace(/@.*$/,"")}function Ne(e){return M[e]?.text??e}function fn(e){let t=new Set(ln);for(let n of e.policies)for(let r of n.rules)if(r.primitive!=="durable_key_dedup")if(r.id==="hold-risky-actions")for(let o of r.applies_to??[])t.add(Ee(null,o));else t.add(Ee(r.id,""));return t.size}function st(e){let t=new Set;for(let n of e.policies)for(let r of n.rules)if(r.primitive!=="durable_key_dedup")for(let o of r.applies_to??n.allowed_actions)t.add(o);return[...t]}function pn(e,t){let n=st(e).filter(o=>M[o]),r=n.filter(o=>oe(t,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===n.length?"enforce":`${r.length} enforced, rest ghost`}}var it="anvil-claude";function L(e){let t=e.trim();return t===it||t.endsWith(` ${it}`)||t.endsWith(`/${it}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var gn="\u{1F539}",lt=e=>`${gn} ${e} ${gn}`;var hn="anvil";function at(e){hn=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}var x=e=>`${L(hn)} ${e}`;import{spawnSync as Oc}from"child_process";import{createHash as Nc}from"crypto";import{chmodSync as Lc,existsSync as jc,lstatSync as Ho,mkdirSync as Ic,readdirSync as Tc,readFileSync as Uo,readlinkSync as Bo,realpathSync as jn,rmdirSync as Dc,statSync as gt,unlinkSync as Mc,writeFileSync as Fc}from"fs";import{dirname as Ko,isAbsolute as Hc,join as Uc,relative as Bc,resolve as zo}from"path";import{createHash as ic}from"crypto";import{appendFileSync as jo,closeSync as kn,constants as bn,fstatSync as vn,mkdirSync as Io,openSync as xn,readdirSync as ac,readFileSync as To,readSync as _n,renameSync as Do,statSync as $n,unlinkSync as cc,writeFileSync as Mo}from"fs";import{homedir as Fo}from"os";import{dirname as fc,join as F}from"path";import{existsSync as Ul,readdirSync as Bl,statSync as Kl}from"fs";import{dirname as Jl,isAbsolute as ql,join as Vl,posix as Gl,resolve as Yl}from"path";import{posix as wn}from"path";var Ao=null;function Pe(){return Ao??process.platform==="win32"}var yn=/^([A-Za-z]):(.*)$/s,Co=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function ct(e,t){let n=wn.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function se(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,i=t?o:o.replace(/[. ]+$/,"");return i===""?".":i}).join("/")}function ut(e){if(!Pe())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let a=r[2];if(r[1]===".")return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(a))t=`\\\\${a.slice(4)}`;else if(yn.test(a))t=a;else return`/dev/${a.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let a=`/unc/${se(o[1],n).toLowerCase()}${o[2]?`/${se(o[2],n).toLowerCase()}`:""}`;return ct(a,se(o[3]??"",n).toLowerCase())}let i=yn.exec(t);if(i){let a=i[2];return a===""?`/${i[1].toLowerCase()}`:a.startsWith("/")?ct(`/${i[1].toLowerCase()}`,se(a,n).toLowerCase()):null}let l=Co.exec(t);if(l)return ct(`/${l[1].toLowerCase()}`,se(l[2]??"",n).toLowerCase());let s=se(t,n).toLowerCase();if(s.startsWith("/")){let a=wn.normalize(s);return a.length>1&&a.endsWith("/")?a.slice(0,-1):a}return s}function Ro(e){return ut(e)??e}function dt(e){return!Pe()||typeof e!="string"||e===""?e:Ro(e)}import{domainToASCII as sa}from"url";var pa="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Ea,readdirSync as Na,realpathSync as Pa}from"fs";import{basename as ja,dirname as Ia,join as Ta}from"path";var pt="anvil-claude-compiled/1";function Po(e,t){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(t)}function ie(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Lo(t,e.project_dir))}function Le(e,t,n){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!ie(o,n))){for(let i of o.rules)i.mode&&Po(i,t)&&(r=me(r,i.mode));o.off?.includes(t)&&(r=me(r,"off"))}return r}function Lo(e,t){let n=dt(e),r=dt(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}function Sn(e=Fo()){return je(F(e,".anvil","claude"))}function je(e){return{dir:e,bin:F(e,"bin"),compiled:F(e,"compiled.json"),modes:F(e,"modes.json"),decisions:F(e,"decisions.jsonl"),install:F(e,"install.json"),state:F(e,"state"),approvals:F(e,"approvals"),counts:F(e,"counts"),backups:F(e,"backups")}}var Wo=3500;function y(e,t=8*1024*1024){try{let n=$n(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function ft(e,t=8*1024*1024){let n;try{n=xn(e,bn.O_RDONLY|bn.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=vn(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),i=0;for(;i<r.size;){let l=_n(n,o,i,r.size-i,i);if(l===0)break;i+=l}return o.subarray(0,i)}finally{kn(n)}}function we(e){try{let t=$n(e);return t.isFile()?t.size:0}catch{return 0}}function An(e,t){let n=t.endsWith(`
|
|
1
|
+
import{existsSync as Vi,linkSync as Gi,readFileSync as Yi,renameSync as Zi,statSync as qt,unlinkSync as zt,writeFileSync as Xi}from"fs";import{homedir as Oe,hostname as wo}from"os";import{basename as Ge,dirname as te,join as O}from"path";import{fileURLToPath as Qi,pathToFileURL as bo}from"url";import{createHmac as is,randomBytes as yt,timingSafeEqual as as}from"crypto";import{closeSync as qn,existsSync as wt,fsyncSync as Vn,linkSync as ls,mkdirSync as Gn,openSync as Yn,readdirSync as cs,readFileSync as de,unlinkSync as Zn,writeSync as Xn}from"fs";import{basename as us,dirname as Me,join as L}from"path";var v={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"},$o="Anvil. Claude Code",V=80,_o=11;function B(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 t=e==="truecolor",n=l=>c=>`\x1B[${l}m${c}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),s=n(t?"38;2;245;165;36":"38;5;214"),a=n(t?"38;2;34;197;94":"32"),i={[v.on]:r,[v.blocked]:r,[v.held]:r,[v.next]:r,[v.watching]:o,[v.problem]:s,[v.ok]:a};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:s,mark:l=>(i[l]??(c=>c))(l),field:l=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${et(l)}\x1B[0m`}}var G=B(!1),xo=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function et(e){return e.replace(xo,"")}function en(e){return et(e).length}function tn(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function nn(e,t){let n=[],r="";for(let o of e.split(/\s+/).filter(Boolean))r&&r.length+1+o.length>t?(n.push(r),r=o):r=r?`${r} ${o}`:o;return r&&n.push(r),n.length>0?n:[""]}function So(e,t){let n=[],r="";for(let o of e){if(r&&r.length+3+o.length<=t){r=`${r} \xB7 ${o}`;continue}r&&n.push(r);let s=o.length>t?nn(o,t):[o];n.push(...s.slice(0,-1)),r=s[s.length-1]}return r&&n.push(r),n.length>0?n:[""]}function Ee(e,t,n=G){return` ${n.mark(e)} ${t}`}function N(e,t,n=G){return` ${n.dim(e.padEnd(_o))}${t}`}function tt(e,t,n=G,r=V){let o=` ${$o} \xB7 ${e}`,s=r-o.length-3,a=s>=8&&t?`${t.length>s?`\u2026${t.slice(t.length-s+1)}`:t} `:"",i=`${o}${" ".repeat(Math.max(2,r-o.length-a.length))}${a}`.slice(0,r);return n.on?n.field(i):i.trimEnd()}function nt(e=V){return e-7}function rn(e,t,n=G,r=V,o={}){let s=r-3,a=s-4,i=o.tone??n.grey,l=o.mark?`${n.mark(o.mark)} `:"",c=(o.mark?2:0)+e.length,u=o.note?` ${o.note}`:"",f=Math.max(1,s-4-c-1-u.length-(u?2:1)),p=` ${i("\u256D\u2500 ")}${l}${n.bold(e)} ${i("\u2500".repeat(f))}${u?`${n.dim(u)}${i(" \u2500\u256E")}`:i("\u2500\u256E")}`,g=t.map(d=>{let E=en(d)>a?tn(et(d),a):d;return` ${i("\u2502")} ${E}${" ".repeat(Math.max(0,a-en(E)))} ${i("\u2502")}`});return[p,...g,` ${i(`\u2570${"\u2500".repeat(s-2)}\u256F`)}`]}function ne(e,t,n,r=G,o=V-7,s=9,a=i=>i){let i=e===null?0:2,l=Math.max(10,o-i-s);return(typeof n=="string"?nn(n,l):So(n,l)).map((u,f)=>f===0?`${e===null?"":`${r.mark(e)} `}${r.bold(t.padEnd(s))}${a(u)}`:`${" ".repeat(i+s)}${a(u)}`)}function Ao(e,t,n,r=G,o="blue",s=V){let i=` ${(o==="blue"?r.blue:o==="amber"?r.amber:r.grey)("\u258C")} ${r.dim(e.padEnd(9))}`,l=t?`${r.blue(r.bold(t))}${n?" ":""}`:"",c=s-3-9-(t?t.length+(n?3:0):0);return`${i}${l}${n?r.dim(tn(n,Math.max(0,c))):""}`}function rt(e,t,n=G,r=0,o="Next"){return Ao(o,e.padEnd(t?r:0),t??"",n,"blue")}var an="production";function M(e){let t=e?.turned_off;return Array.isArray(t)?t:[]}var on=e=>e.length>0?{turned_off:e}:{};var P="claude";function Y(e){return e==="ghost"||e==="enforce"?e:null}function re(e,t){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let n=Y(e.services?.[P]?.actions?.[t]?.mode);return n||(Y(e.default_mode)??"ghost")}function ot(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[P]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function oe(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function ln(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:ot(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[P]:{actions:{}}},updated_at:r.toISOString(),...on(t==="enforce"?[]:M(o))};let s={...o.services?.[P]?.actions??{}};for(let a of n)s[a]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:Y(o.default_mode)??"ghost",services:{...o.services??{},[P]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{},...on(M(o))}}function Co(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:Y(e.default_mode)==="enforce"?!0:Object.values(e.services?.[P]?.actions??{}).some(t=>Y(t?.mode)==="enforce")}var ye="claude.agent.controls";function se(e,t){return t===ye&&Co(e)?"enforce":re(e,t)}var sn={off:0,ghost:1,enforce:2};function we(e,t){return e===null?t:t===null?e:sn[t]>sn[e]?t:e}function cn(e,t){return!e||typeof e!="object"?null:Y(e.services?.[P]?.actions?.[t]?.mode)??(Y(e.default_mode)==="enforce"?"enforce":null)}function st(e,t,n,r=!1){let s=we(cn(e,t),n)??(r&&oe(e)?"enforce":se(e,t));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function un(e,t,n){return we(cn(e,t),n)===null&&oe(e)&&se(e,t)!=="enforce"}function _(e){return Object.assign(Object.create(null),e)}var be=[{id:"protect",verdict:"block",short:"wiping your home folder or the project",slugs:["protected"]},{id:"protect-main",verdict:"block",short:"force-pushing main",slugs:["protected"]},{id:"protect-processes",verdict:"block",short:"killing every process",slugs:["protected"]},{id:"keep-work",verdict:"hold",short:"throwing away uncommitted work",slugs:["uncommitted"]},{id:"stay-in-project",verdict:"hold",short:"deletes outside your project",slugs:["outside-folder"]},{id:"stay-out-of-prod",verdict:"hold",short:"changes aimed at production",slugs:["prod-changes"]},{id:"keep-anvil-on",verdict:"hold",short:"changes to Anvil",slugs:["agent-controls"]},{id:"stop-loops",verdict:"hold",short:"delete bursts and repeats",slugs:["delete-burst","repeat"]},{id:"stop-helper-bursts",verdict:"hold",short:"helper bursts",slugs:["helper-burst"]},{id:"keep-keys-in",verdict:"hold",short:"use of your account keys",slugs:["credentials","secrets-expose"]},{id:"keep-env-out",verdict:"hold",short:"showing secrets files in the chat",slugs:["env-in-chat"]},{id:"hold-unchecked",verdict:"hold",short:"actions it can't check",slugs:["could-not-check","too-long-to-check"]}],Ro="home and project wipes and force-pushes to main",Oo=`always blocking ${Ro}`,va=new Map(be.map(e=>[e.id,e]));var dn=new Set(be.flatMap(e=>e.slugs));var fn=_({"block-protected-targets":["protect","protect-main","protect-processes"],"hold-delete-bursts":["stop-loops"],"hold-repeated-side-effect":["stop-loops"],"hold-helper-bursts":["stop-helper-bursts"],"hold-risky-actions":["keep-work","stay-in-project","stay-out-of-prod","keep-anvil-on","keep-keys-in","keep-env-out"]});function pn(e,t=[]){let n=new Set(Eo(e));return be.filter(r=>!t.includes(r.id)&&!Object.entries(fn).some(([o,s])=>s.includes(r.id)&&n.has(o)))}var ke=new Set([ye,"claude.bash.secrets.expose"]);function Eo(e){let t=new Set(e.policies.filter(n=>n.origin==="baseline").flatMap(n=>n.rules.map(r=>r.id)));return Object.keys(fn).filter(n=>!t.has(n))}var F=_({"claude.bash.fs.delete_recursive":{slug:"delete",text:"recursive delete"},"claude.bash.fs.delete_disposable":{slug:"delete-temp",text:"delete of temp or build files"},"claude.bash.git.force_push":{slug:"force-push",text:"force-push"},"claude.bash.git.push_main":{slug:"push-main",text:"push or merge to main"},"claude.bash.git.discard":{slug:"discard",text:"throw away git work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.bash.deps.add":{slug:"new-dependency",text:"add a new dependency"},"claude.bash.prod.target":{slug:"production",text:"use a production account"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.file.outside_project":{slug:"outside-project",text:"change files outside the project"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}}),gn={slug:"catastrophic",text:"cluster, cloud and database destroys; cloud-credential prints, and new packages"};function hn(e){if(!oe(e))return null;let t="cluster, cloud and database destroys";return{what:t,context:`It also holds ${t}, cloud-credential prints and packages the project doesn't declare, until the user sets a mode for their kinds.`}}var Ne=_({"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 Pe(e,t){return e&&Ne[e]?Ne[e].slug:!e||e==="hold-risky-actions"?F[t]?.slug??t:e.replace(/@.*$/,"")}function je(e){return F[e]?.text??e}function mn(e){let t=new Set(dn);for(let n of e.policies)for(let r of n.rules)if(r.primitive!=="durable_key_dedup")if(r.id==="hold-risky-actions")for(let o of r.applies_to??[])t.add(Pe(null,o));else t.add(Pe(r.id,""));return t.size}function it(e){let t=new Set;for(let n of e.policies)for(let r of n.rules)if(r.primitive!=="durable_key_dedup")for(let o of r.applies_to??n.allowed_actions)t.add(o);return[...t]}function yn(e,t){let n=it(e).filter(o=>F[o]),r=n.filter(o=>se(t,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===n.length?"enforce":`${r.length} enforced, rest ghost`}}var at="anvil-claude";function j(e){let t=e.trim();return t===at||t.endsWith(` ${at}`)||t.endsWith(`/${at}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var wn="\u{1F539}",lt=e=>`${wn} ${e} ${wn}`;var bn="anvil";function ct(e){bn=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}var $=e=>`${j(bn)} ${e}`;import{spawnSync as Tc}from"child_process";import{createHash as Mc}from"crypto";import{chmodSync as Wc,existsSync as Hc,lstatSync as Jo,mkdirSync as Uc,readdirSync as Bc,readFileSync as qo,readlinkSync as Vo,realpathSync as Mn,rmdirSync as Kc,statSync as ht,unlinkSync as zc,writeFileSync as Jc}from"fs";import{dirname as Go,isAbsolute as Vc,join as Gc,relative as Yc,resolve as Yo}from"path";import{createHash as pc}from"crypto";import{appendFileSync as Fo,closeSync as xn,constants as _n,fstatSync as Sn,mkdirSync as Wo,openSync as An,readdirSync as hc,readFileSync as Ho,readSync as Cn,renameSync as Uo,statSync as Rn,unlinkSync as mc,writeFileSync as Bo}from"fs";import{homedir as Ko}from"os";import{dirname as bc,join as W}from"path";import{createHash as qa}from"crypto";import{existsSync as Ga,readdirSync as Ya,statSync as Za}from"fs";import{dirname as Qa,isAbsolute as el,join as tl,posix as nl,resolve as rl}from"path";import{posix as $n}from"path";var No=null;function Ie(){return No??process.platform==="win32"}var vn=/^([A-Za-z]):(.*)$/s,Po=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function ut(e,t){let n=$n.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function ie(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,s=t?o:o.replace(/[. ]+$/,"");return s===""?".":s}).join("/")}function dt(e){if(!Ie())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let l=r[2];if(r[1]===".")return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(l))t=`\\\\${l.slice(4)}`;else if(vn.test(l))t=l;else return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let l=`/unc/${ie(o[1],n).toLowerCase()}${o[2]?`/${ie(o[2],n).toLowerCase()}`:""}`;return ut(l,ie(o[3]??"",n).toLowerCase())}let s=vn.exec(t);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?ut(`/${s[1].toLowerCase()}`,ie(l,n).toLowerCase()):null}let a=Po.exec(t);if(a)return ut(`/${a[1].toLowerCase()}`,ie(a[2]??"",n).toLowerCase());let i=ie(t,n).toLowerCase();if(i.startsWith("/")){let l=$n.normalize(i);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return i}function jo(e){return dt(e)??e}function ft(e){return!Ie()||typeof e!="string"||e===""?e:jo(e)}import{domainToASCII as fl}from"url";var kl="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Dl,readdirSync as Ml,realpathSync as Fl}from"fs";import{basename as Hl,dirname as Ul,join as Bl}from"path";var gt="anvil-claude-compiled/1";function Do(e,t){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(t)}function ae(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Mo(t,e.project_dir))}function Le(e,t,n){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!ae(o,n))){for(let s of o.rules)s.mode&&Do(s,t)&&(r=we(r,s.mode));o.off?.includes(t)&&(r=we(r,"off"))}return r}function Mo(e,t){let n=ft(e),r=ft(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}function On(e=Ko()){return Te(W(e,".anvil","claude"))}function Te(e){return{dir:e,bin:W(e,"bin"),compiled:W(e,"compiled.json"),modes:W(e,"modes.json"),decisions:W(e,"decisions.jsonl"),install:W(e,"install.json"),state:W(e,"state"),approvals:W(e,"approvals"),counts:W(e,"counts"),backups:W(e,"backups")}}var zo=3500;function y(e,t=8*1024*1024){try{let n=Rn(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function pt(e,t=8*1024*1024){let n;try{n=An(e,_n.O_RDONLY|_n.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=Sn(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),s=0;for(;s<r.size;){let a=Cn(n,o,s,r.size-s,s);if(a===0)break;s+=a}return o.subarray(0,s)}finally{xn(n)}}function ve(e){try{let t=Rn(e);return t.isFile()?t.size:0}catch{return 0}}function En(e,t){let n=t.endsWith(`
|
|
2
2
|
`)?t:`${t}
|
|
3
|
-
`;if(Buffer.byteLength(n)>
|
|
4
|
-
`);
|
|
5
|
-
`,"wx");let o=!1;try{t
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`;
|
|
9
|
-
`))if(
|
|
10
|
-
`,o.index)+1;(r.get(
|
|
11
|
-
`,o);try{let
|
|
3
|
+
`;if(Buffer.byteLength(n)>zo)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(y(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);Fo(e,n,{mode:384})}function A(e){Wo(e,{recursive:!0,mode:448})}function I(e,t){if(y(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=An(e,"r")}catch{return""}try{let r=Sn(n).size,o=Math.max(0,r-t),s=r-o;if(s<=0)return"";let a=Buffer.alloc(s);Cn(n,a,0,s,o);let i=a.toString("utf8");if(o>0){let l=i.indexOf(`
|
|
4
|
+
`);i=l<0?"":i.slice(l+1)}return i}finally{xn(n)}}function R(e,t,n=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Bo(r,t,{mode:n}),$e(r,e)}function $e(e,t){for(let n=0;;n++)try{Uo(e,t);return}catch(r){let o=r.code;if(process.platform!=="win32"||n>=12||o!=="EPERM"&&o!=="EACCES"&&o!=="EBUSY")throw r;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20+n*10)}}function b(e){if(y(e)!==!0)return null;try{return JSON.parse(Ho(e,"utf8"))}catch{return null}}var vc=256*1024,$c=1024*1024;var jn="locks.json";var In=e=>e.only===!0?"held by Anvil only":"held by Anvil, not locked";var Nn={filesystem:["denyWrite","denyRead"],network:["deniedDomains"]};function Ln(e,t){if(t.managed==="on"||t.managed==="off")return null;let n=e.filter(s=>Pn(s.sandbox)),r=n.find(s=>typeof s.sandbox.enabled=="boolean");if(r?.sandbox.enabled===!1)return t.userOn?{off:r.file}:null;if(!r&&!t.userOn)return null;let o=t.open?n.find(s=>!s.anvil&&Object.entries(s.sandbox).some(([a,i])=>!(a in Nn)||Pn(i)&&Object.keys(i).some(l=>!Nn[a].includes(l)))):void 0;if(o){let s=n.find(a=>typeof a.sandbox.autoAllowBashIfSandboxed=="boolean");return{widened:o.file,unasked:s?.sandbox.autoAllowBashIfSandboxed===!0}}return r&&!t.userOn?{on:r.file}:null}var Tn=e=>`held by Anvil only in this project: ${e} turns Claude Code's sandbox off`,Dn=e=>`this project's own sandbox (${e.widened}) is widened by Anvil's: commands here can reach any site and any local socket${e.unasked?", and run without asking":""}`;var Pn=e=>!!e&&typeof e=="object"&&!Array.isArray(e);var Zo="/.anvil/claude/bin/claude-hook.js",Xo=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var le=class extends Error{constructor(t){super(t),this.name="SettingsRefused"}};function Fn(e,t){let n=e.startsWith("\uFEFF")?e.slice(1):e;if(n.trim()==="")return{};let r;try{r=JSON.parse(n)}catch(o){throw new le(`${t} 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 le(`${t} is not a JSON object. Anvil changed nothing.`);return r}function Qo(e){if(!e||typeof e!="object")return null;let{command:t,args:n}=e;return typeof t!="string"?null:Array.isArray(n)?[t,...n.filter(r=>typeof r=="string")].join(" "):t}var es=e=>{let t=Qo(e);return t!==null&&(t.includes(Zo)||Xo.test(t))};function ts(e,t){if(!e||typeof e!="object")return!1;let n=e;return typeof t=="string"?n.command===t:n.command===t.command&&Array.isArray(n.args)&&n.args.length===t.args.length&&n.args.every((r,o)=>r===t.args[o])}function Wn(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function ns(e){return pt(e,64*1024*1024)}function Hn(e){try{if(!Jo(e).isSymbolicLink())return e}catch{return e}try{return Mn(e)}catch(t){let n=t.code;throw n==="ENOENT"?new le(`${e} is a link to ${rs(e)}, which does not exist. Anvil changed nothing; create that file or remove the link, and run this again.`):new le(`${e} is a link Anvil cannot follow (${n??String(t)}). Anvil changed nothing.`)}}function rs(e){let t=Go(e);try{t=Mn(t)}catch{}return Yo(t,Vo(e))}function Un(e){try{let t=ns(Hn(e));if(t===null)return null;let n=Fn(t.toString("utf8"),e).hooks?.PreToolUse;if(!Array.isArray(n))return null;let r=n.flatMap(o=>{let s=o&&typeof o=="object"?o.hooks:void 0;return Array.isArray(s)?s.filter(es):[]});return r.length===0?null:r.every(o=>o.onFailure==="block")}catch{return null}}function Bn(e,t){let n;try{n=Hn(e)}catch{return"unreadable"}let r;try{r=ht(n)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=Fn(qo(n,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let s=o.hooks?.PreToolUse;return Array.isArray(s)&&s.some(i=>{let l=i&&typeof i=="object"?i:null,c=l?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(l?.hooks)&&l.hooks.some(u=>ts(u,t))})?"present":"missing"}function os(e){let t=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),n=s=>s.startsWith("'")?s.slice(1,-1).replace(/'\\''/g,"'"):s,r=t?t.findIndex(s=>s==="/bin/sh"||s==="sh"):-1,o=t&&r>=0&&(t[r+3]==="PreToolUse"||t[r+3]==="SessionStart")?/^\d{2,3}$/.test(t[r+4]??"")?2:1:0;if(t&&r>=0&&t[r+3+o]==="||"){let s=r>0&&r%5===0;for(let a=0;s&&a<r;a+=5)s=t[a]==="["&&(t[a+1]==="-s"||t[a+1]==="-f")&&t[a+3]==="]"&&t[a+4]==="&&"&&n(t[a+2])===n(t[r+1]);if(r===0||s)return[n(t[r+1]),n(t[r+2])]}return!t||t.length!==2?null:[n(t[0]),n(t[1])]}function ss(e){if(!e||typeof e!="object")return null;let{command:t,args:n}=e;if(typeof t!="string")return null;if(Array.isArray(n)){let r=n.find(o=>typeof o=="string"&&/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js$/i.test(o));return r?[t,r]:null}return os(t)}function mt(e){let t=ss(e);if(!t)return!1;try{return ht(t[0]).isFile()&&ht(t[1]).isFile()}catch{return!1}}var K="_seal";function He(e){return L(e.dir,"seal.key")}function ue(e,t){return L(e.state,"lkg",t)}function C(e){let t=He(e);if(y(t,1024)!==!0)return null;try{let n=de(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function vt(e){return C(e)?"ok":y(He(e),1024)===null?"missing":"damaged"}var Fe=class extends Error{};function Ue(e,t){return`Anvil's seal key (${He(e)}) is ${t==="damaged"?"damaged":"missing"}`}function ds(e){let t=C(e);if(t)return t;let n=vt(e);if(n==="damaged"||$t(e))throw new Fe(`${Ue(e,n)}; run ${$("on")} to restore it`);let{key:r,created:o}=fs(e,!1);return o&&ps(e,r),r}function Kn(e,t,n){let r=Yn(e,n,384);try{Xn(r,t),Vn(r)}finally{qn(r)}}function fs(e,t){Gn(e.dir,{recursive:!0,mode:448});let n=He(e),r=L(e.dir,`.seal.key.${process.pid}.${yt(4).toString("hex")}.tmp`);Kn(r,`${yt(32).toString("hex")}
|
|
5
|
+
`,"wx");let o=!1;try{t?$e(r,n):ls(r,n),o=!0}catch(a){let i=a.code??"";if(i!=="EEXIST"){if(t||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(i))throw a;try{Kn(n,de(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{Zn(r)}catch{}}let s=C(e);if(!s)throw new Fe(`${Ue(e,"damaged")}; run ${$("on")} to restore it`);return{key:s,created:o}}function ps(e,t){let n=[[e.modes,_e],[e.compiled,tr],[e.install,void 0]];for(let[r,o]of n)if(y(r,8*1024*1024)===!0)try{let s=de(r,"utf8");if(s.includes(`"${K}"`))continue;let a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))continue;r===e.modes&&delete a.turned_off;let i=`${JSON.stringify(kt(t,a),null,2)}
|
|
6
|
+
`;ce(r,i),o&&ce(ue(e,o),i)}catch{}if(y(e.modes)===null&&y(ue(e,_e))===null){let r=`${JSON.stringify(kt(t,ot()),null,2)}
|
|
7
|
+
`;ce(e.modes,r),ce(ue(e,_e),r)}}function bt(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>bt(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(t===0&&r===K)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${bt(e[r],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function Qn(e,t){return is("sha256",e).update(bt(t)).digest("hex")}function De(e){if(!(K in e))return e;let t={...e};return delete t[K],t}function kt(e,t){let n=De(t);return{...n,[K]:Qn(e,n)}}function gs(e,t){let n=t[K];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let r;try{r=Qn(e,t)}catch{return!1}return as(Buffer.from(n,"hex"),Buffer.from(r,"hex"))}function ce(e,t,n=384){Gn(Me(e),{recursive:!0,mode:448});let r=L(Me(e),`.${us(e)}.${process.pid}.${Date.now().toString(36)}.${yt(3).toString("hex")}.tmp`);try{let o=Yn(r,"w",n);try{Xn(o,t),Vn(o)}finally{qn(o)}$e(r,e)}catch(o){try{Zn(r)}catch{}throw o}}function x(e,t,n=8*1024*1024){let r=y(e,n);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(de(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:t?K in o?gs(t,o)?{status:"ok",value:De(o)}:{status:"changed",value:De(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:De(o)}}function er(e,t,n,r){let o=ds(e),s=`${JSON.stringify(kt(o,n),null,2)}
|
|
8
|
+
`;ce(t,s),r&&ce(ue(e,r),s)}var _e="modes.json",tr="compiled.json";function nr(e,t){er(e,e.modes,t,_e)}function $t(e){return wt(L(e.bin,"claude-hook.sh"))||hs(e)}function hs(e){let t=n=>{try{return cs(n).slice(0,200).some(r=>r.endsWith(".json")&&y(L(n,r),65536)===!0&&de(L(n,r),"utf8").includes(`"${K}"`))}catch{return!1}};if(t(L(e.state,"lkg"))||t(L(e.state,"pending"))||t(e.approvals))return!0;for(let n of[e.modes,e.compiled,e.install])if(y(n,8*1024*1024)===!0)try{if(de(n,"utf8").includes(`"${K}"`))return!0}catch{}return!1}var We=_({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function zn(e=new Date){return ln(null,"enforce","all",e)}function Z(e,t=C(e),n={}){if(!t){let a=vt(e);if(n.installed===!0||a==="damaged"||$t(e))return{value:zn(),source:"strict",problem:`${Ue(e,a)}, so every rule is enforced until \`${$("on")}\` restores it`};let i=x(e.modes,null);if(i.status!=="unkeyed")return{value:null,source:"unkeyed",problem:null};let{turned_off:l,...c}=i.value;return{value:c,source:"unkeyed",problem:null}}let r=x(e.modes,t);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${We[r.status]??"cannot be used"}`,s=x(ue(e,_e),t);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:zn(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${$("on")}\` resets it`}}function X(e,t,n=C(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===gt&&Array.isArray(c.policies),s=()=>{if(!t)return null;let c=x(t,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!n){let c=vt(e),u=r.installed===!0||c==="damaged"||$t(e),f=x(e.compiled,null),p=f.status==="unkeyed"&&o(f.value)?f.value:null;return u?{value:null,source:"strict",problem:`${Ue(e,c)}: \`${$("on")}\` restores it`}:{value:p??s(),source:"unkeyed",problem:null}}let a=x(e.compiled,n);if(a.status==="ok"&&o(a.value))return{value:a.value,source:"file",problem:null};let i=`compiled.json ${a.status==="ok"?"is not a rules table":We[a.status]??"cannot be used"}`,l=x(ue(e,tr),n);return l.status==="ok"&&o(l.value)?{value:l.value,source:"last-good",problem:`${i}; Anvil keeps the rules it last compiled`}:a.status==="missing"&&l.status==="missing"&&y(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${i}, and so is Anvil's own copy: \`${$("on")}\` recompiles them`}}function Jn(e,t){return t&&(e===t||e.startsWith(`${t}/`))?`~${e.slice(t.length)}`:e}function Be(e,t,n,r=!0){let o=x(e.install,t,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${We.unreadable}`];if(t&&o.status!=="ok")return[`install.json ${We[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):[],a=[];for(let f of s.slice(0,64)){if(!f||typeof f.real_path!="string"||typeof f.command!="string")continue;let p=Bn(f.settings_path??f.real_path,Wn(f)),g=Jn(f.settings_path??f.real_path,n);p!=="present"&&(p==="no-file"&&f.scope==="project"&&!wt(Me(Me(f.real_path)))||(p==="disabled"?r&&a.push(`${g} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):p==="missing"||p==="no-file"?a.push(`Anvil's hook was taken out of ${g} outside \`${$("off")}\`, so new sessions are not checked`):a.push(`${g} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let i=o.status==="ok"||o.status==="unkeyed"?o.value:null,l=[...Array.isArray(i?.package_dirs)?i.package_dirs:[],...typeof i?.package_dir=="string"?[i.package_dir]:[]].filter(f=>typeof f=="string"&&f.startsWith("/")).slice(0,16),c=l[l.length-1]??"",u=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return s.length>0&&l.length>0&&l.every(f=>!wt(L(f,"package.json")))&&a.push(`the Anvil package that installed this hook is gone (${Jn(c,n)}): keep Anvil with ${j(u)} on, or remove it with ${j(u)} off --purge`),a}function ms(e){return L(e.state,"health.json")}function Ke(e){let t=x(ms(e),null,65536);return t.status==="unkeyed"&&t.value.v===1&&Array.isArray(t.value.problems)?t.value:null}import{accessSync as ar,constants as lr,existsSync as xt,statfsSync as ys}from"fs";import{createHash as hu,randomBytes as mu}from"crypto";import{readdirSync as or,renameSync as wu,unlinkSync as bu}from"fs";import{join as _t}from"path";var _u=600*1e3,xu=1440*60*1e3;function rr(e){return _t(e.state,"pending")}function sr(e,t,n){let r=[];try{r=or(rr(e)).filter(s=>s.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let s of r){let a=_t(rr(e),s),i=x(a,t,64*1024);i.status!=="ok"||i.value.v!==2||!Array.isArray(i.value.stops)||!(Date.parse(i.value.expires_at)>=n)||o.push({hold:i.value,file:a})}return o.sort((s,a)=>Date.parse(a.hold.created_at)-Date.parse(s.hold.created_at))}function ir(e,t){let n=[];try{n=or(e.approvals).filter(o=>o.endsWith(".json")&&!o.includes(".used-")).slice(0,2e3)}catch{return 0}let r=0;for(let o of n){let s=x(_t(e.approvals,o),t,65536);s.status!=="missing"&&(s.status!=="ok"||s.value.v!==2||!Array.isArray(s.value.stops))&&r++}return r}var St=(e,t)=>e===t?"~":e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e;function cr(e,t,n){let r=[],o=b(e.install),s=o&&o.installs&&typeof o.installs=="object"?Object.values(o.installs):[];for(let i of s)!i||typeof i.settings_path!="string"||Un(i.settings_path)===!1&&r.push(`the hook in ${St(i.settings_path,t)} was installed without onFailure, so Claude Code runs a call when Anvil's check fails or stalls: run ${$("on")} to add it`);try{xt(e.decisions)?ar(e.decisions,lr.W_OK):xt(e.dir)&&ar(e.dir,lr.W_OK)}catch{r.push(`${St(e.decisions,t)} cannot be written, so stops are not recorded and the counts here read low`)}try{let i=ys(xt(e.dir)?e.dir:t);Number(i.bavail)*Number(i.bsize)<1024*1024&&r.push(`the disk holding ${St(e.dir,t)} is full, so stops are not recorded and a held call cannot be allowed once`)}catch{}let a=n?ir(e,n):0;return a>0&&r.push(`${a===1?"an approval was":`${a} approvals were`} written outside \`${$("allow")}\`; ${a===1?"it releases":"they release"} nothing (${$("on")} removes ${a===1?"it":"them"})`),r}import{spawn as ju}from"child_process";import{readFileSync as Lu,statSync as Tu}from"fs";import{join as ws}from"path";var ur="sync-next",dr="sync-pulled";var Fu=5*6e4;function fr(e,t){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||ws(t,".anvil","workspace-keys.json")}var Wu=10*6e4;import{join as Re}from"path";import{createHash as bs}from"crypto";import{closeSync as ks,constants as pr,fstatSync as vs,openSync as $s,readdirSync as gr,readFileSync as _s,readSync as xs,statSync as Ss,unlinkSync as At,writeFileSync as As}from"fs";import{join as Q}from"path";var Cs=9,hr=4*1024*1024,Ct=6*36e5,Rt="waiting",Rs=4;function Os(e){let t;try{t=$s(e,pr.O_RDONLY|pr.O_NONBLOCK)}catch(n){if(n.code==="ENOENT")return"";throw n}try{let n=vs(t);if(!n.isFile())throw new Error("the day's cap count is not a regular file");if(n.size>hr)throw new Error(`the day's cap count is over ${hr/1024/1024} MB`);let r=Buffer.alloc(n.size),o=0;for(;o<n.size;){let s=xs(t,r,o,n.size-o,o);if(s===0)break;o+=s}return r.subarray(0,o).toString("utf8")}finally{ks(t)}}function ze(e,t){if(e.window==="minute")return t-6e4;if(e.window==="hour")return t-36e5;let n=new Date(t);return n.setHours(0,0,0,0),e.window==="week"&&n.setDate(n.getDate()-(n.getDay()+6)%7),n.getTime()}function wr(e,t){if(e.window==="minute"||e.window==="hour")return t;let n=new Date(ze(e,t));return n.setDate(n.getDate()+(e.window==="week"?7:1)),n.getTime()}var mr=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`};function Ot(e,t){return e.unit==="money"&&e.money?Es(t,e.money):`${e.unit==="usd"?"$":""}${Math.round(t*100)/100}`}function Es(e,t){let n=String(Math.max(0,Math.round(e))).padStart(t.digits+1,"0"),r=t.digits>0?n.slice(-t.digits):"";return`${t.sign}${n.slice(0,n.length-t.digits).replace(/\B(?=(\d{3})+(?!\d))/g,",")}${r&&!/^0+$/.test(r)?`.${r}`:""}`}var Je=class{constructor(t){this.dir=t}file(t){return Q(this.dir,`${mr(t)}.log`)}write(t){A(this.dir),En(this.file(t.t),JSON.stringify(t)),t.tr&&t.call&&(A(Q(this.dir,Rt)),As(Q(this.dir,Rt,yr(t.cap,t.key)),t.cap,{mode:384}))}settle(t,n,r=null){let o=Q(this.dir,Rt),s;try{s=gr(o)}catch{return}if(s.length===0)return;let a=new Set;for(let c of s)try{let u=Q(o,c);n-Ss(u).mtimeMs>Ct+36e5?At(u):a.add(_s(u,"utf8"))}catch{}let i=t.filter(c=>a.has(c.id)),l=i.length>0?this.resolve(i,n,r).done:[];for(let c of l)try{At(Q(o,c))}catch{}}read(t,n){let r=[],o=new Date(t);for(o.setHours(0,0,0,0);o.getTime()<=n;o.setDate(o.getDate()+1))for(let s of Os(this.file(o.getTime())).split(`
|
|
9
|
+
`))if(s)try{let a=JSON.parse(s);typeof a.t=="number"&&typeof a.cap=="string"&&typeof a.key=="string"&&r.push(a)}catch{}return r}usedIn(t,n,r,o=t.length,s=!1){let a=ze(n,r),i=new Map;for(let c=0;c<o;c++){let u=t[c];u.cap===n.id&&i.set(u.key,u.op==="x"||!i.has(u.key)||i.get(u.key).op==="x"?u:{...i.get(u.key),op:u.op})}let l=0;for(let c of i.values())c.op!=="x"&&c.t>=a&&(s||c.t<=r)&&(l+=c.n);return l}used(t,n,r=null){return this.resolve([t],n,r),this.usedIn(this.read(ze(t,n),n),t,n)}resolve(t,n,r=null){let o=new Set(t.map(d=>d.id)),s=Math.min(...t.map(d=>ze(d,n))),a=new Map;for(let d of this.read(s,n))o.has(d.cap)&&a.set(`${d.cap}\0${d.key}`,d);let i=[...a.values()].filter(d=>d.tr&&d.call&&(d.op==="x"?typeof d.seen=="number":d.op==="ask"||n-d.t<=Ct)),l=[];if(i.length===0)return{left:0,done:l};let c=i.length;i.sort((d,h)=>+(h.op==="x")-+(d.op==="x")||h.t-d.t);let u=new Set(r?.s?i.filter(d=>d.s===r.s).map(d=>d.tr):[]),f=d=>[...new Set(d.map(h=>h.tr))].filter(h=>!u.has(h)).slice(0,Rs),p=[...new Set([...u,...f(i.filter(d=>d.op==="x")),...f(i.filter(d=>d.op!=="x"))])],g=new Map(p.map(d=>[d,br(I(d,4*1024*1024),new Set(i.filter(h=>h.tr===d).map(h=>h.call)))]));for(let d of i){let h=g.get(d.tr);if(!h)continue;let E=h.get(d.call)??[],J=U=>(this.write(U),c--,void l.push(yr(d.cap,d.key)));d.op==="x"?E.length>1||E.length===1&&!E[0].refused?J({t:d.t,op:"ran",cap:d.cap,key:d.key,n:typeof d.was=="number"&&Number.isFinite(d.was)?d.was:0}):n-d.seen>=Ct&&J({t:d.t,op:"x",cap:d.cap,key:d.key,n:0}):E.length===1&&E[0].refused?r&&d.s!==void 0&&r.s===d.s&&(r.a??"")===(d.a??"")&&this.write({t:d.t,op:"x",cap:d.cap,key:d.key,n:0,tr:d.tr,call:d.call,seen:n,was:d.n,s:d.s,a:d.a??""}):E.length>0&&J({t:d.t,op:"ran",cap:d.cap,key:d.key,n:d.n})}return{left:c,done:l}}prune(t){try{let n=mr(t-Cs*864e5);for(let r of gr(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&At(Q(this.dir,r))}catch{}}};var yr=(e,t)=>bs("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32),Ns=new Set(["user-rejected","permission-rule","automode-blocked","automode-unavailable","cancelled"]);function Ps(e,t){return br(e,new Set([t])).get(t)??[]}function br(e,t){let n=new Map,r=new Map;for(let o of e.matchAll(/"tool_use_id":\s?"([^"\\]{1,200})"/g)){if(!t.has(o[1]))continue;let s=e.lastIndexOf(`
|
|
10
|
+
`,o.index)+1;(r.get(s)??r.set(s,new Set).get(s)).add(o[1])}for(let[o,s]of[...r].sort((a,i)=>a[0]-i[0])){let a=e.indexOf(`
|
|
11
|
+
`,o);try{let i=JSON.parse(e.slice(o,a<0?void 0:a));if(i.type!==void 0&&i.type!=="user")continue;let l=Array.isArray(i.message?.content)?i.message.content:[],c=i.toolDenialKind;for(let u of s){let f=l.find(g=>g&&g.type==="tool_result"&&g.tool_use_id===u);if(!f)continue;(n.get(u)??n.set(u,[]).get(u)).push({refused:f.is_error===!0&&(typeof c=="string"?Ns.has(c):i.toolUseResult==="User rejected tool use")})}}catch{for(let i of s)(n.get(i)??n.set(i,[]).get(i)).push({refused:!1})}}return n}function kr(e,t){return!e||!t?null:js(I(e,4*1024*1024),t)}function js(e,t){let n=e.indexOf(`"tool_use_id":"${t}"`);if(n<0)return null;let r=e.slice(e.lastIndexOf(`
|
|
12
12
|
`,n)+1,e.indexOf(`
|
|
13
13
|
`,n)<0?void 0:e.indexOf(`
|
|
14
|
-
`,n));try{let o=JSON.parse(r),
|
|
15
|
-
`)}function
|
|
16
|
-
`)}function
|
|
17
|
-
`)})}function
|
|
18
|
-
`)})}function
|
|
19
|
-
`)}o={...o,source:t.source};let f=
|
|
20
|
-
${
|
|
21
|
-
`))if(o.trim())try{let
|
|
22
|
-
${
|
|
23
|
-
`))if(g.includes(`"ts":"${
|
|
24
|
-
`,{mode:384})}catch{}return n}async function
|
|
25
|
-
`)}catch{return 0}return await Promise.all(
|
|
14
|
+
`,n));try{let o=JSON.parse(r),a=(Array.isArray(o.message?.content)?o.message.content:[]).find(c=>c.type==="tool_result"&&c.tool_use_id===t);if(!a)return null;let i=typeof a.content=="string"?a.content:JSON.stringify(a.content??"");return Ps(r,t)[0]?.refused===!0||a.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(i)?"no":"yes"}catch{return null}}import{createHash as ge}from"crypto";import{closeSync as xe,constants as Cr,fstatSync as Ys,mkdirSync as Zs,openSync as Dr,readdirSync as Xs,readSync as It,statSync as Qs,unlinkSync as Rr}from"fs";import{join as H}from"path";var Is="https://api.anvilcontrol.ai";function Et(e=process.env){let t=e.ANVIL_HOSTED_API_URL?.trim();return(t&&t.length>0?t:Is).replace(/\/+$/,"")}import{chmodSync as Qu,mkdirSync as ed,readFileSync as Ls,writeFileSync as td}from"fs";import{homedir as Ts}from"os";import{dirname as od,join as Ds}from"path";function Ms(){return process.env.ANVIL_WORKSPACE_KEYS_PATH?.trim()||Ds(Ts(),".anvil","workspace-keys.json")}function Fs(e=Ms()){let t;try{t=JSON.parse(Ls(e,"utf8"))}catch{return{}}if(!t||typeof t!="object")return{};let n={};for(let[r,o]of Object.entries(t))typeof o=="string"?o&&(n[r]={apiKey:o}):o&&typeof o=="object"&&typeof o.apiKey=="string"&&o.apiKey&&(n[r]=o);return n}var Ws=new Set(["gmail","googlemail","outlook","hotmail","live","msn","yahoo","ymail","rocketmail","icloud","me","mac","proton","protonmail","pm","aol","gmx","mail","zoho","fastmail","hey","qq","foxmail","163","126","yandex"]);function Nt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Hs(e){let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return Nt(e)||"workspace";let n=e.slice(0,t),o=e.slice(t+1).split(".")[0]??"",s=Ws.has(o.toLowerCase())?n:o;return Nt(s)||Nt(n)||"workspace"}function Us(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,Math.floor((Date.now()-t)/864e5))}function vr(e){let n=Object.entries(Fs(e)).find(([,s])=>s.active===!0);if(!n)return null;let[r,o]=n;return{email:r,workspace:Hs(r),apiKey:o.apiKey,...o.apiBaseUrl?{apiBaseUrl:o.apiBaseUrl}:{},keyAgeDays:Us(o.rememberedAt),...o.rememberedAt?{rememberedAt:o.rememberedAt}:{},...o.keyPrefix?{keyPrefix:o.keyPrefix}:{},...o.label?{label:o.label}:{},...o.workspaceId?{workspaceId:o.workspaceId}:{}}}import{accessSync as Bs,constants as Ks}from"fs";import{join as $r}from"path";var zs=["hook-removed","hooks-disabled","settings-unreadable","no-node","classifier-missing","rules-missing","modes-changed","rules-changed","install-record-changed","key-missing","node-fallback","spool-unwritable","other"],Js=/^claude\.[a-z0-9_]+(?:\.[a-z0-9_]+)*$/,qs=new Set(["hook-removed","hooks-disabled","settings-unreadable","no-node","classifier-missing","rules-missing"]),Vs=[[/^Anvil's seal key \(.*\) is missing/,"key-missing"],[/^modes\.json /,"modes-changed"],[/^compiled\.json /,"rules-changed"],[/^install\.json /,"install-record-changed"],[/\("disableAllHooks"\)/,"hooks-disabled"],[/^Anvil's hook was taken out of /,"hook-removed"],[/cannot be read, so Anvil cannot tell whether new sessions are checked/,"settings-unreadable"],[/^the Node Anvil was set up with is gone/,"node-fallback"],[/no Node 20 or later was found/,"no-node"],[/classifier (file is missing|did not load|answered a known call wrongly)/,"classifier-missing"],[/^no rules (are )?compiled/,"rules-missing"],[/cannot be written, so stops are not recorded/,"spool-unwritable"]];function _r(e){for(let[t,n]of Vs)if(t.test(e))return n;return"other"}var Gs=1440*60*1e3;function xr(e){let t=Date.parse(e.trim());return Number.isFinite(t)?t:null}function Sr(e){let{paths:t,now:n}=e,r=new Set,o=p=>{p&&r.add(_r(p))},s=null;try{s=C(t)}catch{s=null}let a={};try{let p=Z(t,s);o(p.problem);for(let g of e.kinds.slice(0,64))g.length<=200&&Js.test(g)&&(a[g]=ke.has(g)?M(p.value).includes(g===ye?"keep-anvil-on":"keep-keys-in")?"ghost":"enforce":se(p.value,g))}catch{}try{let p=X(t,e.fallbackTable,s);o(p.problem),p.value||r.add("rules-missing")}catch{r.add("rules-missing")}let i=y(t.install,4*1024*1024)===!0;if(i)try{for(let p of Be(t,s,e.home))o(p)}catch{}let l=e.hookBin??(i?t.bin:void 0);l&&y($r(l,"claude-hook-core.js"),64*1024*1024)!==!0&&r.add("classifier-missing");try{Bs(y(t.decisions,Number.MAX_SAFE_INTEGER)===null?t.dir:t.decisions,Ks.W_OK)}catch{(y(t.dir,Number.MAX_SAFE_INTEGER)!==null||i)&&r.add("spool-unwritable")}let c=null;try{let p=Ke(t),g=p?xr(p.at):null;if(p&&g!==null&&(c=g,n-g<Gs))for(let d of p.problems)_r(d)==="node-fallback"&&r.add("node-fallback")}catch{}let u=xr(I($r(t.state,"no-node"),64));u!==null&&(c===null||u>c)&&(r.add("no-node"),c=u);let f=zs.filter(p=>r.has(p));return{modes:a,ok:!f.some(p=>qs.has(p)),problems:f,hook_checked_at:c===null?null:new Date(c).toISOString()}}function Ar(){try{return/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]{1,20})?$/.test("0.10.0")?"0.10.0":null}catch{return null}}var ei=50,ti=50,ni=1e4,Se=512*1024,jt=30*6e4,ri="/v1/claude-code/machine",Mr=360*6e4,oi=_({confirmation_required:"confirmation_required",service_in_blocklist:"service_in_blocklist",resource_mutation_rate_exceeded:"resource_mutation_rate_exceeded",allowlist:"allowlist",spend_per_user:"spend_per_user",time_limit:"anvil_unavailable"});function Ve(e,t){let n=null;try{let s=fr(e,t);y(s,1024*1024)===!0&&(n=vr(s))}catch{n=null}if(n?.apiKey){let s=n.workspaceId?`ws:${ge("sha256").update(n.workspaceId).digest("hex").slice(0,12)}`:Er(n.apiKey);return{apiKey:n.apiKey,baseUrl:Or(n.apiBaseUrl||Et(e)),id:s,linkedAt:n.rememberedAt??null,source:"login"}}let r=e.ANVIL_API_KEY?.trim(),o=e.ANVIL_API_BASE_URL?.trim();return r?{apiKey:r,baseUrl:Or(o||Et(e)),id:Er(r),linkedAt:null,source:"env"}:null}function Or(e){return e.replace(/\/+$/,"")}function Er(e){return`sha256:${ge("sha256").update(e).digest("hex").slice(0,12)}`}function Nr(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\.(local|lan|home|localdomain)$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"")||"machine"}function si(e){return H(e.dir,"machine.json")}function Lt(e,t){let n=b(si(e))?.label;return Nr(typeof n=="string"&&n?n:t)}var fe=e=>typeof e=="string"&&e.length>0?e:null;function ii(e,t){return e===null||e==="hold-risky-actions"||Ne[e]?Pe(e,t):"your-rule"}function ai(e){if(!e)return"none";let t=e.replace(/-/g,"").toLowerCase();return/^[a-f0-9]{8,}$/.test(t)?t.slice(0,8):ge("sha256").update(e).digest("hex").slice(0,8)}function Fr(e,t){let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object"||n.v!==1)return null;let r=fe(n.action),o=n.verdict,s=n.mode,a=fe(n.ts);if(!r||!r.startsWith("claude.")||r.length>200||o!=="hold"&&o!=="block"||s!=="ghost"&&s!=="enforce"||n.delivered==="approved"||n.delivered==="declined"||n.scoped||!a||!Number.isFinite(Date.parse(a)))return null;let i=oi[fe(n.blocked_by)??""];if(!i)return null;let l=s==="ghost"?"would_block":o==="hold"?"held":"blocked",u=fe(n.blocked_by)==="time_limit"?s==="ghost"?"Not checked in time":"Held: could not be checked in time":l==="held"?"Held for your OK":l==="blocked"?"Blocked":o==="hold"?"Would have held":"Would have blocked",f=typeof n.ms=="number"&&Number.isFinite(n.ms)&&n.ms>=0?Math.round(n.ms):0;return{key:`cc/${t}/${ai(fe(n.session))}/${ge("sha256").update(e).digest("hex").slice(0,12)}`,action:r,decided_by:"claude_code_hook",outcome:l,mode:s,blocked_by:i,reason:`${u} \xB7 ${je(r)}`,rule_id:ii(fe(n.rule),r),decided_at:new Date(Date.parse(a)).toISOString(),duration_ms:Math.min(f,6e5)}}function Pr(e,t=null){return{v:2,identity:e,since:t,offset:0,ino:0,last_hash:null,registered:!1,registered_kinds:[],sent:0,rejected:0,last_push_ok:null,last_pull_ok:null,last_error:null,last_note:null,failures:0,next_try_at:0,report_next_at:0,last_report_ok:null,window_start:0,window_sent:0,skip:[],source:null,linked_at:null,last_pass_at:null}}function Wr(e,t){return H(e.state,"sync",`${ge("sha256").update(t).digest("hex").slice(0,16)}.json`)}function Hr(e){return H(e.state,"signed-out.json")}function qe(e){let t=b(Hr(e)),n=o=>typeof o=="string"&&Number.isFinite(Date.parse(o))?o:null,r=Array.isArray(t?.windows)?t.windows.filter(o=>Array.isArray(o)&&o.length===2&&n(o[0])!==null&&n(o[1])!==null):[];return{open:n(t?.open)??n(t?.at),windows:r}}function Ur(e,t,n,r){A(e.state);let o=n.filter(s=>r-Date.parse(s[1])<400*864e5).slice(-500);R(Hr(e),`${JSON.stringify(t!==null?{open:t,windows:o}:{windows:o})}
|
|
15
|
+
`)}function Br(e,t){try{let n=qe(e);n.open===null&&Ur(e,new Date(t).toISOString(),n.windows,t)}catch{}}function li(e,t){try{let n=qe(e);n.open!==null&&Date.parse(n.open)<=t&&Ur(e,null,[...n.windows,[n.open,new Date(t).toISOString()]],t)}catch{}}function Kr(e){let t=[];try{t=Xs(H(e.state,"sync")).filter(n=>n.endsWith(".json"))}catch{return null}for(let n of t){let r=b(H(e.state,"sync",n)),o=typeof r?.last_pull_ok=="string"?Date.parse(r.last_pull_ok):NaN;if(typeof r?.identity=="string"&&r.source==="env"&&Number.isFinite(o))return r.identity}return null}function Ce(e,t,n=Date.now()){let r=b(Wr(e,t));if(!r||r.v!==2||r.identity!==t)return Pr(t);let o={...Pr(t),...r,v:2,identity:t},s=Number.isFinite(o.next_try_at)?Math.min(o.next_try_at,n+jt):0,a=typeof o.report_next_at=="number"&&Number.isFinite(o.report_next_at)?Math.min(o.report_next_at,n+Mr):0,i=Number.isFinite(o.window_start)&&o.window_start<=n?o.window_start:0,l=Array.isArray(o.skip)?o.skip.filter(f=>Array.isArray(f)&&f.length===2&&f.every(p=>typeof p=="string"&&Number.isFinite(Date.parse(p)))).slice(-500):[],c=f=>typeof f=="string"&&Number.isFinite(Date.parse(f))?f:null,u=Array.isArray(o.registered_kinds)?o.registered_kinds.filter(f=>typeof f=="string").slice(0,256):[];return{...o,next_try_at:s,report_next_at:a,last_report_ok:c(o.last_report_ok),window_start:i,window_sent:i===0?0:o.window_sent,skip:l,linked_at:c(o.linked_at),last_pass_at:c(o.last_pass_at),registered_kinds:u}}function ci(e,t){let n=Wr(e,t.identity);Zs(H(e.state,"sync"),{recursive:!0,mode:448}),R(n,`${JSON.stringify(t,null,2)}
|
|
16
|
+
`)}function Tt(e){return H(e.state,"mode-pending.json")}function ui(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.action=="string"&&t.action.startsWith("claude.")&&(t.mode==="ghost"||t.mode==="enforce")&&typeof t.at=="string"&&typeof t.identity=="string"&&(t.from===null||t.from==="ghost"||t.from==="enforce")&&(t.origin===void 0||t.origin==="link")}function pe(e){let t=b(Tt(e));return{v:2,changes:Array.isArray(t?.changes)?t.changes.filter(ui):[]}}var ee=e=>`${e.identity}|${e.action}|${e.at}`;function zr(e,t){A(e.state);let n=H(e.state,"mode-pending.lock"),r=!1;for(let o=0;o<40&&!r;o++)try{xe(Dr(n,"wx",384)),r=!0}catch{try{Date.now()-Qs(n).mtimeMs>1e4&&Rr(n)}catch{}let s=Date.now()+25;for(;Date.now()<s;);}try{return t()}finally{if(r)try{Rr(n)}catch{}}}function di(e,t){t.length!==0&&zr(e,()=>{let n=pe(e).changes,r=(a,i)=>a.identity===i.identity&&a.action===i.action,o=t.map(a=>{let i=n.find(l=>r(l,a));return i?{...a,from:i.from}:a}),s=n.filter(a=>!t.some(i=>r(a,i)));R(Tt(e),`${JSON.stringify({v:2,changes:[...s,...o]},null,2)}
|
|
17
|
+
`)})}function fi(e,t){t.size!==0&&zr(e,()=>{let n=pe(e).changes.filter(r=>!t.has(ee(r)));R(Tt(e),`${JSON.stringify({v:2,changes:n},null,2)}
|
|
18
|
+
`)})}function pi(e){if(!/^[\x21-\x7e]+$/.test(e.apiKey))return"the key has characters no key has";let t;try{t=new URL(e.baseUrl)}catch{return"the workspace address isn't a URL"}if(t.username||t.password)return"the workspace address carries a password";let n=["localhost","127.0.0.1","[::1]"].includes(t.hostname)||t.hostname.endsWith(".localhost")||t.hostname.endsWith(".test");return t.protocol!=="https:"&&!(t.protocol==="http:"&&n)?"the workspace address isn't https":null}function gi(e){if(e instanceof Error&&e.name==="TimeoutError")return"timed out";let t=e?.cause?.code;return typeof t=="string"&&/^[A-Z][A-Z0-9_]{1,40}$/.test(t)?t:"no answer"}async function Ae(e,t,n,r,o){let s=pi(t);if(s)return{status:0,body:null,retryAfterMs:null,error:s};try{let a=await e.fetch(`${t.baseUrl}${r}`,{method:n,headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"application/json","User-Agent":"anvil-claude-sync",...o===void 0?{}:{"Content-Type":"application/json"}},...o===void 0?{}:{body:JSON.stringify(o)},signal:AbortSignal.timeout(e.timeoutMs??ni)}),i=await a.text().catch(()=>""),l=null;try{l=i?JSON.parse(i):null}catch{l=null}let c=Number(a.headers.get("retry-after"));return{status:a.status,body:l,retryAfterMs:Number.isFinite(c)&&c>0?c*1e3:null,error:null}}catch(a){return{status:0,body:null,retryAfterMs:null,error:gi(a)}}}function z(e,t,n="anvil"){if(e.status===0)return`could not reach the workspace (${e.error})`;if(e.status===401||e.status===403)return t.source==="env"?`the workspace refused ANVIL_API_KEY (HTTP ${e.status}): set a valid key, or unset it and run ${n} login`:`the workspace refused this machine's key (HTTP ${e.status}): run ${n} login again`;if(e.status===429)return"rate limited by the workspace (HTTP 429)";let r=e.body&&typeof e.body=="object"?e.body.code:null;return`HTTP ${e.status}${typeof r=="string"&&/^[a-z][a-z0-9_]{0,39}$/.test(r)?` (${r})`:""}`}function hi(e){return e?it(e).filter(t=>t.startsWith("claude.")).sort().slice(0,ti):[]}async function jr(e,t,n,r,o=!1){return Ae(e,t,"POST","/v1/modes",o?{action:n,mode:"ghost",if_not_stronger:!0}:{action:n,mode:r,reason:`anvil claude ${r} (Claude Code on ${e.machine})`})}async function mi(e,t,n){for(let r=0;r<e.length;r+=t)if((await Promise.all(e.slice(r,r+t).map(n))).includes(!1))return!1;return!0}function Ir(e){if(e.status!==200||!e.body||typeof e.body!="object"||!Array.isArray(e.body.modes))return null;let t=new Map;for(let n of e.body.modes){if(!n||typeof n!="object")continue;let r=n;typeof r.action=="string"&&t.set(r.action,{explicit:r.explicit===!0,effective:r.explicit===!0&&r.mode==="enforce"?"enforce":"ghost"})}return t}function yi(e){return e.status===0||e.status===401||e.status===403||e.status===429||e.status>=500}var Lr={linked:!1,sent:0,rejected:0,waiting:0,modesPulled:!1,modesChanged:!1,error:null};async function Dt(e){if(!e.identity)return Lr;try{return await wi(e,e.identity)}catch(t){return{...Lr,linked:!0,error:`the sync failed: ${t instanceof Error?t.message:String(t)}`}}}async function wi(e,t){let{paths:n}=e,r=e.now(),o=Ce(n,t.id,r),s=o.since!==null;if(!s){let m=t.linkedAt&&Number.isFinite(Date.parse(t.linkedAt))?t.linkedAt:new Date(r).toISOString();o={...o,since:m}}let a=H(n.state,"sync-active.json"),i=b(a),l=typeof i?.at=="string"&&Number.isFinite(Date.parse(i.at))?i.at:null,c=t.linkedAt!==null&&Number.isFinite(Date.parse(t.linkedAt))?t.linkedAt:null;if(s&&typeof i?.id=="string"&&i.id!==t.id&&l!==null&&Date.parse(l)<r){let m=c!==null&&Date.parse(c)>Date.parse(l)&&Date.parse(c)<r?c:new Date(r).toISOString();o={...o,skip:[...o.skip,[l,m]].slice(-500)}}let u=!(e.force===!0&&t.source==="env"&&typeof i?.id=="string"&&i.id!==t.id);if(i?.id!==t.id&&u){A(n.state);let m=c!==null&&l!==null&&Date.parse(c)>Date.parse(l)&&Date.parse(c)<=r?c:s?new Date(r).toISOString():o.since;R(a,`${JSON.stringify({id:t.id,at:m})}
|
|
19
|
+
`)}o={...o,source:t.source};let f=qe(n);c!==null&&f.open!==null&&Date.parse(f.open)<=Date.parse(c)&&li(n,Date.parse(c));for(let m of qe(n).windows)o.skip.some(S=>S[0]===m[0]&&S[1]===m[1])||(o={...o,skip:[...o.skip,m].slice(-500)});o={...o,linked_at:c??o.linked_at,last_pass_at:new Date(r).toISOString()};let p=!e.force&&r<o.next_try_at,g=hi(X(n,e.fallbackTable).value),d=[],h=null,E=pe(n).changes,J=o.registered?g.filter(m=>!o.registered_kinds.includes(m)):g,U=null;if(g.length>0&&(J.length>0||E.length>0)){let m=await Ae(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);U=Ir(m),U||(h=m)}if(!h&&U&&J.length>0){let m=Z(n).value,S=!o.registered&&m!==null&&m.source!=="workspace"?g.filter(k=>re(m,k)==="enforce"&&U.get(k)?.effective!=="enforce"):[];di(n,S.map(k=>({action:k,mode:"enforce",at:new Date(r).toISOString(),identity:t.id,from:U.get(k)?.effective??null,origin:"link"})));let w=null;await mi(J.filter(k=>!S.includes(k)&&!U.get(k)?.explicit),4,async k=>{let me=await jr(e,t,k,"ghost",!0);return me.status>=200&&me.status<300?!0:(w??=me,!1)})?o={...o,registered:!0,registered_kinds:[...new Set([...o.registered_kinds,...J])]}:w&&yi(w)?h=w:w&&d.push(`could not register the kinds of action yet (${z(w,t,e.cli)})`)}let Vt=pe(n).changes;if(!h&&Vt.length>0){let m=new Set,S=[];for(let w of Vt){if(w.identity!==t.id){m.add(ee(w)),d.push("a mode change made under another account was not sent to this one");continue}if(h)break;if(!pe(n).changes.some(me=>ee(me)===ee(w)))continue;let Qe=U?.get(w.action);if(w.from!==null&&Qe&&Qe.effective!==w.from){m.add(ee(w)),d.push(`your workspace changed ${w.action} after you set it offline, so its mode stands`);continue}let k=await jr(e,t,w.action,w.mode);k.status>=200&&k.status<300?(m.add(ee(w)),w.origin==="link"&&S.push(w.action)):k.status===400||k.status===422?(m.add(ee(w)),d.push(`the workspace refused a mode change for ${w.action} (${z(k,t,e.cli)})`)):h=k}fi(n,m),S.length>0&&d.push(`at sign-in, this machine's enforce for ${S.length===1?je(S[0]):`${S.length} kinds of action`} went to your workspace`)}let Ze=!1,Gt=!1,Yt=()=>pe(n).changes.some(m=>m.identity===t.id);if(!h&&g.length>0&&!Yt()){let m=await Ae(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);Ir(m)?Yt()||(Ze=!0,Gt=_i(n,m.body.modes,new Date(r)),o={...o,last_pull_ok:new Date(r).toISOString()},bi(n,r)):h=m}let Xe=h!==null&&(h.status===0||h.status===401||h.status===403);!Xe&&r>=o.report_next_at&&(o=await ki(e,t,o,g,Ze,r,d));let Zt=0,Xt=0,Qt=null;if(!p&&!Xe){let m=await $i(e,t,o,r);o=m.state,Zt=m.sent,Xt=m.rejected,Qt=m.failed}let q=Qt??(Xe&&!p?h:null);if(q){let m=o.failures+1,S=q.status===429&&q.retryAfterMs?Math.min(q.retryAfterMs,jt):q.status===0?6e4:Math.min(6e4*2**(m-1),jt);o={...o,failures:m,last_error:z(q,t,e.cli),next_try_at:r+S}}else p?h&&(o={...o,last_error:z(h,t,e.cli)}):o={...o,failures:0,last_error:h?z(h,t,e.cli):null,next_try_at:0};let vo=q?z(q,t,e.cli):h?z(h,t,e.cli):p?o.last_error:null;return d.length>0&&(o={...o,last_note:d[d.length-1]}),ci(n,o),{linked:!0,sent:Zt,rejected:Xt,waiting:Mt(n,o,e.machine),modesPulled:Ze,modesChanged:Gt,error:vo}}function bi(e,t){try{A(e.state),R(H(e.state,dr),String(t))}catch{}}async function ki(e,t,n,r,o,s,a){let i;try{i=Sr({paths:e.paths,kinds:r,now:s,...e.home?{home:e.home}:{},...e.fallbackTable?{fallbackTable:e.fallbackTable}:{},...e.hookBin?{hookBin:e.hookBin}:{}})}catch{return n}let l=await Ae(e,t,"POST",ri,{machine:e.machine,version:Ar(),modes:i.modes,ok:i.ok,problems:i.problems,hook_checked_at:i.hook_checked_at,modes_pulled:o});return l.status>=200&&l.status<300?{...n,last_report_ok:new Date(s).toISOString()}:l.status===404||l.status===405?{...n,report_next_at:s+Mr}:((l.status===400||l.status===422)&&a.push(`the workspace refused this machine's health report (${z(l,t,e.cli)})`),n)}function Pt(e){let t;try{t=Dr(e,Cr.O_RDONLY|Cr.O_NONBLOCK)}catch{return null}try{let n=Ys(t);if(n.isFile())return{fd:t,ino:n.ino,size:n.size}}catch{}return xe(t),null}function Jr(e,t){let n=Pt(e.decisions);if(t.ino!==0){if(n&&n.ino===t.ino&&n.size>=t.offset)return[{...n,start:t.offset}];let a=Pt(`${e.decisions}.1`);if(a&&a.ino===t.ino&&a.size>=t.offset)return n?[{...a,start:t.offset},{...n,start:0}]:[{...a,start:t.offset}];a&&xe(a.fd)}let r=Pt(`${e.decisions}.1`),o=r&&t.last_hash?Tr(r.fd,r.size,t.last_hash):null;if(r&&o!==null)return n?[{...r,start:o},{...n,start:0}]:[{...r,start:o}];let s=n&&t.last_hash?Tr(n.fd,n.size,t.last_hash):null;return s!==null&&n?(r&&xe(r.fd),[{...n,start:s}]):[...r?[{...r,start:0}]:[],...n?[{...n,start:0}]:[]]}function qr(e){for(let t of e)try{xe(t.fd)}catch{}}function Tr(e,t,n){let r=0,o=Buffer.alloc(0);for(;r<t;){let s=Math.min(Se,t-r),a=Buffer.alloc(s);It(e,a,0,s,r);let i=o.length>0?Buffer.concat([o,a]):a,l=r-o.length,c=0;for(let u=0;u<i.length;u++)if(i[u]===10){if(Vr(i.toString("utf8",c,u))===n)return l+u+1;c=u+1}o=i.subarray(c),o.length>4*Se&&(o=Buffer.alloc(0)),r+=s}return null}function Vr(e){return ge("sha256").update(e).digest("hex").slice(0,16)}function vi(e,t,n){for(let r=t;r<n;){let o=Math.min(Se,n-r),s=Buffer.alloc(o);It(e,s,0,o,r);let a=s.indexOf(10);if(a>=0)return r+a+1;r+=o}return null}function Gr(e,t,n){let r=Math.min(Se,n-t);if(r<=0)return{lines:[],skipTo:null};let o=Buffer.alloc(r);It(e,o,0,r,t);let s=[],a=0;for(let i=0;i<r;i++)o[i]===10&&(s.push({text:o.toString("utf8",a,i),end:t+i+1}),a=i+1);return{lines:s,skipTo:s.length===0&&r===Se?vi(e,t+r,n):null}}function Yr(e,t){try{let n=JSON.parse(e).ts;if(typeof n!="string")return!1;let r=Date.parse(n);return t.since&&!(r>=Date.parse(t.since))?!1:!t.skip.some(([o,s])=>r>=Date.parse(o)&&r<Date.parse(s))}catch{return!1}}async function $i(e,t,n,r){let o=n;r-o.window_start>=6e4&&(o={...o,window_start:r,window_sent:0});let s=Jr(e.paths,o),a=0,i=0,l=null;try{e:for(let c of s){o={...o,ino:c.ino,offset:c.start};let u=c.start;for(;u<c.size;){let{lines:f,skipTo:p}=Gr(c.fd,u,c.size);if(f.length===0){if(p===null)break;i++,o={...o,rejected:o.rejected+1,offset:p,last_note:"an unreadable stretch of the spool was skipped"},u=p;continue}for(let g of f){let d=Yr(g.text,o)?Fr(g.text,e.machine):null;if(d){if(o.window_sent>=ei)break e;let h=await Ae(e,t,"POST","/v1/decision",d);if(h.status>=200&&h.status<300)a++,o={...o,sent:o.sent+1,window_sent:o.window_sent+1,last_push_ok:new Date(r).toISOString()};else if(h.status===400||h.status===422)i++,o={...o,rejected:o.rejected+1,last_note:`a stop was refused: ${z(h,t,e.cli)}`};else{l=h;break e}}o={...o,offset:g.end,last_hash:Vr(g.text)}}u=f[f.length-1].end}}}finally{qr(s)}return{state:o,sent:a,rejected:i,failed:l}}function Mt(e,t,n){let r=Jr(e,t);try{let o=0;for(let s of r)o+=Gr(s.fd,s.start,s.size).lines.filter(a=>Yr(a.text,t)&&Fr(a.text,n)!==null).length;return o}finally{qr(r)}}function _i(e,t,n){let r={};for(let u of t){if(!u||typeof u!="object")continue;let f=u;typeof f.action!="string"||!f.action.startsWith("claude.")||f.explicit===!0&&(f.mode==="enforce"||f.mode==="ghost")&&(r[f.action]={mode:f.mode})}let o=Z(e),s=o.value,a=new Set([...Object.keys(r),...Object.keys(s?.services?.[P]?.actions??{}),...Object.keys(F)]),i=o.source==="strict"||oe(s)||s?.day_one===!0,l={version:1,kill_switch:!1,default_mode:"ghost",services:{[P]:{actions:r}},updated_at:n.toISOString(),source:"workspace",...i?{day_one:!0}:{},...o.source!=="strict"&&M(s).length>0?{turned_off:M(s)}:{}},c=[...a].some(u=>re(s,u)!==re(l,u))||s?.source!=="workspace"||s?.day_one===!0!==i;return(c||o.source!=="file")&&nr(e,l),c}var T=e=>e.toLocaleString("en-US"),Ft=e=>e.mode==="ghost"&&(e.verdict==="hold"||e.verdict==="block")&&!e.scoped;function Wt(e,t){let n=[],r=`${I(`${e.decisions}.1`,2097152)}
|
|
20
|
+
${I(e.decisions,4194304)}`;for(let o of r.split(`
|
|
21
|
+
`))if(o.trim())try{let s=JSON.parse(o);s.ts&&Date.parse(s.ts)>=t&&n.push(s)}catch{}return n}function xi(e,t){let n=e?Date.parse(e):NaN;if(!Number.isFinite(n))return null;let r=Math.max(0,Math.round((t.getTime()-n)/1e3));return r<90?`${r}s ago`:r<5400?`${Math.round(r/60)} min ago`:r<129600?`${Math.round(r/3600)} h ago`:`${Math.round(r/86400)} d ago`}function Si(e,t,n,r,o,s=B(!1),a=i=>`${o} ${i}`){if(!t)return Kr(e)!==null?N("Dashboard",`synced by a key this terminal does not have (ANVIL_API_KEY where Claude Code runs) \xB7 ${a("login")} here to change modes from this terminal`,s):null;let i=Ce(e,t.id,r.getTime()),l=i.since===null?0:Mt(e,i,n),c=xi(i.last_pull_ok,r),u=[a("open"),`this machine shows as ${n}`];return t.source==="env"&&u.push("using ANVIL_API_KEY"),u.push("sends stops, not commands"),c&&u.push(`synced ${c}`),l>0&&u.push(`${T(l)} ${l===1?"stop":"stops"} waiting to send`),i.last_error?u.push(i.last_error):i.last_note&&u.push(i.last_note),N("Dashboard",u.join(" \xB7 "),s)}var Ai="what every Claude Code session spends",Zr=e=>e.split(/, and |; /).map(t=>t.trim()).filter(Boolean);function Ci(e,t=B(!1),n=nt()){let r=l=>l==="claude.bash.prod.target"?"changes through a production account":F[l]?.text??l,o=[...e.floor.filter(l=>l.verdict==="block").flatMap(l=>Zr(l.short)),...e.held.filter(l=>e.blocking.has(l)).map(r)],s=[...e.held.filter(l=>!e.blocking.has(l)).map(r),...e.dayOne?Zr(gn.text):[],...e.floor.filter(l=>l.verdict==="hold").map(l=>l.short)],a=e.all>0&&e.held.length>=e.all&&!e.ownOff?.length,i=[...be.filter(l=>e.ownOff?.includes(l.id)).map(l=>l.short),...e.ownOff?.includes(an)?["risky steps on production"]:[],...e.off.map(l=>F[l]?.slug??l)];return[...o.length>0?ne(v.blocked,"Blocks",o,t,n):[],...s.length>0?ne(v.held,"Holds",s,t,n):[],...ne(v.watching,"Watches",a?"nothing else: every risky kind is held":"every other risky action \xB7 it runs, with a note",t,n,9,t.dim),...i.length>0?ne(" ","Off",i,t,n,9,t.dim):[],...e.spend!==void 0?ne(v.watching,"Counts",`${Ai}${e.spend?` \xB7 ${e.spend}`:""}`,t,n,9,t.dim):[]]}function Ri(e,t=B(!1),n=V,r=[],o="What it does now"){return rn(o,[...Ci(e,t,nt(n)),...r],t,n)}function Oi(e,t){let n=new Set;for(let r of e?.policies??[])if(!(r.origin==="baseline"||!ae(r,t))){for(let o of r.rules)if(o.intent==="block")for(let s of o.applies_to??[])n.add(s)}return n}var Xr=Object.keys(F).filter(e=>!["claude.bash.unclassified","claude.tool.other","claude.mcp.call","claude.agent.helper"].includes(e)&&!ke.has(e));function Ei(e,t,n){return Xr.filter(r=>st(t,r,e?Le(e,r,n):null)==="enforce")}function Ni(e,t,n){return Xr.filter(r=>st(t,r,e?Le(e,r,n):null)==="off")}var Pi=["claude.bash.deploy","claude.bash.db.destructive","claude.bash.secrets.print","claude.bash.fs.delete_recursive","claude.bash.deps.add"];function Qr(e,t){return t&&!Pi.some(n=>un(e,n,Le(t,n,null)))?null:hn(e)}function ji(e,t){return mn(e)+(Qr(t,e)?1:0)}function Ii(e,t,n){let r=e.filter(o=>o.floor).length;return`stopped ${T(e.length)}${r?` (${T(r)} by Anvil's own rules)`:""}${t?` \xB7 allowed once ${T(t)}`:""}${n?` \xB7 declined ${T(n)}`:""} \xB7 ${eo(e)}`}function eo(e){let t=new Map;for(let n of e)t.set(n.slug??"other",(t.get(n.slug??"other")??0)+1);return[...t.entries()].sort((n,r)=>r[1]-n[1]).slice(0,5).map(([n,r])=>`${n} ${T(r)}`).join(" \xB7 ")}function Li(e,t){return e.window==="minute"||e.window==="hour"?"rolling":e.window==="day"?"resets at midnight":`resets ${new Date(wr(e,t.getTime())).toLocaleDateString("en-US",{weekday:"long"})}`}function Ti(e,t,n,r=B(!1),o=null){let s=(e?.policies??[]).filter(i=>ae(i,o)).flatMap(i=>i.caps??[]);if(s.length===0)return[];let a=new Je(Re(t.dir,"caps"));return s.map((i,l)=>{let c;try{c=a.used(i,n.getTime())}catch{c=null}let u=i.window==="minute"||i.window==="hour"?"":` \xB7 ${Li(i,n)}`;return N(l===0?"Caps":"",`${i.text} \xB7 ${c===null?"can't be counted now: its calls are held":`${Ot(i,c)} of ${Ot(i,i.limit)} used`}${u}${i.unit!=="calls"&&i.unit!=="money"?" \xB7 an estimate":""}`,r)})}function Di(e,t){let n=["settings.local.json","settings.json"].map(r=>{let o=Re(e,".claude",r);return{file:`.claude/${r}`,sandbox:b(o)?.sandbox,anvil:t.whole?.includes(o)===!0}});return Ln(n,{managed:t.managed,open:t.open===!0,userOn:t.rules.some(r=>r.project===null&&r.layer!=="hook")})}function Mi(e,t=B(!1),n=null){let r=x(Re(e.dir,jn),C(e),4194304);if(r.status!=="ok"&&r.status!=="unkeyed")return[];let o=Array.isArray(r.value.rules)?r.value.rules:[],s=n!==null&&o.some(i=>i.project===null&&i.entries.length>0)?Di(n,r.value):null,a=o.map((i,l)=>N(l===0?"Locks":"",s&&i.project===null&&i.entries.length>0&&("off"in s?i.layer!=="hook":i.layer==="hook")?`${i.text} \xB7 ${"off"in s?Tn(s.off):"locked in this project"}`:i.layer==="both"?`${i.text} \xB7 locked`:i.layer==="part"?`${i.text} \xB7 partly locked: ${i.why}`:`${i.text} \xB7 ${In(i)}: ${i.why}`,t));return s&&"widened"in s?[...a,N("Sandbox",Dn(s),t)]:a}function to(e,t,n,r="anvil",o=null,s=!1){if(n)return`${lt("Anvil isn't working")} run in a terminal: ${j(r)} on`;let a=t.toISOString().slice(0,10),i=ve(Re(e.counts,a)),l=`${I(`${e.decisions}.1`,2*1024*1024)}
|
|
22
|
+
${I(e.decisions,4*1024*1024)}`,c=0;for(let g of l.split(`
|
|
23
|
+
`))if(g.includes(`"ts":"${a}`))try{let d=JSON.parse(g);d.mode==="enforce"&&(d.delivered==="deny"||d.delivered==="ask")&&(c+=1)}catch{}let u=0;try{u=sr(e,C(e),t.getTime()).length}catch{u=0}let f=[...i>0?[`${T(i)} checked`]:[],...c>0?[`${T(c)} stopped`]:[],...o?.today?[o.text]:[]],p=[...s?["model rules can't hear this session's model"]:[],...f.length>0?[`${f.join(" \xB7 ")} today`]:[],...o&&!o.today?[o.text]:[],...u>0?[`${T(u)} waiting for your OK \xB7 in a terminal: ${j(r)} allow`]:[]];return[lt("Anvil on"),...p.length>0?[p.join(" \xB7 ")]:[]].join(" ")}function Fi(e,t,n=B(!1)){let r=t.toISOString().slice(0,10),o=ve(Re(e.counts,r)),s=Wt(e,Date.parse(`${r}T00:00:00.000Z`)),a=s.filter(Ft),i=s.filter(p=>p.mode==="enforce"&&(p.delivered==="deny"||p.delivered==="ask")),l=i.filter(p=>p.delivered==="ask").map(p=>kr(p.transcript,p.call)),c=s.filter(p=>p.delivered==="approved").length+l.filter(p=>p==="yes").length,u=s.filter(p=>p.delivered==="declined").length+l.filter(p=>p==="no").length,f=[`${T(o)} ${o===1?"action":"actions"} checked`];return i.length>0&&f.push(Ii(i,c,u)),a.length>0&&f.push(`would have stopped ${T(a.length)} \xB7 ${eo(a)}`),i.length===0&&a.length===0&&f.push("nothing it would stop"),N("Today",f.join(" \xB7 "),n)}function no(e){let t=B(!1);if(!e.table)return[tt("Report","not checking",t),"",Ee(v.problem,e.installed?"Not working \xB7 Claude's calls are held until it's fixed":"No rules compiled, so nothing is checked"),"",...(e.problems??[]).map(s=>N("Problem",s)),...(e.problems??[]).length>0?[""]:[],rt(`${j(e.cli)} on`,e.installed?"fix it, in your own terminal":"turn it on")];let{text:n}=yn(e.table,e.modes),r=Ei(e.table,e.modes,null),o=e.problems??[];return[tt("Report",o.length>0?"on, with a problem":"on",t),"",o.length>0?Ee(v.problem,"On, with a problem"):Ee(v.on,"On. Every action Claude Code takes is checked before it runs."),"",...o.map(s=>N("Problem",s)),...o.length>0?[""]:[],...Ri({floor:pn(e.table,M(e.modes)),held:r,blocking:Oi(e.table,null),off:Ni(e.table,e.modes,null),ownOff:M(e.modes),dayOne:Qr(e.modes,e.table)!==null,all:n==="enforce"?r.length:Number.POSITIVE_INFINITY,spend:null},t),"",N("Rules",String(ji(e.table,e.modes))),...Mi(e.paths,t,e.dir??null),...e.advisor?[N("Advisor",e.advisor)]:[],...Ti(e.table,e.paths,e.now),Fi(e.paths,e.now),...[Si(e.paths,e.identity,e.machine,e.now,e.cli)].filter(s=>s!==null),"",rt(`${j(e.cli)} rules edit`,"change rules, in your terminal")]}import{randomUUID as Hi}from"crypto";import{existsSync as io,mkdirSync as ao,readFileSync as lo,writeFileSync as Ui}from"fs";import{join as he}from"path";import{existsSync as Vd,mkdirSync as Gd,readFileSync as Yd,writeFileSync as Zd}from"fs";import{homedir as Qd}from"os";import{join as tf}from"path";import{randomUUID as rf}from"crypto";var Wi="https://app.anvilcontrol.ai";function Ht(e=process.env){let t=e.ANVIL_HOSTED_DASHBOARD_URL?.trim();return(t&&t.length>0?t:Wi).replace(/\/+$/,"")}import{lookup as Kd}from"dns/promises";function Ut(){return/^(1|true|on|yes)$/i.test((process.env.ANVIL_FUNNEL_DISABLED||"").trim())||/^(1|true|on|yes)$/i.test((process.env.DO_NOT_TRACK||"").trim())}function ro(e,t,n,r){try{if(Ut()||!t||!/^https?:\/\//i.test(t)||!n)return Promise.resolve();let o=new AbortController,s=setTimeout(()=>o.abort(),1200);typeof s.unref=="function"&&s.unref();let a=r!=null&&Object.keys(r).length>0;return fetch(t.replace(/\/+$/,"")+"/api/funnel",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a?{fid:n,event:e,props:r}:{fid:n,event:e}),signal:o.signal}).then(()=>{clearTimeout(s)},()=>{clearTimeout(s)})}catch{return Promise.resolve()}}var oo={claude_on:["mode","scope","linked","plugin"],replay_run:["window","sessions","actions","would_stop","active_days"],decisions_daily:["day","calls","held","blocked","would","approved","errors"]};var Bi=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD","JENKINS_URL","TEAMCITY_VERSION"],Bt=e=>e!==void 0&&e.trim()!==""&&!/^(0|false|no|off)$/i.test(e.trim());function co(e){return Bt(e.DO_NOT_TRACK)||Bt(e.ANVIL_FUNNEL_DISABLED)?!1:!Bi.some(t=>Bt(e[t]))}function uo(e){return he(e,".anvil","telemetry-notice")}function fo(e){return io(uo(e))}function Ki(e){return!Number.isFinite(e)||e<=0?"0":e<10?"1-9":e<100?"10-99":e<1e3?"100-999":e<1e4?"1k-9k":"10k+"}function zi(e){let t=he(e,".anvil","claude","telemetry-id");try{let r=lo(t,"utf8").trim();if(/^c_[a-f0-9]{32}$/.test(r))return r}catch{}let n=`c_${Hi().replace(/-/g,"")}`;try{ao(he(e,".anvil","claude"),{recursive:!0,mode:448}),Ui(t,`${n}
|
|
24
|
+
`,{mode:384})}catch{}return n}async function Ji(e,t,n,r){try{if(!co(n)||Ut()||!fo(r)||!oo[e].every(o=>o in t)||Object.keys(t).some(o=>!oo[e].includes(o)))return;await ro(e,Ht(n),zi(r),t)}catch{}}function so(e){return he(e.state,"telemetry.json")}function qi(e,t){let n=ve(he(e.counts,t)),r=Date.parse(`${t}T00:00:00.000Z`),o=r+864e5,s=Wt(e,r).filter(i=>i.ts&&Date.parse(i.ts)<o),a=i=>s.filter(i).length;return{day:t,calls:Ki(n),held:a(i=>i.mode==="enforce"&&i.verdict==="hold"&&(i.delivered==="deny"||i.delivered==="ask")),blocked:a(i=>i.mode==="enforce"&&i.verdict==="block"&&i.delivered!=="pause"),would:a(Ft),approved:a(i=>i.delivered==="approved"),errors:a(i=>i.verdict==="error")}}async function po(e,t,n,r){if(!co(t)||!fo(n))return 0;let o=r.toISOString().slice(0,10),s=b(so(e))?.last_daily??null,a="";try{a=new Date(Date.parse(lo(uo(n),"utf8").trim())).toISOString().slice(0,10)}catch{return 0}let i=[];for(let l=7;l>=1;l--){let c=new Date(Date.parse(`${o}T00:00:00.000Z`)-l*864e5).toISOString().slice(0,10);c<a||s!==null&&c<=s||io(he(e.counts,c))&&i.push(c)}if(i.length===0)return 0;try{ao(e.state,{recursive:!0}),R(so(e),`${JSON.stringify({last_daily:i[i.length-1]})}
|
|
25
|
+
`)}catch{return 0}return await Promise.all(i.map(l=>Ji("decisions_daily",qi(e,l),t,n))),i.length}var D=te(Qi(import.meta.url)),Jt=Ge(D)==="bin"&&Ge(te(D))==="claude"&&Ge(te(te(D)))===".anvil"?te(D):void 0,Ye=!Jt&&Ge(D)==="bin"&&Vi(O(te(D),".claude-plugin","plugin.json"))?O(D,"baseline.json"):void 0,Kt=6e4,go=5e3,ea=30*6e4,ta=720*6e4,na=780*6e4;function ra(e){try{return process.kill(e,0),!0}catch{return!1}}function oa(e,t){let n=b(e),r=typeof n?.pid=="number"?n.pid:0,o=typeof n?.started=="number"?n.started:0;if(r>0&&o>0)return r===process.pid||!ra(r)||t-o>=na;try{return t-qt(e).mtimeMs>1e4}catch{return!0}}function sa(e,t){A(e.state);let n=O(e.state,"sync.lock"),r=O(e.state,`sync.lock.${process.pid}.${t}.tmp`);try{Xi(r,JSON.stringify({pid:process.pid,started:t}),{mode:384})}catch{return!1}try{for(let o=0;o<2;o++)try{return Gi(r,n),!0}catch(s){if(s.code!=="EEXIST"||!oa(n,t))return!1;try{Zi(n,`${n}.stale.${process.pid}`),zt(`${n}.stale.${process.pid}`)}catch{return!1}}return!1}finally{try{zt(r)}catch{}}}function ko(e){let t=O(e.state,"sync.lock");try{b(t)?.pid===process.pid&&zt(t)}catch{}}function ia(e,t){let n=0,r=o=>new Date(t-o).toISOString().slice(0,10);for(let o of[O(e.counts,r(0)),O(e.counts,r(864e5)),e.decisions])try{n=Math.max(n,qt(o).mtimeMs)}catch{}return n}function aa(e){try{return qt(e.decisions).size}catch{return 0}}function la(e,t){if(t)return!0;if(y(e.install,1024*1024)!==!0)return!1;try{let n=JSON.parse(Yi(e.install,"utf8"));return Object.keys(n.installs??{}).length>0}catch{return!1}}function ho(e,t){try{A(e.state),R(O(e.state,ur),String(Math.round(t)))}catch{}}function mo(e,t){return{paths:e.paths,identity:t,machine:Lt(e.paths,e.hostname),fetch:e.fetch,now:e.now,home:e.home,...e.pluginBaseline?{fallbackTable:e.pluginBaseline,hookBin:te(e.pluginBaseline)}:{}}}async function ca(e){let{paths:t}=e,n=e.now();if(!sa(t,n))return"locked";let r="idle",o=e.now()+6e4;try{let s=0,a=-1;for(;;){let l=e.now(),c=Ve(e.env,e.home);if(!c)return Br(t,l),r="unlinked",o=l+10*6e4,r;let u=aa(t),f=Ce(t,c.id,l).next_try_at;if((l-s>=Kt||u!==a||f>0&&l>=f)&&(a=u,await Dt(mo(e,c)),l-s>=Kt&&(s=l,await(e.sendDaily??po)(t,e.env,e.home,new Date(l)))),ho(t,e.now()+3*go+Kt),!la(t,e.pluginBaseline!==void 0)){r="off";break}if(e.now()-ia(t,e.now())>ea){r="idle";break}if(e.now()-n>ta){r="lifetime";break}await e.sleep(go)}let i=Ve(e.env,e.home);return i&&await Dt(mo(e,i)),o=r==="off"?e.now()+10*6e4:0,r}finally{ho(t,o),ko(t)}}function ua(e,t=null){let n=g=>typeof g=="string"&&/^[\w@./ -]{1,60}$/.test(g),r=b(e.install),o=r?.cli;ct(n(o)?o:"anvil");let s=X(e,Ye??O(D,"baseline.json")),a=Z(e),i=s.value,l=[i?.cli,o].find(n)??"anvil";ct(l);let c=Object.values(r?.installs??{}).filter(g=>g&&typeof g.command=="string"&&!mt(g)).map(g=>`Anvil's hook in ${g.settings_path} can't start (its files are gone), so new sessions are not checked: run ${$("on")}`),u=C(e),f=[...new Set([...c,s.problem,a.problem,...Be(e,u,Oe()),...cr(e,Oe(),u),...Ke(e)?.problems??[]].filter(g=>!!g))],p=no({paths:e,table:i,modes:a.value,identity:Ve(process.env,Oe()),machine:Lt(e,wo()),now:new Date,cli:l,problems:f,installed:Object.keys(r?.installs??{}).length>0,advisor:t,dir:process.env.CLAUDE_PROJECT_DIR||process.cwd()});process.stdout.write(`${p.join(`
|
|
26
26
|
`)}
|
|
27
|
-
`)}async function
|
|
28
|
-
`)}catch{process.stdout.write(`\u{1F539} Anvil isn't working \u{1F539} run in a terminal: ${
|
|
29
|
-
`)}process.exit(0)}if(process.argv.includes("--status")){try{
|
|
30
|
-
`)}process.exit(0)}try{await
|
|
27
|
+
`)}async function da(e){let t=Date.now(),n={spend:null,unheard:!1};try{n=(await import(bo(O(D,"claude-meter.js")).href)).statusFacts(e,t)}catch{}let r=c=>typeof c=="string"&&/^[\w@./ -]{1,60}$/.test(c),o=b(e.install),s=o?.cli,a=r(s)?s:"anvil",i=X(e,Ye??O(D,"baseline.json")),l=Object.values(o?.installs??{}).some(c=>c&&typeof c.command=="string"&&!mt(c));return to(e,new Date(t),!i.value||l?"not working":null,a,n.spend,n.unheard)}var yo=()=>import(bo(O(D,"claude-meter.js")).href).catch(()=>({}));async function fa(){let e=Jt?Te(Jt):On(Oe());for(let t of["SIGTERM","SIGINT","SIGHUP"])process.on(t,()=>{ko(e),process.exit(0)});if(process.argv.includes("--statusline")){try{process.stdout.write(`${await da(e)}${(await yo()).advisorTail?.(e)??""}
|
|
28
|
+
`)}catch{process.stdout.write(`\u{1F539} Anvil isn't working \u{1F539} run in a terminal: ${$("on")}
|
|
29
|
+
`)}process.exit(0)}if(process.argv.includes("--status")){try{ua(e,(await yo()).advisorRow?.(e,process.cwd())??null)}catch(t){process.stdout.write(`Anvil could not read its status: ${t instanceof Error?t.message:String(t)}
|
|
30
|
+
`)}process.exit(0)}try{await ca({paths:e,env:process.env,home:Oe(),hostname:wo(),fetch:globalThis.fetch,now:()=>Date.now(),sleep:t=>new Promise(n=>setTimeout(n,t)),...Ye?{pluginBaseline:Ye}:{}})}catch{}process.exit(0)}process.argv[1]&&/claude-sync\.js$/.test(process.argv[1])&&fa();export{ea as IDLE_EXIT_MS,ta as MAX_LIFE_MS,Kt as PULL_EVERY_MS,go as TICK_MS,ho as holdSpawns,ia as lastActivity,ko as releaseLock,ca as runSyncLoop,sa as takeLock};
|