@useanvil/claude-code 0.0.0-stage → 0.8.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.
@@ -0,0 +1,35 @@
1
+ import{appendFileSync as Pn,closeSync as lt,constants as ae,fstatSync as ut,openSync as ct,readdirSync as Eo,readSync as Le,rmSync as st,statSync as ge}from"fs";import{createHash as dt}from"crypto";import{homedir as Mo}from"os";import{basename as qt,dirname as Po,isAbsolute as Bn,join as v,resolve as jo}from"path";import{isatty as To}from"tty";import{createHash as Tl}from"crypto";import{appendFileSync as $o,closeSync as On,constants as Rn,fstatSync as Nn,mkdirSync as _o,openSync as En,readdirSync as Il,readFileSync as xo,readSync as Mn,renameSync as So,statSync as Ao,unlinkSync as Dl,writeFileSync as Co}from"fs";import{homedir as Hl}from"os";import{dirname as Ul,join as zl}from"path";var Me="claude";function go(e){return e==="ghost"||e==="enforce"?e:null}function Lt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[Me]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function xn(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:Lt(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[Me]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[Me]?.actions??{}};for(let i of n)s[i]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:go(o.default_mode)??"ghost",services:{...o.services??{},[Me]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}import{existsSync as wa,readdirSync as ba,statSync as va}from"fs";import{dirname as $a,isAbsolute as _a,join as xa,posix as Sa,resolve as Aa}from"path";import{posix as An}from"path";var ho=null;function ot(){return ho??process.platform==="win32"}var Sn=/^([A-Za-z]):(.*)$/s,yo=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function It(e,t){let n=An.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function ve(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(!ot())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(Sn.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/${ve(o[1],n).toLowerCase()}${o[2]?`/${ve(o[2],n).toLowerCase()}`:""}`;return It(l,ve(o[3]??"",n).toLowerCase())}let s=Sn.exec(t);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?It(`/${s[1].toLowerCase()}`,ve(l,n).toLowerCase()):null}let i=yo.exec(t);if(i)return It(`/${i[1].toLowerCase()}`,ve(i[2]??"",n).toLowerCase());let a=ve(t,n).toLowerCase();if(a.startsWith("/")){let l=An.normalize(a);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return a}function wo(e){return Dt(e)??e}function Ft(e){return!ot()||typeof e!="string"||e===""?e:wo(e)}import{domainToASCII as ja}from"url";var Wa="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as sl,readdirSync as il,realpathSync as al}from"fs";import{basename as ul,dirname as cl,join as dl}from"path";var Ht="anvil-claude-compiled/1";function Cn(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&ko(t,e.project_dir))}function ko(e,t){let n=Ft(e),r=Ft(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}var Ro=3500;function K(e,t=8*1024*1024){try{let n=Ao(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function ke(e,t=8*1024*1024){let n;try{n=En(e,Rn.O_RDONLY|Rn.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=Nn(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 i=Mn(n,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{On(n)}}function $e(e,t){let n=t.endsWith(`
2
+ `)?t:`${t}
3
+ `;if(Buffer.byteLength(n)>Ro)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(K(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);$o(e,n,{mode:384})}function A(e){_o(e,{recursive:!0,mode:448})}function ne(e,t){if(K(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=En(e,"r")}catch{return""}try{let r=Nn(n).size,o=Math.max(0,r-t),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);Mn(n,i,0,s,o);let a=i.toString("utf8");if(o>0){let l=a.indexOf(`
4
+ `);a=l<0?"":a.slice(l+1)}return a}finally{On(n)}}function U(e,t,n=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Co(r,t,{mode:n}),Pe(r,e)}function Pe(e,t){for(let n=0;;n++)try{So(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 L(e){if(K(e)!==!0)return null;try{return JSON.parse(xo(e,"utf8"))}catch{return null}}var Kl=256*1024,ql=1024*1024;var Oo={"claude-fable-5-2":{input:8,output:40,read:.2},"claude-mythos-5-2":{input:8,output:40,read:.2},"claude-fable-5-1":{input:10,output:50,read:.25},"claude-mythos-5-1":{input:10,output:50,read:.25},"claude-fable-5":{input:10,output:50,read:1},"claude-mythos-5":{input:10,output:50,read:1},"claude-opus-5-5":{input:4,output:20,read:.2},"claude-opus-5":{input:5,output:25},"claude-opus-4-8":{input:5,output:25},"claude-opus-4-7":{input:5,output:25},"claude-opus-4-6":{input:5,output:25},"claude-opus-4-5":{input:5,output:25},"claude-opus-4-1":{input:15,output:75},"claude-opus-4-0":{input:15,output:75},"claude-opus-4":{input:15,output:75},"claude-sonnet-5-5":{input:2,output:10,read:.1},"claude-sonnet-5":{input:2,output:10},"claude-sonnet-4-6":{input:3,output:15},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4-0":{input:3,output:15},"claude-sonnet-4":{input:3,output:15},"claude-haiku-5-5":{input:.1,output:.5,tier:{above:1e5,over:{input:.5,output:2.5}}},"claude-haiku-4-5":{input:1,output:5}};function No(e){let t=/claude-[a-z]+-\d+(?:-\d+)?/.exec(e.toLowerCase().replace(/@.*$/,"").replace(/\[1m\]$/,""));return t?t[0].replace(/-(\d{8})$/,""):e}function pe(e,t){let n=Oo[No(e)];if(!n)return null;let r=t.input+t.write5m+t.write1h+t.read,o=n.tier&&r>n.tier.above?{...n,...n.tier.over}:n,s=n.tier&&r>n.tier.above?o.input*.1:n.read??n.input*.1;return(t.input*o.input+t.output*o.output+t.write5m*o.input*1.25+t.write1h*o.input*2+t.read*s)/1e6*(t.fast?2:1)+(t.webSearches??0)*.01}var zt=64*1024,Kn=8*1024*1024,jn=8*1024*1024,Lo=32*1024*1024,_e=40,Ie=/^[A-Za-z0-9._-]{1,128}$/,qn=/^[\w.:@/[\]-]{1,100}$/,Tn=Buffer.from('"usage":{"input_tokens":'),Wt=Buffer.from('{"type":"cost-state"'),at=Buffer.from('{"type":"session-owner"'),Ln=Buffer.from('"timestamp":"'),De=36e5,M=e=>typeof e=="number"&&Number.isFinite(e)?e:null,T=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function In(e){let t=T(e),n=M(t?.used_percentage),r=M(t?.resets_at);return n===null||r===null?null:{pct:Math.max(0,Math.min(100,n)),resetsAt:r<1e11?r*1e3:r}}function Io(e){if(!e||Buffer.byteLength(e)>zt)return null;let t;try{t=T(JSON.parse(e))}catch{return null}if(!t)return null;let n=typeof t.session_id=="string"&&Ie.test(t.session_id)?t.session_id:null,r=T(t.model)?.id,o=typeof r=="string"&&qn.test(r)?r:null,s=M(T(t.cost)?.total_cost_usd),i=T(t.rate_limits),a=typeof t.transcript_path=="string"&&Bn(t.transcript_path)&&t.transcript_path.endsWith(".jsonl")?t.transcript_path:null;return{session:n,model:o,costUsd:s!==null&&s>=0?s:null,fiveHour:In(i?.five_hour),sevenDay:In(i?.seven_day),transcript:a}}function q(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function Q(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function Fe(e){let t=new Date(Q(e));return t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}var V=e=>v(e.dir,"meter"),re=e=>Math.round(e*1e6)/1e6,X=e=>{try{return Eo(e)}catch{return[]}},xe=e=>{try{let t=ge(e);return t.isFile()?t.mtimeMs:0}catch{return 0}};function Do(e){let t;try{t=ct(e,ae.O_RDONLY|ae.O_NONBLOCK)}catch{return!1}try{let n=ut(t);if(!n.isFile()||n.size===0)return!1;let r=Buffer.alloc(1);return Le(t,r,0,1,n.size-1)===1&&r[0]!==10}finally{lt(t)}}function Jt(e,t){if(t.length===0)return;if(K(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);let n=Do(e)?`
5
+ `:"";for(let r of t)n.length+r.length+1>6e4&&n&&(Pn(e,n,{mode:384}),n=""),n+=`${r}
6
+ `;n&&Pn(e,n,{mode:384})}var Fo=4;function Dn(e){let t=T(e);return!!t&&Number.isInteger(t.e)&&t.e>=0&&M(t.u)!==null&&M(t.b)!==null&&typeof t.day=="string"&&M(t.at)!==null}function ft(e){let t=L(e);if(!t||M(t.at)===null)return null;let n=typeof t.m=="string"?t.m:null,r=t.p===0||t.p===1?{p:t.p}:{};if(t.v===2&&Array.isArray(t.totals))return{v:2,totals:t.totals.filter(Dn),m:n,at:t.at,...r};let o={e:t.e,u:t.u,b:t.b,day:t.day,at:t.at};return t.v===1&&Dn(o)?{v:2,totals:[o],m:n,at:t.at}:null}var pt=e=>dt("sha256").update(e).digest("hex").slice(0,16),Jn=e=>e?jo(e):"";function Fn(e){let t=e?Math.max(e.lastIndexOf("/projects/"),e.lastIndexOf("\\projects\\")):-1;return t>0?Jn(e.slice(0,t)):""}var Gn=(e,t)=>`a${pt(`${e}|${t}`)}`;function Yn(e){try{let t=T(JSON.parse(e.toString("utf8"))),n=t?.accountUuid;return t?.type==="session-owner"&&typeof n=="string"&&n.length>0?Gn(n,typeof t.organizationUuid=="string"?t.organizationUuid:""):null}catch{return null}}function Ho(e){let t;try{t=ct(e,ae.O_RDONLY|ae.O_NONBLOCK)}catch{return null}try{if(!ut(t).isFile())return null;let n=Buffer.alloc(64*1024),r=n.subarray(0,Le(t,n,0,n.length,0));for(let o=r.indexOf(at);o>=0;o=r.indexOf(at,o+1)){if(o>0&&r[o-1]!==10)continue;let s=r.indexOf(10,o);if(s<0)break;let i=Yn(r.subarray(o,s));if(i)return i}return null}finally{lt(t)}}function Ae(e,t){let n=pt(Fn(e));if(!e)return{key:`c${n}`,cfg:n};let r=t?L(He(t,e))?.ow:void 0;return{key:(typeof r=="string"&&/^a[0-9a-f]{16}$/.test(r)?r:Ho(e)??(Kt(e)===0?Gt(Fn(e)):null))??`c${n}`,cfg:n}}function Gt(e){if(!e)return null;let t=[v(e,".claude.json"),...qt(e)===".claude"?[v(Po(e),".claude.json")]:[]];for(let n of t){let r=ke(n,16777216);if(r)try{let o=T(T(JSON.parse(r.toString("utf8")))?.oauthAccount),s=o?.accountUuid;if(typeof s=="string"&&s.length>0)return Gn(s,typeof o?.organizationUuid=="string"?o.organizationUuid:"")}catch{}}return null}var gt=e=>({cfg:pt(Jn(e))});function Yt(e,t,n,r){let o=V(e);if(A(o),t.fiveHour||t.sevenDay){let g=r??Ae(t.transcript,e);A(v(o,"limits"));let w=v(o,"limits",`${g.key}.json`),b=L(w);typeof b?.at=="number"&&b.at>n||U(w,`${JSON.stringify({v:2,at:n,cfg:g.cfg,fiveHour:t.fiveHour,sevenDay:t.sevenDay})}
7
+ `)}if(!t.session||t.costUsd===null)return;A(v(o,"sessions"));let s=v(o,"sessions",`${t.session}.json`),i=ft(s);if(i&&n<i.at)return;let a=q(n),l=t.costUsd,u=i?.totals??[],c=-1;for(let g=0;g<u.length;g++)l>=u[g].u-.01&&(c<0||u[g].u>u[c].u)&&(c=g);let d=c>=0?u[c]:null,y=d?{e:d.e,u:Math.max(d.u,l),b:d.day===a?d.b:Wo(e,t.session,d,l,n),day:a,at:n}:{e:u.reduce((g,w)=>Math.max(g,w.e+1),0),u:l,b:i?zo(e,t.transcript,l):l,day:a,at:n},p=[y,...u.filter(g=>g.e!==y.e)].slice(0,Fo);Jt(v(o,`${a}.log`),[JSON.stringify({k:"c",t:n,s:t.session,e:y.e,u:re(l),b:re(y.b),...d?{}:{f:1}})]);let f=t.fiveHour||t.sevenDay?1:l>0?0:i?.p;U(s,`${JSON.stringify({v:2,totals:p.map(g=>({...g,u:re(g.u),b:re(g.b)})),m:t.model??i?.m??null,at:n,...f===void 0?{}:{p:f}})}
8
+ `)}function Wo(e,t,n,r,o){let s=Q(o),i=n.u;try{let a=new Set;for(let l of Te(Math.max(n.at,o-_e*864e5),o))for(let u of Se(e,l)){if(u.k!=="s"||u.s!==t||a.has(u.id)||u.t<=n.at||u.a>=s||u.u<n.u-.005||u.u>r+.01)continue;a.add(u.id);let c=u.t<s?1:u.w>0?Math.min(1,Uo(e,t,u.a,s)/u.w):0;i=Math.max(i,u.p+(u.u-u.p)*c)}}catch{}return Math.min(i,r)}function Uo(e,t,n,r){let o=0,s=new Set;for(let i of Te(Math.max(n,r-(_e+1)*864e5),r))for(let a of Se(e,i))a.k!=="u"||a.h===1||a.s!==t||a.t<=n||a.t>r||s.has(a.id)||(s.add(a.id),o+=Zt(a));return o}function zo(e,t,n){if(!t)return 0;let r=L(He(e,t))?.cs,o=0;for(let s of Array.isArray(r)?r.filter(Zn):[])for(let i of s.v)i<=n+.01&&(o=Math.max(o,i));return Math.min(o,n)}function Vt(e,t){return!t||!Ie.test(t)?!1:ft(v(V(e),"sessions",`${t}.json`))?.p===0}function Vn(e,t){if(!t||!Ie.test(t))return!1;let n=ft(v(V(e),"sessions",`${t}.json`));return n?.p===1&&Date.now()-n.at<De}function nu(e,t){let n=v(V(e),"sessions"),r=!1,o=!1,s=!1;for(let i of X(n)){if(!i.endsWith(".json"))continue;try{if(ge(v(n,i)).mtimeMs<t)continue}catch{continue}let a=ft(v(n,i));!a||!(a.at>=t)||(r=!0,a.p===1&&(o=!0),a.p===0&&(s=!0))}return{any:r,plan:o,off:s}}function Bo(e){let t;try{t=T(JSON.parse(e.toString("utf8")))}catch{return null}if(!t||t.type!=="assistant")return null;let n=T(t.message),r=T(n?.usage),o=typeof n?.model=="string"?n.model:null;if(!r||!o||o==="<synthetic>")return null;let s=qn.test(o)?o:"unknown",i=typeof t.timestamp=="string"?Date.parse(t.timestamp):NaN,a=typeof t.sessionId=="string"&&Ie.test(t.sessionId)?t.sessionId:null,l=typeof n?.id=="string"?n.id:"",u=typeof t.requestId=="string"?t.requestId:"";if(!Number.isFinite(i)||!a||!l&&!u)return null;let c=w=>Math.max(0,M(r[w])??0),d=T(r.cache_creation),y=d?Math.max(0,M(d.ephemeral_1h_input_tokens)??0):0,p=c("cache_creation_input_tokens"),f=M(T(r.server_tool_use)?.web_search_requests)??0,g=dt("sha256").update(`${l}\0${u}`).digest("base64url").slice(0,22);return{t:i,s:a,id:g,m:s,usage:{input:c("input_tokens"),output:c("output_tokens"),write5m:Math.max(0,p-y),write1h:Math.min(y,p),read:c("cache_read_input_tokens"),...r.speed==="fast"?{fast:!0}:{},...f>0?{webSearches:f}:{}}}}function Ko(e){let t;try{t=T(JSON.parse(e.toString("utf8")))}catch{return null}if(!t||t.type!=="cost-state")return null;let n=typeof t.sessionId=="string"&&Ie.test(t.sessionId)?t.sessionId:null,r=M(t.totalCostUSD),o=M(t.startTime);return!n||r===null||r<0||r>1e9||o===null||o<=0?null:{s:n,u:r,st:o,unknown:t.hasUnknownModelCost===!0}}function qo(e,t,n){if(t<=n)return NaN;let r=e.lastIndexOf(Ln,t-1);if(r<n)return NaN;let o=r+Ln.length,s=e.indexOf(34,o);return s>o&&s-o<=40?Date.parse(e.subarray(o,s).toString("latin1")):NaN}var Zt=e=>e.i+5*e.o+1.25*e.w5+2*e.w1+.1*e.r,Jo=16,Zn=e=>{let t=T(e);return!!t&&M(t.st)!==null&&M(t.t)!==null&&Array.isArray(t.v)&&t.v.every(n=>M(n)!==null)},it=e=>e.includes("/subagents/")||e.includes("\\subagents\\"),Go=e=>qt(e,".jsonl").replace(/^agent-/,"").replace(/[^A-Za-z0-9_-]/g,"").slice(0,40),He=(e,t)=>v(V(e),"read",`${dt("sha256").update(t).digest("hex").slice(0,32)}.json`);function Bt(e,t,n=Kn){let r=V(e),o=He(e,t),s=it(t),i=s?Go(t):"",a;try{a=ct(t,ae.O_RDONLY|ae.O_NONBLOCK)}catch{return 0}try{let l=ut(a);if(!l.isFile())return 0;let u=L(o),c=!!u&&u.v===1&&u.ino===l.ino&&Number.isInteger(u.off)&&u.off>=0&&u.off<=l.size,d=c?u.off:0;if(d>=l.size)return 0;let y=d,p=c&&typeof u.ow=="string"?u.ow:void 0,f=[],g=[],w=Math.min(l.size-d,Math.max(1024*1024,n)),b=!1;for(;d<l.size&&d-y<n;){let N=Buffer.alloc(Math.min(w,l.size-d)),x=0;for(;x<N.length;){let R=Le(a,N,x,N.length-x,d+x);if(R===0)break;x+=R}let C=x<N.length,$=N.subarray(0,x),S=$.lastIndexOf(10);if(S<0){if(C||d+x>=l.size)break;if(w>=jn||b){b=!0,d+=x;continue}w=Math.min(jn,w*4);continue}let P=0;b&&(P=$.indexOf(10)+1,b=!1);let _=$.subarray(0,S+1),H=_.indexOf(Tn,P),j=s?-1:_.indexOf(Wt,P);for(;H>=0||j>=0;){let R=j>=0&&(H<0||j<H),B=R?j:H,m=Math.max(P,_.lastIndexOf(10,B)+1);if(R&&m!==B){j=_.indexOf(Wt,B+1);continue}let h=_.indexOf(10,B),E=_.subarray(m,h<0?_.length:h);if(R){let D=Ko(E);D&&g.push({c:D,after:f.length,ts:qo(_,m,P),last:d+(h<0?_.length:h+1)>=l.size})}else{let D=Bo(E);D&&f.push(D)}if(h<0)break;H>=0&&H<=h&&(H=_.indexOf(Tn,h+1)),j>=0&&j<=h&&(j=_.indexOf(Wt,h+1))}if(!s)for(let R=_.lastIndexOf(at);R>=P;R=R>P?_.lastIndexOf(at,R-1):-1){if(R>P&&_[R-1]!==10)continue;let B=Yn(_.subarray(R,_.indexOf(10,R)));if(B){p=B;break}}if(d+=S+1,C)break;w=Math.min(l.size-d,Math.max(1024*1024,n-(d-y)))}if(f.length>0){A(r);let N=new Map,x=new Set;for(let C of f){if(x.has(C.id))continue;x.add(C.id);let $=q(C.t),S=C.usage;if(S.input+S.output+S.write5m+S.write1h+S.read===0&&!S.webSearches)continue;let P=JSON.stringify({k:"u",t:C.t,s:C.s,id:C.id,m:C.m,i:S.input,o:S.output,w5:S.write5m,w1:S.write1h,r:S.read,...S.fast?{f:1}:{},...S.webSearches?{ws:S.webSearches}:{},...s?{h:1,...i?{a:i}:{}}:{}}),_=N.get($);_?_.push(P):N.set($,[P])}for(let[C,$]of N)Jt(v(r,`${C}.log`),$)}let k=c&&M(u.lt)!==null?u.lt:0,O=c&&Array.isArray(u.cs)?u.cs.filter(Zn):[],F=c&&M(u.ev)!==null?u.ev:-1/0;if(g.length>0){let N=qt(t,".jsonl"),x=[],C=0;for(let{c:$,after:S,ts:P,last:_}of g){for(;C<S;C++)k=Math.max(k,f[C].t);if($.st>l.mtimeMs+6e4)continue;let H=Math.max(k,Number.isFinite(P)&&P>=$.st&&P<=l.mtimeMs+6e4?P:0,$.st);_&&l.mtimeMs>H&&(H=l.mtimeMs);let j=O.find(m=>m.st===$.st),R=j?j.v.filter(m=>m<=$.u+.005):[],B=j?R.length>0?Math.min($.u,Math.max(...R)):null:$.st<=F?null:0;B!==null&&$.s===N&&!$.unknown&&x.push({t:H,s:N,u:$.u,p:B,a:j?j.t:$.st-1,st:$.st}),O=[{st:$.st,t:H,v:[...j?.v??[],$.u].slice(-4)},...O.filter(m=>m.st!==$.st)];for(let m of O.splice(Jo))F=Math.max(F,m.t);k=Math.max(k,H)}for(;C<f.length;C++)k=Math.max(k,f[C].t);x.length>0&&Yo(e,x)}else for(let N of f)k=Math.max(k,N.t);return A(v(r,"read")),U(o,`${JSON.stringify({v:1,ino:l.ino,off:d,...k>0?{lt:k}:{},...O.length>0?{cs:O}:{},...Number.isFinite(F)?{ev:F}:{},...p?{ow:p}:{}})}
9
+ `),d-y}finally{lt(a)}}function Yo(e,t){let n=V(e);A(n);let r=t.map(()=>0),o=t.map(()=>0),s=t.map(()=>new Set),i=Math.max(Math.min(...t.map(l=>l.a)),Math.max(...t.map(l=>l.t))-(_e+1)*864e5);for(let l of Te(i,Math.max(...t.map(u=>u.t))))for(let u of Se(e,l))u.k==="u"&&t.forEach((c,d)=>{u.s!==c.s||u.t<=c.a||u.t>c.t||s[d].has(u.id)||(s[d].add(u.id),o[d]+=pe(u.m,{input:u.i,output:u.o,write5m:u.w5,write1h:u.w1,read:u.r,...u.f?{fast:!0}:{},...u.ws?{webSearches:u.ws}:{}})??0,u.h!==1&&(r[d]+=Zt(u)))});let a=new Map;t.forEach((l,u)=>{let c=dt("sha256").update(`${l.s}\0${l.st}\0${l.u}\0${l.p}`).digest("base64url").slice(0,22),d=JSON.stringify({k:"s",t:l.t,s:l.s,id:c,u:re(l.u),p:re(l.p),a:l.a,w:Math.round(r[u]),l:re(o[u])});for(let y of Te(Math.max(l.a,l.t-_e*864e5),l.t)){let p=a.get(y);p?p.push(d):a.set(y,[d])}});for(let[l,u]of a)Jt(v(n,`${l}.log`),u)}function mt(e,t=-1/0){let n=v(e,"subagents"),r=X(n),o=r.filter(s=>s.endsWith(".jsonl")).map(s=>v(n,s));if(r.includes("workflows")){let s=v(n,"workflows");for(let i of X(s)){let a=v(s,i);if(!(t>-1/0&&Vo(a)<t))for(let l of X(a))l.endsWith(".jsonl")&&o.push(v(a,l))}}return o}var Vo=e=>{try{return ge(e).mtimeMs}catch{return 0}},Zo=24*36e5;function Xn(e,t){if(!e.endsWith(".jsonl")||!/^[A-Za-z0-9_-]{1,64}$/.test(t))return null;let n=v(e.slice(0,-6),"subagents"),r=`agent-${t}.jsonl`;if(xe(v(n,r))>0)return v(n,r);let o=v(n,"workflows");for(let s of X(o))if(xe(v(o,s,r))>0)return v(o,s,r);return null}var Xo=15*6e4;function Xt(e,t,n,r=Kn){let o=r,s=mt(t.slice(0,-6),n-Zo).map(i=>({file:i,at:xe(i)})).filter(i=>n-i.at<=Xo).sort((i,a)=>a.at-i.at);for(let{file:i}of s){if(o<=r/2)break;o-=Bt(e,i,o-r/2)}Bt(e,t,o)}function Qn(e,t,n){let r=0,o=(s,i)=>{try{let a=ge(s);if(!a.isFile()||!i&&a.mtimeMs<n)return;let l=L(He(e,s)),u=l&&l.v===1&&l.ino===a.ino&&Number.isInteger(l.off)&&l.off>=0&&l.off<=a.size?l.off:0,c=a.size-u;if(c<=0||c<=1024*1024&&ht(s,u,a.size).indexOf(10)<0)return;r+=c}catch{}};o(t,!0);for(let s of mt(t.slice(0,-6),n))o(s,!1);return r}function ee(e,t){let n=e.CLAUDE_CONFIG_DIR?.trim();return n&&Bn(n)?n:v(t,".claude")}function er(e,t,n,r=1024*1024*1024,o){let s=v(t,"projects"),i=[],a=p=>{let f;try{f=ge(p)}catch{return}if(!f.isFile()||f.mtimeMs<n)return;let g=L(He(e,p)),w=g&&g.v===1&&g.ino===f.ino&&Number.isInteger(g.off)&&g.off<=f.size?g.off:0;f.size>w&&i.push({file:p,at:f.mtimeMs,left:f.size-w})};for(let p of X(s)){let f=v(s,p);for(let g of X(f)){if(g.endsWith(".jsonl")){a(v(f,g));continue}for(let w of mt(v(f,g)))a(w)}}o?.(Math.min(r,i.reduce((p,f)=>p+f.left,0)));let l=p=>it(p)?p.slice(0,Math.max(p.indexOf("/subagents/"),p.indexOf("\\subagents\\"))):p.slice(0,-6),u=new Map;for(let p of i)u.set(l(p.file),Math.max(u.get(l(p.file))??0,p.at));i.sort((p,f)=>u.get(l(f.file))-u.get(l(p.file))||l(p.file).localeCompare(l(f.file))||Number(it(f.file))-Number(it(p.file))||f.at-p.at);let c=r,d=0,y=0;for(let p of i){let f=0,g=0;for(;c>0&&(g=Bt(e,p.file,Math.min(c,256*1024*1024)),c-=g,f+=g,g!==0););g===0&&c>0||f>=p.left||(d+=p.left-f,y=Math.max(y,p.at))}return{left:d,upto:y}}function ru(e,t,n,r=1024*1024*1024,o){return er(e,t,n,r,o).left===0}var je=new Map;function Qo(e,t){for(let n of e.split(`
10
+ `))if(n)try{let r=JSON.parse(n);if(!r||typeof r.t!="number"||typeof r.s!="string")continue;(r.k==="c"&&Number.isInteger(r.e)&&typeof r.u=="number"&&typeof r.b=="number"||r.k==="u"&&typeof r.id=="string"&&typeof r.m=="string"||r.k==="s"&&typeof r.id=="string"&&typeof r.u=="number"&&typeof r.p=="number"&&typeof r.a=="number"&&typeof r.w=="number"&&(r.l===void 0||typeof r.l=="number")&&r.u>=r.p&&r.a<r.t)&&t.push(r)}catch{}}function ht(e,t,n){let r=ct(e,ae.O_RDONLY|ae.O_NONBLOCK);try{if(!ut(r).isFile())throw new Error(`${e} is not a regular file`);let o=Buffer.alloc(Math.max(0,n-t)),s=0;for(;s<o.length;){let i=Le(r,o,s,o.length-s,t+s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{lt(r)}}function Se(e,t,n){let r=v(V(e),`${t}.log`),o;try{if(o=ge(r),o.size>Lo)return n?.("large"),[]}catch(d){return d.code!=="ENOENT"&&n?.("unreadable"),[]}let s=je.get(r);if(s&&s.ino===o.ino&&s.size===o.size&&s.mtime===o.mtimeMs)return s.lines;let i=s&&s.ino===o.ino&&o.size>s.size?s.end:0,a;try{a=ht(r,i,o.size)}catch{return n?.("unreadable"),[]}let l=a.lastIndexOf(10)+1,u=[];Qo(a.subarray(0,l).toString("utf8"),u);let c=i>0?s.lines.concat(u):u;return je.size>=64&&!je.has(r)&&je.clear(),je.set(r,{ino:o.ino,size:o.size,mtime:o.mtimeMs,end:i+l,lines:c}),c}function Te(e,t){let n=[],r=new Date(Q(e));for(;r.getTime()<=t;r.setDate(r.getDate()+1))n.push(q(r.getTime()));return n}function Hn(e,t,n){let r=e.totals.get(t);r||e.totals.set(t,r=new Map);let o=r.get(n);return o||r.set(n,o={open:-1/0,credit:0,days:[]}),o}function es(e,t){let{from:n,to:r,only:o}=e,s=new Map;for(let i of t)if(!(o!==null&&i.s!==o))if(i.k==="u"){if(i.t<n||i.t>r||e.seen.has(i.id))continue;e.seen.add(i.id),e.replies+=1,e.sessions.add(i.s),e.tokens.input+=i.i,e.tokens.output+=i.o,e.tokens.write+=i.w5+i.w1,e.tokens.read+=i.r;let a=pe(i.m,{input:i.i,output:i.o,write5m:i.w5,write1h:i.w1,read:i.r,...i.f?{fast:!0}:{},...i.ws?{webSearches:i.ws}:{}}),l=e.priced.get(i.s);l?l.push({t:i.t,usd:a,m:i.m,l:i}):e.priced.set(i.s,[{t:i.t,usd:a,m:i.m,l:i}]);let u=e.perModel.get(i.m)??{fresh:0,usd:0};e.perModel.set(i.m,{fresh:u.fresh+i.i+i.o+i.w5+i.w1,usd:a===null||u.usd===null?null:u.usd+a})}else if(i.k==="c"){if(i.t>r)continue;let a=Hn(e,i.s,i.e);i.f===1&&(a.open===-1/0||i.t<a.open)&&(a.open=i.t,a.credit=i.t>=n?Math.max(0,i.u-i.b):0);let l=e.marks.get(i.s);l?l.push({t:i.t,u:i.u}):e.marks.set(i.s,[{t:i.t,u:i.u}]);let u=`${i.s}\0${i.e}`,c=s.get(u)??{s:i.s,e:i.e,max:-1/0,before:null,base:1/0,last:-1/0};i.t<n?c.before=Math.max(c.before??-1/0,i.u):c.max=Math.max(c.max,i.u),c.base=Math.min(c.base,i.b),c.last=Math.max(c.last,i.t),s.set(u,c)}else{let a=e.segs.get(i.s);a||e.segs.set(i.s,a=new Map),a.has(i.id)||a.set(i.id,i)}for(let i of s.values()){if(i.max===-1/0)continue;let a=i.before??i.base;Hn(e,i.s,i.e).days.push({start:a,max:i.max,last:i.last}),e.statusUsd.set(i.s,(e.statusUsd.get(i.s)??0)+Math.max(0,i.max-a)),e.sessions.add(i.s)}}function ts(e,t,n){let{from:r,to:o}=e,s=e.statusUsd.get(t)??0,i=!1,a=e.priced.get(t)??[];if(!e.totals.has(t)&&!e.segs.has(t)){for(let f of a)f.usd===null?n.add(f.m):s+=f.usd;return{usd:s,estimated:a.length>0}}let l=[...e.totals.get(t)?.values()??[]],u=(e.marks.get(t)??[]).sort((f,g)=>f.t-g.t),c=[...e.segs.get(t)?.values()??[]].filter(f=>{if(f.t<r||f.a>=o)return!1;let g=0,w=u.length;for(;g<w;){let b=g+w>>1;u[b].t<=f.a?g=b+1:w=b}for(let b=g;b<u.length&&u[b].t<=f.t;b++)if(u[b].u>f.p+.005&&u[b].u<=f.u+.005)return!1;return!l.some(b=>b.days.some(k=>k.last>f.t&&k.start<f.u-.005&&k.max>=f.u-.005))}),d=new Map;for(let f of c){let g=1,w=Math.max(f.a,r),b=Math.min(f.t,o);if(f.a<r||f.t>o){let O=0;for(let F of a)F.l.h!==1&&F.t>w&&F.t<=b&&(O+=Zt(F.l));g=f.w>0?Math.min(1,O/f.w):f.t>=r&&f.t<=o?1:0}let k=0;for(let O of a)O.usd!==null&&O.t>w&&O.t<=b&&(k+=O.usd);f.l!==void 0&&(k=Math.max(k,f.l)),!(k>(f.u-f.p)*1.25+.05)&&d.set(f,g)}for(let[f,g]of d)g<=0||(s+=(f.u-f.p)*g,e.sessions.add(t));let y=[...d.keys()],p=a.map(f=>l.some(g=>g.open<f.t&&g.days.some(w=>w.last>=f.t))||y.some(g=>g.a<f.t&&f.t<=g.t));for(let f of l){if(f.credit<.005)continue;let g=f.credit*1.1+.005,w=a.map((b,k)=>k).filter(b=>!p[b]&&a[b].t<f.open&&a[b].usd!==null).sort((b,k)=>a[k].t-a[b].t);for(let b of w){if(a[b].usd>g)break;g-=a[b].usd,p[b]=!0}}return a.forEach((f,g)=>{p[g]||(i=!0,f.usd===null?n.add(f.m):s+=f.usd)}),{usd:s,estimated:i}}function yt(e,t,n,r=null){let o=Math.max(t,Q(n-(_e+1)*864e5)),s={paths:e,from:o,to:n,only:r,statusUsd:new Map,totals:new Map,marks:new Map,segs:new Map,seen:new Set,tokens:{input:0,output:0,write:0,read:0},priced:new Map,perModel:new Map,sessions:new Set,replies:0},i,a=g=>{i=i==="large"?"large":g};for(let g of Te(o,n))es(s,Se(e,g,a));let l=0,u=!1,c=new Set;for(let g of new Set([...s.sessions,...s.segs.keys()])){let w=ts(s,g,c);l+=w.usd,u||=w.estimated}let{tokens:d,replies:y,sessions:p,perModel:f}=s;return{usd:re(l),estimated:u,unpriced:[...c].sort(),tokens:{...d,fresh:d.input+d.output+d.write},replies:y,sessions:p.size,models:[...f.entries()].map(([g,w])=>({model:g,fresh:w.fresh,usd:w.usd===null?null:re(w.usd)})).sort((g,w)=>w.fresh-g.fresh),...i?{problem:i}:{}}}var ns=pt("");function Ce(e,t,n={}){let r=v(V(e),"limits"),o=n.key!==void 0?/^[ac][0-9a-f]{16}$/.test(n.key)?[`${n.key}.json`]:[]:X(r).filter(i=>i.endsWith(".json")),s=null;for(let i of o){let a=L(v(r,i));if(!a||a.v!==2||typeof a.at!="number"||a.at>t+6e4||n.cfg!==void 0&&a.cfg!==n.cfg&&a.cfg!==ns)continue;let l=u=>{let c=T(u),d=M(c?.pct),y=M(c?.resetsAt);return d!==null&&y!==null?{pct:d,resetsAt:y}:null};(!s||a.at>s.at)&&(s={fiveHour:l(a.fiveHour),sevenDay:l(a.sevenDay),at:a.at})}return s}function rs(e,t,n={}){let r=Ce(e,t,n),o=a=>a&&a.resetsAt>t?a:null,s=o(r?.fiveHour??null),i=o(r?.sevenDay??null);return r&&(s||i)?{fiveHour:s,sevenDay:i,at:r.at}:null}function wt(e){return typeof e.prompt=="string"&&/^\s*<task-notification>/.test(e.prompt.slice(0,64))}function tr(e){if(!e)return null;let t="";try{t=ht(e,0,512*1024).toString("utf8")}catch{return null}for(let n of t.split(`
11
+ `))if(!(!n.includes('"type":"assistant"')||!n.includes('"usage"')))try{let r=JSON.parse(n).message?.usage;if(!r)continue;let o=s=>typeof r[s]=="number"?r[s]:0;return o("input_tokens")+o("cache_creation_input_tokens")+o("cache_read_input_tokens")}catch{}return null}var Ut=3;function nr(e,t,n,r=0){let o=[],s=new Map,i={},a=null,l=new Map,u=[],c=m=>{let h=l.get(m.s);m.s!==t&&(!h||m.t<h.t)&&l.set(m.s,{t:m.t,c:y(m)}),m.s!==t&&u.push({t:m.t,s:m.s,c:y(m)})},d=new Set,y=(m,h=!0)=>({usd:pe(m.m,{input:m.i,output:m.o,write5m:h?m.w5:0,write1h:h?m.w1:0,read:m.r,...m.f?{fast:!0}:{},...m.ws?{webSearches:m.ws}:{}})??0,fresh:m.i+m.o+(h?m.w5+m.w1:0)}),p=m=>{let h=`${m.s}/${m.a}`,E=s.get(h)??[];E.push({t:m.t,c:y(m),own:m.s===t,warm:m.r>m.w5+m.w1}),s.set(h,E)},f=[];for(let m of[q(n),q(n-864e5)]){if(m!==q(n)&&o.length>0)break;for(let h of Se(e,m))h.k!=="u"||d.has(h.id)||(d.add(h.id),h.h===1&&h.a&&m===q(n)&&p(h),h.h===1&&m===q(n)&&h.t<=n&&(i[h.m]>=h.t||(i[h.m]=h.t),h.s===t&&(!a||h.t>a.t)&&(a={t:h.t,m:h.m})),h.h!==1&&m===q(n)&&c(h),h.s===t&&(h.h===1?f.push({t:h.t,c:y(h),a:h.a}):o.push({t:h.t,c:y(h),m:h.m,u:h})))}for(let m=1;m<=r&&(s.size===0||l.size===0);m++){let h=s.size,E=l.size;for(let D of Se(e,q(n-m*864e5)))D.k==="u"&&(D.h===1&&D.a&&h===0&&p(D),D.h!==1&&E===0&&c(D))}let g=m=>m.sort((h,E)=>h.t-E.t).slice(-Ut).map(h=>h.c);o.sort((m,h)=>m.t-h.t);let w=o.slice(-Ut).reduce((m,h)=>!m||h.c.fresh>m.fresh?h.c:m,null),b=o.at(-1)?.t??null,k=o[0]?.u;o.length>0&&(o[0]={...o[0],c:y(o[0].u,!1)});let O=[],F=[],N=new Set;for(let[m,h]of s)h.sort((E,D)=>E.t-D.t),O.push(h[0]),F.push(...h.slice(1)),N.add(`${m}@${h[0].t}`);let x=m=>m.sort((h,E)=>h.t-E.t).slice(-Ut).reduce((h,E)=>!h||E.c.fresh>h.fresh?E.c:h,null),C=x(O.filter(m=>m.own))??x(O),$=m=>x(O.filter(h=>h.own&&h.warm===m))??x(O.filter(h=>h.warm===m)),S=$(!0),P=$(!1),_=f.filter(m=>!m.a||!N.has(`${t}/${m.a}@${m.t}`)),H=k?k.i+k.w5+k.w1+k.r:null,j=m=>{let h=o.find(E=>E.t>=m);return g(o.filter(E=>E!==h))},R=x([...l.values()]),B=g(u.filter(m=>m.t!==l.get(m.s)?.t));return{main:g(o),helpers:g(_),helperFirst:C,helperFirstWarm:S,helperFirstCold:P,helperRepliedAt:i,helperModel:a?.m??null,helpersToday:g(F),chatPrompt:H,chatFirst:R,chatToday:B,chatRecent:w,lastMainAt:b,mainSince:j,model:o.at(-1)?.m??null}}var Wn=9e4;function rr(e,t){if(!e?.endsWith(".jsonl"))return[];let n=[];for(let r of mt(e.slice(0,-6),t-Wn)){if(xe(r)<t-Wn)continue;let o=0;try{let a=ht(r,0,Math.min(4096,Kt(r))).toString("utf8").split(`
12
+ `)[0]??"",l=T(JSON.parse(a))?.timestamp;o=typeof l=="string"&&Date.parse(l)||0}catch{o=0}let s=ne(r,64*1024).split(`
13
+ `).filter(a=>a.startsWith("{")),i="starting";for(let a=s.length-1;a>=0;a--)if(s[a].includes('"type":"assistant"')){try{i=T(T(JSON.parse(s[a]))?.message)?.stop_reason==="end_turn"&&a===s.length-1?"done":"running"}catch{i="running"}break}i==="starting"&&Kt(r)>64*1024&&!(o>0&&t-o<6e4)&&(i="running"),n.push({state:i,started:o})}return n}var Kt=e=>{try{return ge(e).size}catch{return 0}};function We(e){return e<6e4?"under a minute":e<36e5?`${Math.floor(e/6e4)} min`:e<48*36e5?`${Math.floor(e/36e5)} h`:`${Math.floor(e/864e5)} days`}var Qt=e=>`read ${e<6e4?"just now":`${We(e)} ago`}`,or=e=>`${Math.max(1,Math.round(e/1048576))} MB`,os=(e,t=!1)=>e.unpriced.length>0||t?`~${zn(e.usd)}+`:`${e.estimated?"~":""}${zn(e.usd)}`;function ss(e,t){let n=V(e),r=v(n,"pruned"),o=q(t);try{if(ke(r,64)?.toString("utf8").trim()===o)return}catch{}let s=t-_e*864e5,i=q(s);for(let a of X(n))/^\d{4}-\d{2}-\d{2}\.log$/.test(a)&&a.slice(0,10)<i&&st(v(n,a),{force:!0});st(v(n,"limits.json"),{force:!0});for(let a of["launches","live"])for(let l of X(v(n,a))){let u=v(n,a,l);xe(u)<t-864e5&&st(u,{force:!0})}for(let a of["sessions","read","tasks","said","limits"])for(let l of X(v(n,a))){let u=v(n,a,l);xe(u)<s&&st(u,{force:!0})}try{A(n),U(r,o)}catch{}}function Un(e,t,n){let r=e&&n!==void 0&&n-e.at>=6e4?` (${We(n-e.at)} ago)`:"";return e?.sevenDay?{text:`${Math.round(e.sevenDay.pct)}% of week${r}`,today:!1}:e?.fiveHour?{text:`${Math.round(e.fiveHour.pct)}% of 5 hours${r}`,today:!1}:e||!t||t.usd<.005&&t.unpriced.length===0?null:{text:os(t),today:!0}}function zn(e){return e<10?`$${e.toFixed(2)}`:`$${String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`}function Ue(e){return e>=1e9?`${(e/1e9).toFixed(e>=1e10?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function is(){if(To(0))return null;let e=Buffer.alloc(zt+1),t=0;for(let n=0;;){let r=0;try{r=Le(0,e,t,e.length-t,null)}catch(o){if(o.code==="EAGAIN"&&n++<50){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,2);continue}return t>0?e.subarray(0,t).toString("utf8"):null}if(r===0)break;if(t+=r,t>zt)return null}return t>0?e.subarray(0,t).toString("utf8"):null}function as(e,t,n,r=null){let o=t?Io(t):null,s=l=>{try{l()}catch{}};o?.transcript&&s(()=>Xt(e,o.transcript,n));let i=null;try{i=o?Ae(o.transcript,e):null}catch{}let a=i;o&&s(()=>Yt(e,o,n,a??void 0)),r&&s(()=>fs(e,r,n)),s(()=>ss(e,n));try{let l=o!==null&&!o.fiveHour&&!o.sevenDay&&(o.costUsd??0)>0,u=i?{key:i.key}:r?gt(r):{},c=l?null:rs(e,n,u),d=c&&n-c.at<=De?c:null;return d?Un(d,null,n):Un(null,yt(e,Q(n),n))}catch{return null}}var ls=5*6e4,us=3e4,cs=32*1024*1024;function ds(e){let t="";try{t=ke(e,4096)?.toString("utf8").trim()??""}catch{return null}if(/^\d+$/.test(t))return{at:Number(t),since:Q(Number(t)),left:0,upto:0};try{let n=T(JSON.parse(t)),r=M(n?.at),o=M(n?.since);return r!==null&&o!==null?{at:r,since:o,left:Math.max(0,M(n?.left)??0),upto:M(n?.upto)??0}:null}catch{return null}}function en(e,t,n,r){let o=v(V(e),"caught"),s=ds(o);if(s&&s.at<=r&&s.since<=n&&r-s.at<(s.left>0?us:ls))return s;let i=s&&s.at<=r&&r-s.at<864e5&&s.since<n&&s.since>=Fe(r)?s.since:n;A(V(e)),U(o,JSON.stringify({v:1,at:r,since:i,left:s?.left??0,upto:s?.upto??0}));let a=er(e,t,i,cs),l={at:r,since:i,left:a.left,upto:a.upto};return U(o,JSON.stringify({v:1,...l})),l}function fs(e,t,n){en(e,t,Q(n),n)}function ou(e,t){return as(e,is(),t,ee(process.env,Mo()))}import{createHash as ci}from"crypto";import{accessSync as di,closeSync as fi,constants as pi,openSync as gi,readdirSync as Wr,readFileSync as mi,rmSync as hi}from"fs";import{homedir as yi}from"os";import{basename as Ur,dirname as wi,join as G}from"path";function ze(e){let t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}import{createHash as kr,randomBytes as $r}from"crypto";import{readdirSync as _r,renameSync as Es,unlinkSync as wc}from"fs";import{join as Ge}from"path";import{createHmac as vs,randomBytes as rn,timingSafeEqual as ks}from"crypto";import{closeSync as cr,existsSync as $s,fsyncSync as dr,linkSync as _s,mkdirSync as fr,openSync as pr,readdirSync as xs,readFileSync as Ne,unlinkSync as gr,writeSync as mr}from"fs";import{basename as Ss,dirname as ar,join as se}from"path";var oe={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function ps(e){if(!e){let l=u=>u;return{on:!1,bold:l,dim:l,blue:l,grey:l,amber:l,mark:l,field:l}}let t=e==="truecolor",n=l=>u=>`\x1B[${l}m${u}\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"),i=n(t?"38;2;34;197;94":"32"),a={[oe.on]:r,[oe.blocked]:r,[oe.held]:r,[oe.next]:r,[oe.watching]:o,[oe.problem]:s,[oe.ok]:i};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:s,mark:l=>(a[l]??(u=>u))(l),field:l=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${ms(l)}\x1B[0m`}}var au=ps(!1),gs=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function ms(e){return e.replace(gs,"")}var sr=[{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)"}}],hs="home and project wipes and force-pushes to main",fu=`always blocking ${hs}`,pu=new Map(sr.map(e=>[e.id,e]));var ys=new Set(sr.flatMap(e=>Object.keys(e.slugs)));var tn="anvil-claude";function z(e){let t=e.trim();return t===tn||t.endsWith(` ${tn}`)||t.endsWith(`/${tn}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ir="\u{1F539}",I=e=>`${ir} ${e} ${ir}`;var Be=e=>`
14
+ ${oe.next} ${e}`;function Ke(e,t,n){return`${Be(`To ${e}, run this in a terminal (not in this chat):`)}
15
+ ${t}${n?Be(`Then ${n}.`):""}`}var nn=e=>Be(e),ws=72;function bt(e,t){let n=`To ${e}, run in a terminal: ${t}`;return n.length+5<=ws?Be(n):`${Be(`To ${e}, run in a terminal:`)}
16
+ ${t}`}var vt=(e,t)=>`they run \`${z(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${t}`;var bs="anvil";var le=e=>`${z(bs)} ${e}`;import{spawnSync as Mu}from"child_process";import{createHash as ju}from"crypto";import{chmodSync as Lu,existsSync as Iu,lstatSync as Du,mkdirSync as Fu,readdirSync as Hu,readFileSync as Wu,readlinkSync as Uu,realpathSync as zu,rmdirSync as Bu,statSync as Ku,unlinkSync as qu,writeFileSync as Ju}from"fs";import{dirname as Yu,join as Vu,resolve as Zu}from"path";var ie="_seal";function xt(e){return se(e.dir,"seal.key")}function Oe(e,t){return se(e.state,"lkg",t)}function J(e){let t=xt(e);if(K(t,1024)!==!0)return null;try{let n=Ne(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function an(e){return J(e)?"ok":K(xt(e),1024)===null?"missing":"damaged"}var _t=class extends Error{};function St(e,t){return`Anvil's seal key (${xt(e)}) is ${t==="damaged"?"damaged":"missing"}`}function As(e){let t=J(e);if(t)return t;let n=an(e);if(n==="damaged"||ln(e))throw new _t(`${St(e,n)}; run ${le("on")} to restore it`);let{key:r,created:o}=Cs(e,!1);return o&&Rs(e,r),r}function lr(e,t,n){let r=pr(e,n,384);try{mr(r,t),dr(r)}finally{cr(r)}}function Cs(e,t){fr(e.dir,{recursive:!0,mode:448});let n=xt(e),r=se(e.dir,`.seal.key.${process.pid}.${rn(4).toString("hex")}.tmp`);lr(r,`${rn(32).toString("hex")}
17
+ `,"wx");let o=!1;try{t?Pe(r,n):_s(r,n),o=!0}catch(i){let a=i.code??"";if(a!=="EEXIST"){if(t||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(a))throw i;try{lr(n,Ne(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{gr(r)}catch{}}let s=J(e);if(!s)throw new _t(`${St(e,"damaged")}; run ${le("on")} to restore it`);return{key:s,created:o}}function Rs(e,t){let n=[[e.modes,$t],[e.compiled,yr],[e.install,void 0]];for(let[r,o]of n)if(K(r,8*1024*1024)===!0)try{let s=Ne(r,"utf8");if(s.includes(`"${ie}"`))continue;let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=`${JSON.stringify(sn(t,i),null,2)}
18
+ `;Re(r,a),o&&Re(Oe(e,o),a)}catch{}if(K(e.modes)===null&&K(Oe(e,$t))===null){let r=`${JSON.stringify(sn(t,Lt()),null,2)}
19
+ `;Re(e.modes,r),Re(Oe(e,$t),r)}}function on(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>on(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(t===0&&r===ie)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${on(e[r],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function hr(e,t){return vs("sha256",e).update(on(t)).digest("hex")}function kt(e){if(!(ie in e))return e;let t={...e};return delete t[ie],t}function sn(e,t){let n=kt(t);return{...n,[ie]:hr(e,n)}}function Os(e,t){let n=t[ie];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let r;try{r=hr(e,t)}catch{return!1}return ks(Buffer.from(n,"hex"),Buffer.from(r,"hex"))}function Re(e,t,n=384){fr(ar(e),{recursive:!0,mode:448});let r=se(ar(e),`.${Ss(e)}.${process.pid}.${Date.now().toString(36)}.${rn(3).toString("hex")}.tmp`);try{let o=pr(r,"w",n);try{mr(o,t),dr(o)}finally{cr(o)}Pe(r,e)}catch(o){try{gr(r)}catch{}throw o}}function Z(e,t,n=8*1024*1024){let r=K(e,n);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(Ne(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:t?ie in o?Os(t,o)?{status:"ok",value:kt(o)}:{status:"changed",value:kt(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:kt(o)}}function At(e,t,n,r){let o=As(e),s=`${JSON.stringify(sn(o,n),null,2)}
20
+ `;Re(t,s),r&&Re(Oe(e,r),s)}var $t="modes.json",yr="compiled.json";function ln(e){return $s(se(e.bin,"claude-hook.sh"))||Ns(e)}function Ns(e){let t=n=>{try{return xs(n).slice(0,200).some(r=>r.endsWith(".json")&&K(se(n,r),65536)===!0&&Ne(se(n,r),"utf8").includes(`"${ie}"`))}catch{return!1}};if(t(se(e.state,"lkg"))||t(se(e.state,"pending"))||t(e.approvals))return!0;for(let n of[e.modes,e.compiled,e.install])if(K(n,8*1024*1024)===!0)try{if(Ne(n,"utf8").includes(`"${ie}"`))return!0}catch{}return!1}var wr={missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"};function ur(e=new Date){return xn(null,"enforce","all",e)}function qe(e,t=J(e),n={}){if(!t){let i=an(e);if(n.installed===!0||i==="damaged"||ln(e))return{value:ur(),source:"strict",problem:`${St(e,i)}, so every rule is enforced until \`${le("on")}\` restores it`};let a=Z(e.modes,null);return{value:a.status==="unkeyed"?a.value:null,source:"unkeyed",problem:null}}let r=Z(e.modes,t);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${wr[r.status]??"cannot be used"}`,s=Z(Oe(e,$t),t);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:ur(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${le("on")}\` resets it`}}function Je(e,t,n=J(e),r={}){let o=u=>!!u&&typeof u=="object"&&u.format===Ht&&Array.isArray(u.policies),s=()=>{if(!t)return null;let u=Z(t,null);return u.status==="unkeyed"&&o(u.value)?u.value:null};if(!n){let u=an(e),c=r.installed===!0||u==="damaged"||ln(e),d=Z(e.compiled,null),y=d.status==="unkeyed"&&o(d.value)?d.value:null;return c?{value:null,source:"strict",problem:`${St(e,u)}: \`${le("on")}\` restores it`}:{value:y??s(),source:"unkeyed",problem:null}}let i=Z(e.compiled,n);if(i.status==="ok"&&o(i.value))return{value:i.value,source:"file",problem:null};let a=`compiled.json ${i.status==="ok"?"is not a rules table":wr[i.status]??"cannot be used"}`,l=Z(Oe(e,yr),n);return l.status==="ok"&&o(l.value)?{value:l.value,source:"last-good",problem:`${a}; Anvil keeps the rules it last compiled`}:i.status==="missing"&&l.status==="missing"&&K(e.install)===null&&r.installed!==!0?{value:s(),source:"file",problem:null}:{value:null,source:"strict",problem:`${a}, and so is Anvil's own copy: \`${le("on")}\` recompiles them`}}var $c=600*1e3,Ms=1440*60*1e3,br="23456789abcdefghjkmnpqrstuvwxyz",vr=8;function me(e){return Ge(e.state,"pending")}function Ps(){let e=$r(vr),t="";for(let n=0;n<vr;n++)t+=br[e[n]%br.length];return t}function js(e){return kr("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var Ts=()=>$r(8).toString("hex"),Ls=e=>`${kr("sha256").update(e??"").digest("hex").slice(0,12)}.`;function xr(e,t,n){let r=Ps(),o=Ts();A(me(e));let s={v:2,id:o,code_sha256:js(r),...t,created_at:new Date(n).toISOString(),expires_at:new Date(n+Ms).toISOString()};return At(e,Ge(me(e),`${Ls(t.session)}${o}.json`),s),{code:r,id:o}}function Is(e,t){return e.kind===t.kind&&(e.target??null)===(t.target??null)}function Sr(e,t,n){let r=[];try{r=_r(me(e)).filter(s=>s.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let s of r){let i=Ge(me(e),s),a=Z(i,t,64*1024);a.status!=="ok"||a.value.v!==2||!Array.isArray(a.value.stops)||!(Date.parse(a.value.expires_at)>=n)||o.push({hold:a.value,file:i})}return o.sort((s,i)=>Date.parse(i.hold.created_at)-Date.parse(s.hold.created_at))}function Ar(e,t,n,r,o,s){let i=[];try{i=_r(e.approvals).filter(l=>l.endsWith(".json")&&!l.includes(".used-")).slice(0,2e3)}catch{return{approved:!1,forged:0}}let a=0;for(let l of i){let u=Ge(e.approvals,l),c=Z(u,t,64*1024);if(c.status==="missing")continue;if(c.status!=="ok"||c.value.v!==2||!Array.isArray(c.value.stops)){a++;continue}let d=c.value;if(Date.parse(d.expires_at)>=s&&!((d.session??null)!==(n??null)||(d.project??null)!==(r??null))&&o.every(y=>d.stops.some(p=>Is(p,y))))try{return Es(u,Ge(e.approvals,`${l.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:a}}catch{}}return{approved:!1,forged:a}}import{spawn as Ds,spawnSync as Cr}from"child_process";import{closeSync as Fs,openSync as Hs,readdirSync as Ws,readlinkSync as Us,statSync as Rr,unlinkSync as Or,writeSync as zs}from"fs";import{delimiter as Bs,isAbsolute as Ks,join as he}from"path";var qs=5*6e4,un=2*6e4,Nr=3,Js=15*6e4,Gs=6*36e5,Er=3e4,Ys=6e4,Vs=["-p","/usage","--output-format","stream-json","--verbose","--no-session-persistence","--setting-sources","project","--settings",'{"autoMemoryEnabled":false}',"--strict-mcp-config","--model","anvil-reads-usage-only"],Mr="ANVIL_PLAN_PROBE",Pr=(e,t)=>he(e.state,`plan-probe-${t}.json`),cn=(e,t)=>he(e.state,`plan-probe-next-${t}`),jr=e=>he(e.state,"plan-probe.lock"),Zs=e=>he(e.dir,"plan-probe");function Tr(e,t){let n=t?[Pr(e,t)]:Xs(e),r=null;for(let o of n){let s=L(o);if(!s||typeof s.at!="number"||typeof s.ok!="boolean")continue;let i=typeof s.why=="string"&&["nobinary","failed","unavailable","noplan","unreadable","otheraccount"].includes(s.why)?s.why:void 0,a={at:s.at,ok:s.ok,...i?{why:i}:{},...typeof s.version=="string"?{version:s.version}:{}};(!r||a.at>r.at)&&(r=a)}return r}function Xs(e){try{return Ws(e.state).filter(t=>/^plan-probe-[ac][0-9a-f]{16}\.json$/.test(t)).map(t=>he(e.state,t))}catch{return[]}}function Qs(e){let t=null,n,r=!1;for(let a of e.split(`
21
+ `)){if(!a.startsWith("{"))continue;let l;try{l=JSON.parse(a)}catch{continue}l.type==="system"&&l.subtype==="init"&&typeof l.claude_code_version=="string"&&(t=l.claude_code_version),l.type==="result"&&typeof l.result=="string"&&/using your (subscription|overages) to power/.test(l.result)&&(r=!0);let u=l.usage_report;if(n===void 0&&u&&typeof u=="object"){let c=u.rate_limits;n=c&&Array.isArray(c.limits)?c.limits:null}}if(n===void 0)return null;if(!n||n.length===0)return r?null:"noplan";let o=a=>{let l=n.find(d=>!!d&&typeof d=="object"&&d.kind===a),u=typeof l?.percent=="number"&&Number.isFinite(l.percent)?l.percent:null,c=typeof l?.resets_at=="string"?Date.parse(l.resets_at):Number.NaN;return u!==null&&Number.isFinite(c)?{pct:Math.max(0,Math.min(100,u)),resetsAt:c}:null},s=o("session"),i=o("weekly_all");return s||i?{fiveHour:s,sevenDay:i,version:t}:null}function ei(e,t=ti,n=!1){let r=a=>{try{return a&&Ks(a)&&Rr(a).isFile()?a:null}catch{return null}},o=a=>a&&/(^|[\\/])claude(\.exe)?$|[\\/]claude[\\/]versions[\\/][^\\/]+$/.test(a)?a:null,s=o(r(e.CLAUDE_CODE_EXECPATH?.trim()));if(s)return s;let i=Number(e.CLAUDE_PID);if(Number.isInteger(i)&&i>1){let a=o(r(t(i)));if(a)return a}if(!n)return null;for(let a of(e.PATH??"").split(Bs)){let l=a?r(he(a,"claude"))??(process.platform==="win32"?r(he(a,"claude.exe")):null):null;if(l)return l}return null}function ti(e){try{return Us(`/proc/${e}/exe`)}catch{}try{let t=Cr("ps",["-o","comm=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{PATH:"/bin:/usr/bin",LC_ALL:"C"}});return t.status===0&&t.stdout.trim()||null}catch{return null}}function ni(e){let t=["HOME","USER","LOGNAME","PATH","Path","TMPDIR","TEMP","TMP","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERNAME","ProgramFiles","ProgramData","LANG","LC_ALL","LC_CTYPE","SHELL","CLAUDE_CONFIG_DIR","CLAUDE_CODE_OAUTH_TOKEN","HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","NO_PROXY","no_proxy","ALL_PROXY","all_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR","XDG_CONFIG_HOME","XDG_RUNTIME_DIR"],n={};for(let r of t)e[r]!==void 0&&e[r]!==""&&(n[r]=e[r]);return n[Mr]="1",n.DISABLE_AUTOUPDATER="1",n}var ri=(e,t,n)=>{let r=Cr(e,t,{cwd:n.cwd,env:n.env,timeout:n.timeout,encoding:"utf8",input:"",maxBuffer:4194304,killSignal:"SIGKILL",windowsHide:!0});return{status:r.status,stdout:r.stdout??"",...r.error?{error:r.error}:{}}};function oi(e,t){let n=jr(e);for(let r=0;r<2;r++)try{let o=Hs(n,"wx",384);return zs(o,String(t)),Fs(o),!0}catch(o){if(o.code!=="EEXIST")return!1;let s=Number(ne(n,64).trim());if(Number.isFinite(s)&&t-s<Ys&&s<=t+6e4)return!1;try{Or(n)}catch{return!1}}return!1}function si(e){try{Or(jr(e))}catch{}}function ii(e){try{if(A(e.paths.state),!oi(e.paths,e.now()))return null;try{let t=Ce(e.paths,e.now(),{key:e.account.key});if(!e.screen&&t&&e.now()-t.at<un)return null;let n=ai(e);if(e.screen&&!n.ok)return n;U(Pr(e.paths,e.account.key),`${JSON.stringify(n)}
22
+ `);let r=n.ok?un:n.why==="noplan"||n.why==="unavailable"||n.why==="nobinary"?Gs:Js;return U(cn(e.paths,e.account.key),String(e.now()+r)),n}finally{si(e.paths)}}catch{return null}}function ai(e){let t=e.binary??ei(e.env,e.exeOf);if(!t)return{at:e.now(),ok:!1,why:"nobinary"};let n=Zs(e.paths);A(n);let r=(e.run??ri)(t,Vs,{cwd:n,env:ni(e.env),timeout:Er}),o=e.now();if(r.error||r.status===null)return{at:o,ok:!1,why:"failed"};let s=Qs(r.stdout),i=/"claude_code_version":"([0-9.]{1,20})"/.exec(r.stdout)?.[1],a=i?{version:i}:{};if(s==="noplan")return{at:o,ok:!1,why:"noplan",...a};if(s===null)return{at:o,ok:!1,why:/unrecognized_model|isn't installed|Unknown command/.test(r.stdout)?"unavailable":/usage_report|using your (subscription|overages)/.test(r.stdout)?"failed":r.stdout.trim()?"unreadable":"failed",...a};if(!e.env.CLAUDE_CODE_OAUTH_TOKEN&&e.account.key.startsWith("a")){let l=Gt(ee(e.env,e.env.HOME??e.env.USERPROFILE??""));if(l&&l!==e.account.key)return{at:o,ok:!1,why:"otheraccount",...a}}return Yt(e.paths,{session:null,model:null,costUsd:null,fiveHour:s.fiveHour,sevenDay:s.sevenDay,transcript:null},o,e.account),{at:o,ok:!0,...a}}var Lr="ANVIL_PLAN_PROBE_FOR";function Ir(e){try{if(e.env[Mr]==="1"||!e.env.CLAUDE_CODE_EXECPATH&&!e.env.CLAUDE_PID)return!1;let t=e.near?un:qs;if(e.readingAt!==null&&e.now-e.readingAt<t&&e.readingAt<=e.now+6e4)return!1;let n=Number(ne(cn(e.paths,e.account.key),64).trim());if(Number.isFinite(n)&&n>e.now&&n-e.now<=24*36e5)return!1;try{Rr(e.hookFile)}catch{return!1}return A(e.paths.state),U(cn(e.paths,e.account.key),String(e.now+Er+5e3)),(e.start??li)(e.node,[e.hookFile,"--plan-probe"],e.paths.dir,{...e.env,[Lr]:`${e.account.key}|${e.account.cfg}`}),!0}catch{return!1}}function li(e,t,n,r){let o=Ds(e,t,{detached:!0,stdio:"ignore",cwd:n,env:r,windowsHide:!0});o.on("error",()=>{}),o.unref()}function ui(e){let t=/^([ac][0-9a-f]{16})\|([0-9a-f]{16})$/.exec(e[Lr]??"");return t?{key:t[1],cfg:t[2]}:null}function zr(e){let t=r=>typeof r=="string"&&r.length>0?r:null,n=t(e.env.CLAUDE_PROJECT_DIR)??t(e.payload.cwd);return{...e,session:t(e.payload.session_id),transcript:t(e.payload.transcript_path),project:n&&n.startsWith("/")?ze(n):n}}var fn=36e5,bi=/^[A-Za-z0-9._-]{1,128}$/,vi=.8;function mn(e){return(e?.policies??[]).flatMap(t=>t.budgets??[])}var ce=e=>G(e.dir,"meter"),Br=(e,t)=>G(ce(e),"tasks",`${t}.json`),hn=e=>e!==null&&bi.test(e)&&e!=="."&&e!=="..";function yn(e,t){if(!hn(t))return null;let n=Z(Br(e,t),J(e),4096);if(n.status!=="ok"&&n.status!=="unkeyed")return null;let r=n.value;if(!r||r.v!==1||typeof r.t!="number"||!Number.isFinite(r.t))return null;let o=i=>typeof i=="number"&&Number.isFinite(i),s=(Array.isArray(r.passes)?r.passes:[]).filter(i=>!!i&&typeof i=="object"&&typeof i.id=="string"&&o(i.w)&&o(i.end)&&(i.at===null||o(i.at)));return{v:1,t:r.t,...s.length>0?{passes:s}:{},...o(r.until)?{until:r.until}:{}}}function Kr(e,t,n){hn(t)&&(A(G(ce(e),"tasks")),At(e,Br(e,t),n))}var qr=(e,t,n)=>e.window==="day"?Q(t):e.window==="week"?Fe(t):e.window==="task"?n?.t??Number.NaN:Number.NaN;function Jr(e,t){try{if(e.unit==="plan"){if(t.apiKey||Vt(t.paths,t.session))return{budget:e,used:null,why:"offplan"};let o=t.reading(),s=e.window==="seven_day"?o?.sevenDay:o?.fiveHour;if(o&&!s&&t.now-o.at<=De&&(e.window==="seven_day"?o.fiveHour:o.sevenDay))return{budget:e,used:null,why:"nowindow"};if(!o||!s)return{budget:e,used:null,why:"plan"};let i=Math.max(0,t.now-o.at);return s.resetsAt>t.now&&s.pct>=e.limit?{budget:e,used:s.pct,resetsAt:s.resetsAt,age:i}:s.resetsAt<=t.now||i>De?{budget:e,used:null,why:"stale",age:i,...s.resetsAt<=t.now?{reset:!0}:{}}:{budget:e,used:s.pct,resetsAt:s.resetsAt,age:i}}if(e.window==="task"&&(!t.task||!hn(t.session)))return{budget:e,used:null,why:"task"};let n=qr(e,t.now,t.task),r=e.window==="task"?t.own():t.unread.left>0&&t.unread.upto>=n?t.unread.left:0;return Ti(e,t.totals(n,e.window==="task"?t.session:null),r)}catch{return{budget:e,used:null,why:"meter"}}}var ki=.5,Ye=e=>{if(e.length===0)return null;let t=n=>{let r=e.map(o=>o[n]).sort((o,s)=>o-s);return r.length%2?r[(r.length-1)/2]:(r[r.length/2-1]+r[r.length/2])/2};return{usd:t("usd"),fresh:t("fresh")}},dn=1e4,$i=.5,_i=3e5,Dr=2.25;function xi(e,t){let n=G(ce(e),"priors.json"),r=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0,o=l=>l&&typeof l=="object"&&r(l.usd)&&r(l.fresh)?{usd:l.usd,fresh:l.fresh}:null,s=L(n),i={warm:o(s?.warm),cold:o(s?.cold)},a={warm:t.warm??i.warm,cold:t.cold??i.cold};if((t.warm||t.cold)&&JSON.stringify(a)!==JSON.stringify(i))try{A(ce(e)),U(n,`${JSON.stringify({v:1,...a})}
23
+ `)}catch{}return a}var Si=9e4,Ai=1e4,Ve=e=>e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,128),Ze=e=>G(ce(e),"live"),ue=(e,t,n=1)=>({usd:e.usd+n*t.usd,fresh:e.fresh+n*t.fresh}),ye={usd:0,fresh:0};function Ci(e,t,n){try{A(Ze(e)),U(G(Ze(e),`${Ve(t)}.json`),`${JSON.stringify(n)}
24
+ `)}catch{}}function Ri(e,t,n){let r=new Map,o=`${Ve(t)}.json`,s=[];try{s=Wr(Ze(e))}catch{return r}let i=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0,a=l=>!!l&&typeof l=="object"&&i(l.usd)&&i(l.fresh);for(let l of s){if(l===o||!l.endsWith(".json"))continue;let u=L(G(Ze(e),l));!u||u.v!==1||!i(u.t)||u.t<n-864e5||u.t>n+6e4||!a(u.chat)||!a(u.perRunning)||!a(u.each)||r.set(l.slice(0,-5),{...u,transcript:typeof u.transcript=="string"?u.transcript:null})}return r}function Oi(e){if(!e.session)return null;let t=e.payload,n=t.tool_name==="Agent"||t.tool_name==="Task",r=nr(e.paths,e.session,e.now,n?7:0),o=yn(e.paths,e.session)?.t??null,s=Ye(o!==null?r.mainSince(o):r.main)??Ye(r.main),i=n&&typeof t.tool_use_id=="string"?t.tool_use_id.slice(0,128):null,a=r.main.length<=1?Ye(r.chatToday):null,l=s?a&&a.fresh>s.fresh?a:s:ye,u=Ye(r.helpers)??Ye(r.helpersToday),c=u??l,d=r.model??"claude-opus-5-5",y=n?tr(e.transcript??null)??r.chatPrompt:r.chatPrompt,p=Math.max(dn,Math.round((y??0)*$i)),f={usd:pe(d,{input:0,output:0,write5m:p,write1h:0,read:0})??0,fresh:p},g=r.helperModel??r.model,w=g!==null&&e.now-(r.helperRepliedAt[g]??-1/0)<_i,b=n?xi(e.paths,{warm:r.helperFirstWarm,cold:r.helperFirstCold}):{warm:r.helperFirstWarm,cold:r.helperFirstCold},k=b.warm?{usd:Dr*b.warm.usd,fresh:Math.round(Dr*b.warm.fresh)}:null,O=w?b.warm??b.cold:b.cold??k,F=W=>O?.[W]??f[W],N={usd:F("usd")+c.usd+l.usd,fresh:F("fresh")+c.fresh+l.fresh},x=u?ue(ue(ye,u,2),l):N,C=s!==null&&o!==null&&r.lastMainAt!==null&&r.lastMainAt<o,$=s?C&&r.chatRecent?r.chatRecent:ye:r.chatFirst??{usd:pe(d,{input:0,output:0,write5m:dn,write1h:0,read:0})??0,fresh:dn},S=ue($,l,2),P={v:1,t:e.now,transcript:e.transcript??null,chat:S,perRunning:x,each:N},_=L(G(Ze(e.paths),`${Ve(e.session)}.json`)),H=W=>!!W&&JSON.stringify({...W,t:0})===JSON.stringify({...P,t:0});_&&typeof _.t=="number"&&e.now-_.t>=0&&e.now-_.t<Ai&&H(_)||Ci(e.paths,e.session,P),i&&Yr(e.paths,e.session,i,e.now);let j=Ve(e.session),R=Ei(e.paths,e.now),B=i?R.findIndex(W=>W.s===j&&W.id===i.replace(/\s/g,"_")):-1,m=B>=0?R.slice(0,B):R,h=(W,we,be)=>{let jt=rr(we,e.now),Tt=m.filter(te=>te.s===W),uo=Tt.length>0?Math.min(...Tt.map(te=>te.t))-2e3:1/0,co=Math.max(0,Tt.length-jt.filter(te=>te.started>=uo).length),fo=jt.filter(te=>te.state==="running").length,po=jt.filter(te=>te.state==="starting").length;return ue(ue(ye,be.perRunning,fo),be.each,po+co)},E=ue(S,h(j,e.transcript??null,{perRunning:x,each:N})),D=Ri(e.paths,e.session,e.now);for(let W of m)W.s!==j&&!D.has(W.s)&&D.set(W.s,{v:1,t:0,transcript:null,chat:ye,perRunning:x,each:N});let Pt=ye,_n=0;for(let[W,we]of D){let be=ue(we.t>=e.now-Si?we.chat:ye,h(W,we.transcript,we));(be.fresh>0||be.usd>0)&&(Pt=ue(Pt,be),_n++)}return{running:E,others:Pt,otherSessions:_n,launches:n?N:null,guess:n&&!O,parts:{underWay:$.fresh,chat:l.fresh,first:F("fresh"),helper:c.fresh,warm:w,pending:E.fresh-S.fresh}}}var Ni=2e4,Gr=e=>G(ce(e),"launches","all.log");function Ei(e,t){let n=[],r=new Set;for(let o of ne(Gr(e),64*1024).split(`
25
+ `)){let[s,i,a,l]=o.split(" "),u=Number(s);if(!i||!a||!(u>t-Ni&&u<=t+6e4))continue;let c=`${i} ${a}`;l==="x"?r.add(c):n.some(d=>d.s===i&&d.id===a)||n.push({s:i,id:a,t:u})}return n.filter(o=>!r.has(`${o.s} ${o.id}`))}function Yr(e,t,n,r,o=!1){try{let s=Gr(e);A(wi(s)),$e(s,`${r} ${Ve(t)} ${n.replace(/\s/g,"_")}${o?" x":""}`)}catch{}}function Mi(e){let t=e.payload;e.session&&(t.tool_name==="Agent"||t.tool_name==="Task")&&typeof t.tool_use_id=="string"&&Yr(e.paths,e.session,t.tool_use_id.slice(0,128),e.now,!0)}function Pi(e,t,n){if(!t.some(s=>s.used!==null&&s.budget.unit!=="plan"&&s.used<s.budget.limit))return t;let r,o=n==="message";try{return t.map(s=>{if(s.used===null||s.budget.unit==="plan"||s.used>=s.budget.limit||(r??=Oi(e),!r))return s;let i=s.budget.unit==="usd"?"usd":"fresh",a=s.budget.window!=="task"&&r.others[i]>0,l=s.used+Math.min(r.running[i]+(a?r.others[i]:0),ki*s.budget.limit),u=a?{others:r.otherSessions}:{};return l>=s.budget.limit?{...s,early:{why:o?"next":"running",...u}}:r.launches&&l+r.launches[i]>=s.budget.limit?{...s,early:{why:"launch",...u,...r.guess?{guess:!0}:{}}}:s})}catch(s){return Ct={err:s instanceof Error?s.message.slice(0,200):String(s).slice(0,200)},t}finally{r!==void 0&&Ct?.err===void 0&&(Ct=r?{running:r.running.fresh,launches:r.launches?.fresh??null,others:r.others.fresh,otherSessions:r.otherSessions,usd:{running:r.running.usd,launches:r.launches?.usd??null,others:r.others.usd},...r.parts?{parts:r.parts}:{}}:{none:!0})}}var Ct;function ji(e,t,n){let r=e.env.ANVIL_BUDGET_TRACE?.trim();if(r)try{let o=e.payload;$e(r,JSON.stringify({t:e.now,at:t,tool:typeof o.tool_name=="string"?o.tool_name:null,id:typeof o.tool_use_id=="string"?o.tool_use_id.slice(-8):null,m:n.map(s=>({b:s.budget.id,used:s.used,why:s.why??null,early:s.early?.why??null,left:s.left??null})),r:Ct??null}))}catch{}}function Vr(e,t,n,r){let o={left:0,upto:0};try{e.transcript&&Xt(e.paths,e.transcript,e.now);let u=Math.min(...t.map(c=>qr(c,e.now,n)).filter(c=>Number.isFinite(c)));Number.isFinite(u)&&(o=en(e.paths,ee(e.env,e.home),u,e.now))}catch{}let s=new Map,i,a={paths:e.paths,now:e.now,task:n,session:e.session,reading:()=>i===void 0?i=Ce(e.paths,e.now,{key:Ae(e.transcript,e.paths).key}):i,totals:(u,c)=>{let d=`${u}|${c??""}`,y=s.get(d);return y||s.set(d,y=yt(e.paths,u,e.now,c)),y},unread:o,own:()=>e.transcript&&n?Qn(e.paths,e.transcript,n.t):0,apiKey:!!(e.env.ANTHROPIC_API_KEY?.trim()||e.env.CLAUDE_CODE_USE_BEDROCK?.trim()||e.env.CLAUDE_CODE_USE_VERTEX?.trim())},l=Pi(e,t.map(u=>Jr(u,a)),r);ji(e,r,l);try{if(e.probe&&!a.apiKey&&t.some(u=>u.unit==="plan")&&!Vt(e.paths,e.session)&&!Vn(e.paths,e.session)){let u=a.reading(),c=t.some(d=>{let y=d.unit!=="plan"?null:d.window==="seven_day"?u?.sevenDay:u?.fiveHour;return!!y&&y.resetsAt>e.now&&y.pct>=d.limit-Nr&&y.pct<d.limit});Ir({paths:e.paths,env:e.env,now:e.now,account:Ae(e.transcript,e.paths),readingAt:u?.at??null,near:c,hookFile:e.probe.hookFile,node:e.probe.node,...e.probe.start?{start:e.probe.start}:{}})}}catch{}return l}function Ti(e,t,n){if(t.problem)return{budget:e,used:null,why:t.problem==="large"?"large":"meter"};let r=e.unit==="usd"?t.usd:t.tokens.fresh,o=e.unit==="usd"?{budget:e,used:r,estimated:t.estimated}:{budget:e,used:r};return r>=e.limit?o:e.unit==="usd"&&t.unpriced.length>0?{budget:e,used:null,why:"price",models:t.unpriced}:n>0?{budget:e,used:null,why:"counting",left:n}:o}var Rt=e=>e.why==="large"||e.early!==void 0||e.used!==null&&e.used>=e.budget.limit,de={day:"today's",week:"this week's",task:"this task's",seven_day:"your week's",five_hour:"these 5 hours'"},pn=(e,t=1e3)=>`$${e<t?e.toFixed(2):String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,Nt=e=>Number.isInteger(e)?pn(e,0):pn(e),wn=(e,t,n=1e3)=>{let r=pn(e,n),o=Number(r.slice(1).replace(/,/g,""));return e>=t?o===t&&e!==t?`$${e.toFixed(2)}`:r:o>=t?`$${(Math.floor(e*100)/100).toFixed(2)}`:r};function Ee(e){let t=e.budget,n=e.used??0;return t.unit==="usd"?`${e.estimated?"~":""}${wn(n,t.limit)} of ${Nt(t.limit)}`:t.unit==="tokens"?`${Ue(n)} of ${t.text.replace(/ a (day|week|task)$/,"")}`:`${Math.round(n)}% of ${t.window==="seven_day"?"your week":"these 5 hours"} used, budget ${t.limit}%`}function Xe(e,t){let n=e.budget.window;if(n==="day")return"resets at midnight";if(n==="week")return"resets Monday";if(n==="task")return"ends with your next message";let r=e.resetsAt??t,o=r-t;return o<36e5?`resets in ${Math.max(1,Math.round(o/6e4))} min`:o<24*36e5?`resets in ${Math.round(o/36e5)} h`:`resets ${new Date(r).toLocaleDateString("en-US",{weekday:"long"})}`}var Li=e=>e.charAt(0).toUpperCase()+e.slice(1),Et="a day of Anvil's meter is over 32 MB, more than any person's day: a loop, or something writing to it",tt=e=>e.early&&(e.used??0)<e.budget.limit?e.early.why:null,Mt=e=>tt(e)?"nearly spent":"spent",Fr=e=>{let t=e.early?.others??0;return t>0?` here and in ${t===1?"another Claude Code session":`${t} other Claude Code sessions`}`:""},bn=e=>({running:`, and what's running${Fr(e)} could pass it`,next:`, and the next replies${Fr(e)} could pass it`,launch:""})[tt(e)??"launch"]??"";function Qe(e,t,n="an OK lets this task go on past it"){if(e.why==="large")return`your budget ${e.budget.text} can't be counted: ${Et} \xB7 ${n}`;if(tt(e)==="launch"){let r=e.early?.others??0,o=r>0?`, with ${r===1?"another Claude Code session":`${r} other Claude Code sessions`} working,`:"",s=e.early?.guess?" \xB7 no helper has run on this computer yet, so its size is Anvil's guess until one has":"";return`the helpers starting${o} could pass ${de[e.budget.window]} budget: ${Ee(e)} used${s} \xB7 ${Xe(e,t)} \xB7 ${n}`}return`${de[e.budget.window]} budget is ${Mt(e)}: ${Ee(e)}${bn(e)} \xB7 ${Xe(e,t)} \xB7 ${n}`}function Ii(e,t,n,r){return`${e.why==="large"?`${I("Your budget can't be counted")} ${e.budget.text} \xB7 ${Et}`:`${I(`${Li(de[e.budget.window])} budget is ${Mt(e)}`)} ${Ee(e)}${bn(e)} \xB7 ${Xe(e,t)}`}${Ke("keep going",`${z(n)} allow ${r}`,"send your message again")}${bt("change the budget instead",`${z(n)} rules edit`)}`}function Di(e){let t=e.budget;if(t.unit==="plan")return`${I("Anvil")} ${Math.round(e.used??0)}% of ${t.window==="seven_day"?"your week":"these 5 hours"} used${(e.age??0)>=6e4?` (read ${We(e.age)} ago)`:""} \xB7 your budget stops at ${t.limit}%`;let n=e.used??0,r=t.unit==="usd"?`${e.estimated?"~":""}${wn(n,t.limit,10)}`:Ue(n),o=t.unit==="usd"?Nt(t.limit):`${t.text.replace(/ a (day|week|task)$/,"")}`;return`${I("Anvil")} ${r} of ${de[t.window]} ${o} used`}var Hr={plan:"there is no reading of your plan yet",meter:"Anvil's meter can't be read right now",large:Et};function Fi(e){if(!e||e.ok)return null;switch(e.why){case"noplan":return"can't measure here: no plan pays for this session (an API key or a cloud account does)";case"unavailable":return`can't measure: this Claude Code${e.version?` (${e.version})`:""} doesn't report your plan's use \xB7 update Claude Code`;case"otheraccount":return"can't measure right now: Claude Code here is signed in as another account than this session's";case"nobinary":return"can't measure: Anvil can't find Claude Code to ask for your plan's use";default:return"can't measure right now: Claude Code's /usage didn't answer \xB7 asked again in 15 min"}}function Zr(e){switch(e.why){case"large":return`can't be counted: ${Et}`;case"price":return`can't measure: no price for ${(e.models??[]).join(", ")}`;case"stale":return`can't measure (last reading ${We(e.age??0)} ago${e.reset?", before its window reset":""})`;case"counting":return`can't measure yet: Anvil is still reading ${de[e.budget.window]} session files (${or(e.left??0)} left)`;case"offplan":return"can't measure here: no plan pays for this session (an API key or a cloud account does)";case"nowindow":return`can't measure: your plan has no ${e.budget.window==="five_hour"?"5-hour":"weekly"} limit`;case"plan":return`can't be measured here: ${Hr.plan}`;default:return`can't be measured here: ${Hr.meter}`}}function zc(e,t){try{let r=JSON.parse(mi(G(ee(e,t),"settings.json"),"utf8").replace(/^/,""))?.statusLine?.command;return typeof r=="string"&&!r.includes("/.anvil/claude/bin/claude-sync.js")}catch{return!1}}function et(e,t){let n=G(ce(e),"said");try{return A(n),fi(gi(G(n,ci("sha256").update(t).digest("hex").slice(0,32)),"wx")),!0}catch(r){return r.code!=="EEXIST"}}function Xr(e,t,n){let r=[];for(let o of t){let s=o.budget;if(o.why==="large")continue;if(o.used===null){let a=(o.why==="plan"||o.why==="stale")&&e.probe?Fi(Tr(e.paths,Ae(e.transcript,e.paths).key)):void 0;if(a===null||!et(e.paths,`unmeasured|${e.session??"-"}|${s.id}|${o.why??"meter"}`))continue;r.push(o.why==="task"?`${I("Anvil")} your budget ${s.text} counts from your next message (Claude Code 2.1.318 or later tells Anvil when one is sent) \xB7 not enforced until then`:`${I("Anvil")} your budget ${s.text} ${a??Zr(o)} \xB7 not enforced`);continue}if(o.used<s.limit*vi||o.used>=s.limit)continue;let i=s.window==="day"?q(e.now):s.window==="week"?q(Fe(e.now)):s.window==="task"?`${e.session}@${n?.t??0}`:String(o.resetsAt??0);et(e.paths,`near|${s.id}|${i}`)&&r.push(Di(o))}return r.length>0?r.join(`
26
+ `):null}function Ot(e,t,n,r,o,s){try{A(e.paths.dir);let i=o==="passed"?Qe(t,e.now,"going on with your OK"):Qe(t,e.now);$e(e.paths.decisions,JSON.stringify({v:1,ts:new Date(e.now).toISOString(),session:e.session,tool:n,action:r,verdict:"hold",mode:"enforce",delivered:o,rule:"budget",slug:"budget",policy:"budgets",blocked_by:"budget_reached",why:i,target:null,project:e.project?Ur(e.project):null,...s?{hold:s}:{},path:"none",ms:0}))}catch{}}function Qr(e,t,n){let r=e.budget.window;return r==="day"?Q(t):r==="week"?Fe(t):r==="task"?n?.t??0:e.resetsAt??0}var Hi=36e5;function eo(e,t,n,r){if(e.id!==t.budget.id||!(n<e.end)||e.end-n>fn)return!1;let o=Qr(t,n,r);return(t.budget.unit==="plan"?Math.abs(o-e.w)>Hi:o!==e.w)?!1:e.at===null||t.used===null||t.used<e.at+t.budget.limit}function Wi(e){try{let t=me(e);return A(t),di(t,pi.W_OK),!0}catch{return!1}}var to=(e,t)=>`${me(e)} can't be written: fix its permissions, or run in a terminal: ${z(t)} on`,no=(e,t,n)=>`${I("Anvil")} ${Qe(e,t).replace(/ · an OK lets this task go on past it$/,"")}, but Anvil can't record an OK right now (${n}) \xB7 not stopped`;function ro(e,t,n,r){let o=!1;try{o=Ar(e.paths,J(e.paths),e.session,e.project,[{kind:"claude.budget",target:t.budget.id}],e.now).approved}catch{o=!1}if(!o)return!1;try{for(let{hold:s,file:i}of Sr(e.paths,J(e.paths),e.now))s.session===e.session&&s.stops.length>0&&s.stops.every(a=>a.kind==="claude.budget"&&a.target===t.budget.id)&&hi(i,{force:!0})}catch{}try{let s=n?null:r?.until!==void 0&&e.now<r.until?r.until:e.now+fn,i=(r?.passes??[]).filter(l=>l.id!==t.budget.id&&e.now<l.end),a={id:t.budget.id,w:Qr(t,e.now,n),at:t.used,end:e.now+fn};Kr(e.paths,e.session,{v:1,t:n?.t??e.now,passes:[...i,a],...s!==null?{until:s}:{}})}catch{}return!0}function gn(e,t){return`${e.why==="large"||e.budget.unit==="plan"?"":`up to ${e.budget.unit==="usd"?Nt(e.budget.limit):Ue(e.budget.limit)} more, `}for an hour at most${e.budget.window==="task"?"":`, until it ${Xe(e,t)}`}`}function oo(e,t){return e.why==="large"?`${I("Anvil")} going on as you said, for this task: your budget ${e.budget.text} can't be counted (a day of Anvil's meter is over 32 MB) \xB7 ${gn(e,t)}`:`${I("Anvil")} going on ${tt(e)?`near ${de[e.budget.window]} budget`:`past ${de[e.budget.window]} budget`}, as you said: ${Ee(e)} \xB7 for this task, ${gn(e,t)}`}function Ui(e,t,n){return`Anvil: ${e.why==="large"?`the user's budget ${e.budget.text} can't be counted`:`${de[e.budget.window]} budget is ${Mt(e)} (${Ee(e)}${bn(e)})`}, and the user ran \`${z(t)} allow\` in a terminal to let this task go on past it (${gn(e,n)}). Anvil's earlier hold is lifted: carry on with the task as asked now, without waiting for any other confirmation. If the OK runs out, Anvil holds the next action again and says so.`}var zi=new Set(["SubagentHandback","mcp__ccd_turn__wrap_up","mcp__ccd_turn__update_plan"]);function Bc(e){if(zi.has(String(e.payload.tool_name??"")))return null;try{let t=zr(e),n=mn(t.table);if(n.length===0)return null;let r=yn(t.paths,t.session),o=Date.parse(t.table?.compiled_at??""),s=r&&r.until===void 0&&!(o>r.t)?r:null,i=Vr(t,n,s,"action"),a=r&&(r.until===void 0||t.now<r.until)?r.passes??[]:[],l=y=>a.some(p=>eo(p,y,t.now,s)),u=i.find(y=>Rt(y)&&!l(y)),c=()=>{for(let y of i)Rt(y)&&l(y)&&Ot(t,y,"PreToolUse","claude.budget","passed",null)};if(u){if(ro(t,u,s,r))return Ot(t,u,"PreToolUse","claude.budget","approved",null),c(),{note:oo(u,t.now)};let y=Qe(u,t.now);if(Mi(t),!Wi(t.paths))return{note:no(u,t.now,to(t.paths,t.cli))};let p=u.budget.id,f=u.why==="large"?"the user's budget can't be counted":tt(u)==="launch"?"the helpers starting could pass the user's budget":`the user's budget is ${Mt(u)}`,g={user:`${I("Held by Anvil for your OK")} ${y}${Ke("keep going",`${z(t.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${I("Held by Anvil")} ${y}. Nothing ran: ${f}, so every action waits for their OK. Stop here and tell the user: to keep going, ${vt(t.cli,"tell you to go on")}. Do not try another way. Once they have, Anvil tells you so with their next message (or they tell you themselves): then go on with the task.`};return{stop:{action:"claude.budget",target:p,decision:{verdict:"hold",policy:"budgets",origin:null,ruleId:"budget",blockedBy:"budget_reached",source:u.budget.source},mode:"enforce",floor:null,why:y,said:g}}}c();let d=Xr(t,i.filter(y=>!l(y)),s);return d?{note:d}:null}catch{return null}}function Kc(e){try{if(wt(e.payload))return null;let t=zr(e),n=J(t.paths),r={installed:t.installed===!0},o=t.table??Je(t.paths,t.fallbackTable,n,r).value,s=mn(o);if(s.length===0)return null;let i={v:1,t:t.now};try{Kr(t.paths,t.session,i)}catch{}if(qe(t.paths,n,r).value?.kill_switch===!0)return null;let a=Vr(t,s.filter(c=>c.window!=="task"),i,"message"),l=a.find(Rt);if(l){if(ro(t,l,i,i))return Ot(t,l,"UserPromptSubmit","claude.prompt","approved",null),`${JSON.stringify({systemMessage:oo(l,t.now),hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Ui(l,t.cli,t.now)}})}
27
+ `;let c;try{c=xr(t.paths,{session:t.session,project:t.project,stops:[{kind:"claude.budget",target:l.budget.id}],why:Qe(l,t.now),project_name:t.project?Ur(t.project):null,command:"your next message (Anvil never reads it)"},t.now)}catch(d){let y=d.code;return`${JSON.stringify({systemMessage:no(l,t.now,y==="ENOSPC"||y==="EDQUOT"?"the disk is full: free some space":to(t.paths,t.cli))})}
28
+ `}return Ot(t,l,"UserPromptSubmit","claude.prompt","deny",c.id),`${JSON.stringify({decision:"block",reason:Ii(l,t.now,t.cli,c.code)})}
29
+ `}let u=Xr(t,a,i);return u?`${JSON.stringify({systemMessage:u})}
30
+ `:null}catch{return null}}function Bi(e){if(e.used===null)return null;let t=e.budget,n=t.window==="day"?"today":"this week";return t.unit==="plan"?`${Math.round(e.used)}% of ${t.window==="seven_day"?"your week":"these 5 hours"} \xB7 budget ${t.limit}% \xB7 ${Qt(e.age??0)}`:t.unit==="tokens"?`${Ue(e.used)} of ${t.text.replace(/ a (day|week|task)$/,"")} ${n}`:`${e.estimated?"~":""}${wn(e.used,t.limit,10)} of ${Nt(t.limit)} ${n}`}function Ki(e,t){let n=[],r=[];try{r=Wr(G(ce(e),"tasks"))}catch{return n}for(let o of r){if(!o.endsWith(".json"))continue;let s=yn(e,o.slice(0,-5));if(!(!s||s.until!==void 0&&t>=s.until))for(let i of s.passes??[])t<i.end&&n.push({pass:i,task:s})}return n}var qc=(e,t)=>gt(ee(e,t));function Jc(e,t,n,r){let o=mn(t);if(o.length===0)return[];let s=r??gt(ee(process.env,yi())),i,a={paths:e,now:n,task:null,session:null,reading:()=>i===void 0?i=Ce(e,n,s):i,totals:c=>yt(e,c,n),unread:{left:0,upto:0},own:()=>0,apiKey:!1},l=[],u;for(let c of o){if(c.window==="task"){l.push({budget:c,used:null,share:null,text:"each task: checked while Claude works",short:null});continue}let d=Jr(c,a),y=c.unit==="plan"&&d.used!==null?` \xB7 ${Qt(d.age??0)}`:"",p;if(Rt(d))for(let{pass:f,task:g}of u??=Ki(e,n))eo(f,d,n,g)&&(p=Math.max(p??0,Math.min(f.end,g.until??f.end)));l.push({budget:c,used:d.used,share:d.used===null?null:d.used/c.limit,text:d.used===null?Zr(d):`${Ee(d)} \xB7 ${Xe(d,n)}${y}`,short:Bi(d),...d.why?{why:d.why}:{},...d.age!==void 0?{age:d.age}:{},...p!==void 0?{okUntil:p}:{}})}return l}import{execFileSync as qi}from"child_process";import{readdirSync as Ji,rmSync as Gi,statSync as so}from"fs";import{basename as Yi,join as fe}from"path";function nt(e){let t=e.trim().toLowerCase(),n=/(?:^|[^a-z])(opus|sonnet|haiku|fable|mythos)(?![a-z])/.exec(t);if(!n)return null;let r=n[1],o=/\[1m\]$/.test(t);return{family:r,oneM:o,label:`${r[0].toUpperCase()}${r.slice(1)}${o?" 1M":""}`}}var Y=e=>typeof e=="string"&&e.length>0?e:null,vn=e=>e.split(" \xB7 ")[0]??e,Vi=e=>e==="sdk"||e.startsWith("repl_main_thread"),Zi=e=>Array.isArray(e)&&e.some(t=>typeof t=="string"&&t.startsWith("context-1m-"));function Xi(e,t){return io(e,t)?.model??null}function io(e,t){if(!e||!e.endsWith(".jsonl"))return null;let n=t!==null&&/^[A-Za-z0-9_-]{1,64}$/.test(t);if(t!==null&&!n)return null;let r=n?Xn(e,t)??fe(e.slice(0,-6),"subagents",`agent-${t}.jsonl`):e,o;try{o=so(r).size}catch{return null}for(let s of[256*1024,4*1024*1024]){let i=ne(r,s),a=i?i.split(`
31
+ `):[];for(let l=a.length-1;l>=0;l--){let u=a[l];if(u.includes('"api-request"'))try{let c=JSON.parse(u);if(c.type!=="api-request")continue;let d=typeof c.querySource=="string"?c.querySource:"";if(!n&&!Vi(d))continue;let y=Y(c.params?.model),p=typeof c.timestamp=="string"?Date.parse(c.timestamp):Number.NaN;if(y)return{model:Zi(c.params?.betas)&&!/\[1m\]$/i.test(y)?`${y}[1m]`:y,at:p}}catch{}}if(o<=s)break}return null}function kn(e,t){let n=(e?.policies??[]).filter(r=>Cn(r,t));return{guards:n.flatMap(r=>(r.model_rules?.guards??[]).map(o=>({...o,project:r.origin==="project"}))),never:n.flatMap(r=>r.model_rules?.never??[])}}function Qi(e,t){let n=[];for(let r of t){let o=e.find(s=>s.project&&s.kinds.includes(r))??e.find(s=>s.kinds.includes(r));o&&!n.some(s=>s.id===o.id)&&n.push(o)}return n}var rt=(e,t)=>e.model===t.family&&(!e.one_m||t.oneM);function ad(e){try{let t=kn(e.table,e.projectDir??null),n=e.kinds??[],r=Qi(t.guards,n);if(r.length===0&&t.never.length===0)return null;let o=Y(e.payload.session_id)??"-",s=Y(e.payload.agent_id),i=Xi(Y(e.payload.transcript_path),s),a=i?nt(i):null,l=[];if(!s&&a){let p=t.never.find(f=>rt(f,a));p&&et(e.paths,`model-never|${o}|${p.id}`)&&l.push(`${I("Anvil")} this session runs on ${a.label}, which your rules say never (${vn(p.source)})${nn("Switch it: the model picker, or /model.")}`)}let u,c=(p,f,g,w)=>({action:n.find(b=>p.kinds.includes(b)),decision:{verdict:"hold",policy:"models",origin:null,ruleId:"model",blockedBy:"model_rule",source:p.source},mode:"enforce",floor:null,why:f,said:{user:`${I("Held by Anvil for your OK")} {why}${Ke("allow it once",`${z(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${I("Held by Anvil")} ${g}. Nothing ran. Tell the user: ${w}; or, to allow it once, ${vt(e.cli,"tell you to go on")}. Do not try another way.`}}),d=`to change one, run in a terminal: ${z(e.cli)} rules edit`;if([...new Set(r.map(p=>p.model))].length>1){let[p,f]=r.filter((w,b)=>r.findIndex(k=>k.model===w.model)===b),g=`${p.text} and ${f.text}: no one model meets both`;u=c(p,`${g} \xB7 ${d}`,g,"no switch runs it: they can change one of the two rules")}else if(r.length>0&&!a){let p=r[0],f=i?`Anvil doesn't know the model ${i.slice(0,60)} this ${s?"helper":"session"} runs on`:`Anvil can't tell which model this ${s?"helper":"session"} runs on (Claude Code 2.1.304 or later records it)`;et(e.paths,`model-unknown|${o}|${s??""}|${p.id}`)&&l.push(`${I("Anvil")} ${p.text}, but ${f} \xB7 not enforced`)}else if(r.length>0&&a&&r[0].model!==a.family){let p=r[0],f=s?`this helper runs on ${a.label}`:`this session is ${a.label}`,g=s?void 0:t.never.find(b=>rt(b,{family:p.model,oneM:!1})),w=`${p.model[0].toUpperCase()}${p.model.slice(1)}`;s?u=c(p,`${p.text}; ${f} \xB7 a helper's model: add the rule model: ${p.model} for helper agents`,`${p.text}; ${f}`,`a helper takes its model from the launch or a model: rule (model: ${p.model} for helper agents)`):g?u=c(p,`${p.text}; ${f}, and your rules also say ${g.text} (${vn(g.source)}) \xB7 ${d}`,`${p.text}; ${f}, and their rules also say ${g.text}`,"switching won't run it (their rules refuse that switch): they can change one of the two rules"):u=c(p,`${p.text}; ${f} \xB7 switch to ${w}: /model ${p.model}, or the model picker`,`${p.text}; ${f}`,`they can switch this session to ${w} (/model ${p.model}, or the model picker) and ask you to try again`)}return!u&&l.length===0?null:{...u?{stop:u}:{},...l.length>0?{note:l.join(`
32
+ `)}:{}}}catch{return null}}function ld(e){try{let t=J(e.paths),n={installed:e.installed===!0},r=e.table??Je(e.paths,e.fallbackTable,t,n).value,o=kn(r,e.projectDir??null);if(o.never.length===0)return null;let s=Y(e.payload.to_model),i=Y(e.payload.requested_model),a=(s?nt(s):null)??(i?nt(i):null),l=a!==null&&(a.oneM||/\[1m\]$/i.test(i??"")),u=s&&nt(s)?s:i??s,c=a?o.never.find(f=>rt(f,{family:a.family,oneM:l})):void 0,d=qe(e.paths,t,n).value?.kill_switch===!0;if(!c||d||!a)return ta(e,u&&l&&!/\[1m\]$/i.test(u)?`${u}[1m]`:u),null;let y=`${a.label.replace(/ 1M$/,"")}${l?" 1M":""}`,p=`${I("Anvil")} your rules say ${c.text} \xB7 change it in a terminal: ${z(e.cli)} rules edit`;return ao(e,c,y,"switch"),`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreModelSwitch",permissionDecision:"deny",permissionDecisionReason:p}})}
33
+ `}catch{return null}}function ao(e,t,n,r){try{let o=Y(e.env.CLAUDE_PROJECT_DIR)??Y(e.payload.cwd),s=o&&o.startsWith("/")?ze(o):o;A(e.paths.dir),$e(e.paths.decisions,JSON.stringify({v:1,ts:new Date(e.now).toISOString(),session:Y(e.payload.session_id),tool:r==="switch"?"PreModelSwitch":"UserPromptSubmit",action:`claude.model.${r}`,verdict:"block",mode:"enforce",delivered:"deny",rule:"model",slug:"model",policy:"models",blocked_by:"model_rule",why:r==="switch"?`a switch to ${n}: your rules say ${t.text}`:`a message on ${n}: your rules say ${t.text}`,target:n,project:s?Yi(s):null,path:"none",ms:0}))}catch{}}var lo=/^[A-Za-z0-9_-]{1,80}$/,ea=7*864e5;function ta(e,t){let n=Y(e.payload.session_id);if(!(!n||!lo.test(n)||!t))try{let r=fe(e.paths.dir,"models");A(r),U(fe(r,`${n}.json`),`${JSON.stringify({v:1,model:t.slice(0,80),at:e.now})}
34
+ `);for(let o of Ji(r)){let s=fe(r,o);o.endsWith(".json")&&e.now-so(s).mtimeMs>ea&&Gi(s,{force:!0})}}catch{}}function na(e,t){if(!t||!lo.test(t))return null;let n=L(fe(e.dir,"models",`${t}.json`));return n&&n.v===1&&typeof n.model=="string"&&typeof n.at=="number"?{model:n.model,at:n.at}:null}var $n=e=>{try{return qi("ps",["-ww","-o","lstart=,command=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{PATH:"/bin:/usr/bin",LC_ALL:"C"}})}catch{return null}};function ra(e,t=$n){let n=Number(e.CLAUDE_PID);if(!Number.isInteger(n)||n<=1)return null;let r=t(n)?.trim();if(!r)return null;let o=/^([A-Z][a-z]{2}\s+[A-Z][a-z]{2}\s+\d{1,2}\s+\d{1,2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/s.exec(r);if(!o)return null;let s=Date.parse(o[1].replace(/\s+/g," ")),i=o[2];if(!Number.isFinite(s)||!/(?:^|\/)claude(?:\s|$)|@anthropic-ai\/claude-code/.test(i))return null;let a=null;for(let l of i.matchAll(/(?:^|\s)--model(?:=|\s+)([^\s"']+)/g))a=l[1];return{at:s,model:a}}function oa(e){let t=e.projectDir??null,n=[...t?[fe(t,".claude","settings.local.json"),fe(t,".claude","settings.json")]:[],fe(ee(e.env,e.home),"settings.json")];for(let r of n){let o=L(r)?.model;if(typeof o=="string"&&o.trim())return o.trim()}return null}function sa(e,t=$n){let n=Y(e.payload.session_id),r=ra(e.env,t),o=r?r.at-1e3:Number.NEGATIVE_INFINITY,s=[na(e.paths,n),io(Y(e.payload.transcript_path),null)].filter(i=>i!==null&&Number.isFinite(i.at)&&i.at>=o).sort((i,a)=>a.at-i.at)[0];return s?s.model:r?.model?r.model:Y(e.env.ANTHROPIC_MODEL?.trim())??oa(e)}var ia=["opus","sonnet","fable","haiku"];function ud(e,t=$n){try{if(wt(e.payload))return null;let n=J(e.paths),r={installed:e.installed===!0},o=e.table??Je(e.paths,e.fallbackTable,n,r).value,s=kn(o,e.projectDir??null);if(s.never.length===0||qe(e.paths,n,r).value?.kill_switch===!0)return null;let i=sa(e,t),a=i?nt(i):null;if(!a)return null;let l=s.never.find(d=>rt(d,a));if(!l)return null;let u=ia.find(d=>!(d===a.family&&!a.oneM)&&!s.never.some(y=>rt(y,{family:d,oneM:!1}))),c=`${I(`This session is on ${a.label}`)} your rules say ${l.text} (${vn(l.source)})${nn(`Switch first (the model picker, or /model${u?` ${u}`:""}), then send your message again.`)}${bt("change that rule instead",`${z(e.cli)} rules edit`)}`;return ao(e,l,a.label,"message"),`${JSON.stringify({decision:"block",reason:c})}
35
+ `}catch{return null}}export{Dr as COLD_PER_WARM,zt as FEED_MAX_BYTES,dn as FIRST_HELPER_REPLY_TOKENS,_i as HELPER_CACHE_MS,Wn as HELPER_LIVE_MS,_e as KEEP_DAYS,Ni as LAUNCH_CLAIM_MS,Si as LIVE_MS,De as PLAN_FRESH_MS,zi as REPORT_ONLY_TOOLS,ki as RESERVE_MAX_SHARE,Kn as STATUSLINE_READ_BYTES,$i as UNSEEN_HELPER_SHARE,Ae as accountOf,We as ageWords,Bc as budgetAtAction,Kc as budgetAtPrompt,Jc as budgetStanding,mn as budgetsOf,ru as catchUp,er as catchUpFrom,en as catchUpSince,fs as catchUpToday,wt as claudeCodesOwnTurn,ee as claudeConfigDir,q as dayOf,os as dollarsWords,Vn as feedsPlan,nu as feedsSince,mt as helperFiles,rr as helperStates,Xn as helperTranscript,Ce as lastReading,ra as launchOf,or as megabytes,as as meterStep,yt as meterTotals,ad as modelAtAction,sa as modelAtMessage,ud as modelAtPrompt,ld as modelAtSwitch,Xi as modelNow,nt as modelOf,zn as money,Vt as offPlan,zc as ownStatusLine,Gn as ownerKeyOf,Io as parseStatusFeed,ui as probeAccount,Fi as probeFailure,ss as pruneMeter,Qt as readAgo,is as readFeedFromStdin,rs as readLimits,Xt as readSessionAndHelpers,Bt as readSessionFile,nr as recentReplies,Yt as recordFeed,io as requestNow,ii as runPlanProbe,et as sayOnce,qc as screenPlanScope,gt as screenScope,tr as sessionOpeningPrompt,Qn as sessionUnread,Gt as signedInOwner,Un as spendWords,wn as spentUsd,Q as startOfDay,Fe as startOfWeek,ou as statusSpend,Ue as tokenWords};