@useanvil/claude-code 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +217 -1
- package/dist/claude-conditions.js +6 -6
- package/dist/claude-hook-core.js +84 -82
- package/dist/claude-hook.js +37 -35
- package/dist/claude-meter.js +55 -35
- package/dist/claude-sync.js +26 -24
- package/dist/cli/claude-main.js +7873 -1373
- package/docs/coding-agents/YOUR-RULES.md +293 -49
- package/package.json +1 -1
package/dist/claude-sync.js
CHANGED
|
@@ -1,28 +1,30 @@
|
|
|
1
|
-
import{existsSync as Ai,linkSync as Ci,readFileSync as Ri,renameSync as Ni,statSync as Bt,unlinkSync as Wt,writeFileSync as Oi}from"fs";import{homedir as _e,hostname as no}from"os";import{basename as Je,dirname as Z,join as I}from"path";import{fileURLToPath as Ei,pathToFileURL as Pi}from"url";import{createHmac as zo,randomBytes as mt,timingSafeEqual as Ko}from"crypto";import{closeSync as Ln,existsSync as ht,fsyncSync as Dn,linkSync as Jo,mkdirSync as Mn,openSync as Fn,readdirSync as qo,readFileSync as ie,unlinkSync as Hn,writeSync as Wn}from"fs";import{basename as Vo,dirname as Te,join as E}from"path";var v={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"},so="Anvil. Claude Code",K=80,io=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${Ze(l)}\x1B[0m`}}var J=B(!1),ao=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ze(e){return e.replace(ao,"")}function Yt(e){return Ze(e).length}function Zt(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function Xt(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 lo(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?Xt(o,t):[o];n.push(...s.slice(0,-1)),r=s[s.length-1]}return r&&n.push(r),n.length>0?n:[""]}function Ae(e,t,n=J){return` ${n.mark(e)} ${t}`}function M(e,t,n=J){return` ${n.dim(e.padEnd(io))}${t}`}function Xe(e,t,n=J,r=K){let o=` ${so} \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 Qe(e=K){return e-7}function Qt(e,t,n=J,r=K,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,f=o.note?` ${o.note}`:"",u=Math.max(1,s-4-c-1-f.length-(f?2:1)),d=` ${i("\u256D\u2500 ")}${l}${n.bold(e)} ${i("\u2500".repeat(u))}${f?`${n.dim(f)}${i(" \u2500\u256E")}`:i("\u2500\u256E")}`,g=t.map(h=>{let xe=Yt(h)>a?Zt(Ze(h),a):h;return` ${i("\u2502")} ${xe}${" ".repeat(Math.max(0,a-Yt(xe)))} ${i("\u2502")}`});return[d,...g,` ${i(`\u2570${"\u2500".repeat(s-2)}\u256F`)}`]}function X(e,t,n,r=J,o=K-7,s=9,a=i=>i){let i=e===null?0:2,l=Math.max(10,o-i-s);return(typeof n=="string"?Xt(n,l):lo(n,l)).map((f,u)=>u===0?`${e===null?"":`${r.mark(e)} `}${r.bold(t.padEnd(s))}${a(f)}`:`${" ".repeat(i+s)}${a(f)}`)}function co(e,t,n,r=J,o="blue",s=K){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(Zt(n,Math.max(0,c))):""}`}function et(e,t,n=J,r=0,o="Next"){return co(o,e.padEnd(t?r:0),t??"",n,"blue")}var N="claude";function q(e){return e==="ghost"||e==="enforce"?e:null}function Q(e,t){if(!e||typeof e!="object"||e.kill_switch===!0)return"ghost";let n=q(e.services?.[N]?.actions?.[t]?.mode);return n||(q(e.default_mode)??"ghost")}function tt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[N]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function ee(e){return e==null?!0:typeof e!="object"||e.kill_switch===!0?!1:e.day_one===!0}function tn(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:tt(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[N]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[N]?.actions??{}};for(let a of n)s[a]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:q(o.default_mode)??"ghost",services:{...o.services??{},[N]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function uo(e){return!e||typeof e!="object"||e.kill_switch===!0?!1:q(e.default_mode)==="enforce"?!0:Object.values(e.services?.[N]?.actions??{}).some(t=>q(t?.mode)==="enforce")}var nt="claude.agent.controls";function te(e,t){return t===nt&&uo(e)?"enforce":Q(e,t)}var en={off:0,ghost:1,enforce:2};function fe(e,t){return e===null?t:t===null?e:en[t]>en[e]?t:e}function nn(e,t){return!e||typeof e!="object"?null:q(e.services?.[N]?.actions?.[t]?.mode)??(q(e.default_mode)==="enforce"?"enforce":null)}function rt(e,t,n,r=!1){let s=fe(nn(e,t),n)??(r&&ee(e)?"enforce":te(e,t));return e?.kill_switch===!0&&s==="enforce"?"ghost":s}function rn(e,t,n){return fe(nn(e,t),n)===null&&ee(e)&&te(e,t)!=="enforce"}function _(e){return Object.assign(Object.create(null),e)}var Ce=[{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)"}}],fo="home and project wipes and force-pushes to main",po=`always blocking ${fo}`,ea=new Map(Ce.map(e=>[e.id,e]));var on=new Set(Ce.flatMap(e=>Object.keys(e.slugs)));var sn=_({"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 an(e){let t=new Set(go(e));return Ce.filter(n=>!Object.entries(sn).some(([r,o])=>o.includes(n.id)&&t.has(r)))}var pe=new Set([nt,"claude.bash.secrets.expose"]);function go(e){let t=new Set(e.policies.filter(n=>n.origin==="baseline").flatMap(n=>n.rules.map(r=>r.id)));return Object.keys(sn).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:"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"}}),ln={slug:"catastrophic",text:"cluster, cloud and database destroys, and cloud-credential prints"};function cn(e){if(!ee(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 Re=_({"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 Ne(e,t){return e&&Re[e]?Re[e].slug:!e||e==="hold-risky-actions"?F[t]?.slug??t:e.replace(/@.*$/,"")}function Oe(e){return F[e]?.text??e}function un(e){let t=new Set(on);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(Ne(null,o));else t.add(Ne(r.id,""));return t.size}function ot(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 dn(e,t){let n=ot(e).filter(o=>F[o]),r=n.filter(o=>te(t,o)==="enforce");return{enforced:r,text:r.length===0?"ghost":r.length===n.length?"enforce":`${r.length} enforced, rest ghost`}}var st="anvil-claude";function O(e){let t=e.trim();return t===st||t.endsWith(` ${st}`)||t.endsWith(`/${st}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var fn="\u{1F539}",it=e=>`${fn} ${e} ${fn}`;var pn="anvil";function at(e){pn=typeof e=="string"&&/^[\w@./ -]{1,60}$/.test(e)?e:"anvil"}var $=e=>`${O(pn)} ${e}`;import{spawnSync as oc}from"child_process";import{createHash as ic}from"crypto";import{chmodSync as lc,existsSync as cc,lstatSync as Oo,mkdirSync as uc,readdirSync as dc,readFileSync as Eo,readlinkSync as Po,realpathSync as Cn,rmdirSync as fc,statSync as pt,unlinkSync as pc,writeFileSync as gc}from"fs";import{dirname as Io,join as hc,resolve as jo}from"path";import{createHash as Kl}from"crypto";import{appendFileSync as _o,closeSync as kn,constants as bn,fstatSync as vn,mkdirSync as xo,openSync as $n,readdirSync as ql,readFileSync as So,readSync as _n,renameSync as Ao,statSync as xn,unlinkSync as Vl,writeFileSync as Co}from"fs";import{homedir as Ro}from"os";import{dirname as Zl,join as j}from"path";var gn;var mo="its file (claude-conditions.js) is missing or won't load";function mn(e,t){return gn?gn.capMoved(e,t):`Anvil can't read amounts: ${mo}`}import{existsSync as Aa,readdirSync as Ca,statSync as Ra}from"fs";import{dirname as Oa,isAbsolute as Ea,join as Pa,posix as Ia,resolve as ja}from"path";import{posix as wn}from"path";var ho=null;function Ee(){return ho??process.platform==="win32"}var yn=/^([A-Za-z]):(.*)$/s,yo=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function lt(e,t){let n=wn.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function ne(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 ct(e){if(!Ee())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(yn.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/${ne(o[1],n).toLowerCase()}${o[2]?`/${ne(o[2],n).toLowerCase()}`:""}`;return lt(l,ne(o[3]??"",n).toLowerCase())}let s=yn.exec(t);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?lt(`/${s[1].toLowerCase()}`,ne(l,n).toLowerCase()):null}let a=yo.exec(t);if(a)return lt(`/${a[1].toLowerCase()}`,ne(a[2]??"",n).toLowerCase());let i=ne(t,n).toLowerCase();if(i.startsWith("/")){let l=wn.normalize(i);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return i}function wo(e){return ct(e)??e}function ut(e){return!Ee()||typeof e!="string"||e===""?e:wo(e)}import{domainToASCII as Ba}from"url";var Za="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as ml,readdirSync as hl,realpathSync as yl}from"fs";import{basename as bl,dirname as kl,join as vl}from"path";var ft="anvil-claude-compiled/1";function vo(e,t){return!e.applies_to||e.applies_to.length===0||e.applies_to.includes(t)}function ge(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&$o(t,e.project_dir))}function Pe(e,t,n){let r=null;for(let o of e.policies)if(!(o.origin==="baseline"||!ge(o,n))){for(let s of o.rules)s.mode&&vo(s,t)&&(r=fe(r,s.mode));o.off?.includes(t)&&(r=fe(r,"off"))}return r}function $o(e,t){let n=ut(e),r=ut(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}function Sn(e=Ro()){return Ie(j(e,".anvil","claude"))}function Ie(e){return{dir:e,bin:j(e,"bin"),compiled:j(e,"compiled.json"),modes:j(e,"modes.json"),decisions:j(e,"decisions.jsonl"),install:j(e,"install.json"),state:j(e,"state"),approvals:j(e,"approvals"),counts:j(e,"counts"),backups:j(e,"backups")}}var No=3500;function y(e,t=8*1024*1024){try{let n=xn(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function dt(e,t=8*1024*1024){let n;try{n=$n(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),s=0;for(;s<r.size;){let a=_n(n,o,s,r.size-s,s);if(a===0)break;s+=a}return o.subarray(0,s)}finally{kn(n)}}function me(e){try{let t=xn(e);return t.isFile()?t.size:0}catch{return 0}}function An(e,t){let n=t.endsWith(`
|
|
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(`
|
|
2
2
|
`)?t:`${t}
|
|
3
|
-
`;if(Buffer.byteLength(n)>
|
|
4
|
-
`);
|
|
5
|
-
`,"wx");let o=!1;try{t?
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`;
|
|
9
|
-
`))if(
|
|
3
|
+
`;if(Buffer.byteLength(n)>Wo)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`);jo(e,n,{mode:384})}function A(e){Io(e,{recursive:!0,mode:448})}function j(e,t){if(y(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=xn(e,"r")}catch{return""}try{let r=vn(n).size,o=Math.max(0,r-t),i=r-o;if(i<=0)return"";let l=Buffer.alloc(i);_n(n,l,0,i,o);let s=l.toString("utf8");if(o>0){let a=s.indexOf(`
|
|
4
|
+
`);s=a<0?"":s.slice(a+1)}return s}finally{kn(n)}}function O(e,t,n=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Mo(r,t,{mode:n}),be(r,e)}function be(e,t){for(let n=0;;n++)try{Do(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(To(e,"utf8"))}catch{return null}}var gc=256*1024,hc=1024*1024;var On="locks.json";var En=e=>e.only===!0?"held by Anvil only":"held by Anvil, not locked";var Cn={filesystem:["denyWrite","denyRead"],network:["deniedDomains"]};function Nn(e,t){if(t.managed==="on"||t.managed==="off")return null;let n=e.filter(i=>Rn(i.sandbox)),r=n.find(i=>typeof i.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(i=>!i.anvil&&Object.entries(i.sandbox).some(([l,s])=>!(l in Cn)||Rn(s)&&Object.keys(s).some(a=>!Cn[l].includes(a)))):void 0;if(o){let i=n.find(l=>typeof l.sandbox.autoAllowBashIfSandboxed=="boolean");return{widened:o.file,unasked:i?.sandbox.autoAllowBashIfSandboxed===!0}}return r&&!t.userOn?{on:r.file}:null}var Pn=e=>`held by Anvil only in this project: ${e} turns Claude Code's sandbox off`,Ln=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 Rn=e=>!!e&&typeof e=="object"&&!Array.isArray(e);var Jo="/.anvil/claude/bin/claude-hook.js",qo=/[\\/]\.anvil[\\/]claude[\\/]bin[\\/]claude-hook\.js/i;var le=class extends Error{constructor(t){super(t),this.name="SettingsRefused"}};function In(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 Vo(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 Go=e=>{let t=Vo(e);return t!==null&&(t.includes(Jo)||qo.test(t))};function Yo(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 Tn(e){return Array.isArray(e.args)?{command:e.command,args:e.args}:e.command}function Zo(e){return ft(e,64*1024*1024)}function Dn(e){try{if(!Ho(e).isSymbolicLink())return e}catch{return e}try{return jn(e)}catch(t){let n=t.code;throw n==="ENOENT"?new le(`${e} is a link to ${Xo(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 Xo(e){let t=Ko(e);try{t=jn(t)}catch{}return zo(t,Bo(e))}function Mn(e){try{let t=Zo(Dn(e));if(t===null)return null;let n=In(t.toString("utf8"),e).hooks?.PreToolUse;if(!Array.isArray(n))return null;let r=n.flatMap(o=>{let i=o&&typeof o=="object"?o.hooks:void 0;return Array.isArray(i)?i.filter(Go):[]});return r.length===0?null:r.every(o=>o.onFailure==="block")}catch{return null}}function Fn(e,t){let n;try{n=Dn(e)}catch{return"unreadable"}let r;try{r=gt(n)}catch{return"no-file"}if(!r.isFile()||r.size>4*1024*1024)return"unreadable";let o;try{o=In(Uo(n,"utf8"),e)}catch{return"unreadable"}if(o.disableAllHooks===!0)return"disabled";let i=o.hooks?.PreToolUse;return Array.isArray(i)&&i.some(s=>{let a=s&&typeof s=="object"?s:null,c=a?.matcher;return(c===void 0||c===""||c==="*")&&Array.isArray(a?.hooks)&&a.hooks.some(u=>Yo(u,t))})?"present":"missing"}function Qo(e){let t=e.trim().match(/'(?:[^']|'\\'')*'|[^\s']+/g),n=i=>i.startsWith("'")?i.slice(1,-1).replace(/'\\''/g,"'"):i,r=t?t.findIndex(i=>i==="/bin/sh"||i==="sh"):-1,o=t&&r>=0&&(t[r+3]==="PreToolUse"||t[r+3]==="SessionStart")?1:0;if(t&&r>=0&&t[r+3+o]==="||"){let i=r>0&&r%5===0;for(let l=0;i&&l<r;l+=5)i=t[l]==="["&&(t[l+1]==="-s"||t[l+1]==="-f")&&t[l+3]==="]"&&t[l+4]==="&&"&&n(t[l+2])===n(t[r+1]);if(r===0||i)return[n(t[r+1]),n(t[r+2])]}return!t||t.length!==2?null:[n(t[0]),n(t[1])]}function es(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 Qo(t)}function ht(e){let t=es(e);if(!t)return!1;try{return gt(t[0]).isFile()&>(t[1]).isFile()}catch{return!1}}var B="_seal";function Fe(e){return I(e.dir,"seal.key")}function ce(e,t){return I(e.state,"lkg",t)}function C(e){let t=Fe(e);if(y(t,1024)!==!0)return null;try{let n=ue(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function kt(e){return C(e)?"ok":y(Fe(e),1024)===null?"missing":"damaged"}var De=class extends Error{};function We(e,t){return`Anvil's seal key (${Fe(e)}) is ${t==="damaged"?"damaged":"missing"}`}function is(e){let t=C(e);if(t)return t;let n=kt(e);if(n==="damaged"||vt(e))throw new De(`${We(e,n)}; run ${x("on")} to restore it`);let{key:r,created:o}=ls(e,!1);return o&&as(e,r),r}function Wn(e,t,n){let r=Jn(e,n,384);try{Vn(r,t),Kn(r)}finally{Bn(r)}}function ls(e,t){zn(e.dir,{recursive:!0,mode:448});let n=Fe(e),r=I(e.dir,`.seal.key.${process.pid}.${mt(4).toString("hex")}.tmp`);Wn(r,`${mt(32).toString("hex")}
|
|
5
|
+
`,"wx");let o=!1;try{t?be(r,n):rs(r,n),o=!0}catch(l){let s=l.code??"";if(s!=="EEXIST"){if(t||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(s))throw l;try{Wn(n,ue(r,"utf8"),"wx"),o=!0}catch(a){if(a.code!=="EEXIST")throw a}}}finally{try{qn(r)}catch{}}let i=C(e);if(!i)throw new De(`${We(e,"damaged")}; run ${x("on")} to restore it`);return{key:i,created:o}}function as(e,t){let n=[[e.modes,ke],[e.compiled,Zn],[e.install,void 0]];for(let[r,o]of n)if(y(r,8*1024*1024)===!0)try{let i=ue(r,"utf8");if(i.includes(`"${B}"`))continue;let l=JSON.parse(i);if(!l||typeof l!="object"||Array.isArray(l))continue;let s=`${JSON.stringify(bt(t,l),null,2)}
|
|
6
|
+
`;ae(r,s),o&&ae(ce(e,o),s)}catch{}if(y(e.modes)===null&&y(ce(e,ke))===null){let r=`${JSON.stringify(bt(t,nt()),null,2)}
|
|
7
|
+
`;ae(e.modes,r),ae(ce(e,ke),r)}}function wt(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>wt(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(t===0&&r===B)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${wt(e[r],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function Gn(e,t){return ts("sha256",e).update(wt(t)).digest("hex")}function Ie(e){if(!(B in e))return e;let t={...e};return delete t[B],t}function bt(e,t){let n=Ie(t);return{...n,[B]:Gn(e,n)}}function cs(e,t){let n=t[B];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let r;try{r=Gn(e,t)}catch{return!1}return ns(Buffer.from(n,"hex"),Buffer.from(r,"hex"))}function ae(e,t,n=384){zn(Te(e),{recursive:!0,mode:448});let r=I(Te(e),`.${ss(e)}.${process.pid}.${Date.now().toString(36)}.${mt(3).toString("hex")}.tmp`);try{let o=Jn(r,"w",n);try{Vn(o,t),Kn(o)}finally{Bn(o)}be(r,e)}catch(o){try{qn(r)}catch{}throw o}}function $(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(ue(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:t?B in o?cs(t,o)?{status:"ok",value:Ie(o)}:{status:"changed",value:Ie(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:Ie(o)}}function Yn(e,t,n,r){let o=is(e),i=`${JSON.stringify(bt(o,n),null,2)}
|
|
8
|
+
`;ae(t,i),r&&ae(ce(e,r),i)}var ke="modes.json",Zn="compiled.json";function Xn(e,t){Yn(e,e.modes,t,ke)}function vt(e){return yt(I(e.bin,"claude-hook.sh"))||us(e)}function us(e){let t=n=>{try{return os(n).slice(0,200).some(r=>r.endsWith(".json")&&y(I(n,r),65536)===!0&&ue(I(n,r),"utf8").includes(`"${B}"`))}catch{return!1}};if(t(I(e.state,"lkg"))||t(I(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(ue(n,"utf8").includes(`"${B}"`))return!0}catch{}return!1}var Me=_({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function Hn(e=new Date){return rn(null,"enforce","all",e)}function Y(e,t=C(e),n={}){if(!t){let l=kt(e);if(n.installed===!0||l==="damaged"||vt(e))return{value:Hn(),source:"strict",problem:`${We(e,l)}, so every rule is enforced until \`${x("on")}\` restores it`};let s=$(e.modes,null);return{value:s.status==="unkeyed"?s.value:null,source:"unkeyed",problem:null}}let r=$(e.modes,t);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${Me[r.status]??"cannot be used"}`,i=$(ce(e,ke),t);return i.status==="ok"?{value:i.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:Hn(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${x("on")}\` resets it`}}function Z(e,t,n=C(e),r={}){let o=c=>!!c&&typeof c=="object"&&c.format===pt&&Array.isArray(c.policies),i=()=>{if(!t)return null;let c=$(t,null);return c.status==="unkeyed"&&o(c.value)?c.value:null};if(!n){let c=kt(e),u=r.installed===!0||c==="damaged"||vt(e),f=$(e.compiled,null),p=f.status==="unkeyed"&&o(f.value)?f.value:null;return u?{value:null,source:"strict",problem:`${We(e,c)}: \`${x("on")}\` restores it`}:{value:p??i(),source:"unkeyed",problem:null}}let l=$(e.compiled,n);if(l.status==="ok"&&o(l.value))return{value:l.value,source:"file",problem:null};let s=`compiled.json ${l.status==="ok"?"is not a rules table":Me[l.status]??"cannot be used"}`,a=$(ce(e,Zn),n);return a.status==="ok"&&o(a.value)?{value:a.value,source:"last-good",problem:`${s}; Anvil keeps the rules it last compiled`}:l.status==="missing"&&a.status==="missing"&&y(e.install)===null&&r.installed!==!0?{value:i(),source:"file",problem:null}:{value:null,source:"strict",problem:`${s}, and so is Anvil's own copy: \`${x("on")}\` recompiles them`}}function Un(e,t){return t&&(e===t||e.startsWith(`${t}/`))?`~${e.slice(t.length)}`:e}function He(e,t,n,r=!0){let o=$(e.install,t,4194304);if(o.status==="missing")return[];if(o.status==="unreadable")return[`install.json ${Me.unreadable}`];if(t&&o.status!=="ok")return[`install.json ${Me[o.status]??"cannot be used"}`];let i=(o.status==="ok"||o.status==="unkeyed")&&o.value.installs&&typeof o.value.installs=="object"?Object.values(o.value.installs):[],l=[];for(let f of i.slice(0,64)){if(!f||typeof f.real_path!="string"||typeof f.command!="string")continue;let p=Fn(f.settings_path??f.real_path,Tn(f)),g=Un(f.settings_path??f.real_path,n);p!=="present"&&(p==="no-file"&&f.scope==="project"&&!yt(Te(Te(f.real_path)))||(p==="disabled"?r&&l.push(`${g} turns off every Claude Code hook ("disableAllHooks"), so new sessions are not checked`):p==="missing"||p==="no-file"?l.push(`Anvil's hook was taken out of ${g} outside \`${x("off")}\`, so new sessions are not checked`):l.push(`${g} cannot be read, so Anvil cannot tell whether new sessions are checked`)))}let s=o.status==="ok"||o.status==="unkeyed"?o.value:null,a=[...Array.isArray(s?.package_dirs)?s.package_dirs:[],...typeof s?.package_dir=="string"?[s.package_dir]:[]].filter(f=>typeof f=="string"&&f.startsWith("/")).slice(0,16),c=a[a.length-1]??"",u=/[\\/]@useanvil[\\/]claude-code[\\/]?$/.test(c)?"npx @useanvil/claude-code":"npx @useanvil/sdk";return i.length>0&&a.length>0&&a.every(f=>!yt(I(f,"package.json")))&&l.push(`the Anvil package that installed this hook is gone (${Un(c,n)}): keep Anvil with ${L(u)} on, or remove it with ${L(u)} off --purge`),l}function ds(e){return I(e.state,"health.json")}function Ue(e){let t=$(ds(e),null,65536);return t.status==="unkeyed"&&t.value.v===1&&Array.isArray(t.value.problems)?t.value:null}import{accessSync as rr,constants as or,existsSync as _t,statfsSync as fs}from"fs";import{createHash as au,randomBytes as cu}from"crypto";import{readdirSync as er,renameSync as du,unlinkSync as fu}from"fs";import{join as xt}from"path";var mu=600*1e3,yu=1440*60*1e3;function Qn(e){return xt(e.state,"pending")}function tr(e,t,n){let r=[];try{r=er(Qn(e)).filter(i=>i.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let i of r){let l=xt(Qn(e),i),s=$(l,t,64*1024);s.status!=="ok"||s.value.v!==2||!Array.isArray(s.value.stops)||!(Date.parse(s.value.expires_at)>=n)||o.push({hold:s.value,file:l})}return o.sort((i,l)=>Date.parse(l.hold.created_at)-Date.parse(i.hold.created_at))}function nr(e,t){let n=[];try{n=er(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 i=$(xt(e.approvals,o),t,65536);i.status!=="missing"&&(i.status!=="ok"||i.value.v!==2||!Array.isArray(i.value.stops))&&r++}return r}var $t=(e,t)=>e===t?"~":e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e;function sr(e,t,n){let r=[],o=b(e.install),i=o&&o.installs&&typeof o.installs=="object"?Object.values(o.installs):[];for(let s of i)!s||typeof s.settings_path!="string"||Mn(s.settings_path)===!1&&r.push(`the hook in ${$t(s.settings_path,t)} was installed without onFailure, so Claude Code runs a call when Anvil's check fails or stalls: run ${x("on")} to add it`);try{_t(e.decisions)?rr(e.decisions,or.W_OK):_t(e.dir)&&rr(e.dir,or.W_OK)}catch{r.push(`${$t(e.decisions,t)} cannot be written, so stops are not recorded and the counts here read low`)}try{let s=fs(_t(e.dir)?e.dir:t);Number(s.bavail)*Number(s.bsize)<1024*1024&&r.push(`the disk holding ${$t(e.dir,t)} is full, so stops are not recorded and a held call cannot be allowed once`)}catch{}let l=n?nr(e,n):0;return l>0&&r.push(`${l===1?"an approval was":`${l} approvals were`} written outside \`${x("allow")}\`; ${l===1?"it releases":"they release"} nothing (${x("on")} removes ${l===1?"it":"them"})`),r}import{spawn as Au}from"child_process";import{readFileSync as Ru,statSync as Ou}from"fs";import{join as ps}from"path";var ir="sync-next",lr="sync-pulled";var Pu=5*6e4;function ar(e,t){return e.ANVIL_WORKSPACE_KEYS_PATH?.trim()||ps(t,".anvil","workspace-keys.json")}var Lu=10*6e4;import{join as Se}from"path";import{createHash as gs}from"crypto";import{closeSync as hs,constants as cr,fstatSync as ms,openSync as ys,readdirSync as ur,readFileSync as ws,readSync as bs,statSync as ks,unlinkSync as St,writeFileSync as vs}from"fs";import{join as X}from"path";var xs=9,dr=4*1024*1024,At=6*36e5,Ct="waiting",_s=4;function $s(e){let t;try{t=ys(e,cr.O_RDONLY|cr.O_NONBLOCK)}catch(n){if(n.code==="ENOENT")return"";throw n}try{let n=ms(t);if(!n.isFile())throw new Error("the day's cap count is not a regular file");if(n.size>dr)throw new Error(`the day's cap count is over ${dr/1024/1024} MB`);let r=Buffer.alloc(n.size),o=0;for(;o<n.size;){let i=bs(t,r,o,n.size-o,o);if(i===0)break;o+=i}return r.subarray(0,o).toString("utf8")}finally{hs(t)}}function Be(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 gr(e,t){if(e.window==="minute"||e.window==="hour")return t;let n=new Date(Be(e,t));return n.setDate(n.getDate()+(e.window==="week"?7:1)),n.getTime()}var fr=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`};function Rt(e,t){return e.unit==="money"&&e.money?Ss(t,e.money):`${e.unit==="usd"?"$":""}${Math.round(t*100)/100}`}function Ss(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 Ke=class{constructor(t){this.dir=t}file(t){return X(this.dir,`${fr(t)}.log`)}write(t){A(this.dir),An(this.file(t.t),JSON.stringify(t)),t.tr&&t.call&&(A(X(this.dir,Ct)),vs(X(this.dir,Ct,pr(t.cap,t.key)),t.cap,{mode:384}))}settle(t,n,r=null){let o=X(this.dir,Ct),i;try{i=ur(o)}catch{return}if(i.length===0)return;let l=new Set;for(let c of i)try{let u=X(o,c);n-ks(u).mtimeMs>At+36e5?St(u):l.add(ws(u,"utf8"))}catch{}let s=t.filter(c=>l.has(c.id)),a=s.length>0?this.resolve(s,n,r).done:[];for(let c of a)try{St(X(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 i of $s(this.file(o.getTime())).split(`
|
|
9
|
+
`))if(i)try{let l=JSON.parse(i);typeof l.t=="number"&&typeof l.cap=="string"&&typeof l.key=="string"&&r.push(l)}catch{}return r}usedIn(t,n,r,o=t.length,i=!1){let l=Be(n,r),s=new Map;for(let c=0;c<o;c++){let u=t[c];u.cap===n.id&&s.set(u.key,u.op==="x"||!s.has(u.key)||s.get(u.key).op==="x"?u:{...s.get(u.key),op:u.op})}let a=0;for(let c of s.values())c.op!=="x"&&c.t>=l&&(i||c.t<=r)&&(a+=c.n);return a}used(t,n,r=null){return this.resolve([t],n,r),this.usedIn(this.read(Be(t,n),n),t,n)}resolve(t,n,r=null){let o=new Set(t.map(d=>d.id)),i=Math.min(...t.map(d=>Be(d,n))),l=new Map;for(let d of this.read(i,n))o.has(d.cap)&&l.set(`${d.cap}\0${d.key}`,d);let s=[...l.values()].filter(d=>d.tr&&d.call&&(d.op==="x"?typeof d.seen=="number":d.op==="ask"||n-d.t<=At)),a=[];if(s.length===0)return{left:0,done:a};let c=s.length;s.sort((d,h)=>+(h.op==="x")-+(d.op==="x")||h.t-d.t);let u=new Set(r?.s?s.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,_s),p=[...new Set([...u,...f(s.filter(d=>d.op==="x")),...f(s.filter(d=>d.op!=="x"))])],g=new Map(p.map(d=>[d,hr(j(d,4*1024*1024),new Set(s.filter(h=>h.tr===d).map(h=>h.call)))]));for(let d of s){let h=g.get(d.tr);if(!h)continue;let N=h.get(d.call)??[],z=H=>(this.write(H),c--,void a.push(pr(d.cap,d.key)));d.op==="x"?N.length>1||N.length===1&&!N[0].refused?z({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>=At&&z({t:d.t,op:"x",cap:d.cap,key:d.key,n:0}):N.length===1&&N[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??""}):N.length>0&&z({t:d.t,op:"ran",cap:d.cap,key:d.key,n:d.n})}return{left:c,done:a}}prune(t){try{let n=fr(t-xs*864e5);for(let r of ur(this.dir))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&St(X(this.dir,r))}catch{}}};var pr=(e,t)=>gs("sha256").update(`${e}\0${t}`).digest("hex").slice(0,32),As=new Set(["user-rejected","permission-rule","automode-blocked","automode-unavailable","cancelled"]);function Cs(e,t){return hr(e,new Set([t])).get(t)??[]}function hr(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 i=e.lastIndexOf(`
|
|
10
|
+
`,o.index)+1;(r.get(i)??r.set(i,new Set).get(i)).add(o[1])}for(let[o,i]of[...r].sort((l,s)=>l[0]-s[0])){let l=e.indexOf(`
|
|
11
|
+
`,o);try{let s=JSON.parse(e.slice(o,l<0?void 0:l));if(s.type!==void 0&&s.type!=="user")continue;let a=Array.isArray(s.message?.content)?s.message.content:[],c=s.toolDenialKind;for(let u of i){let f=a.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"?As.has(c):s.toolUseResult==="User rejected tool use")})}}catch{for(let s of i)(n.get(s)??n.set(s,[]).get(s)).push({refused:!1})}}return n}function mr(e,t){return!e||!t?null:Rs(j(e,4*1024*1024),t)}function Rs(e,t){let n=e.indexOf(`"tool_use_id":"${t}"`);if(n<0)return null;let r=e.slice(e.lastIndexOf(`
|
|
10
12
|
`,n)+1,e.indexOf(`
|
|
11
13
|
`,n)<0?void 0:e.indexOf(`
|
|
12
|
-
`,n));try{let o=JSON.parse(r),
|
|
13
|
-
`)}function
|
|
14
|
-
`)}function
|
|
15
|
-
`)})}function
|
|
16
|
-
`)})}function
|
|
17
|
-
`)}o={...o,source:t.source};let
|
|
18
|
-
${
|
|
19
|
-
`))if(o.trim())try{let
|
|
20
|
-
${
|
|
21
|
-
`))if(
|
|
22
|
-
`,{mode:384})}catch{}return n}async function
|
|
23
|
-
`)}catch{return 0}return await Promise.all(
|
|
14
|
+
`,n));try{let o=JSON.parse(r),l=(Array.isArray(o.message?.content)?o.message.content:[]).find(c=>c.type==="tool_result"&&c.tool_use_id===t);if(!l)return null;let s=typeof l.content=="string"?l.content:JSON.stringify(l.content??"");return Cs(r,t)[0]?.refused===!0||l.is_error===!0&&/doesn't want to proceed with this tool use|The tool use was rejected/.test(s)?"no":"yes"}catch{return null}}import{createHash as pe}from"crypto";import{closeSync as ve,constants as _r,fstatSync as zs,mkdirSync as Js,openSync as Lr,readdirSync as qs,readSync as Lt,statSync as Vs,unlinkSync as $r}from"fs";import{join as W}from"path";var Os="https://api.anvilcontrol.ai";function Ot(e=process.env){let t=e.ANVIL_HOSTED_API_URL?.trim();return(t&&t.length>0?t:Os).replace(/\/+$/,"")}import{chmodSync as Ju,mkdirSync as qu,readFileSync as Es,writeFileSync as Vu}from"fs";import{homedir as Ns}from"os";import{dirname as Zu,join as Ps}from"path";function Ls(){return process.env.ANVIL_WORKSPACE_KEYS_PATH?.trim()||Ps(Ns(),".anvil","workspace-keys.json")}function js(e=Ls()){let t;try{t=JSON.parse(Es(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 Is=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 Et(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ts(e){let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return Et(e)||"workspace";let n=e.slice(0,t),o=e.slice(t+1).split(".")[0]??"",i=Is.has(o.toLowerCase())?n:o;return Et(i)||Et(n)||"workspace"}function Ds(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 yr(e){let n=Object.entries(js(e)).find(([,i])=>i.active===!0);if(!n)return null;let[r,o]=n;return{email:r,workspace:Ts(r),apiKey:o.apiKey,...o.apiBaseUrl?{apiBaseUrl:o.apiBaseUrl}:{},keyAgeDays:Ds(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 Ms,constants as Fs}from"fs";import{join as wr}from"path";var Ws=["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"],Hs=/^claude\.[a-z0-9_]+(?:\.[a-z0-9_]+)*$/,Us=new Set(["hook-removed","hooks-disabled","settings-unreadable","no-node","classifier-missing","rules-missing"]),Bs=[[/^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 br(e){for(let[t,n]of Bs)if(t.test(e))return n;return"other"}var Ks=1440*60*1e3;function kr(e){let t=Date.parse(e.trim());return Number.isFinite(t)?t:null}function vr(e){let{paths:t,now:n}=e,r=new Set,o=p=>{p&&r.add(br(p))},i=null;try{i=C(t)}catch{i=null}let l={};try{let p=Y(t,i);o(p.problem);for(let g of e.kinds.slice(0,64))g.length<=200&&Hs.test(g)&&(l[g]=ye.has(g)?"enforce":oe(p.value,g))}catch{}try{let p=Z(t,e.fallbackTable,i);o(p.problem),p.value||r.add("rules-missing")}catch{r.add("rules-missing")}let s=y(t.install,4*1024*1024)===!0;if(s)try{for(let p of He(t,i,e.home))o(p)}catch{}let a=e.hookBin??(s?t.bin:void 0);a&&y(wr(a,"claude-hook-core.js"),64*1024*1024)!==!0&&r.add("classifier-missing");try{Ms(y(t.decisions,Number.MAX_SAFE_INTEGER)===null?t.dir:t.decisions,Fs.W_OK)}catch{(y(t.dir,Number.MAX_SAFE_INTEGER)!==null||s)&&r.add("spool-unwritable")}let c=null;try{let p=Ue(t),g=p?kr(p.at):null;if(p&&g!==null&&(c=g,n-g<Ks))for(let d of p.problems)br(d)==="node-fallback"&&r.add("node-fallback")}catch{}let u=kr(j(wr(t.state,"no-node"),64));u!==null&&(c===null||u>c)&&(r.add("no-node"),c=u);let f=Ws.filter(p=>r.has(p));return{modes:l,ok:!f.some(p=>Us.has(p)),problems:f,hook_checked_at:c===null?null:new Date(c).toISOString()}}function xr(){try{return/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]{1,20})?$/.test("0.9.0")?"0.9.0":null}catch{return null}}var Gs=50,Ys=50,Zs=1e4,xe=512*1024,Pt=30*6e4,Xs="/v1/claude-code/machine",jr=360*6e4,Qs=_({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 Je(e,t){let n=null;try{let i=ar(e,t);y(i,1024*1024)===!0&&(n=yr(i))}catch{n=null}if(n?.apiKey){let i=n.workspaceId?`ws:${pe("sha256").update(n.workspaceId).digest("hex").slice(0,12)}`:Ar(n.apiKey);return{apiKey:n.apiKey,baseUrl:Sr(n.apiBaseUrl||Ot(e)),id:i,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:Sr(o||Ot(e)),id:Ar(r),linkedAt:null,source:"env"}:null}function Sr(e){return e.replace(/\/+$/,"")}function Ar(e){return`sha256:${pe("sha256").update(e).digest("hex").slice(0,12)}`}function Cr(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 ei(e){return W(e.dir,"machine.json")}function jt(e,t){let n=b(ei(e))?.label;return Cr(typeof n=="string"&&n?n:t)}var de=e=>typeof e=="string"&&e.length>0?e:null;function ti(e,t){return e===null||e==="hold-risky-actions"||Oe[e]?Ee(e,t):"your-rule"}function ni(e){if(!e)return"none";let t=e.replace(/-/g,"").toLowerCase();return/^[a-f0-9]{8,}$/.test(t)?t.slice(0,8):pe("sha256").update(e).digest("hex").slice(0,8)}function Ir(e,t){let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object"||n.v!==1)return null;let r=de(n.action),o=n.verdict,i=n.mode,l=de(n.ts);if(!r||!r.startsWith("claude.")||r.length>200||o!=="hold"&&o!=="block"||i!=="ghost"&&i!=="enforce"||n.delivered==="approved"||!l||!Number.isFinite(Date.parse(l)))return null;let s=Qs[de(n.blocked_by)??""];if(!s)return null;let a=i==="ghost"?"would_block":o==="hold"?"held":"blocked",u=de(n.blocked_by)==="time_limit"?i==="ghost"?"Not checked in time":"Held: could not be checked in time":a==="held"?"Held for your OK":a==="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}/${ni(de(n.session))}/${pe("sha256").update(e).digest("hex").slice(0,12)}`,action:r,decided_by:"claude_code_hook",outcome:a,mode:i,blocked_by:s,reason:`${u} \xB7 ${Ne(r)}`,rule_id:ti(de(n.rule),r),decided_at:new Date(Date.parse(l)).toISOString(),duration_ms:Math.min(f,6e5)}}function Rr(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 Tr(e,t){return W(e.state,"sync",`${pe("sha256").update(t).digest("hex").slice(0,16)}.json`)}function Dr(e){return W(e.state,"signed-out.json")}function ze(e){let t=b(Dr(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 Mr(e,t,n,r){A(e.state);let o=n.filter(i=>r-Date.parse(i[1])<400*864e5).slice(-500);O(Dr(e),`${JSON.stringify(t!==null?{open:t,windows:o}:{windows:o})}
|
|
15
|
+
`)}function Fr(e,t){try{let n=ze(e);n.open===null&&Mr(e,new Date(t).toISOString(),n.windows,t)}catch{}}function ri(e,t){try{let n=ze(e);n.open!==null&&Date.parse(n.open)<=t&&Mr(e,null,[...n.windows,[n.open,new Date(t).toISOString()]],t)}catch{}}function Wr(e){let t=[];try{t=qs(W(e.state,"sync")).filter(n=>n.endsWith(".json"))}catch{return null}for(let n of t){let r=b(W(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 $e(e,t,n=Date.now()){let r=b(Tr(e,t));if(!r||r.v!==2||r.identity!==t)return Rr(t);let o={...Rr(t),...r,v:2,identity:t},i=Number.isFinite(o.next_try_at)?Math.min(o.next_try_at,n+Pt):0,l=typeof o.report_next_at=="number"&&Number.isFinite(o.report_next_at)?Math.min(o.report_next_at,n+jr):0,s=Number.isFinite(o.window_start)&&o.window_start<=n?o.window_start:0,a=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:i,report_next_at:l,last_report_ok:c(o.last_report_ok),window_start:s,window_sent:s===0?0:o.window_sent,skip:a,linked_at:c(o.linked_at),last_pass_at:c(o.last_pass_at),registered_kinds:u}}function oi(e,t){let n=Tr(e,t.identity);Js(W(e.state,"sync"),{recursive:!0,mode:448}),O(n,`${JSON.stringify(t,null,2)}
|
|
16
|
+
`)}function It(e){return W(e.state,"mode-pending.json")}function si(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 fe(e){let t=b(It(e));return{v:2,changes:Array.isArray(t?.changes)?t.changes.filter(si):[]}}var Q=e=>`${e.identity}|${e.action}|${e.at}`;function Hr(e,t){A(e.state);let n=W(e.state,"mode-pending.lock"),r=!1;for(let o=0;o<40&&!r;o++)try{ve(Lr(n,"wx",384)),r=!0}catch{try{Date.now()-Vs(n).mtimeMs>1e4&&$r(n)}catch{}let i=Date.now()+25;for(;Date.now()<i;);}try{return t()}finally{if(r)try{$r(n)}catch{}}}function ii(e,t){t.length!==0&&Hr(e,()=>{let n=fe(e).changes,r=(l,s)=>l.identity===s.identity&&l.action===s.action,o=t.map(l=>{let s=n.find(a=>r(a,l));return s?{...l,from:s.from}:l}),i=n.filter(l=>!t.some(s=>r(l,s)));O(It(e),`${JSON.stringify({v:2,changes:[...i,...o]},null,2)}
|
|
17
|
+
`)})}function li(e,t){t.size!==0&&Hr(e,()=>{let n=fe(e).changes.filter(r=>!t.has(Q(r)));O(It(e),`${JSON.stringify({v:2,changes:n},null,2)}
|
|
18
|
+
`)})}function ai(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 ci(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 _e(e,t,n,r,o){let i=ai(t);if(i)return{status:0,body:null,retryAfterMs:null,error:i};try{let l=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??Zs)}),s=await l.text().catch(()=>""),a=null;try{a=s?JSON.parse(s):null}catch{a=null}let c=Number(l.headers.get("retry-after"));return{status:l.status,body:a,retryAfterMs:Number.isFinite(c)&&c>0?c*1e3:null,error:null}}catch(l){return{status:0,body:null,retryAfterMs:null,error:ci(l)}}}function K(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 ui(e){return e?st(e).filter(t=>t.startsWith("claude.")).sort().slice(0,Ys):[]}async function Or(e,t,n,r,o=!1){return _e(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 di(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 Er(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 fi(e){return e.status===0||e.status===401||e.status===403||e.status===429||e.status>=500}var Nr={linked:!1,sent:0,rejected:0,waiting:0,modesPulled:!1,modesChanged:!1,error:null};async function Tt(e){if(!e.identity)return Nr;try{return await pi(e,e.identity)}catch(t){return{...Nr,linked:!0,error:`the sync failed: ${t instanceof Error?t.message:String(t)}`}}}async function pi(e,t){let{paths:n}=e,r=e.now(),o=$e(n,t.id,r),i=o.since!==null;if(!i){let m=t.linkedAt&&Number.isFinite(Date.parse(t.linkedAt))?t.linkedAt:new Date(r).toISOString();o={...o,since:m}}let l=W(n.state,"sync-active.json"),s=b(l),a=typeof s?.at=="string"&&Number.isFinite(Date.parse(s.at))?s.at:null,c=t.linkedAt!==null&&Number.isFinite(Date.parse(t.linkedAt))?t.linkedAt:null;if(i&&typeof s?.id=="string"&&s.id!==t.id&&a!==null&&Date.parse(a)<r){let m=c!==null&&Date.parse(c)>Date.parse(a)&&Date.parse(c)<r?c:new Date(r).toISOString();o={...o,skip:[...o.skip,[a,m]].slice(-500)}}let u=!(e.force===!0&&t.source==="env"&&typeof s?.id=="string"&&s.id!==t.id);if(s?.id!==t.id&&u){A(n.state);let m=c!==null&&a!==null&&Date.parse(c)>Date.parse(a)&&Date.parse(c)<=r?c:i?new Date(r).toISOString():o.since;O(l,`${JSON.stringify({id:t.id,at:m})}
|
|
19
|
+
`)}o={...o,source:t.source};let f=ze(n);c!==null&&f.open!==null&&Date.parse(f.open)<=Date.parse(c)&&ri(n,Date.parse(c));for(let m of ze(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=ui(Z(n,e.fallbackTable).value),d=[],h=null,N=fe(n).changes,z=o.registered?g.filter(m=>!o.registered_kinds.includes(m)):g,H=null;if(g.length>0&&(z.length>0||N.length>0)){let m=await _e(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);H=Er(m),H||(h=m)}if(!h&&H&&z.length>0){let m=Y(n).value,S=!o.registered&&m!==null&&m.source!=="workspace"?g.filter(k=>ne(m,k)==="enforce"&&H.get(k)?.effective!=="enforce"):[];ii(n,S.map(k=>({action:k,mode:"enforce",at:new Date(r).toISOString(),identity:t.id,from:H.get(k)?.effective??null,origin:"link"})));let w=null;await di(z.filter(k=>!S.includes(k)&&!H.get(k)?.explicit),4,async k=>{let he=await Or(e,t,k,"ghost",!0);return he.status>=200&&he.status<300?!0:(w??=he,!1)})?o={...o,registered:!0,registered_kinds:[...new Set([...o.registered_kinds,...z])]}:w&&fi(w)?h=w:w&&d.push(`could not register the kinds of action yet (${K(w,t,e.cli)})`)}let Jt=fe(n).changes;if(!h&&Jt.length>0){let m=new Set,S=[];for(let w of Jt){if(w.identity!==t.id){m.add(Q(w)),d.push("a mode change made under another account was not sent to this one");continue}if(h)break;if(!fe(n).changes.some(he=>Q(he)===Q(w)))continue;let Ze=H?.get(w.action);if(w.from!==null&&Ze&&Ze.effective!==w.from){m.add(Q(w)),d.push(`your workspace changed ${w.action} after you set it offline, so its mode stands`);continue}let k=await Or(e,t,w.action,w.mode);k.status>=200&&k.status<300?(m.add(Q(w)),w.origin==="link"&&S.push(w.action)):k.status===400||k.status===422?(m.add(Q(w)),d.push(`the workspace refused a mode change for ${w.action} (${K(k,t,e.cli)})`)):h=k}li(n,m),S.length>0&&d.push(`at sign-in, this machine's enforce for ${S.length===1?Ne(S[0]):`${S.length} kinds of action`} went to your workspace`)}let Ge=!1,qt=!1,Vt=()=>fe(n).changes.some(m=>m.identity===t.id);if(!h&&g.length>0&&!Vt()){let m=await _e(e,t,"GET",`/v1/modes?actions=${g.map(encodeURIComponent).join(",")}`);Er(m)?Vt()||(Ge=!0,qt=wi(n,m.body.modes,new Date(r)),o={...o,last_pull_ok:new Date(r).toISOString()},gi(n,r)):h=m}let Ye=h!==null&&(h.status===0||h.status===401||h.status===403);!Ye&&r>=o.report_next_at&&(o=await hi(e,t,o,g,Ge,r,d));let Gt=0,Yt=0,Zt=null;if(!p&&!Ye){let m=await yi(e,t,o,r);o=m.state,Gt=m.sent,Yt=m.rejected,Zt=m.failed}let J=Zt??(Ye&&!p?h:null);if(J){let m=o.failures+1,S=J.status===429&&J.retryAfterMs?Math.min(J.retryAfterMs,Pt):J.status===0?6e4:Math.min(6e4*2**(m-1),Pt);o={...o,failures:m,last_error:K(J,t,e.cli),next_try_at:r+S}}else p?h&&(o={...o,last_error:K(h,t,e.cli)}):o={...o,failures:0,last_error:h?K(h,t,e.cli):null,next_try_at:0};let mo=J?K(J,t,e.cli):h?K(h,t,e.cli):p?o.last_error:null;return d.length>0&&(o={...o,last_note:d[d.length-1]}),oi(n,o),{linked:!0,sent:Gt,rejected:Yt,waiting:Dt(n,o,e.machine),modesPulled:Ge,modesChanged:qt,error:mo}}function gi(e,t){try{A(e.state),O(W(e.state,lr),String(t))}catch{}}async function hi(e,t,n,r,o,i,l){let s;try{s=vr({paths:e.paths,kinds:r,now:i,...e.home?{home:e.home}:{},...e.fallbackTable?{fallbackTable:e.fallbackTable}:{},...e.hookBin?{hookBin:e.hookBin}:{}})}catch{return n}let a=await _e(e,t,"POST",Xs,{machine:e.machine,version:xr(),modes:s.modes,ok:s.ok,problems:s.problems,hook_checked_at:s.hook_checked_at,modes_pulled:o});return a.status>=200&&a.status<300?{...n,last_report_ok:new Date(i).toISOString()}:a.status===404||a.status===405?{...n,report_next_at:i+jr}:((a.status===400||a.status===422)&&l.push(`the workspace refused this machine's health report (${K(a,t,e.cli)})`),n)}function Nt(e){let t;try{t=Lr(e,_r.O_RDONLY|_r.O_NONBLOCK)}catch{return null}try{let n=zs(t);if(n.isFile())return{fd:t,ino:n.ino,size:n.size}}catch{}return ve(t),null}function Ur(e,t){let n=Nt(e.decisions);if(t.ino!==0){if(n&&n.ino===t.ino&&n.size>=t.offset)return[{...n,start:t.offset}];let l=Nt(`${e.decisions}.1`);if(l&&l.ino===t.ino&&l.size>=t.offset)return n?[{...l,start:t.offset},{...n,start:0}]:[{...l,start:t.offset}];l&&ve(l.fd)}let r=Nt(`${e.decisions}.1`),o=r&&t.last_hash?Pr(r.fd,r.size,t.last_hash):null;if(r&&o!==null)return n?[{...r,start:o},{...n,start:0}]:[{...r,start:o}];let i=n&&t.last_hash?Pr(n.fd,n.size,t.last_hash):null;return i!==null&&n?(r&&ve(r.fd),[{...n,start:i}]):[...r?[{...r,start:0}]:[],...n?[{...n,start:0}]:[]]}function Br(e){for(let t of e)try{ve(t.fd)}catch{}}function Pr(e,t,n){let r=0,o=Buffer.alloc(0);for(;r<t;){let i=Math.min(xe,t-r),l=Buffer.alloc(i);Lt(e,l,0,i,r);let s=o.length>0?Buffer.concat([o,l]):l,a=r-o.length,c=0;for(let u=0;u<s.length;u++)if(s[u]===10){if(Kr(s.toString("utf8",c,u))===n)return a+u+1;c=u+1}o=s.subarray(c),o.length>4*xe&&(o=Buffer.alloc(0)),r+=i}return null}function Kr(e){return pe("sha256").update(e).digest("hex").slice(0,16)}function mi(e,t,n){for(let r=t;r<n;){let o=Math.min(xe,n-r),i=Buffer.alloc(o);Lt(e,i,0,o,r);let l=i.indexOf(10);if(l>=0)return r+l+1;r+=o}return null}function zr(e,t,n){let r=Math.min(xe,n-t);if(r<=0)return{lines:[],skipTo:null};let o=Buffer.alloc(r);Lt(e,o,0,r,t);let i=[],l=0;for(let s=0;s<r;s++)o[s]===10&&(i.push({text:o.toString("utf8",l,s),end:t+s+1}),l=s+1);return{lines:i,skipTo:i.length===0&&r===xe?mi(e,t+r,n):null}}function Jr(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,i])=>r>=Date.parse(o)&&r<Date.parse(i))}catch{return!1}}async function yi(e,t,n,r){let o=n;r-o.window_start>=6e4&&(o={...o,window_start:r,window_sent:0});let i=Ur(e.paths,o),l=0,s=0,a=null;try{e:for(let c of i){o={...o,ino:c.ino,offset:c.start};let u=c.start;for(;u<c.size;){let{lines:f,skipTo:p}=zr(c.fd,u,c.size);if(f.length===0){if(p===null)break;s++,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=Jr(g.text,o)?Ir(g.text,e.machine):null;if(d){if(o.window_sent>=Gs)break e;let h=await _e(e,t,"POST","/v1/decision",d);if(h.status>=200&&h.status<300)l++,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)s++,o={...o,rejected:o.rejected+1,last_note:`a stop was refused: ${K(h,t,e.cli)}`};else{a=h;break e}}o={...o,offset:g.end,last_hash:Kr(g.text)}}u=f[f.length-1].end}}}finally{Br(i)}return{state:o,sent:l,rejected:s,failed:a}}function Dt(e,t,n){let r=Ur(e,t);try{let o=0;for(let i of r)o+=zr(i.fd,i.start,i.size).lines.filter(l=>Jr(l.text,t)&&Ir(l.text,n)!==null).length;return o}finally{Br(r)}}function wi(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=Y(e),i=o.value,l=new Set([...Object.keys(r),...Object.keys(i?.services?.[P]?.actions??{}),...Object.keys(M)]),s=o.source==="strict"||re(i)||i?.day_one===!0,a={version:1,kill_switch:!1,default_mode:"ghost",services:{[P]:{actions:r}},updated_at:n.toISOString(),source:"workspace",...s?{day_one:!0}:{}},c=[...l].some(u=>ne(i,u)!==ne(a,u))||i?.source!=="workspace"||i?.day_one===!0!==s;return(c||o.source!=="file")&&Xn(e,a),c}var T=e=>e.toLocaleString("en-US");function Mt(e,t){let n=[],r=`${j(`${e.decisions}.1`,2097152)}
|
|
20
|
+
${j(e.decisions,4194304)}`;for(let o of r.split(`
|
|
21
|
+
`))if(o.trim())try{let i=JSON.parse(o);i.ts&&Date.parse(i.ts)>=t&&n.push(i)}catch{}return n}function bi(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 ki(e,t,n,r,o,i=U(!1),l=s=>`${o} ${s}`){if(!t)return Wr(e)!==null?R("Dashboard",`synced by a key this terminal does not have (ANVIL_API_KEY where Claude Code runs) \xB7 ${l("login")} here to change modes from this terminal`,i):R("Dashboard",`${l("login")} ${i.dim("see every session in one place (optional)")}`,i);let s=$e(e,t.id,r.getTime()),a=s.since===null?0:Dt(e,s,n),c=bi(s.last_pull_ok,r),u=[l("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}`),a>0&&u.push(`${T(a)} ${a===1?"stop":"stops"} waiting to send`),s.last_error?u.push(s.last_error):s.last_note&&u.push(s.last_note),R("Dashboard",u.join(" \xB7 "),i)}var vi="what every Claude Code session spends",qr=e=>e.split(/, and |; /).map(t=>t.trim()).filter(Boolean);function xi(e,t=U(!1),n=et()){let r=s=>M[s]?.text??s,o=[...e.floor.filter(s=>s.verdict==="block").flatMap(s=>qr(s.short)),...e.held.filter(s=>e.blocking.has(s)).map(r)],i=[...e.held.filter(s=>!e.blocking.has(s)).map(r),...e.dayOne?qr(un.text):[],...e.floor.filter(s=>s.verdict==="hold").map(s=>s.short)],l=e.all>0&&e.held.length>=e.all;return[...o.length>0?te(v.blocked,"Blocks",o,t,n):[],...i.length>0?te(v.held,"Holds",i,t,n):[],...te(v.watching,"Watches",l?"nothing else: every risky kind is held":"every other risky action \xB7 it runs, with a note",t,n,9,t.dim),...e.off.length>0?te(" ","Off",e.off.map(s=>M[s]?.slug??s),t,n,9,t.dim):[],...e.spend!==void 0?te(v.watching,"Counts",`${vi}${e.spend?` \xB7 ${e.spend}`:""}`,t,n,9,t.dim):[]]}function _i(e,t=U(!1),n=q,r=[],o="What it does now"){return tn(o,[...xi(e,t,et(n)),...r],t,n)}function $i(e,t){let n=new Set;for(let r of e?.policies??[])if(!(r.origin==="baseline"||!ie(r,t))){for(let o of r.rules)if(o.intent==="block")for(let i of o.applies_to??[])n.add(i)}return n}var Vr=Object.keys(M).filter(e=>!["claude.bash.unclassified","claude.tool.other","claude.mcp.call","claude.agent.helper"].includes(e)&&!ye.has(e));function Si(e,t,n){return Vr.filter(r=>ot(t,r,e?Le(e,r,n):null)==="enforce")}function Ai(e,t,n){return Vr.filter(r=>ot(t,r,e?Le(e,r,n):null)==="off")}var Ci=["claude.bash.deploy","claude.bash.db.destructive","claude.bash.secrets.print","claude.bash.fs.delete_recursive"];function Ri(e,t){return t&&!Ci.some(n=>sn(e,n,Le(t,n,null)))?null:dn(e)}function Oi(e,t,n){let r=e.filter(o=>o.floor).length;return`stopped ${T(e.length)}${r?` (${T(r)} always on)`:""}${t?` \xB7 allowed once ${T(t)}`:""}${n?` \xB7 declined ${T(n)}`:""} \xB7 ${Gr(e)}`}function Gr(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 Ei(e,t){return e.window==="minute"||e.window==="hour"?"rolling":e.window==="day"?"resets at midnight":`resets ${new Date(gr(e,t.getTime())).toLocaleDateString("en-US",{weekday:"long"})}`}function Ni(e,t,n,r=U(!1),o=null){let i=(e?.policies??[]).filter(s=>ie(s,o)).flatMap(s=>s.caps??[]);if(i.length===0)return[];let l=new Ke(Se(t.dir,"caps"));return i.map((s,a)=>{let c;try{c=l.used(s,n.getTime())}catch{c=null}let u=s.window==="minute"||s.window==="hour"?"":` \xB7 ${Ei(s,n)}`;return R(a===0?"Caps":"",`${s.text} \xB7 ${c===null?"can't be counted now: its calls are held":`${Rt(s,c)} of ${Rt(s,s.limit)} used`}${u}${s.unit!=="calls"&&s.unit!=="money"?" \xB7 an estimate":""}`,r)})}function Pi(e,t){let n=["settings.local.json","settings.json"].map(r=>{let o=Se(e,".claude",r);return{file:`.claude/${r}`,sandbox:b(o)?.sandbox,anvil:t.whole?.includes(o)===!0}});return Nn(n,{managed:t.managed,open:t.open===!0,userOn:t.rules.some(r=>r.project===null&&r.layer!=="hook")})}function Li(e,t=U(!1),n=null){let r=$(Se(e.dir,On),C(e),4194304);if(r.status!=="ok"&&r.status!=="unkeyed")return[];let o=Array.isArray(r.value.rules)?r.value.rules:[],i=n!==null&&o.some(s=>s.project===null&&s.entries.length>0)?Pi(n,r.value):null,l=o.map((s,a)=>R(a===0?"Locks":"",i&&s.project===null&&s.entries.length>0&&("off"in i?s.layer!=="hook":s.layer==="hook")?`${s.text} \xB7 ${"off"in i?Pn(i.off):"locked in this project"}`:s.layer==="both"?`${s.text} \xB7 locked`:s.layer==="part"?`${s.text} \xB7 partly locked: ${s.why}`:`${s.text} \xB7 ${En(s)}: ${s.why}`,t));return i&&"widened"in i?[...l,R("Sandbox",Ln(i),t)]:l}function Yr(e,t,n,r="anvil",o=null,i=!1){if(n)return`${lt("Anvil isn't working")} run in a terminal: ${L(r)} on`;let l=t.toISOString().slice(0,10),s=we(Se(e.counts,l)),a=`${j(`${e.decisions}.1`,2*1024*1024)}
|
|
22
|
+
${j(e.decisions,4*1024*1024)}`,c=0;for(let g of a.split(`
|
|
23
|
+
`))if(g.includes(`"ts":"${l}`))try{let d=JSON.parse(g);d.mode==="enforce"&&(d.delivered==="deny"||d.delivered==="ask")&&(c+=1)}catch{}let u=0;try{u=tr(e,C(e),t.getTime()).length}catch{u=0}let f=[...s>0?[`${T(s)} checked`]:[],...c>0?[`${T(c)} stopped`]:[],...o?.today?[o.text]:[]],p=[...i?["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: ${L(r)} allow`]:[]];return[lt("Anvil on"),...p.length>0?[p.join(" \xB7 ")]:[]].join(" ")}function ji(e,t,n=U(!1)){let r=t.toISOString().slice(0,10),o=we(Se(e.counts,r)),i=Mt(e,Date.parse(`${r}T00:00:00.000Z`)),l=i.filter(p=>p.mode==="ghost"&&(p.verdict==="hold"||p.verdict==="block")),s=i.filter(p=>p.mode==="enforce"&&(p.delivered==="deny"||p.delivered==="ask")),a=s.filter(p=>p.delivered==="ask").map(p=>mr(p.transcript,p.call)),c=i.filter(p=>p.delivered==="approved").length+a.filter(p=>p==="yes").length,u=a.filter(p=>p==="no").length,f=[`${T(o)} ${o===1?"action":"actions"} checked`];return s.length>0&&f.push(Oi(s,c,u)),l.length>0&&f.push(`would have stopped ${T(l.length)} \xB7 ${Gr(l)}`),s.length===0&&l.length===0&&f.push("nothing it would stop"),R("Today",f.join(" \xB7 "),n)}function Zr(e){let t=U(!1);if(!e.table)return[Qe("Report","not checking",t),"",Ce(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(i=>R("Problem",i)),...(e.problems??[]).length>0?[""]:[],tt(`${L(e.cli)} on`,e.installed?"fix it, in your own terminal":"turn it on")];let{text:n}=pn(e.table,e.modes),r=Si(e.table,e.modes,null),o=e.problems??[];return[Qe("Report",o.length>0?"on, with a problem":"on",t),"",o.length>0?Ce(v.problem,"On, with a problem"):Ce(v.on,"On. Every action Claude Code takes is checked before it runs."),"",...o.map(i=>R("Problem",i)),...o.length>0?[""]:[],..._i({floor:cn(e.table),held:r,blocking:$i(e.table,null),off:Ai(e.table,e.modes,null),dayOne:Ri(e.modes,e.table)!==null,all:n==="enforce"?r.length:Number.POSITIVE_INFINITY,spend:null},t),"",R("Rules",String(fn(e.table))),...Li(e.paths,t,e.dir??null),...e.advisor?[R("Advisor",e.advisor)]:[],...Ni(e.table,e.paths,e.now),ji(e.paths,e.now),ki(e.paths,e.identity,e.machine,e.now,e.cli),"",tt(`${L(e.cli)} rules edit`,"change rules, in your terminal")]}import{randomUUID as Ti}from"crypto";import{existsSync as to,mkdirSync as no,readFileSync as ro,writeFileSync as Di}from"fs";import{join as ge}from"path";import{existsSync as Hd,mkdirSync as Ud,readFileSync as Bd,writeFileSync as Kd}from"fs";import{homedir as Jd}from"os";import{join as Vd}from"path";import{randomUUID as Yd}from"crypto";var Ii="https://app.anvilcontrol.ai";function Ft(e=process.env){let t=e.ANVIL_HOSTED_DASHBOARD_URL?.trim();return(t&&t.length>0?t:Ii).replace(/\/+$/,"")}import{lookup as Dd}from"dns/promises";function Wt(){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 Xr(e,t,n,r){try{if(Wt()||!t||!/^https?:\/\//i.test(t)||!n)return Promise.resolve();let o=new AbortController,i=setTimeout(()=>o.abort(),1200);typeof i.unref=="function"&&i.unref();let l=r!=null&&Object.keys(r).length>0;return fetch(t.replace(/\/+$/,"")+"/api/funnel",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l?{fid:n,event:e,props:r}:{fid:n,event:e}),signal:o.signal}).then(()=>{clearTimeout(i)},()=>{clearTimeout(i)})}catch{return Promise.resolve()}}var Qr={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 Mi=["CI","GITHUB_ACTIONS","GITLAB_CI","BUILDKITE","CIRCLECI","TF_BUILD","JENKINS_URL","TEAMCITY_VERSION"],Ht=e=>e!==void 0&&e.trim()!==""&&!/^(0|false|no|off)$/i.test(e.trim());function oo(e){return Ht(e.DO_NOT_TRACK)||Ht(e.ANVIL_FUNNEL_DISABLED)?!1:!Mi.some(t=>Ht(e[t]))}function so(e){return ge(e,".anvil","telemetry-notice")}function io(e){return to(so(e))}function Fi(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 Wi(e){let t=ge(e,".anvil","claude","telemetry-id");try{let r=ro(t,"utf8").trim();if(/^c_[a-f0-9]{32}$/.test(r))return r}catch{}let n=`c_${Ti().replace(/-/g,"")}`;try{no(ge(e,".anvil","claude"),{recursive:!0,mode:448}),Di(t,`${n}
|
|
24
|
+
`,{mode:384})}catch{}return n}async function Hi(e,t,n,r){try{if(!oo(n)||Wt()||!io(r)||!Qr[e].every(o=>o in t)||Object.keys(t).some(o=>!Qr[e].includes(o)))return;await Xr(e,Ft(n),Wi(r),t)}catch{}}function eo(e){return ge(e.state,"telemetry.json")}function Ui(e,t){let n=we(ge(e.counts,t)),r=Date.parse(`${t}T00:00:00.000Z`),o=r+864e5,i=Mt(e,r).filter(s=>s.ts&&Date.parse(s.ts)<o),l=s=>i.filter(s).length;return{day:t,calls:Fi(n),held:l(s=>s.mode==="enforce"&&s.verdict==="hold"&&(s.delivered==="deny"||s.delivered==="ask")),blocked:l(s=>s.mode==="enforce"&&s.verdict==="block"&&s.delivered!=="pause"),would:l(s=>s.mode==="ghost"&&(s.verdict==="hold"||s.verdict==="block")),approved:l(s=>s.delivered==="approved"),errors:l(s=>s.verdict==="error")}}async function lo(e,t,n,r){if(!oo(t)||!io(n))return 0;let o=r.toISOString().slice(0,10),i=b(eo(e))?.last_daily??null,l="";try{l=new Date(Date.parse(ro(so(n),"utf8").trim())).toISOString().slice(0,10)}catch{return 0}let s=[];for(let a=7;a>=1;a--){let c=new Date(Date.parse(`${o}T00:00:00.000Z`)-a*864e5).toISOString().slice(0,10);c<l||i!==null&&c<=i||to(ge(e.counts,c))&&s.push(c)}if(s.length===0)return 0;try{no(e.state,{recursive:!0}),O(eo(e),`${JSON.stringify({last_daily:s[s.length-1]})}
|
|
25
|
+
`)}catch{return 0}return await Promise.all(s.map(a=>Hi("decisions_daily",Ui(e,a),t,n))),s.length}var D=ee(Vi(import.meta.url)),Kt=qe(D)==="bin"&&qe(ee(D))==="claude"&&qe(ee(ee(D)))===".anvil"?ee(D):void 0,Ve=!Kt&&qe(D)==="bin"&&Bi(E(ee(D),".claude-plugin","plugin.json"))?E(D,"baseline.json"):void 0,Ut=6e4,ao=5e3,Gi=30*6e4,Yi=720*6e4,Zi=780*6e4;function Xi(e){try{return process.kill(e,0),!0}catch{return!1}}function Qi(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||!Xi(r)||t-o>=Zi;try{return t-zt(e).mtimeMs>1e4}catch{return!0}}function el(e,t){A(e.state);let n=E(e.state,"sync.lock"),r=E(e.state,`sync.lock.${process.pid}.${t}.tmp`);try{qi(r,JSON.stringify({pid:process.pid,started:t}),{mode:384})}catch{return!1}try{for(let o=0;o<2;o++)try{return Ki(r,n),!0}catch(i){if(i.code!=="EEXIST"||!Qi(n,t))return!1;try{Ji(n,`${n}.stale.${process.pid}`),Bt(`${n}.stale.${process.pid}`)}catch{return!1}}return!1}finally{try{Bt(r)}catch{}}}function ho(e){let t=E(e.state,"sync.lock");try{b(t)?.pid===process.pid&&Bt(t)}catch{}}function tl(e,t){let n=0,r=o=>new Date(t-o).toISOString().slice(0,10);for(let o of[E(e.counts,r(0)),E(e.counts,r(864e5)),e.decisions])try{n=Math.max(n,zt(o).mtimeMs)}catch{}return n}function nl(e){try{return zt(e.decisions).size}catch{return 0}}function rl(e,t){if(t)return!0;if(y(e.install,1024*1024)!==!0)return!1;try{let n=JSON.parse(zi(e.install,"utf8"));return Object.keys(n.installs??{}).length>0}catch{return!1}}function co(e,t){try{A(e.state),O(E(e.state,ir),String(Math.round(t)))}catch{}}function uo(e,t){return{paths:e.paths,identity:t,machine:jt(e.paths,e.hostname),fetch:e.fetch,now:e.now,home:e.home,...e.pluginBaseline?{fallbackTable:e.pluginBaseline,hookBin:ee(e.pluginBaseline)}:{}}}async function ol(e){let{paths:t}=e,n=e.now();if(!el(t,n))return"locked";let r="idle",o=e.now()+6e4;try{let i=0,l=-1;for(;;){let a=e.now(),c=Je(e.env,e.home);if(!c)return Fr(t,a),r="unlinked",o=a+10*6e4,r;let u=nl(t),f=$e(t,c.id,a).next_try_at;if((a-i>=Ut||u!==l||f>0&&a>=f)&&(l=u,await Tt(uo(e,c)),a-i>=Ut&&(i=a,await(e.sendDaily??lo)(t,e.env,e.home,new Date(a)))),co(t,e.now()+3*ao+Ut),!rl(t,e.pluginBaseline!==void 0)){r="off";break}if(e.now()-tl(t,e.now())>Gi){r="idle";break}if(e.now()-n>Yi){r="lifetime";break}await e.sleep(ao)}let s=Je(e.env,e.home);return s&&await Tt(uo(e,s)),o=r==="off"?e.now()+10*6e4:0,r}finally{co(t,o),ho(t)}}function sl(e,t=null){let n=g=>typeof g=="string"&&/^[\w@./ -]{1,60}$/.test(g),r=b(e.install),o=r?.cli;at(n(o)?o:"anvil");let i=Z(e,Ve??E(D,"baseline.json")),l=Y(e),s=i.value,a=[s?.cli,o].find(n)??"anvil";at(a);let c=Object.values(r?.installs??{}).filter(g=>g&&typeof g.command=="string"&&!ht(g)).map(g=>`Anvil's hook in ${g.settings_path} can't start (its files are gone), so new sessions are not checked: run ${x("on")}`),u=C(e),f=[...new Set([...c,i.problem,l.problem,...He(e,u,Ae()),...sr(e,Ae(),u),...Ue(e)?.problems??[]].filter(g=>!!g))],p=Zr({paths:e,table:s,modes:l.value,identity:Je(process.env,Ae()),machine:jt(e,po()),now:new Date,cli:a,problems:f,installed:Object.keys(r?.installs??{}).length>0,advisor:t,dir:process.env.CLAUDE_PROJECT_DIR||process.cwd()});process.stdout.write(`${p.join(`
|
|
24
26
|
`)}
|
|
25
|
-
`)}async function
|
|
26
|
-
`)}catch{process.stdout.write(`\u{1F539} Anvil isn't working \u{1F539} run in a terminal: ${
|
|
27
|
-
`)}process.exit(0)}if(process.argv.includes("--status")){try{
|
|
28
|
-
`)}process.exit(0)}try{await
|
|
27
|
+
`)}async function il(e){let t=Date.now(),n={spend:null,unheard:!1};try{n=(await import(go(E(D,"claude-meter.js")).href)).statusFacts(e,t)}catch{}let r=c=>typeof c=="string"&&/^[\w@./ -]{1,60}$/.test(c),o=b(e.install),i=o?.cli,l=r(i)?i:"anvil",s=Z(e,Ve??E(D,"baseline.json")),a=Object.values(o?.installs??{}).some(c=>c&&typeof c.command=="string"&&!ht(c));return Yr(e,new Date(t),!s.value||a?"not working":null,l,n.spend,n.unheard)}var fo=()=>import(go(E(D,"claude-meter.js")).href).catch(()=>({}));async function ll(){let e=Kt?je(Kt):Sn(Ae());for(let t of["SIGTERM","SIGINT","SIGHUP"])process.on(t,()=>{ho(e),process.exit(0)});if(process.argv.includes("--statusline")){try{process.stdout.write(`${await il(e)}${(await fo()).advisorTail?.(e)??""}
|
|
28
|
+
`)}catch{process.stdout.write(`\u{1F539} Anvil isn't working \u{1F539} run in a terminal: ${x("on")}
|
|
29
|
+
`)}process.exit(0)}if(process.argv.includes("--status")){try{sl(e,(await fo()).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 ol({paths:e,env:process.env,home:Ae(),hostname:po(),fetch:globalThis.fetch,now:()=>Date.now(),sleep:t=>new Promise(n=>setTimeout(n,t)),...Ve?{pluginBaseline:Ve}:{}})}catch{}process.exit(0)}process.argv[1]&&/claude-sync\.js$/.test(process.argv[1])&&ll();export{Gi as IDLE_EXIT_MS,Yi as MAX_LIFE_MS,Ut as PULL_EVERY_MS,ao as TICK_MS,co as holdSpawns,tl as lastActivity,ho as releaseLock,ol as runSyncLoop,el as takeLock};
|