@useanvil/claude-code 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,35 +1,55 @@
1
- import{appendFileSync as jn,closeSync as ut,constants as le,fstatSync as ct,openSync as dt,readdirSync as Mo,readSync as Ie,rmSync as it,statSync as me}from"fs";import{createHash as ft}from"crypto";import{homedir as Po}from"os";import{basename as Jt,dirname as jo,isAbsolute as Kn,join as v,resolve as To}from"path";import{isatty as Lo}from"tty";import{createHash as Wl}from"crypto";import{appendFileSync as _o,closeSync as Nn,constants as On,fstatSync as En,mkdirSync as xo,openSync as Mn,readdirSync as zl,readFileSync as So,readSync as Pn,renameSync as Ao,statSync as Co,unlinkSync as Bl,writeFileSync as Ro}from"fs";import{homedir as ql}from"os";import{dirname as Gl,join as Yl}from"path";var Pe="claude";function mo(e){return e==="ghost"||e==="enforce"?e:null}function It(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[Pe]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function Sn(e,t,n,r=new Date){let o=e&&typeof e=="object"?e:It(r);if(n==="all")return{version:1,kill_switch:!1,default_mode:t,services:{[Pe]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[Pe]?.actions??{}};for(let i of n)s[i]={mode:t};return{version:1,kill_switch:o.kill_switch===!0,default_mode:mo(o.default_mode)??"ghost",services:{...o.services??{},[Pe]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function X(e){return Object.assign(Object.create(null),e)}import{existsSync as ka,readdirSync as $a,statSync as _a}from"fs";import{dirname as Sa,isAbsolute as Aa,join as Ca,posix as Ra,resolve as Oa}from"path";import{posix as Cn}from"path";var yo=null;function st(){return yo??process.platform==="win32"}var An=/^([A-Za-z]):(.*)$/s,wo=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function Dt(e,t){let n=Cn.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function ke(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 Ft(e){if(!st())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(An.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/${ke(o[1],n).toLowerCase()}${o[2]?`/${ke(o[2],n).toLowerCase()}`:""}`;return Dt(l,ke(o[3]??"",n).toLowerCase())}let s=An.exec(t);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?Dt(`/${s[1].toLowerCase()}`,ke(l,n).toLowerCase()):null}let i=wo.exec(t);if(i)return Dt(`/${i[1].toLowerCase()}`,ke(i[2]??"",n).toLowerCase());let a=ke(t,n).toLowerCase();if(a.startsWith("/")){let l=Cn.normalize(a);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return a}function bo(e){return Ft(e)??e}function Ht(e){return!st()||typeof e!="string"||e===""?e:bo(e)}import{domainToASCII as Da}from"url";var qa="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as cl,readdirSync as dl,realpathSync as fl}from"fs";import{basename as gl,dirname as ml,join as hl}from"path";var Wt="anvil-claude-compiled/1";function Rn(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&$o(t,e.project_dir))}function $o(e,t){let n=Ht(e),r=Ht(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}var Oo=3500;function K(e,t=8*1024*1024){try{let n=Co(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function $e(e,t=8*1024*1024){let n;try{n=Mn(e,On.O_RDONLY|On.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=En(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=Pn(n,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Nn(n)}}function _e(e,t){let n=t.endsWith(`
2
- `)?t:`${t}
3
- `;if(Buffer.byteLength(n)>Oo)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){xo(e,{recursive:!0,mode:448})}function re(e,t){if(K(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=Mn(e,"r")}catch{return""}try{let r=En(n).size,o=Math.max(0,r-t),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);Pn(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{Nn(n)}}function U(e,t,n=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;Ro(r,t,{mode:n}),je(r,e)}function je(e,t){for(let n=0;;n++)try{Ao(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(So(e,"utf8"))}catch{return null}}var Zl=256*1024,Xl=1024*1024;var No=X({"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 Eo(e){let t=/claude-[a-z]+-\d+(?:-\d+)?/.exec(e.toLowerCase().replace(/@.*$/,"").replace(/\[1m\]$/,""));return t?t[0].replace(/-(\d{8})$/,""):e}function ge(e,t){let n=No[Eo(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 Bt=64*1024,qn=8*1024*1024,Tn=8*1024*1024,Io=32*1024*1024,xe=40,De=/^[A-Za-z0-9._-]{1,128}$/,Jn=/^[\w.:@/[\]-]{1,100}$/,Ln=Buffer.from('"usage":{"input_tokens":'),Ut=Buffer.from('{"type":"cost-state"'),lt=Buffer.from('{"type":"session-owner"'),In=Buffer.from('"timestamp":"'),Fe=36e5,M=e=>typeof e=="number"&&Number.isFinite(e)?e:null,T=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function Dn(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 Do(e){if(!e||Buffer.byteLength(e)>Bt)return null;let t;try{t=T(JSON.parse(e))}catch{return null}if(!t)return null;let n=typeof t.session_id=="string"&&De.test(t.session_id)?t.session_id:null,r=T(t.model)?.id,o=typeof r=="string"&&Jn.test(r)?r:null,s=M(T(t.cost)?.total_cost_usd),i=T(t.rate_limits),a=typeof t.transcript_path=="string"&&Kn(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:Dn(i?.five_hour),sevenDay:Dn(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 ee(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function He(e){let t=new Date(ee(e));return t.setDate(t.getDate()-(t.getDay()+6)%7),t.getTime()}var V=e=>v(e.dir,"meter"),oe=e=>Math.round(e*1e6)/1e6,Q=e=>{try{return Mo(e)}catch{return[]}},Se=e=>{try{let t=me(e);return t.isFile()?t.mtimeMs:0}catch{return 0}};function Fo(e){let t;try{t=dt(e,le.O_RDONLY|le.O_NONBLOCK)}catch{return!1}try{let n=ct(t);if(!n.isFile()||n.size===0)return!1;let r=Buffer.alloc(1);return Ie(t,r,0,1,n.size-1)===1&&r[0]!==10}finally{ut(t)}}function Gt(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=Fo(e)?`
5
- `:"";for(let r of t)n.length+r.length+1>6e4&&n&&(jn(e,n,{mode:384}),n=""),n+=`${r}
6
- `;n&&jn(e,n,{mode:384})}var Ho=4;function Fn(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 pt(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(Fn),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&&Fn(o)?{v:2,totals:[o],m:n,at:t.at}:null}var gt=e=>ft("sha256").update(e).digest("hex").slice(0,16),Gn=e=>e?To(e):"";function Hn(e){let t=e?Math.max(e.lastIndexOf("/projects/"),e.lastIndexOf("\\projects\\")):-1;return t>0?Gn(e.slice(0,t)):""}var Yn=(e,t)=>`a${gt(`${e}|${t}`)}`;function Vn(e){try{let t=T(JSON.parse(e.toString("utf8"))),n=t?.accountUuid;return t?.type==="session-owner"&&typeof n=="string"&&n.length>0?Yn(n,typeof t.organizationUuid=="string"?t.organizationUuid:""):null}catch{return null}}function Wo(e){let t;try{t=dt(e,le.O_RDONLY|le.O_NONBLOCK)}catch{return null}try{if(!ct(t).isFile())return null;let n=Buffer.alloc(64*1024),r=n.subarray(0,Ie(t,n,0,n.length,0));for(let o=r.indexOf(lt);o>=0;o=r.indexOf(lt,o+1)){if(o>0&&r[o-1]!==10)continue;let s=r.indexOf(10,o);if(s<0)break;let i=Vn(r.subarray(o,s));if(i)return i}return null}finally{ut(t)}}function Ce(e,t){let n=gt(Hn(e));if(!e)return{key:`c${n}`,cfg:n};let r=t?L(We(t,e))?.ow:void 0;return{key:(typeof r=="string"&&/^a[0-9a-f]{16}$/.test(r)?r:Wo(e)??(qt(e)===0?Yt(Hn(e)):null))??`c${n}`,cfg:n}}function Yt(e){if(!e)return null;let t=[v(e,".claude.json"),...Jt(e)===".claude"?[v(jo(e),".claude.json")]:[]];for(let n of t){let r=$e(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 Yn(s,typeof o?.organizationUuid=="string"?o.organizationUuid:"")}catch{}}return null}var mt=e=>({cfg:gt(Gn(e))});function Vt(e,t,n,r){let o=V(e);if(A(o),t.fiveHour||t.sevenDay){let g=r??Ce(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=pt(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:Uo(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?Bo(e,t.transcript,l):l,day:a,at:n},p=[y,...u.filter(g=>g.e!==y.e)].slice(0,Ho);Gt(v(o,`${a}.log`),[JSON.stringify({k:"c",t:n,s:t.session,e:y.e,u:oe(l),b:oe(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:oe(g.u),b:oe(g.b)})),m:t.model??i?.m??null,at:n,...f===void 0?{}:{p:f}})}
8
- `)}function Uo(e,t,n,r,o){let s=ee(o),i=n.u;try{let a=new Set;for(let l of Le(Math.max(n.at,o-xe*864e5),o))for(let u of Ae(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,zo(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 zo(e,t,n,r){let o=0,s=new Set;for(let i of Le(Math.max(n,r-(xe+1)*864e5),r))for(let a of Ae(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+=Xt(a));return o}function Bo(e,t,n){if(!t)return 0;let r=L(We(e,t))?.cs,o=0;for(let s of Array.isArray(r)?r.filter(Xn):[])for(let i of s.v)i<=n+.01&&(o=Math.max(o,i));return Math.min(o,n)}function Zt(e,t){return!t||!De.test(t)?!1:pt(v(V(e),"sessions",`${t}.json`))?.p===0}function Zn(e,t){if(!t||!De.test(t))return!1;let n=pt(v(V(e),"sessions",`${t}.json`));return n?.p===1&&Date.now()-n.at<Fe}function uu(e,t){let n=v(V(e),"sessions"),r=!1,o=!1,s=!1;for(let i of Q(n)){if(!i.endsWith(".json"))continue;try{if(me(v(n,i)).mtimeMs<t)continue}catch{continue}let a=pt(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 Ko(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=Jn.test(o)?o:"unknown",i=typeof t.timestamp=="string"?Date.parse(t.timestamp):NaN,a=typeof t.sessionId=="string"&&De.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=ft("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 qo(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"&&De.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 Jo(e,t,n){if(t<=n)return NaN;let r=e.lastIndexOf(In,t-1);if(r<n)return NaN;let o=r+In.length,s=e.indexOf(34,o);return s>o&&s-o<=40?Date.parse(e.subarray(o,s).toString("latin1")):NaN}var Xt=e=>e.i+5*e.o+1.25*e.w5+2*e.w1+.1*e.r,Go=16,Xn=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)},at=e=>e.includes("/subagents/")||e.includes("\\subagents\\"),Yo=e=>Jt(e,".jsonl").replace(/^agent-/,"").replace(/[^A-Za-z0-9_-]/g,"").slice(0,40),We=(e,t)=>v(V(e),"read",`${ft("sha256").update(t).digest("hex").slice(0,32)}.json`);function Kt(e,t,n=qn){let r=V(e),o=We(e,t),s=at(t),i=s?Yo(t):"",a;try{a=dt(t,le.O_RDONLY|le.O_NONBLOCK)}catch{return 0}try{let l=ct(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=Ie(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>=Tn||b){b=!0,d+=x;continue}w=Math.min(Tn,w*4);continue}let P=0;b&&(P=$.indexOf(10)+1,b=!1);let _=$.subarray(0,S+1),H=_.indexOf(Ln,P),j=s?-1:_.indexOf(Ut,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(Ut,B+1);continue}let h=_.indexOf(10,B),E=_.subarray(m,h<0?_.length:h);if(R){let D=qo(E);D&&g.push({c:D,after:f.length,ts:Jo(_,m,P),last:d+(h<0?_.length:h+1)>=l.size})}else{let D=Ko(E);D&&f.push(D)}if(h<0)break;H>=0&&H<=h&&(H=_.indexOf(Ln,h+1)),j>=0&&j<=h&&(j=_.indexOf(Ut,h+1))}if(!s)for(let R=_.lastIndexOf(lt);R>=P;R=R>P?_.lastIndexOf(lt,R-1):-1){if(R>P&&_[R-1]!==10)continue;let B=Vn(_.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)Gt(v(r,`${C}.log`),$)}let k=c&&M(u.lt)!==null?u.lt:0,O=c&&Array.isArray(u.cs)?u.cs.filter(Xn):[],F=c&&M(u.ev)!==null?u.ev:-1/0;if(g.length>0){let N=Jt(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(Go))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&&Vo(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{ut(a)}}function Vo(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))-(xe+1)*864e5);for(let l of Le(i,Math.max(...t.map(u=>u.t))))for(let u of Ae(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]+=ge(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]+=Xt(u)))});let a=new Map;t.forEach((l,u)=>{let c=ft("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:oe(l.u),p:oe(l.p),a:l.a,w:Math.round(r[u]),l:oe(o[u])});for(let y of Le(Math.max(l.a,l.t-xe*864e5),l.t)){let p=a.get(y);p?p.push(d):a.set(y,[d])}});for(let[l,u]of a)Gt(v(n,`${l}.log`),u)}function ht(e,t=-1/0){let n=v(e,"subagents"),r=Q(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 Q(s)){let a=v(s,i);if(!(t>-1/0&&Zo(a)<t))for(let l of Q(a))l.endsWith(".jsonl")&&o.push(v(a,l))}}return o}var Zo=e=>{try{return me(e).mtimeMs}catch{return 0}},Xo=24*36e5;function Qn(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(Se(v(n,r))>0)return v(n,r);let o=v(n,"workflows");for(let s of Q(o))if(Se(v(o,s,r))>0)return v(o,s,r);return null}var Qo=15*6e4;function Qt(e,t,n,r=qn){let o=r,s=ht(t.slice(0,-6),n-Xo).map(i=>({file:i,at:Se(i)})).filter(i=>n-i.at<=Qo).sort((i,a)=>a.at-i.at);for(let{file:i}of s){if(o<=r/2)break;o-=Kt(e,i,o-r/2)}Kt(e,t,o)}function er(e,t,n){let r=0,o=(s,i)=>{try{let a=me(s);if(!a.isFile()||!i&&a.mtimeMs<n)return;let l=L(We(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&&yt(s,u,a.size).indexOf(10)<0)return;r+=c}catch{}};o(t,!0);for(let s of ht(t.slice(0,-6),n))o(s,!1);return r}function te(e,t){let n=e.CLAUDE_CONFIG_DIR?.trim();return n&&Kn(n)?n:v(t,".claude")}function tr(e,t,n,r=1024*1024*1024,o){let s=v(t,"projects"),i=[],a=p=>{let f;try{f=me(p)}catch{return}if(!f.isFile()||f.mtimeMs<n)return;let g=L(We(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 Q(s)){let f=v(s,p);for(let g of Q(f)){if(g.endsWith(".jsonl")){a(v(f,g));continue}for(let w of ht(v(f,g)))a(w)}}o?.(Math.min(r,i.reduce((p,f)=>p+f.left,0)));let l=p=>at(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(at(f.file))-Number(at(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=Kt(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 cu(e,t,n,r=1024*1024*1024,o){return tr(e,t,n,r,o).left===0}var Te=new Map;function es(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 yt(e,t,n){let r=dt(e,le.O_RDONLY|le.O_NONBLOCK);try{if(!ct(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=Ie(r,o,s,o.length-s,t+s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{ut(r)}}function Ae(e,t,n){let r=v(V(e),`${t}.log`),o;try{if(o=me(r),o.size>Io)return n?.("large"),[]}catch(d){return d.code!=="ENOENT"&&n?.("unreadable"),[]}let s=Te.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=yt(r,i,o.size)}catch{return n?.("unreadable"),[]}let l=a.lastIndexOf(10)+1,u=[];es(a.subarray(0,l).toString("utf8"),u);let c=i>0?s.lines.concat(u):u;return Te.size>=64&&!Te.has(r)&&Te.clear(),Te.set(r,{ino:o.ino,size:o.size,mtime:o.mtimeMs,end:i+l,lines:c}),c}function Le(e,t){let n=[],r=new Date(ee(e));for(;r.getTime()<=t;r.setDate(r.getDate()+1))n.push(q(r.getTime()));return n}function Wn(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 ts(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=ge(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=Wn(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;Wn(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 ns(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+=Xt(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 wt(e,t,n,r=null){let o=Math.max(t,ee(n-(xe+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 Le(o,n))ts(s,Ae(e,g,a));let l=0,u=!1,c=new Set;for(let g of new Set([...s.sessions,...s.segs.keys()])){let w=ns(s,g,c);l+=w.usd,u||=w.estimated}let{tokens:d,replies:y,sessions:p,perModel:f}=s;return{usd:oe(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:oe(w.usd)})).sort((g,w)=>w.fresh-g.fresh),...i?{problem:i}:{}}}var rs=gt("");function Re(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`]:[]:Q(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!==rs)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 os(e,t,n={}){let r=Re(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 bt(e){return typeof e.prompt=="string"&&/^\s*<task-notification>/.test(e.prompt.slice(0,64))}function nr(e){if(!e)return null;let t="";try{t=yt(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 zt=3;function rr(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:ge(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 Ae(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 Ae(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(-zt).map(h=>h.c);o.sort((m,h)=>m.t-h.t);let w=o.slice(-zt).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(-zt).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 Un=9e4;function or(e,t){if(!e?.endsWith(".jsonl"))return[];let n=[];for(let r of ht(e.slice(0,-6),t-Un)){if(Se(r)<t-Un)continue;let o=0;try{let a=yt(r,0,Math.min(4096,qt(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=re(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"&&qt(r)>64*1024&&!(o>0&&t-o<6e4)&&(i="running"),n.push({state:i,started:o})}return n}var qt=e=>{try{return me(e).size}catch{return 0}};function Ue(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 en=e=>`read ${e<6e4?"just now":`${Ue(e)} ago`}`,sr=e=>`${Math.max(1,Math.round(e/1048576))} MB`,ss=(e,t=!1)=>e.unpriced.length>0||t?`~${Bn(e.usd)}+`:`${e.estimated?"~":""}${Bn(e.usd)}`;function is(e,t){let n=V(e),r=v(n,"pruned"),o=q(t);try{if($e(r,64)?.toString("utf8").trim()===o)return}catch{}let s=t-xe*864e5,i=q(s);for(let a of Q(n))/^\d{4}-\d{2}-\d{2}\.log$/.test(a)&&a.slice(0,10)<i&&it(v(n,a),{force:!0});it(v(n,"limits.json"),{force:!0});for(let a of["launches","live"])for(let l of Q(v(n,a))){let u=v(n,a,l);Se(u)<t-864e5&&it(u,{force:!0})}for(let a of["sessions","read","tasks","said","limits"])for(let l of Q(v(n,a))){let u=v(n,a,l);Se(u)<s&&it(u,{force:!0})}try{A(n),U(r,o)}catch{}}function zn(e,t,n){let r=e&&n!==void 0&&n-e.at>=6e4?` (${Ue(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:ss(t),today:!0}}function Bn(e){return e<10?`$${e.toFixed(2)}`:`$${String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`}function ze(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 as(){if(Lo(0))return null;let e=Buffer.alloc(Bt+1),t=0;for(let n=0;;){let r=0;try{r=Ie(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>Bt)return null}return t>0?e.subarray(0,t).toString("utf8"):null}function ls(e,t,n,r=null){let o=t?Do(t):null,s=l=>{try{l()}catch{}};o?.transcript&&s(()=>Qt(e,o.transcript,n));let i=null;try{i=o?Ce(o.transcript,e):null}catch{}let a=i;o&&s(()=>Vt(e,o,n,a??void 0)),r&&s(()=>ps(e,r,n)),s(()=>is(e,n));try{let l=o!==null&&!o.fiveHour&&!o.sevenDay&&(o.costUsd??0)>0,u=i?{key:i.key}:r?mt(r):{},c=l?null:os(e,n,u),d=c&&n-c.at<=Fe?c:null;return d?zn(d,null,n):zn(null,wt(e,ee(n),n))}catch{return null}}var us=5*6e4,cs=3e4,ds=32*1024*1024;function fs(e){let t="";try{t=$e(e,4096)?.toString("utf8").trim()??""}catch{return null}if(/^\d+$/.test(t))return{at:Number(t),since:ee(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 tn(e,t,n,r){let o=v(V(e),"caught"),s=fs(o);if(s&&s.at<=r&&s.since<=n&&r-s.at<(s.left>0?cs:us))return s;let i=s&&s.at<=r&&r-s.at<864e5&&s.since<n&&s.since>=He(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=tr(e,t,i,ds),l={at:r,since:i,left:a.left,upto:a.upto};return U(o,JSON.stringify({v:1,...l})),l}function ps(e,t,n){tn(e,t,ee(n),n)}function du(e,t){return ls(e,as(),t,te(process.env,Po()))}import{createHash as di}from"crypto";import{accessSync as fi,closeSync as pi,constants as gi,openSync as mi,readdirSync as Ur,readFileSync as hi,rmSync as yi}from"fs";import{homedir as wi}from"os";import{basename as zr,dirname as bi,join as G}from"path";function Be(e){let t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}import{createHash as $r,randomBytes as _r}from"crypto";import{readdirSync as xr,renameSync as Ms,unlinkSync as Oc}from"fs";import{join as Ye}from"path";import{createHmac as ks,randomBytes as on,timingSafeEqual as $s}from"crypto";import{closeSync as dr,existsSync as _s,fsyncSync as fr,linkSync as xs,mkdirSync as pr,openSync as gr,readdirSync as Ss,readFileSync as Ee,unlinkSync as mr,writeSync as hr}from"fs";import{basename as As,dirname as lr,join as ie}from"path";var se={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function gs(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={[se.on]:r,[se.blocked]:r,[se.held]:r,[se.next]:r,[se.watching]:o,[se.problem]:s,[se.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${hs(l)}\x1B[0m`}}var gu=gs(!1),ms=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function hs(e){return e.replace(ms,"")}var ir=[{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)"}}],ys="home and project wipes and force-pushes to main",vu=`always blocking ${ys}`,ku=new Map(ir.map(e=>[e.id,e]));var ws=new Set(ir.flatMap(e=>Object.keys(e.slugs)));var nn="anvil-claude";function z(e){let t=e.trim();return t===nn||t.endsWith(` ${nn}`)||t.endsWith(`/${nn}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ar="\u{1F539}",I=e=>`${ar} ${e} ${ar}`;var Ke=e=>`
14
- ${se.next} ${e}`;function qe(e,t,n){return`${Ke(`To ${e}, run this in a terminal (not in this chat):`)}
15
- ${t}${n?Ke(`Then ${n}.`):""}`}var rn=e=>Ke(e),bs=72;function vt(e,t){let n=`To ${e}, run in a terminal: ${t}`;return n.length+5<=bs?Ke(n):`${Ke(`To ${e}, run in a terminal:`)}
16
- ${t}`}var kt=(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 vs="anvil";var ue=e=>`${z(vs)} ${e}`;import{spawnSync as Uu}from"child_process";import{createHash as Bu}from"crypto";import{chmodSync as qu,existsSync as Ju,lstatSync as Gu,mkdirSync as Yu,readdirSync as Vu,readFileSync as Zu,readlinkSync as Xu,realpathSync as Qu,rmdirSync as ec,statSync as tc,unlinkSync as nc,writeFileSync as rc}from"fs";import{dirname as sc,join as ic,resolve as ac}from"path";var ae="_seal";function St(e){return ie(e.dir,"seal.key")}function Ne(e,t){return ie(e.state,"lkg",t)}function J(e){let t=St(e);if(K(t,1024)!==!0)return null;try{let n=Ee(t,"utf8").trim();return/^[0-9a-f]{64}$/.test(n)?Buffer.from(n,"hex"):null}catch{return null}}function ln(e){return J(e)?"ok":K(St(e),1024)===null?"missing":"damaged"}var xt=class extends Error{};function At(e,t){return`Anvil's seal key (${St(e)}) is ${t==="damaged"?"damaged":"missing"}`}function Cs(e){let t=J(e);if(t)return t;let n=ln(e);if(n==="damaged"||un(e))throw new xt(`${At(e,n)}; run ${ue("on")} to restore it`);let{key:r,created:o}=Rs(e,!1);return o&&Os(e,r),r}function ur(e,t,n){let r=gr(e,n,384);try{hr(r,t),fr(r)}finally{dr(r)}}function Rs(e,t){pr(e.dir,{recursive:!0,mode:448});let n=St(e),r=ie(e.dir,`.seal.key.${process.pid}.${on(4).toString("hex")}.tmp`);ur(r,`${on(32).toString("hex")}
17
- `,"wx");let o=!1;try{t?je(r,n):xs(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{ur(n,Ee(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{mr(r)}catch{}}let s=J(e);if(!s)throw new xt(`${At(e,"damaged")}; run ${ue("on")} to restore it`);return{key:s,created:o}}function Os(e,t){let n=[[e.modes,_t],[e.compiled,wr],[e.install,void 0]];for(let[r,o]of n)if(K(r,8*1024*1024)===!0)try{let s=Ee(r,"utf8");if(s.includes(`"${ae}"`))continue;let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=`${JSON.stringify(an(t,i),null,2)}
18
- `;Oe(r,a),o&&Oe(Ne(e,o),a)}catch{}if(K(e.modes)===null&&K(Ne(e,_t))===null){let r=`${JSON.stringify(an(t,It()),null,2)}
19
- `;Oe(e.modes,r),Oe(Ne(e,_t),r)}}function sn(e,t=0){if(t>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(n=>sn(n===void 0?null:n,t+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(t===0&&r===ae)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${sn(e[r],t+1)}`).join(",")}}`:JSON.stringify(e??null)}function yr(e,t){return ks("sha256",e).update(sn(t)).digest("hex")}function $t(e){if(!(ae in e))return e;let t={...e};return delete t[ae],t}function an(e,t){let n=$t(t);return{...n,[ae]:yr(e,n)}}function Ns(e,t){let n=t[ae];if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))return!1;let r;try{r=yr(e,t)}catch{return!1}return $s(Buffer.from(n,"hex"),Buffer.from(r,"hex"))}function Oe(e,t,n=384){pr(lr(e),{recursive:!0,mode:448});let r=ie(lr(e),`.${As(e)}.${process.pid}.${Date.now().toString(36)}.${on(3).toString("hex")}.tmp`);try{let o=gr(r,"w",n);try{hr(o,t),fr(o)}finally{dr(o)}je(r,e)}catch(o){try{mr(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(Ee(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:t?ae in o?Ns(t,o)?{status:"ok",value:$t(o)}:{status:"changed",value:$t(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:$t(o)}}function Ct(e,t,n,r){let o=Cs(e),s=`${JSON.stringify(an(o,n),null,2)}
20
- `;Oe(t,s),r&&Oe(Ne(e,r),s)}var _t="modes.json",wr="compiled.json";function un(e){return _s(ie(e.bin,"claude-hook.sh"))||Es(e)}function Es(e){let t=n=>{try{return Ss(n).slice(0,200).some(r=>r.endsWith(".json")&&K(ie(n,r),65536)===!0&&Ee(ie(n,r),"utf8").includes(`"${ae}"`))}catch{return!1}};if(t(ie(e.state,"lkg"))||t(ie(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(Ee(n,"utf8").includes(`"${ae}"`))return!0}catch{}return!1}var br=X({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function cr(e=new Date){return Sn(null,"enforce","all",e)}function Je(e,t=J(e),n={}){if(!t){let i=ln(e);if(n.installed===!0||i==="damaged"||un(e))return{value:cr(),source:"strict",problem:`${At(e,i)}, so every rule is enforced until \`${ue("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 ${br[r.status]??"cannot be used"}`,s=Z(Ne(e,_t),t);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:cr(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${ue("on")}\` resets it`}}function Ge(e,t,n=J(e),r={}){let o=u=>!!u&&typeof u=="object"&&u.format===Wt&&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=ln(e),c=r.installed===!0||u==="damaged"||un(e),d=Z(e.compiled,null),y=d.status==="unkeyed"&&o(d.value)?d.value:null;return c?{value:null,source:"strict",problem:`${At(e,u)}: \`${ue("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":br[i.status]??"cannot be used"}`,l=Z(Ne(e,wr),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: \`${ue("on")}\` recompiles them`}}var Pc=600*1e3,Ps=1440*60*1e3,vr="23456789abcdefghjkmnpqrstuvwxyz",kr=8;function he(e){return Ye(e.state,"pending")}function js(){let e=_r(kr),t="";for(let n=0;n<kr;n++)t+=vr[e[n]%vr.length];return t}function Ts(e){return $r("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var Ls=()=>_r(8).toString("hex"),Is=e=>`${$r("sha256").update(e??"").digest("hex").slice(0,12)}.`;function Sr(e,t,n){let r=js(),o=Ls();A(he(e));let s={v:2,id:o,code_sha256:Ts(r),...t,created_at:new Date(n).toISOString(),expires_at:new Date(n+Ps).toISOString()};return Ct(e,Ye(he(e),`${Is(t.session)}${o}.json`),s),{code:r,id:o}}function Ds(e,t){return e.kind===t.kind&&(e.target??null)===(t.target??null)}function Ar(e,t,n){let r=[];try{r=xr(he(e)).filter(s=>s.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let s of r){let i=Ye(he(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 Cr(e,t,n,r,o,s){let i=[];try{i=xr(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=Ye(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=>Ds(p,y))))try{return Ms(u,Ye(e.approvals,`${l.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:a}}catch{}}return{approved:!1,forged:a}}import{spawn as Fs,spawnSync as Rr}from"child_process";import{closeSync as Hs,openSync as Ws,readdirSync as Us,readlinkSync as zs,statSync as Or,unlinkSync as Nr,writeSync as Bs}from"fs";import{delimiter as Ks,isAbsolute as qs,join as ye}from"path";var Js=5*6e4,cn=2*6e4,Er=3,Gs=15*6e4,Ys=6*36e5,Mr=3e4,Vs=6e4,Zs=["-p","/usage","--output-format","stream-json","--verbose","--no-session-persistence","--setting-sources","project","--settings",'{"autoMemoryEnabled":false}',"--strict-mcp-config","--model","anvil-reads-usage-only"],Pr="ANVIL_PLAN_PROBE",jr=(e,t)=>ye(e.state,`plan-probe-${t}.json`),dn=(e,t)=>ye(e.state,`plan-probe-next-${t}`),Tr=e=>ye(e.state,"plan-probe.lock"),Xs=e=>ye(e.dir,"plan-probe");function Lr(e,t){let n=t?[jr(e,t)]:Qs(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 Qs(e){try{return Us(e.state).filter(t=>/^plan-probe-[ac][0-9a-f]{16}\.json$/.test(t)).map(t=>ye(e.state,t))}catch{return[]}}function ei(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 ti(e,t=ni,n=!1){let r=a=>{try{return a&&qs(a)&&Or(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(Ks)){let l=a?r(ye(a,"claude"))??(process.platform==="win32"?r(ye(a,"claude.exe")):null):null;if(l)return l}return null}function ni(e){try{return zs(`/proc/${e}/exe`)}catch{}try{let t=Rr("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 ri(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[Pr]="1",n.DISABLE_AUTOUPDATER="1",n}var oi=(e,t,n)=>{let r=Rr(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 si(e,t){let n=Tr(e);for(let r=0;r<2;r++)try{let o=Ws(n,"wx",384);return Bs(o,String(t)),Hs(o),!0}catch(o){if(o.code!=="EEXIST")return!1;let s=Number(re(n,64).trim());if(Number.isFinite(s)&&t-s<Vs&&s<=t+6e4)return!1;try{Nr(n)}catch{return!1}}return!1}function ii(e){try{Nr(Tr(e))}catch{}}function ai(e){try{if(A(e.paths.state),!si(e.paths,e.now()))return null;try{let t=Re(e.paths,e.now(),{key:e.account.key});if(!e.screen&&t&&e.now()-t.at<cn)return null;let n=li(e);if(e.screen&&!n.ok)return n;U(jr(e.paths,e.account.key),`${JSON.stringify(n)}
22
- `);let r=n.ok?cn:n.why==="noplan"||n.why==="unavailable"||n.why==="nobinary"?Ys:Gs;return U(dn(e.paths,e.account.key),String(e.now()+r)),n}finally{ii(e.paths)}}catch{return null}}function li(e){let t=e.binary??ti(e.env,e.exeOf);if(!t)return{at:e.now(),ok:!1,why:"nobinary"};let n=Xs(e.paths);A(n);let r=(e.run??oi)(t,Zs,{cwd:n,env:ri(e.env),timeout:Mr}),o=e.now();if(r.error||r.status===null)return{at:o,ok:!1,why:"failed"};let s=ei(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=Yt(te(e.env,e.env.HOME??e.env.USERPROFILE??""));if(l&&l!==e.account.key)return{at:o,ok:!1,why:"otheraccount",...a}}return Vt(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 Ir="ANVIL_PLAN_PROBE_FOR";function Dr(e){try{if(e.env[Pr]==="1"||!e.env.CLAUDE_CODE_EXECPATH&&!e.env.CLAUDE_PID)return!1;let t=e.near?cn:Js;if(e.readingAt!==null&&e.now-e.readingAt<t&&e.readingAt<=e.now+6e4)return!1;let n=Number(re(dn(e.paths,e.account.key),64).trim());if(Number.isFinite(n)&&n>e.now&&n-e.now<=24*36e5)return!1;try{Or(e.hookFile)}catch{return!1}return A(e.paths.state),U(dn(e.paths,e.account.key),String(e.now+Mr+5e3)),(e.start??ui)(e.node,[e.hookFile,"--plan-probe"],e.paths.dir,{...e.env,[Ir]:`${e.account.key}|${e.account.cfg}`}),!0}catch{return!1}}function ui(e,t,n,r){let o=Fs(e,t,{detached:!0,stdio:"ignore",cwd:n,env:r,windowsHide:!0});o.on("error",()=>{}),o.unref()}function ci(e){let t=/^([ac][0-9a-f]{16})\|([0-9a-f]{16})$/.exec(e[Ir]??"");return t?{key:t[1],cfg:t[2]}:null}function Br(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("/")?Be(n):n}}var pn=36e5,vi=/^[A-Za-z0-9._-]{1,128}$/,ki=.8;function hn(e){return(e?.policies??[]).flatMap(t=>t.budgets??[])}var de=e=>G(e.dir,"meter"),Kr=(e,t)=>G(de(e),"tasks",`${t}.json`),yn=e=>e!==null&&vi.test(e)&&e!=="."&&e!=="..";function wn(e,t){if(!yn(t))return null;let n=Z(Kr(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 qr(e,t,n){yn(t)&&(A(G(de(e),"tasks")),Ct(e,Kr(e,t),n))}var Jr=(e,t,n)=>e.window==="day"?ee(t):e.window==="week"?He(t):e.window==="task"?n?.t??Number.NaN:Number.NaN;function Gr(e,t){try{if(e.unit==="plan"){if(t.apiKey||Zt(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<=Fe&&(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>Fe?{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||!yn(t.session)))return{budget:e,used:null,why:"task"};let n=Jr(e,t.now,t.task),r=e.window==="task"?t.own():t.unread.left>0&&t.unread.upto>=n?t.unread.left:0;return Li(e,t.totals(n,e.window==="task"?t.session:null),r)}catch{return{budget:e,used:null,why:"meter"}}}var $i=.5,Ve=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")}},fn=1e4,_i=.5,xi=3e5,Fr=2.25;function Si(e,t){let n=G(de(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(de(e)),U(n,`${JSON.stringify({v:1,...a})}
23
- `)}catch{}return a}var Ai=9e4,Ci=1e4,Ze=e=>e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,128),Xe=e=>G(de(e),"live"),ce=(e,t,n=1)=>({usd:e.usd+n*t.usd,fresh:e.fresh+n*t.fresh}),we={usd:0,fresh:0};function Ri(e,t,n){try{A(Xe(e)),U(G(Xe(e),`${Ze(t)}.json`),`${JSON.stringify(n)}
24
- `)}catch{}}function Oi(e,t,n){let r=new Map,o=`${Ze(t)}.json`,s=[];try{s=Ur(Xe(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(Xe(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 Ni(e){if(!e.session)return null;let t=e.payload,n=t.tool_name==="Agent"||t.tool_name==="Task",r=rr(e.paths,e.session,e.now,n?7:0),o=wn(e.paths,e.session)?.t??null,s=Ve(o!==null?r.mainSince(o):r.main)??Ve(r.main),i=n&&typeof t.tool_use_id=="string"?t.tool_use_id.slice(0,128):null,a=r.main.length<=1?Ve(r.chatToday):null,l=s?a&&a.fresh>s.fresh?a:s:we,u=Ve(r.helpers)??Ve(r.helpersToday),c=u??l,d=r.model??"claude-opus-5-5",y=n?nr(e.transcript??null)??r.chatPrompt:r.chatPrompt,p=Math.max(fn,Math.round((y??0)*_i)),f={usd:ge(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)<xi,b=n?Si(e.paths,{warm:r.helperFirstWarm,cold:r.helperFirstCold}):{warm:r.helperFirstWarm,cold:r.helperFirstCold},k=b.warm?{usd:Fr*b.warm.usd,fresh:Math.round(Fr*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?ce(ce(we,u,2),l):N,C=s!==null&&o!==null&&r.lastMainAt!==null&&r.lastMainAt<o,$=s?C&&r.chatRecent?r.chatRecent:we:r.chatFirst??{usd:ge(d,{input:0,output:0,write5m:fn,write1h:0,read:0})??0,fresh:fn},S=ce($,l,2),P={v:1,t:e.now,transcript:e.transcript??null,chat:S,perRunning:x,each:N},_=L(G(Xe(e.paths),`${Ze(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<Ci&&H(_)||Ri(e.paths,e.session,P),i&&Vr(e.paths,e.session,i,e.now);let j=Ze(e.session),R=Mi(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,be,ve)=>{let Tt=or(be,e.now),Lt=m.filter(ne=>ne.s===W),co=Lt.length>0?Math.min(...Lt.map(ne=>ne.t))-2e3:1/0,fo=Math.max(0,Lt.length-Tt.filter(ne=>ne.started>=co).length),po=Tt.filter(ne=>ne.state==="running").length,go=Tt.filter(ne=>ne.state==="starting").length;return ce(ce(we,ve.perRunning,po),ve.each,go+fo)},E=ce(S,h(j,e.transcript??null,{perRunning:x,each:N})),D=Oi(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:we,perRunning:x,each:N});let jt=we,xn=0;for(let[W,be]of D){let ve=ce(be.t>=e.now-Ai?be.chat:we,h(W,be.transcript,be));(ve.fresh>0||ve.usd>0)&&(jt=ce(jt,ve),xn++)}return{running:E,others:jt,otherSessions:xn,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 Ei=2e4,Yr=e=>G(de(e),"launches","all.log");function Mi(e,t){let n=[],r=new Set;for(let o of re(Yr(e),64*1024).split(`
25
- `)){let[s,i,a,l]=o.split(" "),u=Number(s);if(!i||!a||!(u>t-Ei&&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 Vr(e,t,n,r,o=!1){try{let s=Yr(e);A(bi(s)),_e(s,`${r} ${Ze(t)} ${n.replace(/\s/g,"_")}${o?" x":""}`)}catch{}}function Pi(e){let t=e.payload;e.session&&(t.tool_name==="Agent"||t.tool_name==="Task")&&typeof t.tool_use_id=="string"&&Vr(e.paths,e.session,t.tool_use_id.slice(0,128),e.now,!0)}function ji(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??=Ni(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),$i*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 Rt={err:s instanceof Error?s.message.slice(0,200):String(s).slice(0,200)},t}finally{r!==void 0&&Rt?.err===void 0&&(Rt=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 Rt;function Ti(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:Rt??null}))}catch{}}function Zr(e,t,n,r){let o={left:0,upto:0};try{e.transcript&&Qt(e.paths,e.transcript,e.now);let u=Math.min(...t.map(c=>Jr(c,e.now,n)).filter(c=>Number.isFinite(c)));Number.isFinite(u)&&(o=tn(e.paths,te(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=Re(e.paths,e.now,{key:Ce(e.transcript,e.paths).key}):i,totals:(u,c)=>{let d=`${u}|${c??""}`,y=s.get(d);return y||s.set(d,y=wt(e.paths,u,e.now,c)),y},unread:o,own:()=>e.transcript&&n?er(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=ji(e,t.map(u=>Gr(u,a)),r);Ti(e,r,l);try{if(e.probe&&!a.apiKey&&t.some(u=>u.unit==="plan")&&!Zt(e.paths,e.session)&&!Zn(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-Er&&y.pct<d.limit});Dr({paths:e.paths,env:e.env,now:e.now,account:Ce(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 Li(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 Ot=e=>e.why==="large"||e.early!==void 0||e.used!==null&&e.used>=e.budget.limit,fe={day:"today's",week:"this week's",task:"this task's",seven_day:"your week's",five_hour:"these 5 hours'"},gn=(e,t=1e3)=>`$${e<t?e.toFixed(2):String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,Et=e=>Number.isInteger(e)?gn(e,0):gn(e),bn=(e,t,n=1e3)=>{let r=gn(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 Me(e){let t=e.budget,n=e.used??0;return t.unit==="usd"?`${e.estimated?"~":""}${bn(n,t.limit)} of ${Et(t.limit)}`:t.unit==="tokens"?`${ze(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 Qe(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 Ii=e=>e.charAt(0).toUpperCase()+e.slice(1),Mt="a day of Anvil's meter is over 32 MB, more than any person's day: a loop, or something writing to it",nt=e=>e.early&&(e.used??0)<e.budget.limit?e.early.why:null,Pt=e=>nt(e)?"nearly spent":"spent",Hr=e=>{let t=e.early?.others??0;return t>0?` here and in ${t===1?"another Claude Code session":`${t} other Claude Code sessions`}`:""},vn=e=>({running:`, and what's running${Hr(e)} could pass it`,next:`, and the next replies${Hr(e)} could pass it`,launch:""})[nt(e)??"launch"]??"";function et(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: ${Mt} \xB7 ${n}`;if(nt(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 ${fe[e.budget.window]} budget: ${Me(e)} used${s} \xB7 ${Qe(e,t)} \xB7 ${n}`}return`${fe[e.budget.window]} budget is ${Pt(e)}: ${Me(e)}${vn(e)} \xB7 ${Qe(e,t)} \xB7 ${n}`}function Di(e,t,n,r){return`${e.why==="large"?`${I("Your budget can't be counted")} ${e.budget.text} \xB7 ${Mt}`:`${I(`${Ii(fe[e.budget.window])} budget is ${Pt(e)}`)} ${Me(e)}${vn(e)} \xB7 ${Qe(e,t)}`}${qe("keep going",`${z(n)} allow ${r}`,"send your message again")}${vt("change the budget instead",`${z(n)} rules edit`)}`}function Fi(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 ${Ue(e.age)} ago)`:""} \xB7 your budget stops at ${t.limit}%`;let n=e.used??0,r=t.unit==="usd"?`${e.estimated?"~":""}${bn(n,t.limit,10)}`:ze(n),o=t.unit==="usd"?Et(t.limit):`${t.text.replace(/ a (day|week|task)$/,"")}`;return`${I("Anvil")} ${r} of ${fe[t.window]} ${o} used`}var Wr={plan:"there is no reading of your plan yet",meter:"Anvil's meter can't be read right now",large:Mt};function Hi(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 Xr(e){switch(e.why){case"large":return`can't be counted: ${Mt}`;case"price":return`can't measure: no price for ${(e.models??[]).join(", ")}`;case"stale":return`can't measure (last reading ${Ue(e.age??0)} ago${e.reset?", before its window reset":""})`;case"counting":return`can't measure yet: Anvil is still reading ${fe[e.budget.window]} session files (${sr(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: ${Wr.plan}`;default:return`can't be measured here: ${Wr.meter}`}}function ed(e,t){try{let r=JSON.parse(hi(G(te(e,t),"settings.json"),"utf8").replace(/^/,""))?.statusLine?.command;return typeof r=="string"&&!r.includes("/.anvil/claude/bin/claude-sync.js")}catch{return!1}}function tt(e,t){let n=G(de(e),"said");try{return A(n),pi(mi(G(n,di("sha256").update(t).digest("hex").slice(0,32)),"wx")),!0}catch(r){return r.code!=="EEXIST"}}function Qr(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?Hi(Lr(e.paths,Ce(e.transcript,e.paths).key)):void 0;if(a===null||!tt(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??Xr(o)} \xB7 not enforced`);continue}if(o.used<s.limit*ki||o.used>=s.limit)continue;let i=s.window==="day"?q(e.now):s.window==="week"?q(He(e.now)):s.window==="task"?`${e.session}@${n?.t??0}`:String(o.resetsAt??0);tt(e.paths,`near|${s.id}|${i}`)&&r.push(Fi(o))}return r.length>0?r.join(`
26
- `):null}function Nt(e,t,n,r,o,s){try{A(e.paths.dir);let i=o==="passed"?et(t,e.now,"going on with your OK"):et(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?zr(e.project):null,...s?{hold:s}:{},path:"none",ms:0}))}catch{}}function eo(e,t,n){let r=e.budget.window;return r==="day"?ee(t):r==="week"?He(t):r==="task"?n?.t??0:e.resetsAt??0}var Wi=36e5;function to(e,t,n,r){if(e.id!==t.budget.id||!(n<e.end)||e.end-n>pn)return!1;let o=eo(t,n,r);return(t.budget.unit==="plan"?Math.abs(o-e.w)>Wi:o!==e.w)?!1:e.at===null||t.used===null||t.used<e.at+t.budget.limit}function Ui(e){try{let t=he(e);return A(t),fi(t,gi.W_OK),!0}catch{return!1}}var no=(e,t)=>`${he(e)} can't be written: fix its permissions, or run in a terminal: ${z(t)} on`,ro=(e,t,n)=>`${I("Anvil")} ${et(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 oo(e,t,n,r){let o=!1;try{o=Cr(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 Ar(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)&&yi(i,{force:!0})}catch{}try{let s=n?null:r?.until!==void 0&&e.now<r.until?r.until:e.now+pn,i=(r?.passes??[]).filter(l=>l.id!==t.budget.id&&e.now<l.end),a={id:t.budget.id,w:eo(t,e.now,n),at:t.used,end:e.now+pn};qr(e.paths,e.session,{v:1,t:n?.t??e.now,passes:[...i,a],...s!==null?{until:s}:{}})}catch{}return!0}function mn(e,t){return`${e.why==="large"||e.budget.unit==="plan"?"":`up to ${e.budget.unit==="usd"?Et(e.budget.limit):ze(e.budget.limit)} more, `}for an hour at most${e.budget.window==="task"?"":`, until it ${Qe(e,t)}`}`}function so(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 ${mn(e,t)}`:`${I("Anvil")} going on ${nt(e)?`near ${fe[e.budget.window]} budget`:`past ${fe[e.budget.window]} budget`}, as you said: ${Me(e)} \xB7 for this task, ${mn(e,t)}`}function zi(e,t,n){return`Anvil: ${e.why==="large"?`the user's budget ${e.budget.text} can't be counted`:`${fe[e.budget.window]} budget is ${Pt(e)} (${Me(e)}${vn(e)})`}, and the user ran \`${z(t)} allow\` in a terminal to let this task go on past it (${mn(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 Bi=new Set(["SubagentHandback","mcp__ccd_turn__wrap_up","mcp__ccd_turn__update_plan"]);function td(e){if(Bi.has(String(e.payload.tool_name??"")))return null;try{let t=Br(e),n=hn(t.table);if(n.length===0)return null;let r=wn(t.paths,t.session),o=Date.parse(t.table?.compiled_at??""),s=r&&r.until===void 0&&!(o>r.t)?r:null,i=Zr(t,n,s,"action"),a=r&&(r.until===void 0||t.now<r.until)?r.passes??[]:[],l=y=>a.some(p=>to(p,y,t.now,s)),u=i.find(y=>Ot(y)&&!l(y)),c=()=>{for(let y of i)Ot(y)&&l(y)&&Nt(t,y,"PreToolUse","claude.budget","passed",null)};if(u){if(oo(t,u,s,r))return Nt(t,u,"PreToolUse","claude.budget","approved",null),c(),{note:so(u,t.now)};let y=et(u,t.now);if(Pi(t),!Ui(t.paths))return{note:ro(u,t.now,no(t.paths,t.cli))};let p=u.budget.id,f=u.why==="large"?"the user's budget can't be counted":nt(u)==="launch"?"the helpers starting could pass the user's budget":`the user's budget is ${Pt(u)}`,g={user:`${I("Held by Anvil for your OK")} ${y}${qe("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, ${kt(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=Qr(t,i.filter(y=>!l(y)),s);return d?{note:d}:null}catch{return null}}function nd(e){try{if(bt(e.payload))return null;let t=Br(e),n=J(t.paths),r={installed:t.installed===!0},o=t.table??Ge(t.paths,t.fallbackTable,n,r).value,s=hn(o);if(s.length===0)return null;let i={v:1,t:t.now};try{qr(t.paths,t.session,i)}catch{}if(Je(t.paths,n,r).value?.kill_switch===!0)return null;let a=Zr(t,s.filter(c=>c.window!=="task"),i,"message"),l=a.find(Ot);if(l){if(oo(t,l,i,i))return Nt(t,l,"UserPromptSubmit","claude.prompt","approved",null),`${JSON.stringify({systemMessage:so(l,t.now),hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:zi(l,t.cli,t.now)}})}
27
- `;let c;try{c=Sr(t.paths,{session:t.session,project:t.project,stops:[{kind:"claude.budget",target:l.budget.id}],why:et(l,t.now),project_name:t.project?zr(t.project):null,command:"your next message (Anvil never reads it)"},t.now)}catch(d){let y=d.code;return`${JSON.stringify({systemMessage:ro(l,t.now,y==="ENOSPC"||y==="EDQUOT"?"the disk is full: free some space":no(t.paths,t.cli))})}
28
- `}return Nt(t,l,"UserPromptSubmit","claude.prompt","deny",c.id),`${JSON.stringify({decision:"block",reason:Di(l,t.now,t.cli,c.code)})}
29
- `}let u=Qr(t,a,i);return u?`${JSON.stringify({systemMessage:u})}
30
- `:null}catch{return null}}function Ki(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 ${en(e.age??0)}`:t.unit==="tokens"?`${ze(e.used)} of ${t.text.replace(/ a (day|week|task)$/,"")} ${n}`:`${e.estimated?"~":""}${bn(e.used,t.limit,10)} of ${Et(t.limit)} ${n}`}function qi(e,t){let n=[],r=[];try{r=Ur(G(de(e),"tasks"))}catch{return n}for(let o of r){if(!o.endsWith(".json"))continue;let s=wn(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 rd=(e,t)=>mt(te(e,t));function od(e,t,n,r){let o=hn(t);if(o.length===0)return[];let s=r??mt(te(process.env,wi())),i,a={paths:e,now:n,task:null,session:null,reading:()=>i===void 0?i=Re(e,n,s):i,totals:c=>wt(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=Gr(c,a),y=c.unit==="plan"&&d.used!==null?` \xB7 ${en(d.age??0)}`:"",p;if(Ot(d))for(let{pass:f,task:g}of u??=qi(e,n))to(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?Xr(d):`${Me(d)} \xB7 ${Qe(d,n)}${y}`,short:Ki(d),...d.why?{why:d.why}:{},...d.age!==void 0?{age:d.age}:{},...p!==void 0?{okUntil:p}:{}})}return l}import{execFileSync as Ji}from"child_process";import{readdirSync as Gi,rmSync as Yi,statSync as io}from"fs";import{basename as Vi,join as pe}from"path";function rt(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,kn=e=>e.split(" \xB7 ")[0]??e,Zi=e=>e==="sdk"||e.startsWith("repl_main_thread"),Xi=e=>Array.isArray(e)&&e.some(t=>typeof t=="string"&&t.startsWith("context-1m-"));function Qi(e,t){return ao(e,t)?.model??null}function ao(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?Qn(e,t)??pe(e.slice(0,-6),"subagents",`agent-${t}.jsonl`):e,o;try{o=io(r).size}catch{return null}for(let s of[256*1024,4*1024*1024]){let i=re(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&&!Zi(d))continue;let y=Y(c.params?.model),p=typeof c.timestamp=="string"?Date.parse(c.timestamp):Number.NaN;if(y)return{model:Xi(c.params?.betas)&&!/\[1m\]$/i.test(y)?`${y}[1m]`:y,at:p}}catch{}}if(o<=s)break}return null}function $n(e,t){let n=(e?.policies??[]).filter(r=>Rn(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 ea(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 ot=(e,t)=>e.model===t.family&&(!e.one_m||t.oneM);function wd(e){try{let t=$n(e.table,e.projectDir??null),n=e.kinds??[],r=ea(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=Qi(Y(e.payload.transcript_path),s),a=i?rt(i):null,l=[];if(!s&&a){let p=t.never.find(f=>ot(f,a));p&&tt(e.paths,`model-never|${o}|${p.id}`)&&l.push(`${I("Anvil")} this session runs on ${a.label}, which your rules say never (${kn(p.source)})${rn("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}${qe("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, ${kt(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)`;tt(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=>ot(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} (${kn(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 bd(e){try{let t=J(e.paths),n={installed:e.installed===!0},r=e.table??Ge(e.paths,e.fallbackTable,t,n).value,o=$n(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?rt(s):null)??(i?rt(i):null),l=a!==null&&(a.oneM||/\[1m\]$/i.test(i??"")),u=s&&rt(s)?s:i??s,c=a?o.never.find(f=>ot(f,{family:a.family,oneM:l})):void 0,d=Je(e.paths,t,n).value?.kill_switch===!0;if(!c||d||!a)return na(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 lo(e,c,y,"switch"),`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreModelSwitch",permissionDecision:"deny",permissionDecisionReason:p}})}
33
- `}catch{return null}}function lo(e,t,n,r){try{let o=Y(e.env.CLAUDE_PROJECT_DIR)??Y(e.payload.cwd),s=o&&o.startsWith("/")?Be(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?Vi(s):null,path:"none",ms:0}))}catch{}}var uo=/^[A-Za-z0-9_-]{1,80}$/,ta=7*864e5;function na(e,t){let n=Y(e.payload.session_id);if(!(!n||!uo.test(n)||!t))try{let r=pe(e.paths.dir,"models");A(r),U(pe(r,`${n}.json`),`${JSON.stringify({v:1,model:t.slice(0,80),at:e.now})}
34
- `);for(let o of Gi(r)){let s=pe(r,o);o.endsWith(".json")&&e.now-io(s).mtimeMs>ta&&Yi(s,{force:!0})}}catch{}}function ra(e,t){if(!t||!uo.test(t))return null;let n=L(pe(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 Ji("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 oa(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 sa(e){let t=e.projectDir??null,n=[...t?[pe(t,".claude","settings.local.json"),pe(t,".claude","settings.json")]:[],pe(te(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 ia(e,t=_n){let n=Y(e.payload.session_id),r=oa(e.env,t),o=r?r.at-1e3:Number.NEGATIVE_INFINITY,s=[ra(e.paths,n),ao(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())??sa(e)}var aa=["opus","sonnet","fable","haiku"];function vd(e,t=_n){try{if(bt(e.payload))return null;let n=J(e.paths),r={installed:e.installed===!0},o=e.table??Ge(e.paths,e.fallbackTable,n,r).value,s=$n(o,e.projectDir??null);if(s.never.length===0||Je(e.paths,n,r).value?.kill_switch===!0)return null;let i=ia(e,t),a=i?rt(i):null;if(!a)return null;let l=s.never.find(d=>ot(d,a));if(!l)return null;let u=aa.find(d=>!(d===a.family&&!a.oneM)&&!s.never.some(y=>ot(y,{family:d,oneM:!1}))),c=`${I(`This session is on ${a.label}`)} your rules say ${l.text} (${kn(l.source)})${rn(`Switch first (the model picker, or /model${u?` ${u}`:""}), then send your message again.`)}${vt("change that rule instead",`${z(e.cli)} rules edit`)}`;return lo(e,l,a.label,"message"),`${JSON.stringify({decision:"block",reason:c})}
35
- `}catch{return null}}export{Fr as COLD_PER_WARM,Bt as FEED_MAX_BYTES,fn as FIRST_HELPER_REPLY_TOKENS,xi as HELPER_CACHE_MS,Un as HELPER_LIVE_MS,xe as KEEP_DAYS,Ei as LAUNCH_CLAIM_MS,Ai as LIVE_MS,Fe as PLAN_FRESH_MS,Bi as REPORT_ONLY_TOOLS,$i as RESERVE_MAX_SHARE,qn as STATUSLINE_READ_BYTES,_i as UNSEEN_HELPER_SHARE,Ce as accountOf,Ue as ageWords,td as budgetAtAction,nd as budgetAtPrompt,od as budgetStanding,hn as budgetsOf,cu as catchUp,tr as catchUpFrom,tn as catchUpSince,ps as catchUpToday,bt as claudeCodesOwnTurn,te as claudeConfigDir,q as dayOf,ss as dollarsWords,Zn as feedsPlan,uu as feedsSince,ht as helperFiles,or as helperStates,Qn as helperTranscript,Re as lastReading,oa as launchOf,sr as megabytes,ls as meterStep,wt as meterTotals,wd as modelAtAction,ia as modelAtMessage,vd as modelAtPrompt,bd as modelAtSwitch,Qi as modelNow,rt as modelOf,Bn as money,Zt as offPlan,ed as ownStatusLine,Yn as ownerKeyOf,Do as parseStatusFeed,ci as probeAccount,Hi as probeFailure,is as pruneMeter,en as readAgo,as as readFeedFromStdin,os as readLimits,Qt as readSessionAndHelpers,Kt as readSessionFile,rr as recentReplies,Vt as recordFeed,ao as requestNow,ai as runPlanProbe,tt as sayOnce,rd as screenPlanScope,mt as screenScope,nr as sessionOpeningPrompt,er as sessionUnread,Yt as signedInOwner,zn as spendWords,bn as spentUsd,ee as startOfDay,He as startOfWeek,du as statusSpend,ze as tokenWords};
1
+ import{appendFileSync as Nr,closeSync as Pn,constants as we,fstatSync as jn,openSync as Ln,readdirSync as Si,readSync as an,rmSync as On,statSync as Se}from"fs";import{createHash as Tn}from"crypto";import{homedir as Ai}from"os";import{basename as Et,dirname as Ci,isAbsolute as zr,join as S,resolve as Ri}from"path";import{isatty as Oi}from"tty";import{createHash as Mc}from"crypto";import{appendFileSync as gi,closeSync as _r,constants as xr,fstatSync as Sr,mkdirSync as hi,openSync as Ar,readdirSync as jc,readFileSync as mi,readSync as Cr,renameSync as yi,statSync as wi,unlinkSync as Lc,writeFileSync as bi}from"fs";import{homedir as Ic}from"os";import{dirname as Fc,join as pe}from"path";var Xe="claude";function si(e){return e==="ghost"||e==="enforce"?e:null}function pt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[Xe]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function kr(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:pt(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[Xe]:{actions:{}}},updated_at:r.toISOString()};let s={...o.services?.[Xe]?.actions??{}};for(let i of t)s[i]={mode:n};return{version:1,kill_switch:o.kill_switch===!0,default_mode:si(o.default_mode)??"ghost",services:{...o.services??{},[Xe]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{}}}function ne(e){return Object.assign(Object.create(null),e)}import{existsSync as gd,readdirSync as hd,statSync as md}from"fs";import{dirname as wd,isAbsolute as bd,join as kd,posix as vd,resolve as $d}from"path";import{posix as $r}from"path";var li=null;function Qe(){return li??process.platform==="win32"}var vr=/^([A-Za-z]):(.*)$/s,ai=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function gt(e,n){let t=$r.normalize(`/${n}`);return t==="/"?e:`${e}${t.replace(/\/$/,"")}`}function Ie(e,n){return e.split("/").map(t=>{if(t===""||t==="."||t===".."||/[\u0000\u0001]/.test(t))return t;let r=t.indexOf(":"),o=r>=0?t.slice(0,r):t,s=n?o:o.replace(/[. ]+$/,"");return s===""?".":s}).join("/")}function ht(e){if(!Qe())return e;let n=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),t=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(n);if(r){let l=r[2];if(r[1]===".")return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(l))n=`\\\\${l.slice(4)}`;else if(vr.test(l))n=l;else return`/dev/${l.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;t=!0}n=n.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(n);if(o){let l=`/unc/${Ie(o[1],t).toLowerCase()}${o[2]?`/${Ie(o[2],t).toLowerCase()}`:""}`;return gt(l,Ie(o[3]??"",t).toLowerCase())}let s=vr.exec(n);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?gt(`/${s[1].toLowerCase()}`,Ie(l,t).toLowerCase()):null}let i=ai.exec(n);if(i)return gt(`/${i[1].toLowerCase()}`,Ie(i[2]??"",t).toLowerCase());let a=Ie(n,t).toLowerCase();if(a.startsWith("/")){let l=$r.normalize(a);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return a}function ui(e){return ht(e)??e}function mt(e){return!Qe()||typeof e!="string"||e===""?e:ui(e)}import{domainToASCII as Nd}from"url";var Fd="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as nc,readdirSync as tc,realpathSync as rc}from"fs";import{basename as sc,dirname as ic,join as lc}from"path";function Rn(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||Qe()?n.normalize("NFC").toLowerCase():n}var yt="anvil-claude-compiled/1";function en(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&pi(n,e.project_dir))}function pi(e,n){let t=mt(e),r=mt(n),o=r.endsWith("/")?r.slice(0,-1):r;return t===o||t.startsWith(o+"/")}function nn(e){return{dir:e,bin:pe(e,"bin"),compiled:pe(e,"compiled.json"),modes:pe(e,"modes.json"),decisions:pe(e,"decisions.jsonl"),install:pe(e,"install.json"),state:pe(e,"state"),approvals:pe(e,"approvals"),counts:pe(e,"counts"),backups:pe(e,"backups")}}var ki=3500;function U(e,n=8*1024*1024){try{let t=wi(e);return t.isFile()&&t.size<=n}catch(t){return t.code==="ENOENT"?null:!1}}function De(e,n=8*1024*1024){let t;try{t=Ar(e,xr.O_RDONLY|xr.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=Sr(t);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>n)throw new Error(`${e} is over ${n} bytes`);let o=Buffer.alloc(r.size),s=0;for(;s<r.size;){let i=Cr(t,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{_r(t)}}function se(e,n){let t=n.endsWith(`
2
+ `)?n:`${n}
3
+ `;if(Buffer.byteLength(t)>ki)throw new Error(`refusing to append a ${Buffer.byteLength(t)}-byte line`);if(U(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);gi(e,t,{mode:384})}function O(e){hi(e,{recursive:!0,mode:448})}function G(e,n){if(U(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let t;try{t=Ar(e,"r")}catch{return""}try{let r=Sr(t).size,o=Math.max(0,r-n),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);Cr(t,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{_r(t)}}function W(e,n,t=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;bi(r,n,{mode:t}),tn(r,e)}function tn(e,n){for(let t=0;;t++)try{yi(e,n);return}catch(r){let o=r.code;if(process.platform!=="win32"||t>=12||o!=="EPERM"&&o!=="EACCES"&&o!=="EBUSY")throw r;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20+t*10)}}function j(e){if(U(e)!==!0)return null;try{return JSON.parse(mi(e,"utf8"))}catch{return null}}var Hc=256*1024,Uc=1024*1024;import{readdirSync as vi}from"fs";import{join as wt}from"path";var $i=/^[A-Za-z0-9_-]{1,80}$/,bt=7*864e5,rn=e=>wt(e.dir,"models","unheard");function kt(e,n){return $i.test(n)?wt(rn(e),`${n}.json`):null}function vt(e,n,t=null){let r=[];try{let o=t!==null?[kt(e,t)].filter(s=>s!==null):vi(rn(e)).filter(s=>s.endsWith(".json")).slice(0,500).map(s=>wt(rn(e),s));for(let s of o){let i=j(s);!i||i.v!==1||typeof i.at!="number"||n-i.at>bt||i.at>n+6e4||r.push({at:i.at,version:typeof i.version=="string"&&/^\d{1,6}\.\d{1,6}\.\d{1,6}$/.test(i.version)?i.version:null,model:typeof i.model=="string"&&/^[\w.:/@\[\]-]{1,80}$/.test(i.model)?i.model:null})}}catch{}return r.sort((o,s)=>s.at-o.at)}var on=ne({"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 xt(e){let n=/claude-[a-z]+-\d+(?:-\d+)?/.exec(e.toLowerCase().replace(/@.*$/,"").replace(/\[1m\]$/,""));return n?n[0].replace(/-(\d{8})$/,""):e}function xi(e){return on[xt(e)]!==void 0}var Rr=e=>(e.match(/-(\d+)/g)??[]).map(n=>Number(n.slice(1))),Or=(e,n)=>{let t=Rr(e),r=Rr(n);for(let o=0;o<Math.max(t.length,r.length);o++)if((t[o]??-1)!==(r[o]??-1))return(r[o]??-1)-(t[o]??-1);return 0},$t=new Map;function _t(e){let n=$t.get(e);if(n!==void 0)return n;let t=_i(e);return $t.size<256&&$t.set(e,t),t}function _i(e){if(xi(e))return null;let n=/^claude-([a-z]+)-/.exec(xt(e))?.[1]??/^([a-z]+)(?:\[1m\])?$/.exec(e.toLowerCase())?.[1],t=Object.keys(on);return(n?t.filter(o=>o.startsWith(`claude-${n}-`)).sort(Or):[])[0]??t.sort((o,s)=>on[s].output-on[o].output||Or(o,s))[0]}function _e(e,n){return xe(e,n)??xe(_t(e)??"claude-opus-5-5",n)??0}function Er(e){let n=t=>{let r=/^claude-([a-z]+)-(\d+)(?:-(\d+))?$/.exec(t);return r?`${r[1][0].toUpperCase()}${r[1].slice(1)} ${r[2]}${r[3]?`.${r[3]}`:""}`:t};return e.map(t=>`${t.model}: estimated at ${n(t.at)}'s prices`).join("; ")}function xe(e,n){let t=on[xt(e)];if(!t)return null;let r=n.input+n.write5m+n.write1h+n.read,o=t.tier&&r>t.tier.above?{...t,...t.tier.over}:t,s=t.tier&&r>t.tier.above?o.input*.1:t.read??t.input*.1;return(n.input*o.input+n.output*o.output+n.write5m*o.input*1.25+n.write1h*o.input*2+n.read*s)/1e6*(n.fast?2:1)+(n.webSearches??0)*.01}var Ct=64*1024,Kr=8*1024*1024,Mr=8*1024*1024,Ei=32*1024*1024,Fe=40,un=/^[A-Za-z0-9._-]{1,128}$/,In=/^[\w.:@/[\]-]{1,100}$/,Pr=Buffer.from('"usage":{"input_tokens":'),St=Buffer.from('{"type":"cost-state"'),Nn=Buffer.from('{"type":"session-owner"'),jr=Buffer.from('"timestamp":"'),dn=36e5,I=e=>typeof e=="number"&&Number.isFinite(e)?e:null,F=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function Lr(e){let n=F(e),t=I(n?.used_percentage),r=I(n?.resets_at);return t===null||r===null?null:{pct:Math.max(0,Math.min(100,t)),resetsAt:r<1e11?r*1e3:r}}function Jr(e){if(!e||Buffer.byteLength(e)>Ct)return null;let n;try{n=F(JSON.parse(e))}catch{return null}if(!n)return null;let t=typeof n.session_id=="string"&&un.test(n.session_id)?n.session_id:null,r=F(n.model)?.id,o=typeof r=="string"&&In.test(r)?r:null,s=I(F(n.cost)?.total_cost_usd),i=F(n.rate_limits),a=typeof n.transcript_path=="string"&&zr(n.transcript_path)&&n.transcript_path.endsWith(".jsonl")?n.transcript_path:null;return{session:t,model:o,costUsd:s!==null&&s>=0?s:null,fiveHour:Lr(i?.five_hour),sevenDay:Lr(i?.seven_day),transcript:a}}function Y(e){let n=new Date(e);return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`}function le(e){let n=new Date(e);return n.setHours(0,0,0,0),n.getTime()}function cn(e){let n=new Date(le(e));return n.setDate(n.getDate()-(n.getDay()+6)%7),n.getTime()}var te=e=>S(e.dir,"meter"),ie=e=>Math.round(e*1e6)/1e6,re=e=>{try{return Si(e)}catch{return[]}},We=e=>{try{let n=Se(e);return n.isFile()?n.mtimeMs:0}catch{return 0}};function Ni(e){let n;try{n=Ln(e,we.O_RDONLY|we.O_NONBLOCK)}catch{return!1}try{let t=jn(n);if(!t.isFile()||t.size===0)return!1;let r=Buffer.alloc(1);return an(n,r,0,1,t.size-1)===1&&r[0]!==10}finally{Pn(n)}}function Nt(e,n){if(n.length===0)return;if(U(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);let t=Ni(e)?`
5
+ `:"";for(let r of n)t.length+r.length+1>6e4&&t&&(Nr(e,t,{mode:384}),t=""),t+=`${r}
6
+ `;t&&Nr(e,t,{mode:384})}var Mi=4;function Tr(e){let n=F(e);return!!n&&Number.isInteger(n.e)&&n.e>=0&&I(n.u)!==null&&I(n.b)!==null&&typeof n.day=="string"&&I(n.at)!==null}function Dn(e){let n=j(e);if(!n||I(n.at)===null)return null;let t=typeof n.m=="string"?n.m:null,r=n.p===0||n.p===1?{p:n.p}:{};if(n.v===2&&Array.isArray(n.totals))return{v:2,totals:n.totals.filter(Tr),m:t,at:n.at,...r};let o={e:n.e,u:n.u,b:n.b,day:n.day,at:n.at};return n.v===1&&Tr(o)?{v:2,totals:[o],m:t,at:n.at}:null}var Fn=e=>Tn("sha256").update(e).digest("hex").slice(0,16),qr=e=>e?Ri(e):"";function Ir(e){let n=e?Math.max(e.lastIndexOf("/projects/"),e.lastIndexOf("\\projects\\")):-1;return n>0?qr(e.slice(0,n)):""}var Gr=(e,n)=>`a${Fn(`${e}|${n}`)}`;function Vr(e){try{let n=F(JSON.parse(e.toString("utf8"))),t=n?.accountUuid;return n?.type==="session-owner"&&typeof t=="string"&&t.length>0?Gr(t,typeof n.organizationUuid=="string"?n.organizationUuid:""):null}catch{return null}}function Pi(e){let n;try{n=Ln(e,we.O_RDONLY|we.O_NONBLOCK)}catch{return null}try{if(!jn(n).isFile())return null;let t=Buffer.alloc(64*1024),r=t.subarray(0,an(n,t,0,t.length,0));for(let o=r.indexOf(Nn);o>=0;o=r.indexOf(Nn,o+1)){if(o>0&&r[o-1]!==10)continue;let s=r.indexOf(10,o);if(s<0)break;let i=Vr(r.subarray(o,s));if(i)return i}return null}finally{Pn(n)}}function Ue(e,n){let t=Fn(Ir(e));if(!e)return{key:`c${t}`,cfg:t};let r=n?j(fn(n,e))?.ow:void 0;return{key:(typeof r=="string"&&/^a[0-9a-f]{16}$/.test(r)?r:Pi(e)??(Ot(e)===0?Mt(Ir(e)):null))??`c${t}`,cfg:t}}function Mt(e){if(!e)return null;let n=[S(e,".claude.json"),...Et(e)===".claude"?[S(Ci(e),".claude.json")]:[]];for(let t of n){let r=De(t,16777216);if(r)try{let o=F(F(JSON.parse(r.toString("utf8")))?.oauthAccount),s=o?.accountUuid;if(typeof s=="string"&&s.length>0)return Gr(s,typeof o?.organizationUuid=="string"?o.organizationUuid:"")}catch{}}return null}var Wn=e=>({cfg:Fn(qr(e))});function Pt(e,n,t,r){let o=te(e);if(O(o),n.fiveHour||n.sevenDay){let p=r??Ue(n.transcript,e);O(S(o,"limits"));let h=S(o,"limits",`${p.key}.json`),k=j(h);typeof k?.at=="number"&&k.at>t||W(h,`${JSON.stringify({v:2,at:t,cfg:p.cfg,fiveHour:n.fiveHour,sevenDay:n.sevenDay})}
7
+ `)}if(!n.session||n.costUsd===null)return;O(S(o,"sessions"));let s=S(o,"sessions",`${n.session}.json`),i=Dn(s);if(i&&t<i.at)return;let a=Y(t),l=n.costUsd,u=i?.totals??[],d=-1;for(let p=0;p<u.length;p++)l>=u[p].u-.01&&(d<0||u[p].u>u[d].u)&&(d=p);let c=d>=0?u[d]:null,f=c?{e:c.e,u:Math.max(c.u,l),b:c.day===a?c.b:ji(e,n.session,c,l,t),day:a,at:t}:{e:u.reduce((p,h)=>Math.max(p,h.e+1),0),u:l,b:i?Ti(e,n.transcript,l):l,day:a,at:t},g=[f,...u.filter(p=>p.e!==f.e)].slice(0,Mi);Nt(S(o,`${a}.log`),[JSON.stringify({k:"c",t,s:n.session,e:f.e,u:ie(l),b:ie(f.b),...c?{}:{f:1}})]);let m=n.fiveHour||n.sevenDay?1:l>0?0:i?.p;W(s,`${JSON.stringify({v:2,totals:g.map(p=>({...p,u:ie(p.u),b:ie(p.b)})),m:n.model??i?.m??null,at:t,...m===void 0?{}:{p:m}})}
8
+ `)}function ji(e,n,t,r,o){let s=le(o),i=t.u;try{let a=new Set;for(let l of ln(Math.max(t.at,o-Fe*864e5),o))for(let u of He(e,l)){if(u.k!=="s"||u.s!==n||a.has(u.id)||u.t<=t.at||u.a>=s||u.u<t.u-.005||u.u>r+.01)continue;a.add(u.id);let d=u.t<s?1:u.w>0?Math.min(1,Li(e,n,u.a,s)/u.w):0;i=Math.max(i,u.p+(u.u-u.p)*d)}}catch{}return Math.min(i,r)}function Li(e,n,t,r){let o=0,s=new Set;for(let i of ln(Math.max(t,r-(Fe+1)*864e5),r))for(let a of He(e,i))a.k!=="u"||a.h===1||a.s!==n||a.t<=t||a.t>r||s.has(a.id)||(s.add(a.id),o+=Zr(a));return o}function Ti(e,n,t){if(!n)return 0;let r=j(fn(e,n))?.cs,o=0;for(let s of Array.isArray(r)?r.filter(Xr):[])for(let i of s.v)i<=t+.01&&(o=Math.max(o,i));return Math.min(o,t)}function jt(e,n){return!n||!un.test(n)?!1:Dn(S(te(e),"sessions",`${n}.json`))?.p===0}function Yr(e,n){if(!n||!un.test(n))return!1;let t=Dn(S(te(e),"sessions",`${n}.json`));return t?.p===1&&Date.now()-t.at<dn}function of(e,n){let t=S(te(e),"sessions"),r=!1,o=!1,s=!1;for(let i of re(t)){if(!i.endsWith(".json"))continue;try{if(Se(S(t,i)).mtimeMs<n)continue}catch{continue}let a=Dn(S(t,i));!a||!(a.at>=n)||(r=!0,a.p===1&&(o=!0),a.p===0&&(s=!0))}return{any:r,plan:o,off:s}}function Ii(e){if(!Array.isArray(e))return;let n=null,t=0,r={input:0,output:0,write5m:0,write1h:0,read:0};for(let o of e){let s=F(o);if(!s||s.type!=="advisor_message")continue;let i=typeof s.model=="string"?s.model:"",a=In.test(i)?i:"unknown";n=n===null||n===a?a:"unknown";let l=c=>Math.max(0,I(s[c])??0),u=l("cache_creation_input_tokens"),d=Math.min(u,Math.max(0,I(F(s.cache_creation)?.ephemeral_1h_input_tokens)??0));t+=1,r.input+=l("input_tokens"),r.output+=l("output_tokens"),r.read+=l("cache_read_input_tokens"),r.write1h+=d,r.write5m+=u-d}return n===null?void 0:{m:n,n:t,usage:r}}function Di(e){let n;try{n=F(JSON.parse(e.toString("utf8")))}catch{return null}if(!n||n.type!=="assistant")return null;let t=F(n.message),r=F(t?.usage),o=typeof t?.model=="string"?t.model:null;if(!r||!o||o==="<synthetic>")return null;let s=In.test(o)?o:"unknown",i=typeof n.timestamp=="string"?Date.parse(n.timestamp):NaN,a=typeof n.sessionId=="string"&&un.test(n.sessionId)?n.sessionId:null,l=typeof t?.id=="string"?t.id:"",u=typeof n.requestId=="string"?n.requestId:"";if(!Number.isFinite(i)||!a||!l&&!u)return null;let d=k=>Math.max(0,I(r[k])??0),c=F(r.cache_creation),f=c?Math.max(0,I(c.ephemeral_1h_input_tokens)??0):0,g=d("cache_creation_input_tokens"),m=I(F(r.server_tool_use)?.web_search_requests)??0,p=Tn("sha256").update(`${l}\0${u}`).digest("base64url").slice(0,22),h=Ii(r.iterations);return{t:i,s:a,id:p,m:s,usage:{input:d("input_tokens"),output:d("output_tokens"),write5m:Math.max(0,g-f),write1h:Math.min(f,g),read:d("cache_read_input_tokens"),...r.speed==="fast"?{fast:!0}:{},...m>0?{webSearches:m}:{}},...h?{adv:h}:{}}}function Fi(e){let n;try{n=F(JSON.parse(e.toString("utf8")))}catch{return null}if(!n||n.type!=="cost-state")return null;let t=typeof n.sessionId=="string"&&un.test(n.sessionId)?n.sessionId:null,r=I(n.totalCostUSD),o=I(n.startTime);return!t||r===null||r<0||r>1e9||o===null||o<=0?null:{s:t,u:r,st:o,unknown:n.hasUnknownModelCost===!0}}function Wi(e,n,t){if(n<=t)return NaN;let r=e.lastIndexOf(jr,n-1);if(r<t)return NaN;let o=r+jr.length,s=e.indexOf(34,o);return s>o&&s-o<=40?Date.parse(e.subarray(o,s).toString("latin1")):NaN}var Mn=e=>e.i+5*e.o+1.25*e.w5+2*e.w1+.1*e.r,Zr=e=>Mn(e)+(e.ad?Mn(e.ad):0),Hi=16,Xr=e=>{let n=F(e);return!!n&&I(n.st)!==null&&I(n.t)!==null&&Array.isArray(n.v)&&n.v.every(t=>I(t)!==null)},En=e=>e.includes("/subagents/")||e.includes("\\subagents\\"),Ui=e=>Et(e,".jsonl").replace(/^agent-/,"").replace(/[^A-Za-z0-9_-]/g,"").slice(0,40),fn=(e,n)=>S(te(e),"read",`${Tn("sha256").update(n).digest("hex").slice(0,32)}.json`);function Rt(e,n,t=Kr){let r=te(e),o=fn(e,n),s=En(n),i=s?Ui(n):"",a;try{a=Ln(n,we.O_RDONLY|we.O_NONBLOCK)}catch{return 0}try{let l=jn(a);if(!l.isFile())return 0;let u=j(o),d=!!u&&u.v===1&&u.ino===l.ino&&Number.isInteger(u.off)&&u.off>=0&&u.off<=l.size,c=d?u.off:0;if(c>=l.size)return 0;let f=c,g=d&&typeof u.ow=="string"?u.ow:void 0,m=[],p=[],h=Math.min(l.size-c,Math.max(1024*1024,t)),k=!1;for(;c<l.size&&c-f<t;){let x=Buffer.alloc(Math.min(h,l.size-c)),v=0;for(;v<x.length;){let P=an(a,x,v,x.length-v,c+v);if(P===0)break;v+=P}let E=v<x.length,C=x.subarray(0,v),N=C.lastIndexOf(10);if(N<0){if(E||c+v>=l.size)break;if(h>=Mr||k){k=!0,c+=v;continue}h=Math.min(Mr,h*4);continue}let M=0;k&&(M=C.indexOf(10)+1,k=!1);let R=C.subarray(0,N+1),D=R.indexOf(Pr,M),H=s?-1:R.indexOf(St,M);for(;D>=0||H>=0;){let P=H>=0&&(D<0||H<D),q=P?H:D,w=Math.max(M,R.lastIndexOf(10,q)+1);if(P&&w!==q){H=R.indexOf(St,q+1);continue}let b=R.indexOf(10,q),T=R.subarray(w,b<0?R.length:b);if(P){let A=Fi(T);A&&p.push({c:A,after:m.length,ts:Wi(R,w,M),last:c+(b<0?R.length:b+1)>=l.size})}else{let A=Di(T);A&&m.push(A)}if(b<0)break;D>=0&&D<=b&&(D=R.indexOf(Pr,b+1)),H>=0&&H<=b&&(H=R.indexOf(St,b+1))}if(!s)for(let P=R.lastIndexOf(Nn);P>=M;P=P>M?R.lastIndexOf(Nn,P-1):-1){if(P>M&&R[P-1]!==10)continue;let q=Vr(R.subarray(P,R.indexOf(10,P)));if(q){g=q;break}}if(c+=N+1,E)break;h=Math.min(l.size-c,Math.max(1024*1024,t-(c-f)))}if(m.length>0){O(r);let x=new Map,v=new Set;for(let E of m){if(v.has(E.id))continue;v.add(E.id);let C=Y(E.t),N=E.usage,M=E.adv;if(N.input+N.output+N.write5m+N.write1h+N.read===0&&!N.webSearches&&!M)continue;let R=JSON.stringify({k:"u",t:E.t,s:E.s,id:E.id,m:E.m,i:N.input,o:N.output,w5:N.write5m,w1:N.write1h,r:N.read,...N.fast?{f:1}:{},...N.webSearches?{ws:N.webSearches}:{},...s?{h:1,...i?{a:i}:{}}:{},...M?{ad:{m:M.m,n:M.n,i:M.usage.input,o:M.usage.output,w5:M.usage.write5m,w1:M.usage.write1h,r:M.usage.read}}:{}}),D=x.get(C);D?D.push(R):x.set(C,[R])}for(let[E,C]of x)Nt(S(r,`${E}.log`),C)}let y=d&&I(u.lt)!==null?u.lt:0,$=d&&Array.isArray(u.cs)?u.cs.filter(Xr):[],_=d&&I(u.ev)!==null?u.ev:-1/0;if(p.length>0){let x=Et(n,".jsonl"),v=[],E=0;for(let{c:C,after:N,ts:M,last:R}of p){for(;E<N;E++)y=Math.max(y,m[E].t);if(C.st>l.mtimeMs+6e4)continue;let D=Math.max(y,Number.isFinite(M)&&M>=C.st&&M<=l.mtimeMs+6e4?M:0,C.st);R&&l.mtimeMs>D&&(D=l.mtimeMs);let H=$.find(w=>w.st===C.st),P=H?H.v.filter(w=>w<=C.u+.005):[],q=H?P.length>0?Math.min(C.u,Math.max(...P)):null:C.st<=_?null:0;q!==null&&C.s===x&&!C.unknown&&v.push({t:D,s:x,u:C.u,p:q,a:H?H.t:C.st-1,st:C.st}),$=[{st:C.st,t:D,v:[...H?.v??[],C.u].slice(-4)},...$.filter(w=>w.st!==C.st)];for(let w of $.splice(Hi))_=Math.max(_,w.t);y=Math.max(y,D)}for(;E<m.length;E++)y=Math.max(y,m[E].t);v.length>0&&Bi(e,v)}else for(let x of m)y=Math.max(y,x.t);return O(S(r,"read")),W(o,`${JSON.stringify({v:1,ino:l.ino,off:c,...y>0?{lt:y}:{},...$.length>0?{cs:$}:{},...Number.isFinite(_)?{ev:_}:{},...g?{ow:g}:{}})}
9
+ `),c-f}finally{Pn(a)}}function Bi(e,n){let t=te(e);O(t);let r=n.map(()=>0),o=n.map(()=>0),s=n.map(()=>new Set),i=Math.max(Math.min(...n.map(l=>l.a)),Math.max(...n.map(l=>l.t))-(Fe+1)*864e5);for(let l of ln(i,Math.max(...n.map(u=>u.t))))for(let u of He(e,l))u.k==="u"&&n.forEach((d,c)=>{u.s!==d.s||u.t<=d.a||u.t>d.t||s[c].has(u.id)||(s[c].add(u.id),o[c]+=(xe(u.m,no(u))??0)+(u.ad?xe(u.ad.m,to(u.ad))??0:0),u.h!==1&&(r[c]+=Zr(u)))});let a=new Map;n.forEach((l,u)=>{let d=Tn("sha256").update(`${l.s}\0${l.st}\0${l.u}\0${l.p}`).digest("base64url").slice(0,22),c=JSON.stringify({k:"s",t:l.t,s:l.s,id:d,u:ie(l.u),p:ie(l.p),a:l.a,w:Math.round(r[u]),l:ie(o[u])});for(let f of ln(Math.max(l.a,l.t-Fe*864e5),l.t)){let g=a.get(f);g?g.push(c):a.set(f,[c])}});for(let[l,u]of a)Nt(S(t,`${l}.log`),u)}function Hn(e,n=-1/0){let t=S(e,"subagents"),r=re(t),o=r.filter(s=>s.endsWith(".jsonl")).map(s=>S(t,s));if(r.includes("workflows")){let s=S(t,"workflows");for(let i of re(s)){let a=S(s,i);if(!(n>-1/0&&zi(a)<n))for(let l of re(a))l.endsWith(".jsonl")&&o.push(S(a,l))}}return o}var zi=e=>{try{return Se(e).mtimeMs}catch{return 0}},Ki=24*36e5;function pn(e,n){if(!e.endsWith(".jsonl")||!/^[A-Za-z0-9_-]{1,64}$/.test(n))return null;let t=S(e.slice(0,-6),"subagents"),r=`agent-${n}.jsonl`;if(We(S(t,r))>0)return S(t,r);let o=S(t,"workflows");for(let s of re(o))if(We(S(o,s,r))>0)return S(o,s,r);return null}var Ji=15*6e4;function Lt(e,n,t,r=Kr){let o=r,s=Hn(n.slice(0,-6),t-Ki).map(i=>({file:i,at:We(i)})).filter(i=>t-i.at<=Ji).sort((i,a)=>a.at-i.at);for(let{file:i}of s){if(o<=r/2)break;o-=Rt(e,i,o-r/2)}Rt(e,n,o)}function Qr(e,n,t){let r=0,o=(s,i)=>{try{let a=Se(s);if(!a.isFile()||!i&&a.mtimeMs<t)return;let l=j(fn(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,d=a.size-u;if(d<=0||d<=1024*1024&&Un(s,u,a.size).indexOf(10)<0)return;r+=d}catch{}};o(n,!0);for(let s of Hn(n.slice(0,-6),t))o(s,!1);return r}function Z(e,n){let t=e.CLAUDE_CONFIG_DIR?.trim();return t&&zr(t)?t:S(n,".claude")}function eo(e,n,t,r=1024*1024*1024,o){let s=S(n,"projects"),i=[],a=g=>{let m;try{m=Se(g)}catch{return}if(!m.isFile()||m.mtimeMs<t)return;let p=j(fn(e,g)),h=p&&p.v===1&&p.ino===m.ino&&Number.isInteger(p.off)&&p.off<=m.size?p.off:0;m.size>h&&i.push({file:g,at:m.mtimeMs,left:m.size-h})};for(let g of re(s)){let m=S(s,g);for(let p of re(m)){if(p.endsWith(".jsonl")){a(S(m,p));continue}for(let h of Hn(S(m,p)))a(h)}}o?.(Math.min(r,i.reduce((g,m)=>g+m.left,0)));let l=g=>En(g)?g.slice(0,Math.max(g.indexOf("/subagents/"),g.indexOf("\\subagents\\"))):g.slice(0,-6),u=new Map;for(let g of i)u.set(l(g.file),Math.max(u.get(l(g.file))??0,g.at));i.sort((g,m)=>u.get(l(m.file))-u.get(l(g.file))||l(g.file).localeCompare(l(m.file))||Number(En(m.file))-Number(En(g.file))||m.at-g.at);let d=r,c=0,f=0;for(let g of i){let m=0,p=0;for(;d>0&&(p=Rt(e,g.file,Math.min(d,256*1024*1024)),d-=p,m+=p,p!==0););p===0&&d>0||m>=g.left||(c+=g.left-m,f=Math.max(f,g.at))}return{left:c,upto:f}}function sf(e,n,t,r=1024*1024*1024,o){return eo(e,n,t,r,o).left===0}var no=e=>({input:e.i,output:e.o,write5m:e.w5,write1h:e.w1,read:e.r,...e.f?{fast:!0}:{},...e.ws?{webSearches:e.ws}:{}}),to=e=>({input:e.i,output:e.o,write5m:e.w5,write1h:e.w1,read:e.r}),qi=e=>{let n=F(e);return!!n&&typeof n.m=="string"&&In.test(n.m)&&["n","i","o","w5","w1","r"].every(t=>(I(n[t])??-1)>=0)},sn=new Map;function Gi(e,n){for(let t of e.split(`
10
+ `))if(t)try{let r=JSON.parse(t);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"?n.push(r):r.k==="u"&&typeof r.id=="string"&&typeof r.m=="string"?(r.ad!==void 0&&!qi(r.ad)&&delete r.ad,n.push(r)):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&&n.push(r)}catch{}}function Un(e,n,t){let r=Ln(e,we.O_RDONLY|we.O_NONBLOCK);try{if(!jn(r).isFile())throw new Error(`${e} is not a regular file`);let o=Buffer.alloc(Math.max(0,t-n)),s=0;for(;s<o.length;){let i=an(r,o,s,o.length-s,n+s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Pn(r)}}function He(e,n,t){let r=S(te(e),`${n}.log`),o;try{if(o=Se(r),o.size>Ei)return t?.("large"),[]}catch(c){return c.code!=="ENOENT"&&t?.("unreadable"),[]}let s=sn.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=Un(r,i,o.size)}catch{return t?.("unreadable"),[]}let l=a.lastIndexOf(10)+1,u=[];Gi(a.subarray(0,l).toString("utf8"),u);let d=i>0?s.lines.concat(u):u;return sn.size>=64&&!sn.has(r)&&sn.clear(),sn.set(r,{ino:o.ino,size:o.size,mtime:o.mtimeMs,end:i+l,lines:d}),d}function ln(e,n){let t=[],r=new Date(le(e));for(;r.getTime()<=n;r.setDate(r.getDate()+1))t.push(Y(r.getTime()));return t}function Dr(e,n){let t=xe(e,n);if(t!==null)return{usd:t};let r=_t(e)??"claude-opus-5-5";return{usd:xe(r,n)??0,at:r}}function Fr(e,n,t,r){let o=e.priced.get(n);o?o.push(t):e.priced.set(n,[t]);let s=e.perModel.get(t.m)??{fresh:0,usd:0};e.perModel.set(t.m,{fresh:s.fresh+r,usd:t.usd===null||t.at||s.usd===null?null:s.usd+t.usd})}function Wr(e,n,t){let r=e.totals.get(n);r||e.totals.set(n,r=new Map);let o=r.get(t);return o||r.set(t,o={open:-1/0,credit:0,days:[]}),o}function Vi(e,n){let{from:t,to:r,only:o}=e,s=new Map;for(let i of n)if(!(o!==null&&i.s!==o))if(i.k==="u"){if(i.t<t||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,Fr(e,i.s,{t:i.t,...Dr(i.m,no(i)),m:i.m,h:i.h===1,w:Mn(i)},i.i+i.o+i.w5+i.w1);let a=i.ad;if(a){e.tokens.input+=a.i,e.tokens.output+=a.o,e.tokens.write+=a.w5+a.w1,e.tokens.read+=a.r;let l=Dr(a.m,to(a)),u=l.usd,d=a.i+a.o+a.w5+a.w1;Fr(e,i.s,{t:i.t,...l,m:a.m,h:i.h===1,w:Mn(a)},d),e.advice.calls+=a.n,e.advice.fresh+=d,e.advice.usd=u===null||e.advice.usd===null?null:e.advice.usd+u}}else if(i.k==="c"){if(i.t>r)continue;let a=Wr(e,i.s,i.e);i.f===1&&(a.open===-1/0||i.t<a.open)&&(a.open=i.t,a.credit=i.t>=t?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}`,d=s.get(u)??{s:i.s,e:i.e,max:-1/0,before:null,base:1/0,last:-1/0};i.t<t?d.before=Math.max(d.before??-1/0,i.u):d.max=Math.max(d.max,i.u),d.base=Math.min(d.base,i.b),d.last=Math.max(d.last,i.t),s.set(u,d)}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;Wr(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 Yi(e,n,t){let{from:r,to:o}=e,s=e.statusUsd.get(n)??0,i=!1,a=e.priced.get(n)??[],l=p=>{p.at&&e.standIns.set(p.m,p.at),p.usd===null?t.add(p.m):s+=p.usd};if(!e.totals.has(n)&&!e.segs.has(n)){for(let p of a)l(p);return{usd:s,estimated:a.length>0}}let u=[...e.totals.get(n)?.values()??[]],d=(e.marks.get(n)??[]).sort((p,h)=>p.t-h.t),c=[...e.segs.get(n)?.values()??[]].filter(p=>{if(p.t<r||p.a>=o)return!1;let h=0,k=d.length;for(;h<k;){let y=h+k>>1;d[y].t<=p.a?h=y+1:k=y}for(let y=h;y<d.length&&d[y].t<=p.t;y++)if(d[y].u>p.p+.005&&d[y].u<=p.u+.005)return!1;return!u.some(y=>y.days.some($=>$.last>p.t&&$.start<p.u-.005&&$.max>=p.u-.005))}),f=new Map;for(let p of c){let h=1,k=Math.max(p.a,r),y=Math.min(p.t,o);if(p.a<r||p.t>o){let _=0;for(let x of a)!x.h&&x.t>k&&x.t<=y&&(_+=x.w);h=p.w>0?Math.min(1,_/p.w):p.t>=r&&p.t<=o?1:0}let $=0;for(let _ of a)_.usd!==null&&!_.at&&_.t>k&&_.t<=y&&($+=_.usd);p.l!==void 0&&($=Math.max($,p.l)),!($>(p.u-p.p)*1.25+.05)&&f.set(p,h)}for(let[p,h]of f)h<=0||(s+=(p.u-p.p)*h,e.sessions.add(n));let g=[...f.keys()],m=a.map(p=>u.some(h=>h.open<p.t&&h.days.some(k=>k.last>=p.t))||g.some(h=>h.a<p.t&&p.t<=h.t));for(let p of u){if(p.credit<.005)continue;let h=p.credit*1.1+.005,k=a.map((y,$)=>$).filter(y=>!m[y]&&a[y].t<p.open&&a[y].usd!==null).sort((y,$)=>a[$].t-a[y].t);for(let y of k){if(a[y].usd>h)break;h-=a[y].usd,m[y]=!0}}return a.forEach((p,h)=>{m[h]||(i=!0,l(p))}),{usd:s,estimated:i}}function Bn(e,n,t,r=null){let o=Math.max(n,le(t-(Fe+1)*864e5)),s={paths:e,from:o,to:t,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,advice:{calls:0,fresh:0,usd:0},replies:0,standIns:new Map},i,a=k=>{i=i==="large"?"large":k};for(let k of ln(o,t))Vi(s,He(e,k,a));let l=0,u=!1,d=new Set;for(let k of new Set([...s.sessions,...s.segs.keys()])){let y=Yi(s,k,d);l+=y.usd,u||=y.estimated}let{tokens:c,replies:f,sessions:g,perModel:m,advice:p,standIns:h}=s;return{usd:ie(l),estimated:u,...h.size>0?{estimatedAt:[...h.entries()].map(([k,y])=>({model:k,at:y})).sort((k,y)=>k.model.localeCompare(y.model))}:{},unpriced:[...d].sort(),tokens:{...c,fresh:c.input+c.output+c.write},replies:f,sessions:g.size,models:[...m.entries()].map(([k,y])=>({model:k,fresh:y.fresh,usd:y.usd===null?null:ie(y.usd)})).sort((k,y)=>y.fresh-k.fresh),...p.calls>0?{advisor:{calls:p.calls,fresh:p.fresh,usd:p.usd===null?null:ie(p.usd)}}:{},...i?{problem:i}:{}}}var Zi=Fn("");function Be(e,n,t={}){let r=S(te(e),"limits"),o=t.key!==void 0?/^[ac][0-9a-f]{16}$/.test(t.key)?[`${t.key}.json`]:[]:re(r).filter(i=>i.endsWith(".json")),s=null;for(let i of o){let a=j(S(r,i));if(!a||a.v!==2||typeof a.at!="number"||a.at>n+6e4||t.cfg!==void 0&&a.cfg!==t.cfg&&a.cfg!==Zi)continue;let l=u=>{let d=F(u),c=I(d?.pct),f=I(d?.resetsAt);return c!==null&&f!==null?{pct:c,resetsAt:f}:null};(!s||a.at>s.at)&&(s={fiveHour:l(a.fiveHour),sevenDay:l(a.sevenDay),at:a.at})}return s}function Xi(e,n,t={}){let r=Be(e,n,t),o=a=>a&&a.resetsAt>n?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 zn(e){return typeof e.prompt=="string"&&/^\s*<task-notification>/.test(e.prompt.slice(0,64))}function ro(e){if(!e)return null;let n="";try{n=Un(e,0,512*1024).toString("utf8")}catch{return null}for(let t of n.split(`
11
+ `))if(!(!t.includes('"type":"assistant"')||!t.includes('"usage"')))try{let r=JSON.parse(t).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 At=3;function oo(e,n,t,r=0){let o=[],s=new Map,i={},a=null,l=new Map,u=[],d=w=>{let b=l.get(w.s);w.s!==n&&(!b||w.t<b.t)&&l.set(w.s,{t:w.t,c:f(w)}),w.s!==n&&u.push({t:w.t,s:w.s,c:f(w)})},c=new Set,f=(w,b=!0)=>({usd:_e(w.m,{input:w.i,output:w.o,write5m:b?w.w5:0,write1h:b?w.w1:0,read:w.r,...w.f?{fast:!0}:{},...w.ws?{webSearches:w.ws}:{}}),fresh:w.i+w.o+(b?w.w5+w.w1:0)}),g=w=>{let b=`${w.s}/${w.a}`,T=s.get(b)??[];T.push({t:w.t,c:f(w),own:w.s===n,warm:w.r>w.w5+w.w1}),s.set(b,T)},m=[];for(let w of[Y(t),Y(t-864e5)]){if(w!==Y(t)&&o.length>0)break;for(let b of He(e,w))b.k!=="u"||c.has(b.id)||(c.add(b.id),b.h===1&&b.a&&w===Y(t)&&g(b),b.h===1&&w===Y(t)&&b.t<=t&&(i[b.m]>=b.t||(i[b.m]=b.t),b.s===n&&(!a||b.t>a.t)&&(a={t:b.t,m:b.m})),b.h!==1&&w===Y(t)&&d(b),b.s===n&&(b.h===1?m.push({t:b.t,c:f(b),a:b.a}):o.push({t:b.t,c:f(b),m:b.m,u:b})))}for(let w=1;w<=r&&(s.size===0||l.size===0);w++){let b=s.size,T=l.size;for(let A of He(e,Y(t-w*864e5)))A.k==="u"&&(A.h===1&&A.a&&b===0&&g(A),A.h!==1&&T===0&&d(A))}let p=w=>w.sort((b,T)=>b.t-T.t).slice(-At).map(b=>b.c);o.sort((w,b)=>w.t-b.t);let h=o.slice(-At).reduce((w,b)=>!w||b.c.fresh>w.fresh?b.c:w,null),k=o.at(-1)?.t??null,y=o[0]?.u;o.length>0&&(o[0]={...o[0],c:f(o[0].u,!1)});let $=[],_=[],x=new Set;for(let[w,b]of s)b.sort((T,A)=>T.t-A.t),$.push(b[0]),_.push(...b.slice(1)),x.add(`${w}@${b[0].t}`);let v=w=>w.sort((b,T)=>b.t-T.t).slice(-At).reduce((b,T)=>!b||T.c.fresh>b.fresh?T.c:b,null),E=v($.filter(w=>w.own))??v($),C=w=>v($.filter(b=>b.own&&b.warm===w))??v($.filter(b=>b.warm===w)),N=C(!0),M=C(!1),R=m.filter(w=>!w.a||!x.has(`${n}/${w.a}@${w.t}`)),D=y?y.i+y.w5+y.w1+y.r:null,H=w=>{let b=o.find(T=>T.t>=w);return p(o.filter(T=>T!==b))},P=v([...l.values()]),q=p(u.filter(w=>w.t!==l.get(w.s)?.t));return{main:p(o),helpers:p(R),helperFirst:E,helperFirstWarm:N,helperFirstCold:M,helperRepliedAt:i,helperModel:a?.m??null,helpersToday:p(_),chatPrompt:D,chatFirst:P,chatToday:q,chatRecent:h,lastMainAt:k,mainSince:H,model:o.at(-1)?.m??null}}var Hr=9e4;function so(e,n){if(!e?.endsWith(".jsonl"))return[];let t=[];for(let r of Hn(e.slice(0,-6),n-Hr)){if(We(r)<n-Hr)continue;let o=0;try{let a=Un(r,0,Math.min(4096,Ot(r))).toString("utf8").split(`
12
+ `)[0]??"",l=F(JSON.parse(a))?.timestamp;o=typeof l=="string"&&Date.parse(l)||0}catch{o=0}let s=G(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=F(F(JSON.parse(s[a]))?.message)?.stop_reason==="end_turn"&&a===s.length-1?"done":"running"}catch{i="running"}break}i==="starting"&&Ot(r)>64*1024&&!(o>0&&n-o<6e4)&&(i="running"),t.push({state:i,started:o})}return t}var Ot=e=>{try{return Se(e).size}catch{return 0}};function gn(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 Tt=e=>`read ${e<6e4?"just now":`${gn(e)} ago`}`,io=e=>`${Math.max(1,Math.round(e/1048576))} MB`,Qi=(e,n=!1)=>e.unpriced.length>0||n?`~${Br(e.usd)}+`:`${e.estimated?"~":""}${Br(e.usd)}`;function el(e,n){let t=te(e),r=S(t,"pruned"),o=Y(n);try{if(De(r,64)?.toString("utf8").trim()===o)return}catch{}let s=n-Fe*864e5,i=Y(s);for(let a of re(t))/^\d{4}-\d{2}-\d{2}\.log$/.test(a)&&a.slice(0,10)<i&&On(S(t,a),{force:!0});On(S(t,"limits.json"),{force:!0});for(let a of["launches","live"])for(let l of re(S(t,a))){let u=S(t,a,l);We(u)<n-864e5&&On(u,{force:!0})}for(let a of["sessions","read","tasks","said","limits"])for(let l of re(S(t,a))){let u=S(t,a,l);We(u)<s&&On(u,{force:!0})}try{O(t),W(r,o)}catch{}}function Ur(e,n,t){let r=e&&t!==void 0&&t-e.at>=6e4?` (${gn(t-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||!n||n.usd<.005&&n.unpriced.length===0?null:{text:Qi(n),today:!0}}function Br(e){return e<10?`$${e.toFixed(2)}`:`$${String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`}function ze(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 It(){return(nl??={text:tl()}).text}var nl=null;function tl(){if(Oi(0))return null;let e=Buffer.alloc(Ct+1),n=0;for(let t=0;;){let r=0;try{r=an(0,e,n,e.length-n,null)}catch(o){if(o.code==="EAGAIN"&&t++<50){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,2);continue}return n>0?e.subarray(0,n).toString("utf8"):null}if(r===0)break;if(n+=r,n>Ct)return null}return n>0?e.subarray(0,n).toString("utf8"):null}function rl(e,n,t,r=null){let o=n?Jr(n):null,s=l=>{try{l()}catch{}};o?.transcript&&s(()=>Lt(e,o.transcript,t));let i=null;try{i=o?Ue(o.transcript,e):null}catch{}let a=i;o&&s(()=>Pt(e,o,t,a??void 0)),r&&s(()=>al(e,r,t)),s(()=>el(e,t));try{let l=o!==null&&!o.fiveHour&&!o.sevenDay&&(o.costUsd??0)>0,u=i?{key:i.key}:r?Wn(r):{},d=l?null:Xi(e,t,u),c=d&&t-d.at<=dn?d:null;return c?Ur(c,null,t):Ur(null,Bn(e,le(t),t))}catch{return null}}var ol=5*6e4,sl=3e4,il=32*1024*1024;function ll(e){let n="";try{n=De(e,4096)?.toString("utf8").trim()??""}catch{return null}if(/^\d+$/.test(n))return{at:Number(n),since:le(Number(n)),left:0,upto:0};try{let t=F(JSON.parse(n)),r=I(t?.at),o=I(t?.since);return r!==null&&o!==null?{at:r,since:o,left:Math.max(0,I(t?.left)??0),upto:I(t?.upto)??0}:null}catch{return null}}function Dt(e,n,t,r){let o=S(te(e),"caught"),s=ll(o);if(s&&s.at<=r&&s.since<=t&&r-s.at<(s.left>0?sl:ol))return s;let i=s&&s.at<=r&&r-s.at<864e5&&s.since<t&&s.since>=cn(r)?s.since:t;O(te(e)),W(o,JSON.stringify({v:1,at:r,since:i,left:s?.left??0,upto:s?.upto??0}));let a=eo(e,n,i,il),l={at:r,since:i,left:a.left,upto:a.upto};return W(o,JSON.stringify({v:1,...l})),l}function al(e,n,t){Dt(e,n,le(t),t)}function lf(e,n){let t=It(),r=t?Jr(t)?.session??null:null;return{spend:rl(e,t,n,Z(process.env,Ai())),unheard:r!==null&&vt(e,n,r).length>0}}import{createHash as aa}from"crypto";import{accessSync as ua,closeSync as da,constants as ca,openSync as fa,readdirSync as Jo,readFileSync as pa,rmSync as ga}from"fs";import{homedir as ha}from"os";import{basename as qo,dirname as ma,join as ee}from"path";function hn(e){let n=e.replace(/\/{2,}/g,"/");return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}import{createHash as Ao,randomBytes as Co}from"crypto";import{readdirSync as Ro,renameSync as Ol,unlinkSync as Dp}from"fs";import{join as bn}from"path";import{createHmac as wl,randomBytes as qt,timingSafeEqual as bl}from"crypto";import{closeSync as ho,existsSync as kl,fsyncSync as mo,linkSync as vl,mkdirSync as yo,openSync as wo,readdirSync as $l,readFileSync as Ge,unlinkSync as bo,writeSync as ko}from"fs";import{basename as xl,dirname as fo,join as he}from"path";var ge={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function ul(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 n=e==="truecolor",t=l=>u=>`\x1B[${l}m${u}\x1B[0m`,r=t(n?"38;2;76;139;255":"38;5;69"),o=t(n?"38;2;130;134;150":"90"),s=t(n?"38;2;245;165;36":"38;5;214"),i=t(n?"38;2;34;197;94":"32"),a={[ge.on]:r,[ge.blocked]:r,[ge.held]:r,[ge.next]:r,[ge.watching]:o,[ge.problem]:s,[ge.ok]:i};return{on:!0,bold:t("1"),dim:t("2"),blue:r,grey:o,amber:s,mark:l=>(a[l]??(u=>u))(l),field:l=>`\x1B[${n?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${cl(l)}\x1B[0m`}}var df=ul(!1),dl=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function cl(e){return e.replace(dl,"")}var lo=[{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)"}}],fl="home and project wipes and force-pushes to main",mf=`always blocking ${fl}`,yf=new Map(lo.map(e=>[e.id,e]));var pl=new Set(lo.flatMap(e=>Object.keys(e.slugs)));var Ft=ne({"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"}});var Wt="anvil-claude";function K(e){let n=e.trim();return n===Wt||n.endsWith(` ${Wt}`)||n.endsWith(`/${Wt}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var ao="\u{1F539}",L=e=>`${ao} ${e} ${ao}`;var mn=e=>`
14
+ ${ge.next} ${e}`;function be(e,n,t){return`${mn(`To ${e}, run this in a terminal (not in this chat):`)}
15
+ ${n}${t?mn(`Then ${t}.`):""}`}var Ht=e=>mn(e),gl=72;function Kn(e,n){let t=`To ${e}, run in a terminal: ${n}`;return t.length+5<=gl?mn(t):`${mn(`To ${e}, run in a terminal:`)}
16
+ ${n}`}var Ae=(e,n)=>`they run \`${K(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${n}`;var hl="anvil";var ke=e=>`${K(hl)} ${e}`;import{spawnSync as Gf}from"child_process";import{createHash as Yf}from"crypto";import{chmodSync as Xf,existsSync as Qf,lstatSync as ep,mkdirSync as np,readdirSync as tp,readFileSync as rp,readlinkSync as op,realpathSync as sp,rmdirSync as ip,statSync as lp,unlinkSync as ap,writeFileSync as up}from"fs";import{dirname as cp,isAbsolute as fp,join as pp,relative as gp,resolve as hp}from"path";var Ut="locks.json";var uo="Tip: model: smart \u2014 Sonnet works, Opus advises (Anthropic: ~12% cheaper per coding task)";var Bt={haiku:1,sonnet:2,opus:3,fable:4,mythos:4},ml=2;function Ce(e){let n=/(?:^|[^a-z])(opus|sonnet|haiku|fable|mythos)(?![a-z])/.exec((e??"").toLowerCase());if(!n)return null;let t=n[1];return{family:t,label:`${t[0].toUpperCase()}${t.slice(1)}`}}function zt(e,n){let t=Ce(n);if(!t)return null;if(Bt[t.family]<ml)return`${t.label} can't be an advisor`;let r=Ce(e);return r&&Bt[t.family]<Bt[r.family]?`the advisor (${t.label}) ranks below the model (${r.label})`:null}var yn=e=>e!==void 0&&["1","true","yes","on"].includes(e.trim().toLowerCase()),yl=[["CLAUDE_CODE_USE_BEDROCK","Amazon Bedrock"],["CLAUDE_CODE_USE_VERTEX","Google Vertex AI"],["CLAUDE_CODE_USE_FOUNDRY","Microsoft Foundry"]];function Jn(e){if(yn(e.CLAUDE_CODE_DISABLE_ADVISOR_TOOL))return{why:"CLAUDE_CODE_DISABLE_ADVISOR_TOOL is set",fix:"unset CLAUDE_CODE_DISABLE_ADVISOR_TOOL where Claude Code starts"};let n=yl.find(([t])=>yn(e[t]));if(n)return{why:`${n[1]} doesn't offer it`,fix:"Claude Code's advisor runs on Anthropic's API"};if(yn(e.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return{why:"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS is set",fix:"unset CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS where Claude Code starts"};if(!yn(e.CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL)){let t=o=>(e[o]??"")!=="",r=["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","DISABLE_TELEMETRY"].find(t)??["DO_NOT_TRACK","CLAUDE_CODE_DISABLE_FEATURE_FLAGS","DISABLE_GROWTHBOOK"].find(o=>yn(e[o]))??["CLAUDE_CODE_CUSTOM_OAUTH_URL"].find(t);if(r)return{why:`${r} is set, which keeps it off`,fix:`unset ${r} where Claude Code starts, or set CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL=1`}}return null}var Kt="Claude Code didn't attach the advisor for this account (its rollout, your plan's credits, or a telemetry setting)";function co(e){let n=Ce(e.model)?.label??null,t=e.modelFrom?{mainFrom:e.modelFrom}:{},r=Ce(e.advisorModel)?.label??null;if(e.session?.attached)return{on:!0,model:Ce(e.session.attached)?.label??e.session.attached,why:null,fix:null,lasting:!1,main:n,...t,seen:"session"};let o=e.session?"session":"settings",s=Jn(e.env);if(s)return{on:!1,model:r,why:s.why,fix:s.fix,lasting:!0,main:n,...t,seen:o};if(!e.advisorModel)return{on:!1,model:null,why:"no advisor is set",fix:"model: smart sets one: Opus",lasting:!0,main:n,...t,seen:o};let i=zt(e.session?.model??e.model,e.advisorModel);return i?{on:!1,model:r,why:i,fix:"switch to a model at or below it, or set a stronger advisor",lasting:!0,main:n,...t,seen:o}:e.session&&e.since!=null&&e.session.started!=null&&e.session.started>e.since||e.seen==="off"?{on:!1,model:r,why:Kt,fix:null,lasting:!0,main:n,...t,seen:o}:e.session?{on:!1,model:r,why:"this session started before it was set: it comes with your next session",fix:null,lasting:!1,main:n,...t,seen:o}:{on:!0,model:r,why:null,fix:null,lasting:!1,main:n,...t,seen:o,...e.seen==="on"?{}:{unseen:!0}}}function Jt(e){return e.on?`advisor: ${e.model??"on"} \xB7 ${e.unseen?"set: seen at your next session":"on"}`:`advisor: off \xB7 ${e.why??"not attached"}`}function Ke(e){return(e?.policies??[]).some(n=>(n.model_rules?.smart?.length??0)>0)}var me="_seal";function Yn(e){return he(e.dir,"seal.key")}function qe(e,n){return he(e.state,"lkg",n)}function J(e){let n=Yn(e);if(U(n,1024)!==!0)return null;try{let t=Ge(n,"utf8").trim();return/^[0-9a-f]{64}$/.test(t)?Buffer.from(t,"hex"):null}catch{return null}}function Yt(e){return J(e)?"ok":U(Yn(e),1024)===null?"missing":"damaged"}var Vn=class extends Error{};function Zn(e,n){return`Anvil's seal key (${Yn(e)}) is ${n==="damaged"?"damaged":"missing"}`}function _l(e){let n=J(e);if(n)return n;let t=Yt(e);if(t==="damaged"||Zt(e))throw new Vn(`${Zn(e,t)}; run ${ke("on")} to restore it`);let{key:r,created:o}=Sl(e,!1);return o&&Al(e,r),r}function po(e,n,t){let r=wo(e,t,384);try{ko(r,n),mo(r)}finally{ho(r)}}function Sl(e,n){yo(e.dir,{recursive:!0,mode:448});let t=Yn(e),r=he(e.dir,`.seal.key.${process.pid}.${qt(4).toString("hex")}.tmp`);po(r,`${qt(32).toString("hex")}
17
+ `,"wx");let o=!1;try{n?tn(r,t):vl(r,t),o=!0}catch(i){let a=i.code??"";if(a!=="EEXIST"){if(n||!["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS","EXDEV"].includes(a))throw i;try{po(t,Ge(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{bo(r)}catch{}}let s=J(e);if(!s)throw new Vn(`${Zn(e,"damaged")}; run ${ke("on")} to restore it`);return{key:s,created:o}}function Al(e,n){let t=[[e.modes,Gn],[e.compiled,$o],[e.install,void 0]];for(let[r,o]of t)if(U(r,8*1024*1024)===!0)try{let s=Ge(r,"utf8");if(s.includes(`"${me}"`))continue;let i=JSON.parse(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=`${JSON.stringify(Vt(n,i),null,2)}
18
+ `;Je(r,a),o&&Je(qe(e,o),a)}catch{}if(U(e.modes)===null&&U(qe(e,Gn))===null){let r=`${JSON.stringify(Vt(n,pt()),null,2)}
19
+ `;Je(e.modes,r),Je(qe(e,Gn),r)}}function Gt(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>Gt(t===void 0?null:t,n+1)).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).filter(r=>!(n===0&&r===me)&&e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${Gt(e[r],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function vo(e,n){return wl("sha256",e).update(Gt(n)).digest("hex")}function qn(e){if(!(me in e))return e;let n={...e};return delete n[me],n}function Vt(e,n){let t=qn(n);return{...t,[me]:vo(e,t)}}function Cl(e,n){let t=n[me];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let r;try{r=vo(e,n)}catch{return!1}return bl(Buffer.from(t,"hex"),Buffer.from(r,"hex"))}function Je(e,n,t=384){yo(fo(e),{recursive:!0,mode:448});let r=he(fo(e),`.${xl(e)}.${process.pid}.${Date.now().toString(36)}.${qt(3).toString("hex")}.tmp`);try{let o=wo(r,"w",t);try{ko(o,n),mo(o)}finally{ho(o)}tn(r,e)}catch(o){try{bo(r)}catch{}throw o}}function X(e,n,t=8*1024*1024){let r=U(e,t);if(r===null)return{status:"missing"};if(r===!1)return{status:"unreadable"};let o;try{o=JSON.parse(Ge(e,"utf8"))}catch{return{status:"unreadable"}}return!o||typeof o!="object"||Array.isArray(o)?{status:"unreadable"}:n?me in o?Cl(n,o)?{status:"ok",value:qn(o)}:{status:"changed",value:qn(o)}:{status:"unsealed",value:o}:{status:"unkeyed",value:qn(o)}}function Xn(e,n,t,r){let o=_l(e),s=`${JSON.stringify(Vt(o,t),null,2)}
20
+ `;Je(n,s),r&&Je(qe(e,r),s)}var Gn="modes.json",$o="compiled.json";function Zt(e){return kl(he(e.bin,"claude-hook.sh"))||Rl(e)}function Rl(e){let n=t=>{try{return $l(t).slice(0,200).some(r=>r.endsWith(".json")&&U(he(t,r),65536)===!0&&Ge(he(t,r),"utf8").includes(`"${me}"`))}catch{return!1}};if(n(he(e.state,"lkg"))||n(he(e.state,"pending"))||n(e.approvals))return!0;for(let t of[e.modes,e.compiled,e.install])if(U(t,8*1024*1024)===!0)try{if(Ge(t,"utf8").includes(`"${me}"`))return!0}catch{}return!1}var xo=ne({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function go(e=new Date){return kr(null,"enforce","all",e)}function wn(e,n=J(e),t={}){if(!n){let i=Yt(e);if(t.installed===!0||i==="damaged"||Zt(e))return{value:go(),source:"strict",problem:`${Zn(e,i)}, so every rule is enforced until \`${ke("on")}\` restores it`};let a=X(e.modes,null);return{value:a.status==="unkeyed"?a.value:null,source:"unkeyed",problem:null}}let r=X(e.modes,n);if(r.status==="ok")return{value:r.value,source:"file",problem:null};let o=`modes.json ${xo[r.status]??"cannot be used"}`,s=X(qe(e,Gn),n);return s.status==="ok"?{value:s.value,source:"last-good",problem:`${o}; Anvil keeps the modes it last set`}:{value:go(),source:"strict",problem:`${o}, and so is Anvil's own copy, so every rule is enforced until \`${ke("on")}\` resets it`}}function Re(e,n,t=J(e),r={}){let o=u=>!!u&&typeof u=="object"&&u.format===yt&&Array.isArray(u.policies),s=()=>{if(!n)return null;let u=X(n,null);return u.status==="unkeyed"&&o(u.value)?u.value:null};if(!t){let u=Yt(e),d=r.installed===!0||u==="damaged"||Zt(e),c=X(e.compiled,null),f=c.status==="unkeyed"&&o(c.value)?c.value:null;return d?{value:null,source:"strict",problem:`${Zn(e,u)}: \`${ke("on")}\` restores it`}:{value:f??s(),source:"unkeyed",problem:null}}let i=X(e.compiled,t);if(i.status==="ok"&&o(i.value))return{value:i.value,source:"file",problem:null};let a=`compiled.json ${i.status==="ok"?"is not a rules table":xo[i.status]??"cannot be used"}`,l=X(qe(e,$o),t);return l.status==="ok"&&o(l.value)?{value:l.value,source:"last-good",problem:`${a}; Anvil keeps the rules it last compiled`}:i.status==="missing"&&l.status==="missing"&&U(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: \`${ke("on")}\` recompiles them`}}var Up=600*1e3,El=1440*60*1e3,_o="23456789abcdefghjkmnpqrstuvwxyz",So=8;function Oe(e){return bn(e.state,"pending")}function Nl(){let e=Co(So),n="";for(let t=0;t<So;t++)n+=_o[e[t]%_o.length];return n}function Ml(e){return Ao("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var Pl=()=>Co(8).toString("hex"),jl=e=>`${Ao("sha256").update(e??"").digest("hex").slice(0,12)}.`;function Oo(e,n,t){let r=Nl(),o=Pl();O(Oe(e));let s={v:2,id:o,code_sha256:Ml(r),...n,created_at:new Date(t).toISOString(),expires_at:new Date(t+El).toISOString()};return Xn(e,bn(Oe(e),`${jl(n.session)}${o}.json`),s),{code:r,id:o}}function Ll(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function Eo(e,n,t){let r=[];try{r=Ro(Oe(e)).filter(s=>s.endsWith(".json")).slice(0,2e3)}catch{return[]}let o=[];for(let s of r){let i=bn(Oe(e),s),a=X(i,n,64*1024);a.status!=="ok"||a.value.v!==2||!Array.isArray(a.value.stops)||!(Date.parse(a.value.expires_at)>=t)||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 No(e,n,t,r,o,s){let i=[];try{i=Ro(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=bn(e.approvals,l),d=X(u,n,64*1024);if(d.status==="missing")continue;if(d.status!=="ok"||d.value.v!==2||!Array.isArray(d.value.stops)){a++;continue}let c=d.value;if(Date.parse(c.expires_at)>=s&&!((c.session??null)!==(t??null)||(c.project??null)!==(r??null))&&o.every(f=>c.stops.some(g=>Ll(g,f))))try{return Ol(u,bn(e.approvals,`${l.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:a}}catch{}}return{approved:!1,forged:a}}import{spawn as Tl,spawnSync as Mo}from"child_process";import{closeSync as Il,openSync as Dl,readdirSync as Fl,readlinkSync as Wl,statSync as Po,unlinkSync as jo,writeSync as Hl}from"fs";import{delimiter as Ul,isAbsolute as Bl,join as Ee}from"path";var zl=5*6e4,Xt=2*6e4,Lo=3,Kl=15*6e4,Jl=6*36e5,To=3e4,ql=6e4,Gl=["-p","/usage","--output-format","stream-json","--verbose","--no-session-persistence","--setting-sources","project","--settings",'{"autoMemoryEnabled":false}',"--strict-mcp-config","--model","anvil-reads-usage-only"],Io="ANVIL_PLAN_PROBE",Do=(e,n)=>Ee(e.state,`plan-probe-${n}.json`),Qt=(e,n)=>Ee(e.state,`plan-probe-next-${n}`),Fo=e=>Ee(e.state,"plan-probe.lock"),Vl=e=>Ee(e.dir,"plan-probe");function Wo(e,n){let t=n?[Do(e,n)]:Yl(e),r=null;for(let o of t){let s=j(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 Yl(e){try{return Fl(e.state).filter(n=>/^plan-probe-[ac][0-9a-f]{16}\.json$/.test(n)).map(n=>Ee(e.state,n))}catch{return[]}}function Zl(e){let n=null,t,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"&&(n=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(t===void 0&&u&&typeof u=="object"){let d=u.rate_limits;t=d&&Array.isArray(d.limits)?d.limits:null}}if(t===void 0)return null;if(!t||t.length===0)return r?null:"noplan";let o=a=>{let l=t.find(c=>!!c&&typeof c=="object"&&c.kind===a),u=typeof l?.percent=="number"&&Number.isFinite(l.percent)?l.percent:null,d=typeof l?.resets_at=="string"?Date.parse(l.resets_at):Number.NaN;return u!==null&&Number.isFinite(d)?{pct:Math.max(0,Math.min(100,u)),resetsAt:d}:null},s=o("session"),i=o("weekly_all");return s||i?{fiveHour:s,sevenDay:i,version:n}:null}function Xl(e,n=Ql,t=!1){let r=a=>{try{return a&&Bl(a)&&Po(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(n(i)));if(a)return a}if(!t)return null;for(let a of(e.PATH??"").split(Ul)){let l=a?r(Ee(a,"claude"))??(process.platform==="win32"?r(Ee(a,"claude.exe")):null):null;if(l)return l}return null}function Ql(e){try{return Wl(`/proc/${e}/exe`)}catch{}try{let n=Mo("ps",["-o","comm=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{PATH:"/bin:/usr/bin",LC_ALL:"C"}});return n.status===0&&n.stdout.trim()||null}catch{return null}}function ea(e){let n=["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"],t={};for(let r of n)e[r]!==void 0&&e[r]!==""&&(t[r]=e[r]);return t[Io]="1",t.DISABLE_AUTOUPDATER="1",t}var na=(e,n,t)=>{let r=Mo(e,n,{cwd:t.cwd,env:t.env,timeout:t.timeout,encoding:"utf8",input:"",maxBuffer:4194304,killSignal:"SIGKILL",windowsHide:!0});return{status:r.status,stdout:r.stdout??"",...r.error?{error:r.error}:{}}};function ta(e,n){let t=Fo(e);for(let r=0;r<2;r++)try{let o=Dl(t,"wx",384);return Hl(o,String(n)),Il(o),!0}catch(o){if(o.code!=="EEXIST")return!1;let s=Number(G(t,64).trim());if(Number.isFinite(s)&&n-s<ql&&s<=n+6e4)return!1;try{jo(t)}catch{return!1}}return!1}function ra(e){try{jo(Fo(e))}catch{}}function oa(e){try{if(O(e.paths.state),!ta(e.paths,e.now()))return null;try{let n=Be(e.paths,e.now(),{key:e.account.key});if(!e.screen&&n&&e.now()-n.at<Xt)return null;let t=sa(e);if(e.screen&&!t.ok)return t;W(Do(e.paths,e.account.key),`${JSON.stringify(t)}
22
+ `);let r=t.ok?Xt:t.why==="noplan"||t.why==="unavailable"||t.why==="nobinary"?Jl:Kl;return W(Qt(e.paths,e.account.key),String(e.now()+r)),t}finally{ra(e.paths)}}catch{return null}}function sa(e){let n=e.binary??Xl(e.env,e.exeOf);if(!n)return{at:e.now(),ok:!1,why:"nobinary"};let t=Vl(e.paths);O(t);let r=(e.run??na)(n,Gl,{cwd:t,env:ea(e.env),timeout:To}),o=e.now();if(r.error||r.status===null)return{at:o,ok:!1,why:"failed"};let s=Zl(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=Mt(Z(e.env,e.env.HOME??e.env.USERPROFILE??""));if(l&&l!==e.account.key)return{at:o,ok:!1,why:"otheraccount",...a}}return Pt(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 Ho="ANVIL_PLAN_PROBE_FOR";function Uo(e){try{if(e.env[Io]==="1"||!e.env.CLAUDE_CODE_EXECPATH&&!e.env.CLAUDE_PID)return!1;let n=e.near?Xt:zl;if(e.readingAt!==null&&e.now-e.readingAt<n&&e.readingAt<=e.now+6e4)return!1;let t=Number(G(Qt(e.paths,e.account.key),64).trim());if(Number.isFinite(t)&&t>e.now&&t-e.now<=24*36e5)return!1;try{Po(e.hookFile)}catch{return!1}return O(e.paths.state),W(Qt(e.paths,e.account.key),String(e.now+To+5e3)),(e.start??ia)(e.node,[e.hookFile,"--plan-probe"],e.paths.dir,{...e.env,[Ho]:`${e.account.key}|${e.account.cfg}`}),!0}catch{return!1}}function ia(e,n,t,r){let o=Tl(e,n,{detached:!0,stdio:"ignore",cwd:t,env:r,windowsHide:!0});o.on("error",()=>{}),o.unref()}function la(e){let n=/^([ac][0-9a-f]{16})\|([0-9a-f]{16})$/.exec(e[Ho]??"");return n?{key:n[1],cfg:n[2]}:null}function Go(e){let n=r=>typeof r=="string"&&r.length>0?r:null,t=n(e.env.CLAUDE_PROJECT_DIR)??n(e.payload.cwd);return{...e,session:n(e.payload.session_id),transcript:n(e.payload.transcript_path),project:t&&t.startsWith("/")?hn(t):t}}var nr=36e5,ya=/^[A-Za-z0-9._-]{1,128}$/,wa=.8;function sr(e){return(e?.policies??[]).flatMap(n=>n.budgets??[])}var $e=e=>ee(e.dir,"meter"),Vo=(e,n)=>ee($e(e),"tasks",`${n}.json`),ir=e=>e!==null&&ya.test(e)&&e!=="."&&e!=="..";function lr(e,n){if(!ir(n))return null;let t=X(Vo(e,n),J(e),4096);if(t.status!=="ok"&&t.status!=="unkeyed")return null;let r=t.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 Yo(e,n,t){ir(n)&&(O(ee($e(e),"tasks")),Xn(e,Vo(e,n),t))}var Zo=(e,n,t)=>e.window==="day"?le(n):e.window==="week"?cn(n):e.window==="task"?t?.t??Number.NaN:Number.NaN;function Xo(e,n){try{if(e.unit==="plan"){if(n.apiKey||jt(n.paths,n.session))return{budget:e,used:null,why:"offplan"};let o=n.reading(),s=e.window==="seven_day"?o?.sevenDay:o?.fiveHour;if(o&&!s&&n.now-o.at<=dn&&(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,n.now-o.at);return s.resetsAt>n.now&&s.pct>=e.limit?{budget:e,used:s.pct,resetsAt:s.resetsAt,age:i}:s.resetsAt<=n.now||i>dn?{budget:e,used:null,why:"stale",age:i,...s.resetsAt<=n.now?{reset:!0}:{}}:{budget:e,used:s.pct,resetsAt:s.resetsAt,age:i}}if(e.window==="task"&&(!n.task||!ir(n.session)))return{budget:e,used:null,why:"task"};let t=Zo(e,n.now,n.task),r=e.window==="task"?n.own():n.unread.left>0&&n.unread.upto>=t?n.unread.left:0;return Pa(e,n.totals(t,e.window==="task"?n.session:null),r)}catch{return{budget:e,used:null,why:"meter"}}}var ba=.5,kn=e=>{if(e.length===0)return null;let n=t=>{let r=e.map(o=>o[t]).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:n("usd"),fresh:n("fresh")}},er=1e4,ka=.5,va=3e5,Bo=2.25;function $a(e,n){let t=ee($e(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=j(t),i={warm:o(s?.warm),cold:o(s?.cold)},a={warm:n.warm??i.warm,cold:n.cold??i.cold};if((n.warm||n.cold)&&JSON.stringify(a)!==JSON.stringify(i))try{O($e(e)),W(t,`${JSON.stringify({v:1,...a})}
23
+ `)}catch{}return a}var xa=9e4,_a=1e4,vn=e=>e.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,128),$n=e=>ee($e(e),"live"),ve=(e,n,t=1)=>({usd:e.usd+t*n.usd,fresh:e.fresh+t*n.fresh}),Ne={usd:0,fresh:0};function Sa(e,n,t){try{O($n(e)),W(ee($n(e),`${vn(n)}.json`),`${JSON.stringify(t)}
24
+ `)}catch{}}function Aa(e,n,t){let r=new Map,o=`${vn(n)}.json`,s=[];try{s=Jo($n(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=j(ee($n(e),l));!u||u.v!==1||!i(u.t)||u.t<t-864e5||u.t>t+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 Ca(e){if(!e.session)return null;let n=e.payload,t=n.tool_name==="Agent"||n.tool_name==="Task",r=oo(e.paths,e.session,e.now,t?7:0),o=lr(e.paths,e.session)?.t??null,s=kn(o!==null?r.mainSince(o):r.main)??kn(r.main),i=t&&typeof n.tool_use_id=="string"?n.tool_use_id.slice(0,128):null,a=r.main.length<=1?kn(r.chatToday):null,l=s?a&&a.fresh>s.fresh?a:s:Ne,u=kn(r.helpers)??kn(r.helpersToday),d=u??l,c=r.model??"claude-opus-5-5",f=t?ro(e.transcript??null)??r.chatPrompt:r.chatPrompt,g=Math.max(er,Math.round((f??0)*ka)),m={usd:_e(c,{input:0,output:0,write5m:g,write1h:0,read:0}),fresh:g},p=r.helperModel??r.model,h=p!==null&&e.now-(r.helperRepliedAt[p]??-1/0)<va,k=t?$a(e.paths,{warm:r.helperFirstWarm,cold:r.helperFirstCold}):{warm:r.helperFirstWarm,cold:r.helperFirstCold},y=k.warm?{usd:Bo*k.warm.usd,fresh:Math.round(Bo*k.warm.fresh)}:null,$=h?k.warm??k.cold:k.cold??y,_=V=>$?.[V]??m[V],x={usd:_("usd")+d.usd+l.usd,fresh:_("fresh")+d.fresh+l.fresh},v=u?ve(ve(Ne,u,2),l):x,E=s!==null&&o!==null&&r.lastMainAt!==null&&r.lastMainAt<o,C=s?E&&r.chatRecent?r.chatRecent:Ne:r.chatFirst??{usd:_e(c,{input:0,output:0,write5m:er,write1h:0,read:0}),fresh:er},N=ve(C,l,2),M={v:1,t:e.now,transcript:e.transcript??null,chat:N,perRunning:v,each:x},R=j(ee($n(e.paths),`${vn(e.session)}.json`)),D=V=>!!V&&JSON.stringify({...V,t:0})===JSON.stringify({...M,t:0});R&&typeof R.t=="number"&&e.now-R.t>=0&&e.now-R.t<_a&&D(R)||Sa(e.paths,e.session,M),i&&es(e.paths,e.session,i,e.now);let H=vn(e.session),P=Oa(e.paths,e.now),q=i?P.findIndex(V=>V.s===H&&V.id===i.replace(/\s/g,"_")):-1,w=q>=0?P.slice(0,q):P,b=(V,Le,Te)=>{let ct=so(Le,e.now),ft=w.filter(fe=>fe.s===V),ni=ft.length>0?Math.min(...ft.map(fe=>fe.t))-2e3:1/0,ti=Math.max(0,ft.length-ct.filter(fe=>fe.started>=ni).length),ri=ct.filter(fe=>fe.state==="running").length,oi=ct.filter(fe=>fe.state==="starting").length;return ve(ve(Ne,Te.perRunning,ri),Te.each,oi+ti)},T=ve(N,b(H,e.transcript??null,{perRunning:v,each:x})),A=Aa(e.paths,e.session,e.now);for(let V of w)V.s!==H&&!A.has(V.s)&&A.set(V.s,{v:1,t:0,transcript:null,chat:Ne,perRunning:v,each:x});let Q=Ne,ce=0;for(let[V,Le]of A){let Te=ve(Le.t>=e.now-xa?Le.chat:Ne,b(V,Le.transcript,Le));(Te.fresh>0||Te.usd>0)&&(Q=ve(Q,Te),ce++)}return{running:T,others:Q,otherSessions:ce,launches:t?x:null,guess:t&&!$,parts:{underWay:C.fresh,chat:l.fresh,first:_("fresh"),helper:d.fresh,warm:h,pending:T.fresh-N.fresh}}}var Ra=2e4,Qo=e=>ee($e(e),"launches","all.log");function Oa(e,n){let t=[],r=new Set;for(let o of G(Qo(e),64*1024).split(`
25
+ `)){let[s,i,a,l]=o.split(" "),u=Number(s);if(!i||!a||!(u>n-Ra&&u<=n+6e4))continue;let d=`${i} ${a}`;l==="x"?r.add(d):t.some(c=>c.s===i&&c.id===a)||t.push({s:i,id:a,t:u})}return t.filter(o=>!r.has(`${o.s} ${o.id}`))}function es(e,n,t,r,o=!1){try{let s=Qo(e);O(ma(s)),se(s,`${r} ${vn(n)} ${t.replace(/\s/g,"_")}${o?" x":""}`)}catch{}}function Ea(e){let n=e.payload;e.session&&(n.tool_name==="Agent"||n.tool_name==="Task")&&typeof n.tool_use_id=="string"&&es(e.paths,e.session,n.tool_use_id.slice(0,128),e.now,!0)}function Na(e,n,t){if(!n.some(s=>s.used!==null&&s.budget.unit!=="plan"&&s.used<s.budget.limit))return n;let r,o=t==="message";try{return n.map(s=>{if(s.used===null||s.budget.unit==="plan"||s.used>=s.budget.limit||(r??=Ca(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),ba*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}:{}}}:e.advisor&&l+e.advisor[i]>=s.budget.limit?{...s,early:{why:"advisor",...u,advisor:e.advisor}}:s})}catch(s){return Qn={err:s instanceof Error?s.message.slice(0,200):String(s).slice(0,200)},n}finally{r!==void 0&&Qn?.err===void 0&&(Qn=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 Qn;function Ma(e,n,t){let r=e.env.ANVIL_BUDGET_TRACE?.trim();if(r)try{let o=e.payload;se(r,JSON.stringify({t:e.now,at:n,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:t.map(s=>({b:s.budget.id,used:s.used,why:s.why??null,early:s.early?.why??null,left:s.left??null})),r:Qn??null}))}catch{}}function ns(e,n,t,r){let o={left:0,upto:0};try{e.transcript&&Lt(e.paths,e.transcript,e.now);let u=Math.min(...n.map(d=>Zo(d,e.now,t)).filter(d=>Number.isFinite(d)));Number.isFinite(u)&&(o=Dt(e.paths,Z(e.env,e.home),u,e.now))}catch{}let s=new Map,i,a={paths:e.paths,now:e.now,task:t,session:e.session,reading:()=>i===void 0?i=Be(e.paths,e.now,{key:Ue(e.transcript,e.paths).key}):i,totals:(u,d)=>{let c=`${u}|${d??""}`,f=s.get(c);return f||s.set(c,f=Bn(e.paths,u,e.now,d)),f},unread:o,own:()=>e.transcript&&t?Qr(e.paths,e.transcript,t.t):0,apiKey:!!(e.env.ANTHROPIC_API_KEY?.trim()||e.env.CLAUDE_CODE_USE_BEDROCK?.trim()||e.env.CLAUDE_CODE_USE_VERTEX?.trim())},l=Na(e,n.map(u=>Xo(u,a)),r);Ma(e,r,l);try{if(e.probe&&!a.apiKey&&n.some(u=>u.unit==="plan")&&!jt(e.paths,e.session)&&!Yr(e.paths,e.session)){let u=a.reading(),d=n.some(c=>{let f=c.unit!=="plan"?null:c.window==="seven_day"?u?.sevenDay:u?.fiveHour;return!!f&&f.resetsAt>e.now&&f.pct>=c.limit-Lo&&f.pct<c.limit});Uo({paths:e.paths,env:e.env,now:e.now,account:Ue(e.transcript,e.paths),readingAt:u?.at??null,near:d,hookFile:e.probe.hookFile,node:e.probe.node,...e.probe.start?{start:e.probe.start}:{}})}}catch{}return l}function Pa(e,n,t){if(n.problem)return{budget:e,used:null,why:n.problem==="large"?"large":"meter"};let r=e.unit==="usd"?n.usd:n.tokens.fresh,o=e.unit==="usd"?{budget:e,used:r,estimated:n.estimated,...n.estimatedAt?{estimatedAt:n.estimatedAt}:{}}:{budget:e,used:r};return r>=e.limit?o:e.unit==="usd"&&n.unpriced.length>0?{budget:e,used:null,why:"price",models:n.unpriced}:t>0?{budget:e,used:null,why:"counting",left:t,soFar:o}:o}var et=e=>e.why==="large"||e.early!==void 0||e.used!==null&&e.used>=e.budget.limit,ye={day:"today's",week:"this week's",task:"this task's",seven_day:"your week's",five_hour:"these 5 hours'"},tr=(e,n=1e3)=>`$${e<n?e.toFixed(2):String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,tt=e=>Number.isInteger(e)?tr(e,0):tr(e),ar=(e,n,t=1e3)=>{let r=tr(e,t),o=Number(r.slice(1).replace(/,/g,""));return e>=n?o===n&&e!==n?`$${e.toFixed(2)}`:r:o>=n?`$${(Math.floor(e*100)/100).toFixed(2)}`:r};function Me(e){let n=e.budget,t=e.used??0;return n.unit==="usd"?`${e.estimated?"~":""}${ar(t,n.limit)} of ${tt(n.limit)}`:n.unit==="tokens"?`${ze(t)} of ${n.text.replace(/ a (day|week|task)$/,"")}`:`${Math.round(t)}% of ${n.window==="seven_day"?"your week":"these 5 hours"} used, budget ${n.limit}%`}function Ve(e,n){let t=e.budget.window;if(t==="day")return"resets at midnight";if(t==="week")return"resets Monday";if(t==="task")return"ends with your next message";let r=e.resetsAt??n,o=r-n;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 ja=e=>e.charAt(0).toUpperCase()+e.slice(1),rt="a day of Anvil's meter is over 32 MB, more than any person's day: a loop, or something writing to it",Pe=e=>e.early&&(e.used??0)<e.budget.limit?e.early.why:null,ot=e=>Pe(e)?"nearly spent":"spent",rr=e=>{let n=e.early?.others??0;return n>0?` here and in ${n===1?"another Claude Code session":`${n} other Claude Code sessions`}`:""},ur=e=>({running:`, and what's running${rr(e)} could pass it`,next:`, and the next replies${rr(e)} could pass it`,launch:"",advisor:""})[Pe(e)??"launch"]??"",La=e=>{let n=e.early?.advisor;return n?e.budget.unit==="usd"?`about $${n.usd>=1?n.usd.toFixed(1):n.usd.toFixed(2)}`:`about ${ze(n.fresh)} new tokens`:""},Ye=e=>e.estimatedAt?.length?` (${Er(e.estimatedAt)})`:"";function xn(e,n,t="an OK lets this task go on past it"){if(e.why==="large")return`your budget ${e.budget.text} can't be counted: ${rt} \xB7 ${t}`;if(Pe(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 ${ye[e.budget.window]} budget: ${Me(e)} used${Ye(e)}${s} \xB7 ${Ve(e,n)} \xB7 ${t}`}if(Pe(e)==="advisor"){let r=e.early.advisor,o=(e.used??0)+(e.budget.unit==="usd"?r.usd:r.fresh)>=e.budget.limit;return`the advisor's opinion on this ${r.about} would cost ${La(e)} and${o?"":`, with what's running${rr(e)},`} pass ${ye[e.budget.window]} budget: ${Me(e)} used${Ye(e)} \xB7 ${Ve(e,n)} \xB7 ${t}`}return`${ye[e.budget.window]} budget is ${ot(e)}: ${Me(e)}${Ye(e)}${ur(e)} \xB7 ${Ve(e,n)} \xB7 ${t}`}function Ta(e,n,t,r){return`${e.why==="large"?`${L("Your budget can't be counted")} ${e.budget.text} \xB7 ${rt}`:`${L(`${ja(ye[e.budget.window])} budget is ${ot(e)}`)} ${Me(e)}${Ye(e)}${ur(e)} \xB7 ${Ve(e,n)}`}${be("keep going",`${K(t)} allow ${r}`,"send your message again")}${Kn("change the budget instead",`${K(t)} rules edit`)}`}function zo(e){let n=e.budget;if(n.unit==="plan")return`${L("Anvil")} ${Math.round(e.used??0)}% of ${n.window==="seven_day"?"your week":"these 5 hours"} used${(e.age??0)>=6e4?` (read ${gn(e.age)} ago)`:""} \xB7 your budget stops at ${n.limit}%`;let t=e.used??0,r=n.unit==="usd"?`${e.estimated?"~":""}${ar(t,n.limit,10)}`:ze(t),o=n.unit==="usd"?tt(n.limit):`${n.text.replace(/ a (day|week|task)$/,"")}`;return`${L("Anvil")} ${r} of ${ye[n.window]} ${o} used`}var Ko={plan:"there is no reading of your plan yet",meter:"Anvil's meter can't be read right now",large:rt};function Ia(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 ts(e){switch(e.why){case"large":return`can't be counted: ${rt}`;case"price":return`can't measure: no price for ${(e.models??[]).join(", ")}`;case"stale":return`can't measure (last reading ${gn(e.age??0)} ago${e.reset?", before its window reset":""})`;case"counting":return`can't measure yet: Anvil is still reading ${ye[e.budget.window]} session files (${io(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: ${Ko.plan}`;default:return`can't be measured here: ${Ko.meter}`}}function dg(e,n){try{let r=JSON.parse(pa(ee(Z(e,n),"settings.json"),"utf8").replace(/^/,""))?.statusLine?.command;return typeof r=="string"&&!r.includes("/.anvil/claude/bin/claude-sync.js")}catch{return!1}}function je(e,n){let t=ee($e(e),"said");try{return O(t),da(fa(ee(t,aa("sha256").update(n).digest("hex").slice(0,32)),"wx")),!0}catch(r){return r.code!=="EEXIST"}}function rs(e,n,t,r=!0){let o=[];for(let s of n){let i=s.budget;if(s.why==="large")continue;if(s.used===null){let l=(s.why==="plan"||s.why==="stale")&&e.probe?Ia(Wo(e.paths,Ue(e.transcript,e.paths).key)):void 0;if(l===null||!je(e.paths,`unmeasured|${e.session??"-"}|${i.id}|${s.why??"meter"}`))continue;o.push(s.why==="task"?`${L("Anvil")} your budget ${i.text} counts from your next message (Claude Code 2.1.318 or later tells Anvil when one is sent) \xB7 not enforced until then`:`${L("Anvil")} your budget ${i.text} ${l??ts(s)} \xB7 not enforced`);continue}if(s.used<i.limit*wa||s.used>=i.limit)continue;let a=i.window==="day"?Y(e.now):i.window==="week"?Y(cn(e.now)):i.window==="task"?`${e.session}@${t?.t??0}`:String(s.resetsAt??0);je(e.paths,`near|${i.id}|${a}`)&&o.push(r?zo(s):`${zo(s)}
26
+ ${uo}`)}return o.length>0?o.join(`
27
+ `):null}function nt(e,n,t,r,o,s){try{O(e.paths.dir);let i=o==="passed"?xn(n,e.now,"going on with your OK"):xn(n,e.now);se(e.paths.decisions,JSON.stringify({v:1,ts:new Date(e.now).toISOString(),session:e.session,tool:t,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?qo(e.project):null,...s?{hold:s}:{},path:"none",ms:0}))}catch{}}function os(e,n,t){let r=e.budget.window;return r==="day"?le(n):r==="week"?cn(n):r==="task"?t?.t??0:e.resetsAt??0}var Da=36e5;function ss(e,n,t,r){if(e.id!==n.budget.id||!(t<e.end)||e.end-t>nr)return!1;let o=os(n,t,r);return(n.budget.unit==="plan"?Math.abs(o-e.w)>Da:o!==e.w)?!1:e.at===null||n.used===null||n.used<e.at+n.budget.limit}function Fa(e){try{let n=Oe(e);return O(n),ua(n,ca.W_OK),!0}catch{return!1}}var is=(e,n)=>`${Oe(e)} can't be written: fix its permissions, or run in a terminal: ${K(n)} on`,ls=(e,n,t)=>`${L("Anvil")} ${xn(e,n).replace(/ · an OK lets this task go on past it$/,"")}, but Anvil can't record an OK right now (${t}) \xB7 not stopped`;function as(e,n,t,r){let o=!1;try{o=No(e.paths,J(e.paths),e.session,e.project,[{kind:"claude.budget",target:n.budget.id}],e.now).approved}catch{o=!1}if(!o)return!1;try{for(let{hold:s,file:i}of Eo(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===n.budget.id)&&ga(i,{force:!0})}catch{}try{let s=t?null:r?.until!==void 0&&e.now<r.until?r.until:e.now+nr,i=(r?.passes??[]).filter(l=>l.id!==n.budget.id&&e.now<l.end),a={id:n.budget.id,w:os(n,e.now,t),at:n.used,end:e.now+nr};Yo(e.paths,e.session,{v:1,t:t?.t??e.now,passes:[...i,a],...s!==null?{until:s}:{}})}catch{}return!0}function or(e,n){return`${e.why==="large"||e.budget.unit==="plan"?"":`up to ${e.budget.unit==="usd"?tt(e.budget.limit):ze(e.budget.limit)} more, `}for an hour at most${e.budget.window==="task"?"":`, until it ${Ve(e,n)}`}`}function us(e,n){return e.why==="large"?`${L("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 ${or(e,n)}`:`${L("Anvil")} going on ${Pe(e)?`near ${ye[e.budget.window]} budget`:`past ${ye[e.budget.window]} budget`}, as you said: ${Me(e)}${Ye(e)} \xB7 for this task, ${or(e,n)}`}function Wa(e,n,t){return`Anvil: ${e.why==="large"?`the user's budget ${e.budget.text} can't be counted`:`${ye[e.budget.window]} budget is ${ot(e)} (${Me(e)}${ur(e)})`}, and the user ran \`${K(n)} allow\` in a terminal to let this task go on past it (${or(e,t)}). 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 Ha=new Set(["SubagentHandback","mcp__ccd_turn__wrap_up","mcp__ccd_turn__update_plan"]);function Ua(e,n){return n?e.map(t=>{let r=t.used===null&&t.why==="counting"&&t.soFar?t.soFar:t;return r.used===null||r.budget.unit==="plan"||r.used>=r.budget.limit||r.early?t:r.used+(r.budget.unit==="usd"?n.usd:n.fresh)>=r.budget.limit?{...r,early:{why:"advisor",advisor:n}}:t}):e}function ds(e){if(Ha.has(String(e.payload.tool_name??"")))return null;try{let n=Go(e),t=sr(n.table);if(t.length===0)return null;let r=lr(n.paths,n.session),o=Date.parse(n.table?.compiled_at??""),s=r&&r.until===void 0&&!(o>r.t)?r:null,i=Ua(ns(n,t,s,"action"),e.advisor),a=r&&(r.until===void 0||n.now<r.until)?r.passes??[]:[],l=f=>a.some(g=>ss(g,f,n.now,s)),u=i.find(f=>et(f)&&!l(f)),d=()=>{for(let f of i)et(f)&&l(f)&&nt(n,f,"PreToolUse","claude.budget","passed",null)};if(u){if(as(n,u,s,r))return nt(n,u,"PreToolUse","claude.budget","approved",null),d(),{note:us(u,n.now)};let f=xn(u,n.now);if(Ea(n),!Fa(n.paths))return{note:ls(u,n.now,is(n.paths,n.cli))};let g=u.budget.id,m=u.why==="large"?"the user's budget can't be counted":Pe(u)==="launch"?"the helpers starting could pass the user's budget":`the user's budget is ${ot(u)}`,p=Pe(u)==="advisor"?`asking the advisor about this ${u.early?.advisor?.about??"call"} first would pass the user's budget, so it waits for their OK. Don't ask the advisor`:`${m}, so every action waits for their OK`,h={user:`${L("Held by Anvil for your OK")} ${f}${be("keep going",`${K(n.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${L("Held by Anvil")} ${f}. Nothing ran: ${p}. Stop here and tell the user: to keep going, ${Ae(n.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:g,decision:{verdict:"hold",policy:"budgets",origin:null,ruleId:"budget",blockedBy:"budget_reached",source:u.budget.source},mode:"enforce",floor:null,why:f,said:h}}}d();let c=rs(n,i.filter(f=>!l(f)),s,Ke(n.table));return c?{note:c}:null}catch{return null}}function cg(e){try{if(zn(e.payload))return null;let n=Go(e),t=J(n.paths),r={installed:n.installed===!0},o=n.table??Re(n.paths,n.fallbackTable,t,r).value,s=sr(o);if(s.length===0)return null;let i={v:1,t:n.now};try{Yo(n.paths,n.session,i)}catch{}if(wn(n.paths,t,r).value?.kill_switch===!0)return null;let a=ns(n,s.filter(d=>d.window!=="task"),i,"message"),l=a.find(et);if(l){if(as(n,l,i,i))return nt(n,l,"UserPromptSubmit","claude.prompt","approved",null),`${JSON.stringify({systemMessage:us(l,n.now),hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:Wa(l,n.cli,n.now)}})}
28
+ `;let d;try{d=Oo(n.paths,{session:n.session,project:n.project,stops:[{kind:"claude.budget",target:l.budget.id}],why:xn(l,n.now),project_name:n.project?qo(n.project):null,command:"your next message (Anvil never reads it)"},n.now)}catch(c){let f=c.code;return`${JSON.stringify({systemMessage:ls(l,n.now,f==="ENOSPC"||f==="EDQUOT"?"the disk is full: free some space":is(n.paths,n.cli))})}
29
+ `}return nt(n,l,"UserPromptSubmit","claude.prompt","deny",d.id),`${JSON.stringify({decision:"block",reason:Ta(l,n.now,n.cli,d.code)})}
30
+ `}let u=rs(n,a,i,Ke(o));return u?`${JSON.stringify({systemMessage:u})}
31
+ `:null}catch{return null}}function Ba(e){if(e.used===null)return null;let n=e.budget,t=n.window==="day"?"today":"this week";return n.unit==="plan"?`${Math.round(e.used)}% of ${n.window==="seven_day"?"your week":"these 5 hours"} \xB7 budget ${n.limit}% \xB7 ${Tt(e.age??0)}`:n.unit==="tokens"?`${ze(e.used)} of ${n.text.replace(/ a (day|week|task)$/,"")} ${t}`:`${e.estimated?"~":""}${ar(e.used,n.limit,10)} of ${tt(n.limit)} ${t}`}function za(e,n){let t=[],r=[];try{r=Jo(ee($e(e),"tasks"))}catch{return t}for(let o of r){if(!o.endsWith(".json"))continue;let s=lr(e,o.slice(0,-5));if(!(!s||s.until!==void 0&&n>=s.until))for(let i of s.passes??[])n<i.end&&t.push({pass:i,task:s})}return t}var fg=(e,n)=>Wn(Z(e,n));function pg(e,n,t,r){let o=sr(n);if(o.length===0)return[];let s=r??Wn(Z(process.env,ha())),i,a={paths:e,now:t,task:null,session:null,reading:()=>i===void 0?i=Be(e,t,s):i,totals:d=>Bn(e,d,t),unread:{left:0,upto:0},own:()=>0,apiKey:!1},l=[],u;for(let d of o){if(d.window==="task"){l.push({budget:d,used:null,share:null,text:"each task: checked while Claude works",short:null});continue}let c=Xo(d,a),f=d.unit==="plan"&&c.used!==null?` \xB7 ${Tt(c.age??0)}`:"",g;if(et(c))for(let{pass:m,task:p}of u??=za(e,t))ss(m,c,t,p)&&(g=Math.max(g??0,Math.min(m.end,p.until??m.end)));l.push({budget:d,used:c.used,share:c.used===null?null:c.used/d.limit,text:c.used===null?ts(c):`${Me(c)}${Ye(c)} \xB7 ${Ve(c,t)}${f}`,short:Ba(c),...c.why?{why:c.why}:{},...c.age!==void 0?{age:c.age}:{},...g!==void 0?{okUntil:g}:{}})}return l}import{execFileSync as Ka}from"child_process";import{readdirSync as hs,rmSync as cr,statSync as it}from"fs";import{basename as Ja,join as ae}from"path";function ue(e){let n=e.trim().toLowerCase(),t=/(?:^|[^a-z])(opus|sonnet|haiku|fable|mythos)(?![a-z])/.exec(n);if(!t)return null;let r=t[1],o=/\[1m\]$/.test(n);return{family:r,oneM:o,label:`${r[0].toUpperCase()}${r.slice(1)}${o?" 1M":""}`}}var B=e=>typeof e=="string"&&e.length>0?e:null,st=e=>e.split(" \xB7 ")[0]??e,ms=e=>e==="sdk"||e.startsWith("repl_main_thread"),ys=e=>Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.startsWith("context-1m-"));function An(e,n){return qa(e,n)?.model??null}function qa(e,n){if(!e||!e.endsWith(".jsonl"))return null;let t=n!==null&&/^[A-Za-z0-9_-]{1,64}$/.test(n);if(n!==null&&!t)return null;let r=t?pn(e,n)??ae(e.slice(0,-6),"subagents",`agent-${n}.jsonl`):e,o;try{o=it(r).size}catch{return null}for(let s of[256*1024,4*1024*1024]){let i=G(r,s),a=i?i.split(`
32
+ `):[];for(let l=a.length-1;l>=0;l--){let u=a[l];if(u.includes('"api-request"'))try{let d=JSON.parse(u);if(d.type!=="api-request")continue;let c=typeof d.querySource=="string"?d.querySource:"";if(!t&&!ms(c))continue;let f=B(d.params?.model),g=typeof d.timestamp=="string"?Date.parse(d.timestamp):Number.NaN;if(f)return{model:ys(d.params?.betas)&&!/\[1m\]$/i.test(f)?`${f}[1m]`:f,at:g}}catch{}}if(o<=s)break}return null}var _n=500,Ga=3e3,Va="<synthetic>",Ya=/"version":"(\d{1,6}\.\d{1,6}\.\d{1,6})"/,ws=e=>typeof e.timestamp=="string"?Date.parse(e.timestamp):Number.NaN;function cs(e,n){try{let t=JSON.parse(e);if(t.type!=="api-request"||!n&&!ms(typeof t.querySource=="string"?t.querySource:""))return null;let r=B(t.params?.model);return r?{model:ys(t.params?.betas)&&!/\[1m\]$/i.test(r)?`${r}[1m]`:r,id:B(t.id),at:ws(t)}:null}catch{return null}}function fs(e,n,t){try{let r=JSON.parse(e);if(r.type!=="assistant"||!t&&r.isSidechain===!0)return null;let o=B(r.message?.model);if(!o||o===Va)return null;let s=Array.isArray(r.message?.content)?r.message.content:[],i=n!==null&&s.some(l=>l&&l.type==="tool_use"&&l.id===n),a=s.some(l=>l&&l.type==="fallback");return{model:o,ref:B(r.requestRef),own:i,at:ws(r),fallback:a}}catch{return null}}var Za=new Set(["api_error","model_fallback","model_consent_fallback","model_refusal_fallback"]);function dr(e){if(!(e.includes('"type":"user"')&&(e.includes('"content":"')||e.includes('"permissionMode"')))&&!e.includes('"api_error"')&&!e.includes('_fallback"'))return!1;try{let n=JSON.parse(e);return n.type==="system"?typeof n.subtype=="string"&&Za.has(n.subtype):n.type!=="user"?!1:typeof n.permissionMode=="string"||typeof n.message?.content=="string"}catch{return!1}}function bs(e,n){return!e||!e.endsWith(".jsonl")?null:n===null?e:/^[A-Za-z0-9_-]{1,64}$/.test(n)?pn(e,n)??ae(e.slice(0,-6),"subagents",`agent-${n}.jsonl`):null}function fr(e,n,t){let r;try{r=it(e).size}catch{return null}let o={request:null,answer:null,before:null,changed:!1,version:null};for(let s of[256*1024,4*1024*1024]){let i=G(e,s),a=i?i.split(`
33
+ `):[],l=null,u=null,d=!1,c=!1,f=null,g=null,m=-1,p=[];for(let _=a.length-1;_>=0;_--){let x=a[_];if(g===null&&x.includes('"version":"')&&(g=Ya.exec(x)?.[1]??null),l===null){if(x.includes('"assistant"')){let v=fs(x,t,n);v&&p.push({...v,i:_})}else x.includes('"api-request"')?(l=cs(x,n),l&&(m=_)):p.length===0&&dr(x)&&(c=!0);continue}if(x.includes('"assistant"')){let v=fs(x,t,n);if(v){u={model:v.model,at:v.at,reply:!0},v.own&&(f={model:v.model,own:!0,at:v.at,fallback:v.fallback});break}}else if(x.includes('"api-request"')){let v=cs(x,n);if(v){u={model:v.model,at:v.at,reply:!1};break}}else dr(x)&&(d=!0)}let h=null,k=_=>{for(let x=m+1;x<_;x++)if(dr(a[x]))return!0;return!1},y;for(let _ of p)_.own&&(y=_);l&&p.some(_=>_.ref!==null&&_.ref!==l.id&&(_===y||k(_.i)))&&(l=null,u=null);let $=y??f??p[0];if(h=$?{model:$.model,own:$.own,at:$.at,fallback:$.fallback===!0}:null,l||(d=c),o={request:l,answer:h,before:u,changed:d,version:g},r<=s||l&&u)break}return o}function ps(e,n){let t=ue(e),r=ue(n);return t&&r?t.family===r.family:!t&&!r&&e.trim().toLowerCase().replace(/\[1m\]$/,"")===n.trim().toLowerCase().replace(/\[1m\]$/,"")?!0:null}function ks(e,n,t=!1){let r=e?.version??null;if(!e)return{id:null,how:"none",version:r};let{request:o,answer:s,before:i}=e,a=l=>ue(l)!==null;if(o&&s){let l=ps(o.model,s.model);return l===!1&&s.fallback&&s.own?{id:s.model,how:"one",version:r}:l===!1?{id:o.model,how:"differ",other:{model:s.model,from:"reply"},version:r}:l===null&&!a(o.model)&&a(s.model)?{id:s.model,how:"one",version:r}:{id:o.model,how:l?"agree":"one",version:r}}if(o&&i&&!e.changed){let l=ps(o.model,i.model);return l===!1&&!i.reply&&!t&&!n(i)?{id:o.model,how:"differ",other:{model:i.model,from:"last request"},version:r}:l===null&&!a(o.model)&&a(i.model)&&!n(i)?{id:i.model,how:"one",version:r}:{id:o.model,how:l?"agree":"one",version:r}}return o?{id:o.model,how:"one",version:r}:s&&!e.changed&&(s.own||Xa(r)&&!n(s))?{id:s.model,how:"one",version:r}:{id:null,how:"none",version:r}}function Xa(e){let n=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(e??"");return n!==null&&Number(n[1])*1e6+Number(n[2])*1e3+Number(n[3])>=2001304}var vs=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},lt=e=>/^(1|true|yes|on)$/i.test((e.CLAUDE_CODE_EAGER_FLUSH??"").trim())||/^(1|true|yes|on)$/i.test((e.CLAUDE_CODE_IS_COWORK??"").trim())||/^sdk-/.test((e.CLAUDE_CODE_ENTRYPOINT??"").trim());function Qa(e,n,t=Ze,r=e.wait??vs){let o=bs(B(e.payload.transcript_path),n);if(!o)return{id:null,how:"none",version:null};let s=B(e.payload.tool_use_id),i=fr(o,n!==null,s),a=l=>l!==null&&(l.request?l.answer===null:l.answer?.own!==!0);if(r&&s&&lt(e.env)&&a(i)){let l=e.startedAt??(e.wait?null:Date.now()-process.uptime()*1e3),u=Math.min(Date.now()+_n,l===null?Number.POSITIVE_INFINITY:l+Ga);for(let d=0;d<_n/20&&Date.now()<u&&(r(20),i=fr(o,n!==null,s),!!a(i));d++);}return ks(i,l=>n===null&&$s(e,l.at,t),n!==null)}function $s(e,n,t){if(!Number.isFinite(n))return!0;let r=As(e.paths,B(e.payload.session_id));if(r&&r.at>=n)return!0;let o=i=>typeof i=="string"&&/^opusplan\b/i.test(i.trim());if(o(e.env.ANTHROPIC_MODEL)||o(Rs(e)))return!0;let s=Cs(e.env,t);return s!==null&&s.at-1e3>n||o(s?.model)}function eu(e,n,t,r=null,o=!1){let s=B(e.payload.session_id),i=s?kt(e.paths,s):null;if(i)try{if(!n){!o&&U(i)===!0&&cr(i,{force:!0});return}if(U(i)===!0)return;let a=rn(e.paths);O(a),W(i,`${JSON.stringify({v:1,at:e.now,version:t,...r?{model:r.slice(0,80)}:{}})}
34
+ `);for(let l of hs(a)){let u=ae(a,l);l.endsWith(".json")&&e.now-it(u).mtimeMs>bt&&cr(u,{force:!0})}}catch{}}function pr(e,n){let t=(e?.policies??[]).filter(r=>en(r,n));return{guards:t.flatMap(r=>(r.model_rules?.guards??[]).map(o=>({...o,project:r.origin==="project"}))),never:t.flatMap(r=>r.model_rules?.never??[])}}function nu(e,n){let t=[];for(let r of n){let o=e.find(s=>s.project&&s.kinds.includes(r))??e.find(s=>s.kinds.includes(r));o&&!t.some(s=>s.id===o.id)&&t.push(o)}return t}var Sn=(e,n)=>e.model===n.family&&(!e.one_m||n.oneM);function xs(e,n=Ze){try{let t=pr(e.table,e.projectDir??null),r=e.kinds??[],o=nu(t.guards,r);if(o.length===0&&t.never.length===0)return null;let s=B(e.payload.session_id)??"-",i=B(e.payload.agent_id),a=Qa(e,i,n,o.length>0?e.wait??vs:null),l=a.id,u=l?ue(l):null,d=[],c=i?"helper":"session";if(!i&&u&&a.how!=="differ"){let h=t.never.find(k=>Sn(k,u));h&&je(e.paths,`model-never|${s}|${h.id}`)&&d.push(`${L("Anvil")} this session runs on ${u.label}, which your rules say never (${st(h.source)})${Ht("Switch it: the model picker, or /model.")}`)}let f,g=(h,k,y,$)=>({action:r.find(_=>h.kinds.includes(_)),decision:{verdict:"hold",policy:"models",origin:null,ruleId:"model",blockedBy:"model_rule",source:h.source},mode:"enforce",floor:null,why:k,said:{user:`${L("Held by Anvil for your OK")} {why}${be("allow it once",`${K(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${L("Held by Anvil")} ${y}. Nothing ran. Tell the user: ${$}; or, to allow it once, ${Ae(e.cli,"tell you to go on")}. Do not try another way.`}}),m=`to change one, run in a terminal: ${K(e.cli)} rules edit`;if([...new Set(o.map(h=>h.model))].length>1){let[h,k]=o.filter(($,_)=>o.findIndex(x=>x.model===$.model)===_),y=`${h.text} and ${k.text}: no one model meets both`;f=g(h,`${y} \xB7 ${m}`,y,"no switch runs it: they can change one of the two rules")}else if(o.length>0&&a.how==="differ"){let h=o[0],k=$=>ue($)?.label??$.slice(0,60),y=`Anvil's two readings of this ${c}'s model differ (its request says ${k(l)}, its ${a.other.from} ${k(a.other.model)})`;f=g(h,`${h.text}; ${y}`,`${h.text}; ${y}`,`Anvil can't confirm which model this ${c} runs on: they can check it and allow it once`)}else if(o.length>0&&a.how==="none"){let h=o[0];d.push(`${L("Anvil")} ${h.text}, but Anvil can't hear which model this ${c} runs on: Claude Code wrote no record of it \xB7 not held`)}else if(o.length>0&&!u){let h=o[0];je(e.paths,`model-unknown|${s}|${i??""}|${h.id}`)&&d.push(`${L("Anvil")} ${h.text}, but Anvil doesn't know the model ${l.slice(0,60)} this ${c} runs on \xB7 not enforced`)}else if(o.length>0&&u&&o[0].model!==u.family){let h=o[0],k=i?`this helper runs on ${u.label}`:`this session is ${u.label}`,y=i?void 0:t.never.find(_=>Sn(_,{family:h.model,oneM:!1})),$=`${h.model[0].toUpperCase()}${h.model.slice(1)}`;i?f=g(h,`${h.text}; ${k} \xB7 a helper's model: add the rule model: ${h.model} for helper agents`,`${h.text}; ${k}`,`a helper takes its model from the launch or a model: rule (model: ${h.model} for helper agents)`):y?f=g(h,`${h.text}; ${k}, and your rules also say ${y.text} (${st(y.source)}) \xB7 ${m}`,`${h.text}; ${k}, and their rules also say ${y.text}`,"switching won't run it (their rules refuse that switch): they can change one of the two rules"):f=g(h,`${h.text}; ${k} \xB7 switch to ${$}: /model ${h.model}, or the model picker`,`${h.text}; ${k}`,`they can switch this session to ${$} (/model ${h.model}, or the model picker) and ask you to try again`)}return o.length>0&&eu(e,a.how==="none"||l!==null&&!u,a.version,l!==null&&!u?l:null,i!==null),!f&&d.length===0?null:{...f?{stop:f}:{},...d.length>0?{note:d.join(`
35
+ `)}:{}}}catch{return null}}function Rg(e){try{let n=J(e.paths),t={installed:e.installed===!0},r=e.table??Re(e.paths,e.fallbackTable,n,t).value,o=pr(r,e.projectDir??null);if(o.never.length===0&&o.guards.length===0)return null;let s=B(e.payload.to_model),i=B(e.payload.requested_model),a=(s?ue(s):null)??(i?ue(i):null),l=a!==null&&(a.oneM||/\[1m\]$/i.test(i??"")),u=s&&ue(s)?s:i??s;if(o.never.length===0)return gs(e,u&&l&&!/\[1m\]$/i.test(u)?`${u}[1m]`:u),null;let d=a?o.never.find(m=>Sn(m,{family:a.family,oneM:l})):void 0,c=wn(e.paths,n,t).value?.kill_switch===!0;if(!d||c||!a)return gs(e,u&&l&&!/\[1m\]$/i.test(u)?`${u}[1m]`:u),null;let f=`${a.label.replace(/ 1M$/,"")}${l?" 1M":""}`,g=`${L("Anvil")} your rules say ${d.text} \xB7 change it in a terminal: ${K(e.cli)} rules edit`;return _s(e,d,f,"switch"),`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreModelSwitch",permissionDecision:"deny",permissionDecisionReason:g}})}
36
+ `}catch{return null}}function _s(e,n,t,r){try{let o=B(e.env.CLAUDE_PROJECT_DIR)??B(e.payload.cwd),s=o&&o.startsWith("/")?hn(o):o;O(e.paths.dir),se(e.paths.decisions,JSON.stringify({v:1,ts:new Date(e.now).toISOString(),session:B(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 ${t}: your rules say ${n.text}`:`a message on ${t}: your rules say ${n.text}`,target:t,project:s?Ja(s):null,path:"none",ms:0}))}catch{}}var Ss=/^[A-Za-z0-9_-]{1,80}$/,tu=7*864e5;function gs(e,n){let t=B(e.payload.session_id);if(!(!t||!Ss.test(t)||!n))try{let r=ae(e.paths.dir,"models");O(r),W(ae(r,`${t}.json`),`${JSON.stringify({v:1,model:n.slice(0,80),at:e.now})}
37
+ `);for(let o of hs(r)){let s=ae(r,o);o.endsWith(".json")&&e.now-it(s).mtimeMs>tu&&cr(s,{force:!0})}}catch{}}function As(e,n){if(!n||!Ss.test(n))return null;let t=j(ae(e.dir,"models",`${n}.json`));return t&&t.v===1&&typeof t.model=="string"&&typeof t.at=="number"?{model:t.model,at:t.at}:null}var Ze=e=>{try{return Ka("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 Cs(e,n=Ze){let t=Number(e.CLAUDE_PID);if(!Number.isInteger(t)||t<=1)return null;let r=n(t)?.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|^\S*\/claude\/versions\/\d{1,6}\.\d{1,6}\.\d{1,6}(?:\s|$)/.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 Rs(e){let n=e.projectDir??null,t=[...n?[ae(n,".claude","settings.local.json"),ae(n,".claude","settings.json")]:[],ae(Z(e.env,e.home),"settings.json")];for(let r of t){let o=j(r)?.model;if(typeof o=="string"&&o.trim())return o.trim()}return null}function Og(e,n=Ze){return Os(e,n).id}function Os(e,n=Ze){let t=B(e.payload.session_id),r=Cs(e.env,n),o=r?r.at-1e3:Number.NEGATIVE_INFINITY,s=c=>Number.isFinite(c)&&c>=o,i=bs(B(e.payload.transcript_path),null),a=i?fr(i,!1,null):null,l=a?.request&&s(a.request.at)?a.request:null,u=As(e.paths,t),d=u&&s(u.at)?u:null;if(d&&(!l||d.at>=l.at))return{id:d.model};if(l&&a){let c=ks({...a,request:l},f=>$s(e,f.at,n));return c.how==="differ"&&c.other?{id:l.model,other:c.other}:{id:l.model}}return r?.model?{id:r.model}:{id:B(e.env.ANTHROPIC_MODEL?.trim())??Rs(e)}}var ru=["opus","sonnet","fable","haiku"];function Eg(e,n=Ze){try{if(zn(e.payload))return null;let t=J(e.paths),r={installed:e.installed===!0},o=e.table??Re(e.paths,e.fallbackTable,t,r).value,s=pr(o,e.projectDir??null);if(s.never.length===0||wn(e.paths,t,r).value?.kill_switch===!0)return null;let i=Os(e,n),a=i.id?ue(i.id):null,l=i.other?ue(i.other.model):null,u=p=>p?s.never.find(h=>Sn(h,p)):void 0,d=u(a)??u(l);if(!d)return null;let c=u(a)?a:l,f=ru.find(p=>!(p===c.family&&!c.oneM)&&!s.never.some(h=>Sn(h,{family:p,oneM:!1}))),g=`${Ht(`Switch first (the model picker, or /model${f?` ${f}`:""}), then send your message again.`)}${Kn("change that rule instead",`${K(e.cli)} rules edit`)}`,m=i.other?`${L("Anvil can't confirm this session's model")} its request says ${a?.label??i.id.slice(0,60)}, its ${i.other.from} ${l?.label??i.other.model.slice(0,60)}, and your rules say ${d.text} (${st(d.source)})${g}`:`${L(`This session is on ${c.label}`)} your rules say ${d.text} (${st(d.source)})${g}`;return _s(e,d,c.label,"message"),`${JSON.stringify({decision:"block",reason:m})}
38
+ `}catch{return null}}import{closeSync as su,existsSync as iu,fstatSync as lu,openSync as au,readdirSync as uu,readSync as du,realpathSync as cu,statSync as fu,unlinkSync as pu}from"fs";import{homedir as at}from"os";import{basename as gu,isAbsolute as gr,join as oe,resolve as hr}from"path";import{createHash as hu}from"crypto";var ou=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f؜‎‏‪-‮⁦-⁩]/g;function Es(e){return e.replace(ou,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}var Ps=(e,n)=>!e.since||!n||!Number.isFinite(Date.parse(n))||Date.parse(n)>=e.since;function mr(e,n){let t=X(oe(e.dir,Ut),J(e),4194304);if(t.status!=="ok"&&t.status!=="unkeyed")return[];let r=[];for(let o of Array.isArray(t.value.rules)?t.value.rules:[])if(!(!o||o.layer!=="both"&&o.layer!=="part"||!Array.isArray(o.entries)))for(let s of o.entries){if(typeof s!="string"||s==="")continue;let i=s==="~"||s.startsWith("~/")?oe(n,s.slice(1)):s;if(!gr(i))continue;let a=typeof o.since=="string"&&Number.isFinite(Date.parse(o.since))?Date.parse(o.since):null;for(let l of new Set([hr(i),js(hr(i))]))r.push({path:l,folded:Rn(l),rule:String(o.id),text:String(o.text??o.id),project:typeof o.project=="string"?o.project:null,since:a})}return r}function js(e){let n="";for(let t=e;t.length>1;)try{return cu.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}var mu=(e,n)=>{let t=Rn(e);return t===n.folded||t.startsWith(n.folded.endsWith("/")?n.folded:`${n.folded}/`)};function Ls(e,n,t,r=at()){if(t.length===0)return null;for(let o of e.split(/\r?\n/).slice(0,400)){if(!/not permitted/i.test(o))continue;let s=o.slice(0,4096),i=[...s.matchAll(/['"`]([^'"`]+)['"`]/g)].map(f=>f[1]),a=/not permitted:\s+(\S+)/i.exec(s)?.[1];a&&i.push(a);let u=/^(.*?):\s*operation not permitted/i.exec(s)?.[1]?.split(/:\s/).pop()?.trim();u&&!/\s/.test(u)&&i.push(u);let d=f=>f.includes("/")||/^[\w@+-][\w.@+-]*\.[\w-]+$/.test(f),c=[...i,...s.replace(/['"`]/g," ").split(/\s+|:\s|,\s/).filter(d)].map(f=>f.replace(/^[[(]+|[\]),:;]+$/g,"").replace(/\.$/,"")).filter(f=>f!=="");for(let f of c){let g=f==="~"||f.startsWith("~/")?oe(r,f.slice(1)):gr(f)?f:n&&gr(n)?oe(n,f):null;if(g===null)continue;let m=hr(g);for(let p of new Set([m,js(m)])){let h=t.find(k=>mu(p,k));if(h)return{lock:h,path:m}}}}return null}function Ts(e){let n=[];for(let t of e.split(`
39
+ `)){if(!t.includes('"sandboxed":true')||!/not permitted/i.test(t))continue;let r;try{r=JSON.parse(t)}catch{continue}if(!(r.type!=="user"||r.sandboxed!==!0||!Array.isArray(r.message?.content)))for(let o of r.message.content){if(!o||o.type!=="tool_result"||typeof o.tool_use_id!="string")continue;let s=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(l=>typeof l?.text=="string"?l.text:"").join(`
40
+ `):"",i=typeof r.toolUseResult=="string"?r.toolUseResult:r.toolUseResult&&typeof r.toolUseResult=="object"?[r.toolUseResult.stdout,r.toolUseResult.stderr].filter(l=>typeof l=="string").join(`
41
+ `):"",a=`${s}
42
+ ${i}`;/not permitted/i.test(a)&&n.push({call:o.tool_use_id,text:a.slice(0,64*1024),cwd:typeof r.cwd=="string"?r.cwd:null,ts:typeof r.timestamp=="string"?r.timestamp:null})}}return n}var yu=e=>/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:hu("sha256").update(e).digest("hex").slice(0,24),Ns=(e,n=200)=>{let t=Es(e.slice(0,4096).replace(/\s+/g," ").trim());return t.length>n?`${t.slice(0,n-1)}\u2026`:t},Ms=4*1024*1024;function wu(e,n){return oe(e.state,"locks",`${yu(n)}.json`)}function bu(e,n){if(U(e,Number.MAX_SAFE_INTEGER)!==!0)return null;let t=null;try{t=au(e,"r");let r=lu(t),s=!n||n.ino!==r.ino||n.off>r.size?0:n.off;r.size-s>Ms&&(s=r.size-Ms);let i=r.size-s;if(i<=0)return{text:"",ino:r.ino,off:r.size};let a=Buffer.alloc(i),l=0;for(;l<i;){let d=du(t,a,l,i-l,s+l);if(d<=0)break;l+=d}let u=a.lastIndexOf(10,l-1);return u<0?{text:"",ino:r.ino,off:s}:{text:a.subarray(0,u+1).toString("utf8"),ino:r.ino,off:s+u+1}}catch{return null}finally{t!==null&&su(t)}}function ku(e){try{if(!e.transcript||!e.session)return 0;let n=nn(e.anvilDir),t=e.home??at(),r=mr(n,t);return r.length===0?0:Is(n,r,e.session,e.transcript,t,e.now)}catch{return 0}}function Is(e,n,t,r,o,s){let i=wu(e,t),a=j(i),l=a&&a.t===r&&typeof a.off=="number"&&typeof a.ino=="number"&&Array.isArray(a.seen)?a:null,u=bu(r,l);if(!u)return 0;let d=new Set(l?.seen??[]),c=0;for(let f of Ts(u.text)){if(d.has(f.call))continue;let g=n.filter(k=>Ps(k,f.ts)&&(k.project===null||f.cwd!==null&&(f.cwd===k.project||f.cwd.startsWith(`${k.project}/`)))),m=Ls(f.text,f.cwd,g,o);if(!m)continue;d.add(f.call);let p=m.path===o||m.path.startsWith(`${o}/`)?`~${m.path.slice(o.length)}`:m.path,h=f.ts&&Number.isFinite(Date.parse(f.ts))?new Date(Date.parse(f.ts)).toISOString():new Date(s).toISOString();try{O(e.dir),se(e.decisions,JSON.stringify({v:1,ts:h,session:t,tool:"Bash",action:vu,verdict:"block",mode:"enforce",delivered:"deny",rule:m.lock.rule,slug:"locked",policy:null,blocked_by:"sandbox_lock",why:Ns(`locked by your rule: ${m.lock.text} \xB7 the sandbox refused a write to ${p}`,300),target:Ns(p),project:f.cwd?gu(f.cwd):null,path:"none",ms:0,call:f.call,transcript:r})),c++}catch{}}try{O(oe(e.state,"locks")),W(i,JSON.stringify({t:r,ino:u.ino,off:u.off,seen:[...d].slice(-200),session:t}))}catch{}return c}var vu="claude.sandbox.locked";function $u(e,n,t=at()){try{let r=nn(e),o=mr(r,t);if(o.length===0)return 0;let s=0,i=oe(r.state,"locks"),a=[];try{a=uu(i).slice(0,5e3)}catch{return 0}let l=c=>{try{return fu(oe(i,c)).mtimeMs}catch{return 0}},u=a.filter(c=>c.endsWith(".json")).map(c=>({x:c,m:l(c)}));for(let c of u)if(!(n-c.m<7*864e5))try{pu(oe(i,c.x))}catch{}let d=u.filter(c=>n-c.m<864e5).sort((c,f)=>f.m-c.m).slice(0,20);for(let{x:c}of d){let f=j(oe(i,c));f&&typeof f.t=="string"&&typeof f.session=="string"&&(s+=Is(r,o,f.session,f.t,t,n))}return s}catch{return 0}}function xu(e){try{if(!iu(oe(e.anvilDir,Ut)))return 0;let n=r=>{let o=new RegExp(`"${r}"\\s*:\\s*("(?:[^"\\\\]|\\\\.){1,4096}")`).exec(e.input.slice(0,16384));try{return o?JSON.parse(o[1]):null}catch{return null}};return ku({anvilDir:e.anvilDir,transcript:n("transcript_path"),session:n("session_id"),now:e.now,...e.home?{home:e.home}:{}})+(e.sessionStart?$u(e.anvilDir,e.now,e.home):0)}catch{return 0}}function _u(e,n){let t=Su(n);if(t===null)return null;let r=(e.touched?.unknown?.length??0)>0||e.parse==="limited"||e.parse==="partial",o=t.locked!==null?{target:t.locked,why:`runs outside the sandbox right after it refused a write to ${t.locked} (locked by your rule: ${t.rule??"a rule on that folder"})`}:r?{target:"outside the sandbox",why:"runs outside the sandbox, where your locks don't reach, and Anvil can't read every path it writes"}:null;if(o===null)return null;let{housekeeping:s,findings:i,...a}=e,l=e.action!=="claude.bash.unclassified"&&e.action!=="claude.tool.other",u=[...new Set([...l?[e.action]:[],...e.also])].filter($=>$!=="claude.agent.controls"),{environment:d,environment_said:c,repo_dir:f,repo_remote:g,repo_via:m,...p}=e.attributes,h={...d!==void 0?{environment:d,environment_said:c??null}:{},...m!==void 0?{repo_dir:f??null,repo_remote:g??null,repo_via:m}:{}},k=e.findings??(l?[{action:e.action,service:e.service,target:e.attributes.target,why:e.why,...h}]:[]),y=[{action:"claude.agent.controls",service:null,target:o.target,why:o.why},...k].slice(0,16);return{...a,action:"claude.agent.controls",service:null,attributes:{...p,target:o.target,branch:null,host:null,is_local:!0},why:o.why,also:u,...y.length>1?{findings:y}:{}}}function Su(e){try{let n=nn(e.anvilDir),t=e.home??at(),r=mr(n,t);if(r.length===0)return null;if(!e.transcript)return{locked:null,rule:null};let o=G(e.transcript,256*1024).split(`
43
+ `).filter(s=>s.includes('"tool_result"')).slice(-6).reverse();for(let s of o){let i=Ts(s)[0];if(!i)continue;let a=r.filter(c=>Ps(c,i.ts)&&(c.project===null||i.cwd!==null&&(i.cwd===c.project||i.cwd.startsWith(`${c.project}/`)))),l=Ls(i.text,i.cwd,a,t);if(!l)return{locked:null,rule:null};let u=l.path;return{locked:i.cwd&&u.startsWith(`${i.cwd}/`)?u.slice(i.cwd.length+1):u===t||u.startsWith(`${t}/`)?`~${u.slice(t.length)}`:u,rule:l.lock.text}}return{locked:null,rule:null}}catch{return{locked:null,rule:null}}}import{closeSync as Us,openSync as Bs,readdirSync as ut,readSync as zs,rmSync as Au,statSync as Cn}from"fs";import{homedir as Ks}from"os";import{basename as Cu,isAbsolute as Ds,join as z}from"path";var de=e=>typeof e=="string"&&e.length>0?e:null,Fs=/^[A-Za-z0-9_-]{1,80}$/,Ru=7*864e5;function Ou(e){if(!e||!e.endsWith(".jsonl"))return null;for(let n of[256*1024,4*1024*1024]){let t=G(e,n),r=t.lastIndexOf('"promptId":"');if(r>=0){let s=/^"promptId":"([^"\\]{1,120})"/.exec(t.slice(r,r+140));if(s)return s[1]}let o=0;try{o=Cn(e).size}catch{return null}if(o<=n)break}return null}function Js(e){try{let n=JSON.parse(e);if(n.type!=="api-request-shape")return;let r=(Array.isArray(n.shape?.tools)?n.shape.tools:[]).find(o=>!!o&&typeof o=="object"&&o.type==="advisor_20260301");return r?de(r.model)??"advisor":null}catch{return}}function qs(e,n=null){let t;try{t=Cn(e).size}catch{return null}let r=n?j(n):null,o=r?.v===1&&r.file===e&&typeof r.at=="number"&&r.at<=t,s=o?r.at:0,i=o?r.seen===!0:!1,a=o&&typeof r.attached=="string"?r.attached:null,l;try{l=Bs(e,"r")}catch{return null}try{let u=Buffer.alloc(4194304),d="",c=s;for(;c<t;){let f=zs(l,u,0,Math.min(u.length,t-c),c);if(f<=0)break;c+=f;let g=d+u.toString("utf8",0,f),m=g.lastIndexOf(`
44
+ `);if(m<0){d=g;continue}for(let p of g.slice(0,m).split(`
45
+ `)){if(!p.includes('"api-request-shape"'))continue;let h=Js(p);h!==void 0&&(i=!0,a=h)}d=g.slice(m+1),s=c-Buffer.byteLength(d)}}finally{Us(l)}if(n)try{W(n,`${JSON.stringify({v:1,file:e,at:s,seen:i,attached:a})}
46
+ `)}catch{}return i?{attached:a}:null}function dt(e,n,t,r){return Gs(e,n,t,r)?.value??null}function Gs(e,n,t,r){let s=[[process.platform==="darwin"?"/Library/Application Support/ClaudeCode/managed-settings.json":process.platform==="linux"?"/etc/claude-code/managed-settings.json":null,"your organization's managed settings"],...r?[[z(r,".claude","settings.local.json"),"this project's .claude/settings.local.json"],[z(r,".claude","settings.json"),"this project's .claude/settings.json"]]:[],[z(Z(n,t),"settings.json"),null]];for(let[i,a]of s){if(!i)continue;let l=j(i)?.[e];if(typeof l=="string"&&l.trim())return{value:l.trim(),from:a}}return null}function Eu(e,n,t){let r={};for(let o of[z(Z(e,n),"settings.json"),...t?[z(t,".claude","settings.json"),z(t,".claude","settings.local.json")]:[]]){let s=j(o)?.env;if(s&&typeof s=="object")for(let[i,a]of Object.entries(s))typeof a=="string"&&(r[i]=a)}return{...r,...e}}function yr(e){let n=e.shape!==void 0?e.shape:e.transcript?qs(e.transcript,e.cursor??null):null,t=Gs("model",e.env,e.home,e.project);return co({env:e.env,advisorModel:dt("advisorModel",e.env,e.home,e.project),model:t?.value??null,modelFrom:t?.from??null,session:n?{attached:n.attached,model:e.model??null,started:e.since!=null&&e.transcript&&!n.attached?Vs(e.transcript):null}:null,since:e.since??null,seen:e.seen??null})}function wr(e,n){let t;try{t=Bs(e,"r")}catch{return""}try{let r=Buffer.alloc(n),o=zs(t,r,0,n,0);return r.toString("utf8",0,o)}catch{return""}finally{Us(t)}}function Vs(e){for(let n of wr(e,256*1024).split(`
47
+ `)){let t=/"timestamp":"([^"]{1,40})"/.exec(n),r=t?Date.parse(t[1]):NaN;if(Number.isFinite(r))return r}return null}function Nu(e){for(let n of wr(e,2*1024*1024).split(`
48
+ `)){if(!n.includes('"api-request-shape"'))continue;let t=Js(n);if(t!==void 0)return{attached:t}}return null}function br(e){let n=null,t=j(e.install);for(let r of Object.values(t?.installs??{})){let o=typeof r?.models?.at=="string"?Date.parse(r.models.at):NaN;Number.isFinite(o)&&(n=Math.max(n??o,o))}return n}var Ws=e=>z(e.dir,"state","advisor-seen.json"),Mu=8;function Pu(e,n,t,r=!1){let o=Vs(e);if(o===null||o<=n)return null;let s=Nu(e);return s?s.attached?{verdict:"on",started:o}:r||/"entrypoint":"sdk-/.test(wr(e,256*1024))||zt(An(e,null),t)?null:{verdict:"off",started:o}:null}function ju(e,n,t){let r=[],o=z(e,"projects");try{for(let s of ut(o)){let i;try{i=ut(z(o,s))}catch{continue}for(let a of i)if(a.endsWith(".jsonl"))try{let l=Cn(z(o,s,a)).mtimeMs;l>n&&r.push({f:z(o,s,a),t:l})}catch{}}}catch{return[]}return r.sort((s,i)=>i.t-s.t).slice(0,t).map(s=>s.f)}function Ys(e,n,t={}){let r=n===null,o=n??0;try{let s=j(Ws(e)),i=s&&s.v===1&&s.since===o?s:null,a=i?.verdict==="on"||i?.verdict==="off"?i:null,l=c=>{if(a?.file===c)return;let f=Pu(c,o,t.advisorModel??null,r);f&&(a?.started===void 0||f.started>a.started)&&(a={v:1,since:o,...f,file:c})};t.file&&l(t.file);let u=i?.checked;if(t.scan){for(let c of ju(t.scan.configDir,Math.max(o,u??o),Mu))l(c);u=t.scan.now}let d={...a??{v:1,since:o},...u!==void 0?{checked:u}:{}};return JSON.stringify(d)!==JSON.stringify(i)&&(O(z(e.dir,"state")),W(Ws(e),`${JSON.stringify(d)}
49
+ `)),d.verdict??null}catch{return null}}function Lu(e){return!!e&&G(e,256*1024).includes('"entrypoint":"claude-desktop"')}function Tu(e){let n=Ft[e];return n?/^[a-z]+$/.test(n.text)?n.text:`call (${n.text})`:"call"}var Hs=1450,Iu=1700,Du=19e3;function Fu(e,n){let t=Du,r=e?G(e,4*1024*1024):"";for(let s=r.length;s>0;){let i=r.lastIndexOf('"type":"assistant"',s-1);if(i<0)break;let a=r.lastIndexOf(`
50
+ `,i)+1,l=r.indexOf(`
51
+ `,i);s=a;try{let u=JSON.parse(r.slice(a,l<0?void 0:l)),d=u.message?.usage;if(u.type!=="assistant"||!d||u.message?.model==="<synthetic>")continue;let f=(Array.isArray(d.iterations)?d.iterations.filter(m=>m?.type==="message"):[]).at(-1)??d,g=m=>typeof f[m]=="number"&&f[m]>0?f[m]:0;t=g("input_tokens")+g("cache_read_input_tokens")+g("cache_creation_input_tokens")+g("output_tokens");break}catch{}}let o=t+Iu;return{usd:_e(n,{input:o,output:Hs,write5m:0,write1h:0,read:0}),fresh:o+Hs}}function Wu(e,n,t){let r=(e?.policies??[]).filter(o=>en(o,n)).flatMap(o=>(o.model_rules?.second??[]).map(s=>({r:s,project:o.origin==="project"})));for(let o of t){let s=r.find(i=>i.project&&i.r.kinds.includes(o))??r.find(i=>i.r.kinds.includes(o));if(s)return{rule:s.r,kind:o}}return null}var Hu=(e,n)=>z(e.dir,"state","second",`${n}.json`),Uu=(e,n)=>z(e.dir,"state","second",`${n}.shape.json`),Zs=/^[A-Za-z0-9_-]{1,120}$/,Bu=/^[A-Za-z0-9_.:-]{1,120}$/;function zu(e,n){try{for(let t of ut(e)){let r=z(e,t);t.endsWith(".json")&&n-Cn(r).mtimeMs>Ru&&Au(r,{force:!0})}}catch{}}function Ku(e,n){let t=j(e),r={v:2,task:n,done:[],denied:{}};if(!t||t.v!==2||t.task!==n||!Array.isArray(t.done)||!t.denied||typeof t.denied!="object")return r;let o={};for(let[s,i]of Object.entries(t.denied))i&&typeof i.id=="string"&&Zs.test(i.id)&&typeof i.tries=="number"&&Number.isInteger(i.tries)&&i.tries>=0&&(o[s]={id:i.id,tries:i.tries});return{v:2,task:n,done:t.done.filter(s=>typeof s=="string"),denied:o}}function Ju(e){if(!e||typeof e!="object")return!1;let n=e;return(n.type==="advisor_result"||n.type==="advisor_redacted_result")&&n.stop_reason!=="refusal"}function qu(e,n,t){let r=e.split(`
52
+ `),o=(d,c)=>d.includes(`"${c}"`)&&d.includes('"tool_use"'),s=r.findIndex(d=>o(d,t));if(s<0)return null;let i=r.findIndex(d=>o(d,n));if(i<0||i>s)return!1;let a=!1,l=!1,u=new Set;for(let d=i;d<=s;d++){let c=r[d];if(d!==i&&d!==s&&!c.includes('"server_tool_use"')&&!c.includes('"advisor_tool_result"'))continue;let f;try{f=JSON.parse(c).message?.content}catch{continue}for(let g of Array.isArray(f)?f:[])if(g?.type==="tool_use"&&g.id===n)a=!0;else{if(g?.type==="tool_use"&&g.id===t)return l;a&&g?.type==="server_tool_use"&&g.name==="advisor"?u.add(g.id):a&&g?.type==="advisor_tool_result"&&u.has(g.tool_use_id)&&Ju(g.content)&&(l=!0)}}return l}function Gu(e,n,t,r){let o=i=>qu(G(n,i),t,r),s=o(1048576);if(s===null){let i=e.wait??(u=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,u)}),a=e.startedAt??(e.wait?null:Date.now()-process.uptime()*1e3),l=Math.min(Date.now()+_n,a===null?Number.POSITIVE_INFINITY:a+3e3);for(let u=0;u<_n/20&&s===null&&Date.now()<l;u++)i(20),s=o(1024*1024)}return s===!1&&(s=o(8*1024*1024)),s===!0}function Vu(e,n,t,r){try{let o=de(e.payload.tool_name)??"unknown";se(e.paths.decisions,JSON.stringify({v:1,ts:new Date(e.now).toISOString(),session:t,...r?{agent_id:r}:{},tool:o,action:"claude.advisor.second",verdict:"allow",mode:"enforce",delivered:"none",rule:n.id,slug:"second-opinion",policy:"second_opinion",blocked_by:"second_opinion",why:`${n.text}: advisor asked, then let through`,target:null,project:e.projectDir?Cu(e.projectDir):null,path:"none",ms:0}))}catch{}}function Xs(e){try{let b=function(A){return{stop:{action:"claude.advisor.second",decision:{verdict:"block",policy:"second_opinion",origin:null,ruleId:o.id,blockedBy:"second_opinion",source:o.source},mode:"enforce",floor:null,why:`${o.text}: ${A?"rerun without the advisor, sent back":"the advisor first"}`,said:{user:`${L("Anvil")} ${o.text}: Claude was told to ask the advisor (${v.model??"on"}) about this ${E} first${A?", again: it reran without asking":""}. Nothing ran.`,agent:`${L("Anvil")} ${A?`There is no answer from the advisor in this session since this ${E} was refused. `:""}Ask the advisor about this ${E} first. If it advises against it, don't rerun: tell the user. Nothing ran.`}}}},T=function(){return{stop:{action:"claude.advisor.unasked",decision:{verdict:"hold",policy:"second_opinion",origin:null,ruleId:o.id,blockedBy:"second_opinion",source:o.source},mode:"enforce",floor:null,why:`${o.text}: rerun without the advisor`,said:{user:`${L("Held by Anvil for your OK")} {why}${be("allow it once",`${K(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${L("Held by Anvil")} ${o.text}: this ${E} came back twice without the advisor's answer. Nothing ran. Tell the user: to allow it once, ${Ae(e.cli,"tell you to go on")}. Do not try another way.`}}}};var n=b,t=T;let r=Wu(e.table,e.projectDir??null,e.kinds??[]);if(!r)return null;let{rule:o,kind:s}=r,i=de(e.payload.session_id),a=de(e.payload.transcript_path),l=de(e.payload.agent_id),u=l&&Fs.test(l)?l:null,d=de(e.payload.tool_use_id),c=d&&Zs.test(d)?d:null,f=de(e.payload.prompt_id),g=i&&Fs.test(i)?i:null,m=(f&&Bu.test(f)?f:null)??Ou(a)??g??"-",p=a&&u?pn(a,u)??null:a,h=g?`${g}${u?`-${u}`:""}`:null,k=h?Hu(e.paths,h):null,y=k?Ku(k,m):null;if(y?.done.includes(s))return null;let $=e.projectDir??null,_=Eu(e.env,e.home,$),x=p?qs(p,h?Uu(e.paths,h):null):null,v=yr({env:_,home:e.home,project:$,transcript:p,shape:x,model:p?An(a,u):null,since:br(e.paths)});zu(z(e.paths.dir,"state","second"),e.now);let E=Tu(s),C=A=>{try{return O(z(e.paths.dir,"state","second")),W(k,`${JSON.stringify(A)}
53
+ `),!0}catch{return!1}},N,M=()=>{if(N===void 0){let A=x?.attached,Q=A&&A!=="advisor"?A:dt("advisorModel",_,e.home,$)??"opus";N=(e.table?.policies??[]).some(ce=>ce.budgets?.length)?ds({...e,advisor:{...Fu(p,Q),about:E}}):null}return!!N?.stop},R=()=>({stop:N.stop}),D=A=>{let Q=[N?.note,A.note].filter(Boolean).join(`
54
+ `);return Q?{...A,note:Q}:A};if(v.on&&v.seen==="session"&&y!==null&&c!==null&&p!==null&&lt(e.env)){let A=y.denied[s];if(A)if(Gu(e,p,A.id,c)){let{[s]:Q,...ce}=y.denied;return C({...y,done:[...y.done,s],denied:ce}),Vu(e,o,g,u),null}else{let Q=A.tries+1;if(Q===1&&M())return R();let ce=C({...y,denied:{...y.denied,[s]:{id:A.id,tries:Q}}});if(ce&&Q===1)return D(b(!0));if(ce)return T()}else{if(M())return R();if(C({...y,denied:{...y.denied,[s]:{id:c,tries:0}}}))return D(b(!1))}}if(v.on&&M())return R();let P=v.on?v.seen!=="session"?"Anvil can't see an advisor in this session":!lt(e.env)||c===null?"Anvil can't see the advisor's answer here before a rerun runs":"Anvil can't keep its note of this task":v.why??"none is attached",q=v.on?` Ask the advisor about this ${E} and tell the user what it advises.`:"",w=g&&je(e.paths,`second-off|${g}|${o.id}`)?`${L("Anvil")} ${v.on?P:P===Kt?`no advisor in this session: ${P}`:`no advisor in this session (${P})`} \xB7 ${o.text}: each one waits for your OK`:void 0;return D({stop:{action:s,decision:{verdict:"hold",policy:"second_opinion",origin:null,ruleId:o.id,blockedBy:"second_opinion",source:o.source},mode:"enforce",floor:null,why:v.on?`${o.text}: ${P}, so you are the second opinion`:`${o.text}: no advisor in this session, so you are the second opinion`,said:{user:`${L("Held by Anvil for your OK")} {why}${be("allow it once",`${K(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${L("Held by Anvil")} ${o.text}: ${v.on?`${P}, so the user is the second opinion. Nothing ran.${q}`:"there is no advisor in this session, so the user is the second opinion. Nothing ran."} Tell the user: to allow it once, ${Ae(e.cli,"tell you to go on")}. Do not try another way.`}},...w?{note:w}:{}})}catch{return null}}function Yu(e){let n=Xs(e);if(n?.stop?.decision.verdict==="block"||n?.stop?.action==="claude.budget")return n;let t=xs(e);if(!n)return t;let r=[n.note,t?.note].filter(Boolean).join(`
55
+ `),o=t?.stop?{...t.stop,why:`${t.stop.why}; and ${n.stop.why}`}:n.stop;return{...o?{stop:o}:{},...r?{note:r}:{}}}function Zu(e,n,t){return z(Z(e,n),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function Xu(e){let n=null;try{for(let t of ut(e)){if(!t.endsWith(".jsonl"))continue;let r=Cn(z(e,t)).mtimeMs;(!n||r>n.t)&&(n={f:z(e,t),t:r})}}catch{return null}return n?.f??null}function Qs(e){try{return Re(e,void 0,J(e)).value}catch{return null}}var ei=e=>Ke(e)||(e?.policies??[]).some(n=>(n.model_rules?.second?.length??0)>0);function Qu(e,n=It()){try{if(!ei(Qs(e)))return"";let t=JSON.parse(n??"null"),r=de(t?.transcript_path);if(!r||!Ds(r)||!r.endsWith(".jsonl"))return"";let o=de(t?.workspace?.project_dir)??de(t?.cwd),s=Ks(),i=o&&Ds(o)?o:null,a=br(e),l=Ys(e,a,{file:Jn(process.env)?null:r,advisorModel:dt("advisorModel",process.env,s,i)}),u=yr({env:process.env,home:s,project:i,transcript:r,model:An(r,null),since:a,seen:l});return` \xB7 ${Jt(u)}`}catch{return""}}function ed(e,n){try{let t=Qs(e);if(!ei(t))return null;let r=Ks(),o=Xu(Zu(process.env,r,n)),s=o?An(o,null):null,i=br(e),a=Ys(e,i,{file:Jn(process.env)?null:o,advisorModel:dt("advisorModel",process.env,r,n)}),l=Jt(yr({env:process.env,home:r,project:n,transcript:o,model:s,since:i,seen:a})).replace(/^advisor: /,""),u=Ce(s);return Ke(t)&&u&&u.family!=="sonnet"&&Lu(o)?`${l} \xB7 the desktop app runs ${u.label} here, its own pick`:l}catch{return null}}export{_n as ANSWER_WAIT_MS,Bo as COLD_PER_WARM,Ct as FEED_MAX_BYTES,er as FIRST_HELPER_REPLY_TOKENS,va as HELPER_CACHE_MS,Hr as HELPER_LIVE_MS,Fe as KEEP_DAYS,Ra as LAUNCH_CLAIM_MS,xa as LIVE_MS,dn as PLAN_FRESH_MS,Ha as REPORT_ONLY_TOOLS,ba as RESERVE_MAX_SHARE,Kr as STATUSLINE_READ_BYTES,ka as UNSEEN_HELPER_SHARE,Ue as accountOf,ed as advisorRow,Qu as advisorTail,gn as ageWords,ds as budgetAtAction,cg as budgetAtPrompt,pg as budgetStanding,sr as budgetsOf,sf as catchUp,eo as catchUpFrom,Dt as catchUpSince,al as catchUpToday,zn as claudeCodesOwnTurn,Z as claudeConfigDir,Y as dayOf,Qi as dollarsWords,lt as eagerFlush,Yr as feedsPlan,of as feedsSince,Hn as helperFiles,so as helperStates,pn as helperTranscript,ks as judgeReadings,Be as lastReading,Cs as launchOf,_u as lockHold,xu as lockRun,io as megabytes,rl as meterStep,Bn as meterTotals,xs as modelAtAction,Og as modelAtMessage,Eg as modelAtPrompt,Rg as modelAtSwitch,An as modelNow,ue as modelOf,Yu as modelRulesAt,Br as money,jt as offPlan,dg as ownStatusLine,Gr as ownerKeyOf,Jr as parseStatusFeed,la as probeAccount,Ia as probeFailure,el as pruneMeter,Tt as readAgo,It as readFeedFromStdin,Xi as readLimits,Lt as readSessionAndHelpers,Rt as readSessionFile,Qa as readingAtAction,Os as readingAtMessage,oo as recentReplies,Pt as recordFeed,qa as requestNow,oa as runPlanProbe,je as sayOnce,fg as screenPlanScope,Wn as screenScope,Xs as secondOpinion,ro as sessionOpeningPrompt,Qr as sessionUnread,Mt as signedInOwner,Ur as spendWords,ar as spentUsd,le as startOfDay,cn as startOfWeek,lf as statusFacts,fr as threadReadings,ze as tokenWords,vt as unheardSessions};