@useanvil/claude-code 0.0.0-stage → 0.8.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.
- package/CHANGELOG.md +2027 -0
- package/LICENSE +111 -0
- package/README.md +214 -2
- package/TELEMETRY.md +60 -0
- package/dist/claude-conditions.js +12 -0
- package/dist/claude-helpers.js +12 -0
- package/dist/claude-hook-core.js +87 -0
- package/dist/claude-hook.js +38 -0
- package/dist/claude-meter.js +35 -0
- package/dist/claude-powershell.cjs +37 -0
- package/dist/claude-sync.js +28 -0
- package/dist/cli/claude-main.js +23716 -0
- package/dist/cli.js +18 -0
- package/docs/coding-agents/YOUR-RULES.md +701 -0
- package/package.json +34 -4
|
@@ -0,0 +1,35 @@
|
|
|
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};
|