@useanvil/claude-code 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +703 -0
- package/README.md +128 -38
- package/dist/Anvil +0 -0
- package/dist/claude-approve.js +23 -0
- package/dist/claude-conditions.js +19 -12
- package/dist/claude-helpers.js +9 -9
- package/dist/claude-hook-core.js +88 -80
- package/dist/claude-hook.js +38 -37
- package/dist/claude-meter.js +52 -48
- package/dist/claude-powershell.cjs +17 -17
- package/dist/claude-sync.js +26 -26
- package/dist/cli/claude-main.js +5392 -2510
- package/docs/coding-agents/YOUR-RULES.md +507 -654
- package/package.json +1 -1
package/dist/claude-meter.js
CHANGED
|
@@ -1,55 +1,59 @@
|
|
|
1
|
-
import{appendFileSync as
|
|
1
|
+
import{appendFileSync as jr,closeSync as jn,constants as we,fstatSync as Pn,openSync as Tn,readdirSync as Oi,readSync as an,rmSync as On,statSync as Se}from"fs";import{createHash as Ln}from"crypto";import{homedir as Ei}from"os";import{basename as Nt,dirname as Ni,isAbsolute as Jr,join as S,resolve as Mi}from"path";import{isatty as ji}from"tty";import{createHash as Dc}from"crypto";import{appendFileSync as wi,closeSync as Ar,constants as Sr,fstatSync as Cr,mkdirSync as bi,openSync as Rr,readdirSync as Wc,readFileSync as ki,readSync as Or,renameSync as vi,statSync as $i,unlinkSync as Hc,writeFileSync as _i}from"fs";import{homedir as Bc}from"os";import{dirname as Kc,join as pe}from"path";function kr(e){let n=e?.turned_off;return Array.isArray(n)?n:[]}var vr=e=>e.length>0?{turned_off:e}:{};var Xe="claude";function ui(e){return e==="ghost"||e==="enforce"?e:null}function gt(e=new Date){return{version:1,kill_switch:!1,default_mode:"ghost",services:{[Xe]:{actions:{}}},updated_at:e.toISOString(),day_one:!0}}function $r(e,n,t,r=new Date){let o=e&&typeof e=="object"?e:gt(r);if(t==="all")return{version:1,kill_switch:!1,default_mode:n,services:{[Xe]:{actions:{}}},updated_at:r.toISOString(),...vr(n==="enforce"?[]:kr(o))};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:ui(o.default_mode)??"ghost",services:{...o.services??{},[Xe]:{actions:s}},updated_at:r.toISOString(),...o.day_one===!0?{day_one:!0}:{},...vr(kr(o))}}function ne(e){return Object.assign(Object.create(null),e)}import{createHash as wd}from"crypto";import{existsSync as kd,readdirSync as vd,statSync as $d}from"fs";import{dirname as xd,isAbsolute as Sd,join as Ad,posix as Cd,resolve as Rd}from"path";import{posix as xr}from"path";var ci=null;function Qe(){return ci??process.platform==="win32"}var _r=/^([A-Za-z]):(.*)$/s,fi=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function ht(e,n){let t=xr.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 mt(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(_r.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 ht(l,Ie(o[3]??"",t).toLowerCase())}let s=_r.exec(n);if(s){let l=s[2];return l===""?`/${s[1].toLowerCase()}`:l.startsWith("/")?ht(`/${s[1].toLowerCase()}`,Ie(l,t).toLowerCase()):null}let i=fi.exec(n);if(i)return ht(`/${i[1].toLowerCase()}`,Ie(i[2]??"",t).toLowerCase());let a=Ie(n,t).toLowerCase();if(a.startsWith("/")){let l=xr.normalize(a);return l.length>1&&l.endsWith("/")?l.slice(0,-1):l}return a}function pi(e){return mt(e)??e}function yt(e){return!Qe()||typeof e!="string"||e===""?e:pi(e)}import{domainToASCII as Id}from"url";var Kd="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as lc,readdirSync as ac,realpathSync as uc}from"fs";import{basename as cc,dirname as fc,join as pc}from"path";function Rn(e){let n=e.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,"");return process.platform==="darwin"||Qe()?n.normalize("NFC").toLowerCase():n}var wt="anvil-claude-compiled/1";function en(e,n){return e.origin!=="project"||!!(n&&e.project_dir&&yi(n,e.project_dir))}function yi(e,n){let t=yt(e),r=yt(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 xi=3500;function U(e,n=8*1024*1024){try{let t=$i(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=Rr(e,Sr.O_RDONLY|Sr.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=Cr(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=Or(t,o,s,r.size-s,s);if(i===0)break;s+=i}return o.subarray(0,s)}finally{Ar(t)}}function se(e,n){let t=n.endsWith(`
|
|
2
2
|
`)?n:`${n}
|
|
3
|
-
`;if(Buffer.byteLength(t)>
|
|
4
|
-
`);a=l<0?"":a.slice(l+1)}return a}finally{
|
|
5
|
-
`:"";for(let r of n)t.length+r.length+1>6e4&&t&&(
|
|
6
|
-
`;t&&
|
|
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:
|
|
8
|
-
`)}function
|
|
9
|
-
`),c-f}finally{
|
|
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&&!
|
|
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
|
|
12
|
-
`)[0]??"",l=F(JSON.parse(a))?.timestamp;o=typeof l=="string"&&Date.parse(l)||0}catch{o=0}let s=
|
|
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"&&
|
|
3
|
+
`;if(Buffer.byteLength(t)>xi)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`);wi(e,t,{mode:384})}function O(e){bi(e,{recursive:!0,mode:448})}function J(e,n){if(U(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let t;try{t=Rr(e,"r")}catch{return""}try{let r=Cr(t).size,o=Math.max(0,r-n),s=r-o;if(s<=0)return"";let i=Buffer.alloc(s);Or(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{Ar(t)}}function W(e,n,t=384){let r=`${e}.${process.pid}.${Date.now().toString(36)}.tmp`;_i(r,n,{mode:t}),tn(r,e)}function tn(e,n){for(let t=0;;t++)try{vi(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 P(e){if(U(e)!==!0)return null;try{return JSON.parse(ki(e,"utf8"))}catch{return null}}var qc=256*1024,Gc=1024*1024;import{readdirSync as Si}from"fs";import{join as bt}from"path";var Ai=/^[A-Za-z0-9_-]{1,80}$/,kt=7*864e5,rn=e=>bt(e.dir,"models","unheard");function vt(e,n){return Ai.test(n)?bt(rn(e),`${n}.json`):null}function $t(e,n,t=null){let r=[];try{let o=t!==null?[vt(e,t)].filter(s=>s!==null):Si(rn(e)).filter(s=>s.endsWith(".json")).slice(0,500).map(s=>bt(rn(e),s));for(let s of o){let i=P(s);!i||i.v!==1||typeof i.at!="number"||n-i.at>kt||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 Ci(e){return on[xt(e)]!==void 0}var Er=e=>(e.match(/-(\d+)/g)??[]).map(n=>Number(n.slice(1))),Nr=(e,n)=>{let t=Er(e),r=Er(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 St(e){let n=_t.get(e);if(n!==void 0)return n;let t=Ri(e);return _t.size<256&&_t.set(e,t),t}function Ri(e){if(Ci(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(Nr):[])[0]??t.sort((o,s)=>on[s].output-on[o].output||Nr(o,s))[0]}function xe(e,n){return _e(e,n)??_e(St(e)??"claude-opus-5-5",n)??0}function Mr(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 _e(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 Rt=64*1024,qr=8*1024*1024,Pr=8*1024*1024,Pi=32*1024*1024,Fe=40,un=/^[A-Za-z0-9._-]{1,128}$/,In=/^[\w.:@/[\]-]{1,100}$/,Tr=Buffer.from('"usage":{"input_tokens":'),At=Buffer.from('{"type":"cost-state"'),Nn=Buffer.from('{"type":"session-owner"'),Lr=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 Ir(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 Gr(e){if(!e||Buffer.byteLength(e)>Rt)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"&&Jr(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:Ir(i?.five_hour),sevenDay:Ir(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 Oi(e)}catch{return[]}},We=e=>{try{let n=Se(e);return n.isFile()?n.mtimeMs:0}catch{return 0}};function Ti(e){let n;try{n=Tn(e,we.O_RDONLY|we.O_NONBLOCK)}catch{return!1}try{let t=Pn(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{jn(n)}}function Mt(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=Ti(e)?`
|
|
5
|
+
`:"";for(let r of n)t.length+r.length+1>6e4&&t&&(jr(e,t,{mode:384}),t=""),t+=`${r}
|
|
6
|
+
`;t&&jr(e,t,{mode:384})}var Li=4;function Dr(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=P(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(Dr),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&&Dr(o)?{v:2,totals:[o],m:t,at:n.at}:null}var Fn=e=>Ln("sha256").update(e).digest("hex").slice(0,16),Vr=e=>e?Mi(e):"";function Fr(e){let n=e?Math.max(e.lastIndexOf("/projects/"),e.lastIndexOf("\\projects\\")):-1;return n>0?Vr(e.slice(0,n)):""}var Yr=(e,n)=>`a${Fn(`${e}|${n}`)}`;function Zr(e){try{let n=F(JSON.parse(e.toString("utf8"))),t=n?.accountUuid;return n?.type==="session-owner"&&typeof t=="string"&&t.length>0?Yr(t,typeof n.organizationUuid=="string"?n.organizationUuid:""):null}catch{return null}}function Ii(e){let n;try{n=Tn(e,we.O_RDONLY|we.O_NONBLOCK)}catch{return null}try{if(!Pn(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=Zr(r.subarray(o,s));if(i)return i}return null}finally{jn(n)}}function Ue(e,n){let t=Fn(Fr(e));if(!e)return{key:`c${t}`,cfg:t};let r=n?P(fn(n,e))?.ow:void 0;return{key:(typeof r=="string"&&/^a[0-9a-f]{16}$/.test(r)?r:Ii(e)??(Et(e)===0?jt(Fr(e)):null))??`c${t}`,cfg:t}}function jt(e){if(!e)return null;let n=[S(e,".claude.json"),...Nt(e)===".claude"?[S(Ni(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 Yr(s,typeof o?.organizationUuid=="string"?o.organizationUuid:"")}catch{}}return null}var Wn=e=>({cfg:Fn(Vr(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=P(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:Di(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?Wi(e,n.transcript,l):l,day:a,at:t},g=[f,...u.filter(p=>p.e!==f.e)].slice(0,Li);Mt(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 Di(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,Fi(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 Fi(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+=Qr(a));return o}function Wi(e,n,t){if(!n)return 0;let r=P(fn(e,n))?.cs,o=0;for(let s of Array.isArray(r)?r.filter(eo):[])for(let i of s.v)i<=t+.01&&(o=Math.max(o,i));return Math.min(o,t)}function Tt(e,n){return!n||!un.test(n)?!1:Dn(S(te(e),"sessions",`${n}.json`))?.p===0}function Xr(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 cf(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 Hi(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 Ui(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=Ln("sha256").update(`${l}\0${u}`).digest("base64url").slice(0,22),h=Hi(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 Bi(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 zi(e,n,t){if(n<=t)return NaN;let r=e.lastIndexOf(Lr,n-1);if(r<t)return NaN;let o=r+Lr.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,Qr=e=>Mn(e)+(e.ad?Mn(e.ad):0),Ki=16,eo=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\\"),Ji=e=>Nt(e,".jsonl").replace(/^agent-/,"").replace(/[^A-Za-z0-9_-]/g,"").slice(0,40),fn=(e,n)=>S(te(e),"read",`${Ln("sha256").update(n).digest("hex").slice(0,32)}.json`);function Ot(e,n,t=qr){let r=te(e),o=fn(e,n),s=En(n),i=s?Ji(n):"",a;try{a=Tn(n,we.O_RDONLY|we.O_NONBLOCK)}catch{return 0}try{let l=Pn(a);if(!l.isFile())return 0;let u=P(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 _=Buffer.alloc(Math.min(h,l.size-c)),v=0;for(;v<_.length;){let j=an(a,_,v,_.length-v,c+v);if(j===0)break;v+=j}let E=v<_.length,C=_.subarray(0,v),N=C.lastIndexOf(10);if(N<0){if(E||c+v>=l.size)break;if(h>=Pr||k){k=!0,c+=v;continue}h=Math.min(Pr,h*4);continue}let M=0;k&&(M=C.indexOf(10)+1,k=!1);let R=C.subarray(0,N+1),D=R.indexOf(Tr,M),H=s?-1:R.indexOf(At,M);for(;D>=0||H>=0;){let j=H>=0&&(D<0||H<D),G=j?H:D,w=Math.max(M,R.lastIndexOf(10,G)+1);if(j&&w!==G){H=R.indexOf(At,G+1);continue}let b=R.indexOf(10,G),L=R.subarray(w,b<0?R.length:b);if(j){let A=Bi(L);A&&p.push({c:A,after:m.length,ts:zi(R,w,M),last:c+(b<0?R.length:b+1)>=l.size})}else{let A=Ui(L);A&&m.push(A)}if(b<0)break;D>=0&&D<=b&&(D=R.indexOf(Tr,b+1)),H>=0&&H<=b&&(H=R.indexOf(At,b+1))}if(!s)for(let j=R.lastIndexOf(Nn);j>=M;j=j>M?R.lastIndexOf(Nn,j-1):-1){if(j>M&&R[j-1]!==10)continue;let G=Zr(R.subarray(j,R.indexOf(10,j)));if(G){g=G;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 _=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=_.get(C);D?D.push(R):_.set(C,[R])}for(let[E,C]of _)Mt(S(r,`${E}.log`),C)}let y=d&&I(u.lt)!==null?u.lt:0,$=d&&Array.isArray(u.cs)?u.cs.filter(eo):[],x=d&&I(u.ev)!==null?u.ev:-1/0;if(p.length>0){let _=Nt(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),j=H?H.v.filter(w=>w<=C.u+.005):[],G=H?j.length>0?Math.min(C.u,Math.max(...j)):null:C.st<=x?null:0;G!==null&&C.s===_&&!C.unknown&&v.push({t:D,s:_,u:C.u,p:G,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(Ki))x=Math.max(x,w.t);y=Math.max(y,D)}for(;E<m.length;E++)y=Math.max(y,m[E].t);v.length>0&&qi(e,v)}else for(let _ of m)y=Math.max(y,_.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(x)?{ev:x}:{},...g?{ow:g}:{}})}
|
|
9
|
+
`),c-f}finally{jn(a)}}function qi(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]+=(_e(u.m,ro(u))??0)+(u.ad?_e(u.ad.m,oo(u.ad))??0:0),u.h!==1&&(r[c]+=Qr(u)))});let a=new Map;n.forEach((l,u)=>{let d=Ln("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)Mt(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&&Gi(a)<n))for(let l of re(a))l.endsWith(".jsonl")&&o.push(S(a,l))}}return o}var Gi=e=>{try{return Se(e).mtimeMs}catch{return 0}},Vi=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 Yi=15*6e4;function Lt(e,n,t,r=qr){let o=r,s=Hn(n.slice(0,-6),t-Vi).map(i=>({file:i,at:We(i)})).filter(i=>t-i.at<=Yi).sort((i,a)=>a.at-i.at);for(let{file:i}of s){if(o<=r/2)break;o-=Ot(e,i,o-r/2)}Ot(e,n,o)}function no(e,n,t){let r=0,o=(s,i)=>{try{let a=Se(s);if(!a.isFile()||!i&&a.mtimeMs<t)return;let l=P(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&&Jr(t)?t:S(n,".claude")}function to(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=P(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=Ot(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 ff(e,n,t,r=1024*1024*1024,o){return to(e,n,t,r,o).left===0}var ro=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}:{}}),oo=e=>({input:e.i,output:e.o,write5m:e.w5,write1h:e.w1,read:e.r}),Zi=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 Xi(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&&!Zi(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=Tn(e,we.O_RDONLY|we.O_NONBLOCK);try{if(!Pn(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{jn(r)}}function He(e,n,t){let r=S(te(e),`${n}.log`),o;try{if(o=Se(r),o.size>Pi)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=[];Xi(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 Wr(e,n){let t=_e(e,n);if(t!==null)return{usd:t};let r=St(e)??"claude-opus-5-5";return{usd:_e(r,n)??0,at:r}}function Hr(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 Ur(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 Qi(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,Hr(e,i.s,{t:i.t,...Wr(i.m,ro(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=Wr(a.m,oo(a)),u=l.usd,d=a.i+a.o+a.w5+a.w1;Hr(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=Ur(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;Ur(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 el(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 x=0;for(let _ of a)!_.h&&_.t>k&&_.t<=y&&(x+=_.w);h=p.w>0?Math.min(1,x/p.w):p.t>=r&&p.t<=o?1:0}let $=0;for(let x of a)x.usd!==null&&!x.at&&x.t>k&&x.t<=y&&($+=x.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))Qi(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=el(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 nl=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=P(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!==nl)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 tl(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 so(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 Ct=3;function io(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:xe(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}`,L=s.get(b)??[];L.push({t:w.t,c:f(w),own:w.s===n,warm:w.r>w.w5+w.w1}),s.set(b,L)},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,L=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&&L===0&&d(A))}let p=w=>w.sort((b,L)=>b.t-L.t).slice(-Ct).map(b=>b.c);o.sort((w,b)=>w.t-b.t);let h=o.slice(-Ct).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((L,A)=>L.t-A.t),$.push(b[0]),x.push(...b.slice(1)),_.add(`${w}@${b[0].t}`);let v=w=>w.sort((b,L)=>b.t-L.t).slice(-Ct).reduce((b,L)=>!b||L.c.fresh>b.fresh?L.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||!_.has(`${n}/${w.a}@${w.t}`)),D=y?y.i+y.w5+y.w1+y.r:null,H=w=>{let b=o.find(L=>L.t>=w);return p(o.filter(L=>L!==b))},j=v([...l.values()]),G=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(x),chatPrompt:D,chatFirst:j,chatToday:G,chatRecent:h,lastMainAt:k,mainSince:H,model:o.at(-1)?.m??null}}var Br=9e4;function lo(e,n){if(!e?.endsWith(".jsonl"))return[];let t=[];for(let r of Hn(e.slice(0,-6),n-Br)){if(We(r)<n-Br)continue;let o=0;try{let a=Un(r,0,Math.min(4096,Et(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=J(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"&&Et(r)>64*1024&&!(o>0&&n-o<6e4)&&(i="running"),t.push({state:i,started:o})}return t}var Et=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 It=e=>`read ${e<6e4?"just now":`${gn(e)} ago`}`,ao=e=>`${Math.max(1,Math.round(e/1048576))} MB`,rl=(e,n=!1)=>e.unpriced.length>0||n?`~${Kr(e.usd)}+`:`${e.estimated?"~":""}${Kr(e.usd)}`;function ol(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 zr(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:rl(n),today:!0}}function Kr(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 Dt(){return(sl??={text:il()}).text}var sl=null;function il(){if(ji(0))return null;let e=Buffer.alloc(Rt+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>Rt)return null}return n>0?e.subarray(0,n).toString("utf8"):null}function ll(e,n,t,r=null){let o=n?Gr(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(()=>fl(e,r,t)),s(()=>ol(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:tl(e,t,u),c=d&&t-d.at<=dn?d:null;return c?zr(c,null,t):zr(null,Bn(e,le(t),t))}catch{return null}}var al=5*6e4,ul=3e4,dl=32*1024*1024;function cl(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 Ft(e,n,t,r){let o=S(te(e),"caught"),s=cl(o);if(s&&s.at<=r&&s.since<=t&&r-s.at<(s.left>0?ul:al))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=to(e,n,i,dl),l={at:r,since:i,left:a.left,upto:a.upto};return W(o,JSON.stringify({v:1,...l})),l}function fl(e,n,t){Ft(e,n,le(t),t)}function pf(e,n){let t=Dt(),r=t?Gr(t)?.session??null:null;return{spend:ll(e,t,n,Z(process.env,Ei())),unheard:r!==null&&$t(e,n,r).length>0}}import{createHash as fa}from"crypto";import{accessSync as pa,closeSync as ga,constants as ha,openSync as ma,readdirSync as Go,readFileSync as ya,rmSync as wa}from"fs";import{homedir as ba}from"os";import{basename as Vo,dirname as ka,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 Ro,randomBytes as Oo}from"crypto";import{readdirSync as Eo,renameSync as jl,unlinkSync as zp}from"fs";import{join as bn}from"path";import{createHmac as $l,randomBytes as Gt,timingSafeEqual as _l}from"crypto";import{closeSync as yo,existsSync as xl,fsyncSync as wo,linkSync as Sl,mkdirSync as bo,openSync as ko,readdirSync as Al,readFileSync as Ge,unlinkSync as vo,writeSync as $o}from"fs";import{basename as Cl,dirname as go,join as he}from"path";var ge={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function pl(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${hl(l)}\x1B[0m`}}var mf=pl(!1),gl=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function hl(e){return e.replace(gl,"")}var uo=[{id:"protect",verdict:"block",short:"wiping your home folder or the project",slugs:["protected"]},{id:"protect-main",verdict:"block",short:"force-pushing main",slugs:["protected"]},{id:"protect-processes",verdict:"block",short:"killing every process",slugs:["protected"]},{id:"keep-work",verdict:"hold",short:"throwing away uncommitted work",slugs:["uncommitted"]},{id:"stay-in-project",verdict:"hold",short:"deletes outside your project",slugs:["outside-folder"]},{id:"stay-out-of-prod",verdict:"hold",short:"changes aimed at production",slugs:["prod-changes"]},{id:"keep-anvil-on",verdict:"hold",short:"changes to Anvil",slugs:["agent-controls"]},{id:"stop-loops",verdict:"hold",short:"delete bursts and repeats",slugs:["delete-burst","repeat"]},{id:"stop-helper-bursts",verdict:"hold",short:"helper bursts",slugs:["helper-burst"]},{id:"keep-keys-in",verdict:"hold",short:"use of your account keys",slugs:["credentials","secrets-expose"]},{id:"keep-env-out",verdict:"hold",short:"showing secrets files in the chat",slugs:["env-in-chat"]},{id:"hold-unchecked",verdict:"hold",short:"actions it can't check",slugs:["could-not-check","too-long-to-check"]}],ml="home and project wipes and force-pushes to main",$f=`always blocking ${ml}`,_f=new Map(uo.map(e=>[e.id,e]));var yl=new Set(uo.flatMap(e=>e.slugs));var Wt=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:"throw away git work"},"claude.bash.db.destructive":{slug:"db-destroy",text:"destroy database data"},"claude.bash.deploy":{slug:"deploy",text:"deploy"},"claude.bash.publish":{slug:"publish",text:"publish a package or release"},"claude.bash.secrets.print":{slug:"secrets-print",text:"print secrets"},"claude.bash.privilege":{slug:"sudo",text:"run as root, or run code it cannot read"},"claude.bash.process.kill_by_name":{slug:"kill",text:"kill processes by name or port"},"claude.bash.external_write":{slug:"external-write",text:"write to an external API"},"claude.bash.spend":{slug:"spend",text:"start paid compute"},"claude.bash.secrets.expose":{slug:"secrets-expose",text:"commit or send a secrets file"},"claude.bash.net.expose":{slug:"net-expose",text:"open this machine to the internet"},"claude.bash.data.export":{slug:"data-export",text:"copy a remote database here"},"claude.bash.crypto.transaction":{slug:"crypto",text:"send a transaction on a real chain"},"claude.bash.persistence":{slug:"persistence",text:"install background jobs or global git hooks"},"claude.bash.deps.add":{slug:"new-dependency",text:"add a new dependency"},"claude.bash.prod.target":{slug:"production",text:"use a production account"},"claude.agent.controls":{slug:"agent-controls",text:"change its own permissions, hooks or rules"},"claude.agent.helper":{slug:"helper-agent",text:"launch a helper agent"},"claude.file.write_secret":{slug:"secret-file-write",text:"write a secrets file"},"claude.file.read_secret":{slug:"secret-file-read",text:"read a secrets file"},"claude.file.outside_project":{slug:"outside-project",text:"change files outside the project"},"claude.mcp.side_effect":{slug:"mcp-write",text:"MCP tool that changes something"},"claude.mcp.call":{slug:"mcp-read",text:"MCP tool call"},"claude.bash.unclassified":{slug:"other",text:"command"},"claude.tool.other":{slug:"tool",text:"tool call"}});var Ht="anvil-claude";function K(e){let n=e.trim();return n===Ht||n.endsWith(` ${Ht}`)||n.endsWith(`/${Ht}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(n)||/(^|\s)claude$/.test(n)?n:`${n} claude`}var co="\u{1F539}",T=e=>`${co} ${e} ${co}`;var mn=e=>`
|
|
14
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
|
|
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
|
|
17
|
-
`,"wx");let o=!1;try{n?tn(r,t):
|
|
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(
|
|
19
|
-
`;Je(e.modes,r),Je(qe(e,Gn),r)}}function
|
|
20
|
-
`;Je(n,s),r&&Je(qe(e,r),s)}var Gn="modes.json"
|
|
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
|
|
22
|
-
`);let r=t.ok?
|
|
23
|
-
`)}catch{}return a}var
|
|
24
|
-
`)}catch{}}function
|
|
25
|
-
`)){let[s,i,a
|
|
26
|
-
${
|
|
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?
|
|
28
|
-
|
|
29
|
-
`}
|
|
30
|
-
`
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
`
|
|
34
|
-
`
|
|
35
|
-
|
|
36
|
-
`
|
|
37
|
-
`);for(let
|
|
38
|
-
`
|
|
15
|
+
${n}${t?mn(`Then ${t}.`):""}`}var Ut=e=>mn(e),wl=72;function Kn(e,n){let t=`To ${e}, run in a terminal: ${n}`;return t.length+5<=wl?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 bl="anvil";var ke=e=>`${K(bl)} ${e}`;import{spawnSync as ep}from"child_process";import{createHash as tp}from"crypto";import{chmodSync as op,existsSync as sp,lstatSync as ip,mkdirSync as lp,readdirSync as ap,readFileSync as up,readlinkSync as dp,realpathSync as cp,rmdirSync as fp,statSync as pp,unlinkSync as gp,writeFileSync as hp}from"fs";import{dirname as yp,isAbsolute as wp,join as bp,relative as kp,resolve as vp}from"path";var Bt="locks.json";var fo="Tip: model: smart \u2014 Sonnet works, Opus advises (Anthropic: ~12% cheaper per coding task)";var zt={haiku:1,sonnet:2,opus:3,fable:4,mythos:4},kl=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 Kt(e,n){let t=Ce(n);if(!t)return null;if(zt[t.family]<kl)return`${t.label} can't be an advisor`;let r=Ce(e);return r&&zt[t.family]<zt[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()),vl=[["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=vl.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 Jt="Claude Code didn't attach the advisor for this account (its rollout, your plan's credits, or a telemetry setting)";function po(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=Kt(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:Jt,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 qt(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 q(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 Zt(e){return q(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 Rl(e){let n=q(e);if(n)return n;let t=Zt(e);if(t==="damaged"||Xt(e))throw new Vn(`${Zn(e,t)}; run ${ke("on")} to restore it`);let{key:r,created:o}=Ol(e,!1);return o&&El(e,r),r}function ho(e,n,t){let r=ko(e,t,384);try{$o(r,n),wo(r)}finally{yo(r)}}function Ol(e,n){bo(e.dir,{recursive:!0,mode:448});let t=Yn(e),r=he(e.dir,`.seal.key.${process.pid}.${Gt(4).toString("hex")}.tmp`);ho(r,`${Gt(32).toString("hex")}
|
|
17
|
+
`,"wx");let o=!1;try{n?tn(r,t):Sl(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{ho(t,Ge(r,"utf8"),"wx"),o=!0}catch(l){if(l.code!=="EEXIST")throw l}}}finally{try{vo(r)}catch{}}let s=q(e);if(!s)throw new Vn(`${Zn(e,"damaged")}; run ${ke("on")} to restore it`);return{key:s,created:o}}function El(e,n){let t=[[e.modes,Gn],[e.compiled,xo],[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;r===e.modes&&delete i.turned_off;let a=`${JSON.stringify(Yt(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(Yt(n,gt()),null,2)}
|
|
19
|
+
`;Je(e.modes,r),Je(qe(e,Gn),r)}}function Vt(e,n=0){if(n>64)throw new Error("nested too deep to seal");return Array.isArray(e)?`[${e.map(t=>Vt(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)}:${Vt(e[r],n+1)}`).join(",")}}`:JSON.stringify(e??null)}function _o(e,n){return $l("sha256",e).update(Vt(n)).digest("hex")}function qn(e){if(!(me in e))return e;let n={...e};return delete n[me],n}function Yt(e,n){let t=qn(n);return{...t,[me]:_o(e,t)}}function Nl(e,n){let t=n[me];if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))return!1;let r;try{r=_o(e,n)}catch{return!1}return _l(Buffer.from(t,"hex"),Buffer.from(r,"hex"))}function Je(e,n,t=384){bo(go(e),{recursive:!0,mode:448});let r=he(go(e),`.${Cl(e)}.${process.pid}.${Date.now().toString(36)}.${Gt(3).toString("hex")}.tmp`);try{let o=ko(r,"w",t);try{$o(o,n),wo(o)}finally{yo(o)}tn(r,e)}catch(o){try{vo(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?Nl(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=Rl(e),s=`${JSON.stringify(Yt(o,t),null,2)}
|
|
20
|
+
`;Je(n,s),r&&Je(qe(e,r),s)}var Gn="modes.json",xo="compiled.json";function Xt(e){return xl(he(e.bin,"claude-hook.sh"))||Ml(e)}function Ml(e){let n=t=>{try{return Al(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 So=ne({missing:"is missing",unreadable:"cannot be read",unsealed:"was changed outside Anvil",changed:"was changed outside Anvil"});function mo(e=new Date){return $r(null,"enforce","all",e)}function wn(e,n=q(e),t={}){if(!n){let i=Zt(e);if(t.installed===!0||i==="damaged"||Xt(e))return{value:mo(),source:"strict",problem:`${Zn(e,i)}, so every rule is enforced until \`${ke("on")}\` restores it`};let a=X(e.modes,null);if(a.status!=="unkeyed")return{value:null,source:"unkeyed",problem:null};let{turned_off:l,...u}=a.value;return{value:u,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 ${So[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:mo(),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=q(e),r={}){let o=u=>!!u&&typeof u=="object"&&u.format===wt&&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=Zt(e),d=r.installed===!0||u==="damaged"||Xt(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":So[i.status]??"cannot be used"}`,l=X(qe(e,xo),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 Gp=600*1e3,Pl=1440*60*1e3,Ao="23456789abcdefghjkmnpqrstuvwxyz",Co=8;function Oe(e){return bn(e.state,"pending")}function Tl(){let e=Oo(Co),n="";for(let t=0;t<Co;t++)n+=Ao[e[t]%Ao.length];return n}function Ll(e){return Ro("sha256").update(e.trim().toLowerCase().replace(/[\s-]/g,"")).digest("hex")}var Il=()=>Oo(8).toString("hex"),Dl=e=>`${Ro("sha256").update(e??"").digest("hex").slice(0,12)}.`;function No(e,n,t){let r=Tl(),o=Il();O(Oe(e));let s={v:2,id:o,code_sha256:Ll(r),...n,created_at:new Date(t).toISOString(),expires_at:new Date(t+Pl).toISOString()};return Xn(e,bn(Oe(e),`${Dl(n.session)}${o}.json`),s),{code:r,id:o}}function Fl(e,n){return e.kind===n.kind&&(e.target??null)===(n.target??null)}function Mo(e,n,t){let r=[];try{r=Eo(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 jo(e,n,t,r,o,s,i=!0){let a=[];try{a=Eo(e.approvals).filter(u=>u.endsWith(".json")&&!u.includes(".used-")).slice(0,2e3)}catch{return{approved:!1,forged:0}}let l=0;for(let u of a){let d=bn(e.approvals,u),c=X(d,n,64*1024);if(c.status==="missing")continue;if(c.status!=="ok"||c.value.v!==2||!Array.isArray(c.value.stops)){l++;continue}let f=c.value;if(Date.parse(f.expires_at)>=s&&!((f.session??null)!==(t??null)||(f.project??null)!==(r??null))&&o.every(g=>f.stops.some(m=>Fl(m,g)))){if(!i)return{approved:!0,forged:l};try{return jl(d,bn(e.approvals,`${u.slice(0,-5)}.used-${s}-${process.pid}.json`)),{approved:!0,forged:l}}catch{}}}return{approved:!1,forged:l}}import{spawn as Wl,spawnSync as Po}from"child_process";import{closeSync as Hl,openSync as Ul,readdirSync as Bl,readlinkSync as zl,statSync as To,unlinkSync as Lo,writeSync as Kl}from"fs";import{delimiter as Jl,isAbsolute as ql,join as Ee}from"path";var Gl=5*6e4,Qt=2*6e4,Io=3,Vl=15*6e4,Yl=6*36e5,Do=3e4,Zl=6e4,Xl=["-p","/usage","--output-format","stream-json","--verbose","--no-session-persistence","--setting-sources","project","--settings",'{"autoMemoryEnabled":false}',"--strict-mcp-config","--model","anvil-reads-usage-only"],Fo="ANVIL_PLAN_PROBE",Wo=(e,n)=>Ee(e.state,`plan-probe-${n}.json`),er=(e,n)=>Ee(e.state,`plan-probe-next-${n}`),Ho=e=>Ee(e.state,"plan-probe.lock"),Ql=e=>Ee(e.dir,"plan-probe");function Uo(e,n){let t=n?[Wo(e,n)]:ea(e),r=null;for(let o of t){let s=P(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 ea(e){try{return Bl(e.state).filter(n=>/^plan-probe-[ac][0-9a-f]{16}\.json$/.test(n)).map(n=>Ee(e.state,n))}catch{return[]}}function na(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 ta(e,n=ra,t=!1){let r=a=>{try{return a&&ql(a)&&To(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(Jl)){let l=a?r(Ee(a,"claude"))??(process.platform==="win32"?r(Ee(a,"claude.exe")):null):null;if(l)return l}return null}function ra(e){try{return zl(`/proc/${e}/exe`)}catch{}try{let n=Po("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 oa(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[Fo]="1",t.DISABLE_AUTOUPDATER="1",t}var sa=(e,n,t)=>{let r=Po(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 ia(e,n){let t=Ho(e);for(let r=0;r<2;r++)try{let o=Ul(t,"wx",384);return Kl(o,String(n)),Hl(o),!0}catch(o){if(o.code!=="EEXIST")return!1;let s=Number(J(t,64).trim());if(Number.isFinite(s)&&n-s<Zl&&s<=n+6e4)return!1;try{Lo(t)}catch{return!1}}return!1}function la(e){try{Lo(Ho(e))}catch{}}function aa(e){try{if(O(e.paths.state),!ia(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<Qt)return null;let t=ua(e);if(e.screen&&!t.ok)return t;W(Wo(e.paths,e.account.key),`${JSON.stringify(t)}
|
|
22
|
+
`);let r=t.ok?Qt:t.why==="noplan"||t.why==="unavailable"||t.why==="nobinary"?Yl:Vl;return W(er(e.paths,e.account.key),String(e.now()+r)),t}finally{la(e.paths)}}catch{return null}}function ua(e){let n=e.binary??ta(e.env,e.exeOf);if(!n)return{at:e.now(),ok:!1,why:"nobinary"};let t=Ql(e.paths);O(t);let r=(e.run??sa)(n,Xl,{cwd:t,env:oa(e.env),timeout:Do}),o=e.now();if(r.error||r.status===null)return{at:o,ok:!1,why:"failed"};let s=na(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=jt(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 Bo="ANVIL_PLAN_PROBE_FOR";function zo(e){try{if(e.env[Fo]==="1"||!e.env.CLAUDE_CODE_EXECPATH&&!e.env.CLAUDE_PID)return!1;let n=e.near?Qt:Gl;if(e.readingAt!==null&&e.now-e.readingAt<n&&e.readingAt<=e.now+6e4)return!1;let t=Number(J(er(e.paths,e.account.key),64).trim());if(Number.isFinite(t)&&t>e.now&&t-e.now<=24*36e5)return!1;try{To(e.hookFile)}catch{return!1}return O(e.paths.state),W(er(e.paths,e.account.key),String(e.now+Do+5e3)),(e.start??da)(e.node,[e.hookFile,"--plan-probe"],e.paths.dir,{...e.env,[Bo]:`${e.account.key}|${e.account.cfg}`}),!0}catch{return!1}}function da(e,n,t,r){let o=Wl(e,n,{detached:!0,stdio:"ignore",cwd:t,env:r,windowsHide:!0});o.on("error",()=>{}),o.unref()}function ca(e){let n=/^([ac][0-9a-f]{16})\|([0-9a-f]{16})$/.exec(e[Bo]??"");return n?{key:n[1],cfg:n[2]}:null}function Yo(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 tr=36e5,va=/^[A-Za-z0-9._-]{1,128}$/,$a=.8;function ir(e){return(e?.policies??[]).flatMap(n=>n.budgets??[])}var $e=e=>ee(e.dir,"meter"),Zo=(e,n)=>ee($e(e),"tasks",`${n}.json`),lr=e=>e!==null&&va.test(e)&&e!=="."&&e!=="..";function vn(e,n){if(!lr(n))return null;let t=X(Zo(e,n),q(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 Xo(e,n,t){lr(n)&&(O(ee($e(e),"tasks")),Xn(e,Zo(e,n),t))}var Qo=(e,n,t)=>e.window==="day"?le(n):e.window==="week"?cn(n):e.window==="task"?t?.t??Number.NaN:Number.NaN;function es(e,n){try{if(e.unit==="plan"){if(n.apiKey||Tt(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||!lr(n.session)))return{budget:e,used:null,why:"task"};let t=Qo(e,n.now,n.task),r=e.window==="task"?n.own():n.unread.left>0&&n.unread.upto>=t?n.unread.left:0;return Ia(e,n.totals(t,e.window==="task"?n.session:null),r)}catch{return{budget:e,used:null,why:"meter"}}}var _a=.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")}},nr=1e4,xa=.5,Sa=3e5,Ko=2.25;function Aa(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=P(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 Ca=9e4,Ra=1e4,$n=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 Oa(e,n,t){try{O(_n(e)),W(ee(_n(e),`${$n(n)}.json`),`${JSON.stringify(t)}
|
|
24
|
+
`)}catch{}}function Ea(e,n,t){let r=new Map,o=`${$n(n)}.json`,s=[];try{s=Go(_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=P(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 Na(e){if(!e.session)return null;let n=e.payload,t=n.tool_name==="Agent"||n.tool_name==="Task",r=io(e.paths,e.session,e.now,t?7:0),o=vn(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?so(e.transcript??null)??r.chatPrompt:r.chatPrompt,g=Math.max(nr,Math.round((f??0)*xa)),m={usd:xe(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)<Sa,k=t?Aa(e.paths,{warm:r.helperFirstWarm,cold:r.helperFirstCold}):{warm:r.helperFirstWarm,cold:r.helperFirstCold},y=k.warm?{usd:Ko*k.warm.usd,fresh:Math.round(Ko*k.warm.fresh)}:null,$=h?k.warm??k.cold:k.cold??y,x=V=>$?.[V]??m[V],_={usd:x("usd")+d.usd+l.usd,fresh:x("fresh")+d.fresh+l.fresh},v=u?ve(ve(Ne,u,2),l):_,E=s!==null&&o!==null&&r.lastMainAt!==null&&r.lastMainAt<o,C=s?E&&r.chatRecent?r.chatRecent:Ne:r.chatFirst??{usd:xe(c,{input:0,output:0,write5m:nr,write1h:0,read:0}),fresh:nr},N=ve(C,l,2),M={v:1,t:e.now,transcript:e.transcript??null,chat:N,perRunning:v,each:_},R=P(ee(_n(e.paths),`${$n(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<Ra&&D(R)||Oa(e.paths,e.session,M),i&&ts(e.paths,e.session,i,e.now);let H=$n(e.session),j=ja(e.paths,e.now),G=i?j.findIndex(V=>V.s===H&&V.id===i.replace(/\s/g,"_")):-1,w=G>=0?j.slice(0,G):j,b=(V,Te,Le)=>{let ft=lo(Te,e.now),pt=w.filter(fe=>fe.s===V),si=pt.length>0?Math.min(...pt.map(fe=>fe.t))-2e3:1/0,ii=Math.max(0,pt.length-ft.filter(fe=>fe.started>=si).length),li=ft.filter(fe=>fe.state==="running").length,ai=ft.filter(fe=>fe.state==="starting").length;return ve(ve(Ne,Le.perRunning,li),Le.each,ai+ii)},L=ve(N,b(H,e.transcript??null,{perRunning:v,each:_})),A=Ea(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:_});let Q=Ne,ce=0;for(let[V,Te]of A){let Le=ve(Te.t>=e.now-Ca?Te.chat:Ne,b(V,Te.transcript,Te));(Le.fresh>0||Le.usd>0)&&(Q=ve(Q,Le),ce++)}return{running:L,others:Q,otherSessions:ce,launches:t?_:null,guess:t&&!$,parts:{underWay:C.fresh,chat:l.fresh,first:x("fresh"),helper:d.fresh,warm:h,pending:L.fresh-N.fresh}}}var Ma=2e4,ns=e=>ee($e(e),"launches","all.log");function ja(e,n){let t=[];for(let r of J(ns(e),64*1024).split(`
|
|
25
|
+
`)){let[o,s,i,a]=r.split(" "),l=Number(o);if(!s||!i||!(l>n-Ma&&l<=n+6e4))continue;let u=t.findIndex(d=>d.s===s&&d.id===i);a==="x"?u>=0&&t.splice(u,1):u<0&&t.push({s,id:i,t:l})}return t}function ts(e,n,t,r,o=!1){try{let s=ns(e);O(ka(s)),se(s,`${r} ${$n(n)} ${t.replace(/\s/g,"_")}${o?" x":""}`)}catch{}}function Pa(e){let n=e.payload;e.session&&(n.tool_name==="Agent"||n.tool_name==="Task")&&typeof n.tool_use_id=="string"&&ts(e.paths,e.session,n.tool_use_id.slice(0,128),e.now,!0)}function Ta(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??=Na(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),_a*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 La(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 rs(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=>Qo(d,e.now,t)).filter(d=>Number.isFinite(d)));Number.isFinite(u)&&(o=Ft(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?no(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=Ta(e,n.map(u=>es(u,a)),r);La(e,r,l);try{if(e.probe&&!a.apiKey&&n.some(u=>u.unit==="plan")&&!Tt(e.paths,e.session)&&!Xr(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-Io&&f.pct<c.limit});zo({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 Ia(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'"},rr=(e,n=1e3)=>`$${e<n?e.toFixed(2):String(Math.round(e)).replace(/\B(?=(\d{3})+(?!\d))/g,",")}`,tt=e=>Number.isInteger(e)?rr(e,0):rr(e),ar=(e,n,t=1e3)=>{let r=rr(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 Da=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",je=e=>e.early&&(e.used??0)<e.budget.limit?e.early.why:null,ot=e=>je(e)?"nearly spent":"spent",or=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${or(e)} could pass it`,next:`, and the next replies${or(e)} could pass it`,launch:"",advisor:""})[je(e)??"launch"]??"",Fa=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?` (${Mr(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(je(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(je(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 ${Fa(e)} and${o?"":`, with what's running${or(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 Wa(e,n,t,r){return`${e.why==="large"?`${T("Your budget can't be counted")} ${e.budget.text} \xB7 ${rt}`:`${T(`${Da(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 Jo(e){let n=e.budget;if(n.unit==="plan")return`${T("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`${T("Anvil")} ${r} of ${ye[n.window]} ${o} used`}var qo={plan:"there is no reading of your plan yet",meter:"Anvil's meter can't be read right now",large:rt};function Ha(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 os(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 (${ao(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: ${qo.plan}`;default:return`can't be measured here: ${qo.meter}`}}function mg(e,n){try{let r=JSON.parse(ya(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 Pe(e,n){let t=ee($e(e),"said");try{return O(t),ga(ma(ee(t,fa("sha256").update(n).digest("hex").slice(0,32)),"wx")),!0}catch(r){return r.code!=="EEXIST"}}function ss(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?Ha(Uo(e.paths,Ue(e.transcript,e.paths).key)):void 0;if(l===null||!Pe(e.paths,`unmeasured|${e.session??"-"}|${i.id}|${s.why??"meter"}`))continue;o.push(s.why==="task"?`${T("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`:`${T("Anvil")} your budget ${i.text} ${l??os(s)} \xB7 not enforced`);continue}if(s.used<i.limit*$a||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);Pe(e.paths,`near|${i.id}|${a}`)&&o.push(r?Jo(s):`${Jo(s)}
|
|
26
|
+
${fo}`)}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?Vo(e.project):null,...s?{hold:s}:{},path:"none",ms:0}))}catch{}}function is(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 Ua=36e5;function ls(e,n,t,r){if(e.id!==n.budget.id||!(t<e.end)||e.end-t>tr)return!1;let o=is(n,t,r);return(n.budget.unit==="plan"?Math.abs(o-e.w)>Ua:o!==e.w)?!1:e.at===null||n.used===null||n.used<e.at+n.budget.limit}function Ba(e){try{let n=Oe(e);return O(n),pa(n,ha.W_OK),!0}catch{return!1}}var as=(e,n)=>`${Oe(e)} can't be written: fix its permissions, or run in a terminal: ${K(n)} on`,us=(e,n,t)=>`${T("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 ds(e,n,t){try{return jo(e.paths,q(e.paths),e.session,e.project,[{kind:"claude.budget",target:n.budget.id}],e.now,t).approved}catch{return!1}}function cs(e,n,t,r){if(!ds(e,n,!0))return!1;try{for(let{hold:o,file:s}of Mo(e.paths,q(e.paths),e.now))o.session===e.session&&o.stops.length>0&&o.stops.every(i=>i.kind==="claude.budget"&&i.target===n.budget.id)&&wa(s,{force:!0})}catch{}try{let o=t?null:r?.until!==void 0&&e.now<r.until?r.until:e.now+tr,s=(r?.passes??[]).filter(a=>a.id!==n.budget.id&&e.now<a.end),i={id:n.budget.id,w:is(n,e.now,t),at:n.used,end:e.now+tr};Xo(e.paths,e.session,{v:1,t:t?.t??e.now,passes:[...s,i],...o!==null?{until:o}:{}})}catch{}return!0}function sr(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 fs(e,n){return e.why==="large"?`${T("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 ${sr(e,n)}`:`${T("Anvil")} going on ${je(e)?`near ${ye[e.budget.window]} budget`:`past ${ye[e.budget.window]} budget`}, as you said: ${Me(e)}${Ye(e)} \xB7 for this task, ${sr(e,n)}`}function za(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 (${sr(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 Ka=new Set(["SubagentHandback","mcp__ccd_turn__wrap_up","mcp__ccd_turn__update_plan"]);function Ja(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 ps(e){if(Ka.has(String(e.payload.tool_name??"")))return null;try{let n=Yo(e),t=ir(n.table);if(t.length===0)return null;let r=vn(n.paths,n.session),o=Date.parse(n.table?.compiled_at??""),s=r&&r.until===void 0&&!(o>r.t)?r:null,i=Ja(rs(n,t,s,"action"),e.advisor),a=r&&(r.until===void 0||n.now<r.until)?r.passes??[]:[],l=p=>a.some(h=>ls(h,p,n.now,s)),u=[],d,c=r;for(let p of i.filter(h=>et(h)&&!l(h))){if(!cs(n,p,s,c)){d=p;break}nt(n,p,"PreToolUse","claude.budget","approved",null),u.push(fs(p,n.now)),c=vn(n.paths,n.session)??c}let f=()=>{for(let p of i)et(p)&&l(p)&&nt(n,p,"PreToolUse","claude.budget","passed",null)},g=u.length>0?{note:u.join(`
|
|
28
|
+
`)}:{};if(d){let p=xn(d,n.now);if(Pa(n),!Ba(n.paths))return{note:[...u,us(d,n.now,as(n.paths,n.cli))].join(`
|
|
29
|
+
`)};let h=d.budget.id,k=d.why==="large"?"the user's budget can't be counted":je(d)==="launch"?"the helpers starting could pass the user's budget":`the user's budget is ${ot(d)}`,y=je(d)==="advisor"?`asking the advisor about this ${d.early?.advisor?.about??"call"} first would pass the user's budget, so it waits for their OK. Don't ask the advisor`:`${k}, so every action waits for their OK`,$={user:`${T("Held by Anvil for your OK")} ${p}${be("keep going",`${K(n.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${T("Held by Anvil")} ${p}. Nothing ran: ${y}. 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{...g,stop:{action:"claude.budget",target:h,decision:{verdict:"hold",policy:"budgets",origin:null,ruleId:"budget",blockedBy:"budget_reached",source:d.budget.source},mode:"enforce",floor:null,why:p,said:$}}}if(f(),u.length>0)return g;let m=ss(n,i.filter(p=>!l(p)),s,Ke(n.table));return m?{note:m}:null}catch{return null}}function yg(e){try{if(zn(e.payload))return null;let n=Yo(e),t=q(n.paths),r={installed:n.installed===!0},o=n.table??Re(n.paths,n.fallbackTable,t,r).value,s=ir(o);if(s.length===0)return null;let i={v:1,t:n.now};try{Xo(n.paths,n.session,i)}catch{}if(wn(n.paths,t,r).value?.kill_switch===!0)return null;let a=rs(n,s.filter(f=>f.window!=="task"),i,"message"),l=a.filter(et),u=l.find(f=>!ds(n,f,!1)),d=[];if(!u){let f=i;for(let g of l){if(!cs(n,g,i,f)){u=g;break}nt(n,g,"UserPromptSubmit","claude.prompt","approved",null),d.push(g),f=vn(n.paths,n.session)??f}}if(!u&&d.length>0)return`${JSON.stringify({systemMessage:d.map(f=>fs(f,n.now)).join(`
|
|
30
|
+
`),hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:d.map(f=>za(f,n.cli,n.now)).join(`
|
|
31
|
+
`)}})}
|
|
32
|
+
`;if(u){let f;try{f=No(n.paths,{session:n.session,project:n.project,stops:[{kind:"claude.budget",target:u.budget.id}],why:xn(u,n.now),project_name:n.project?Vo(n.project):null,command:"your next message (Anvil never reads it)"},n.now)}catch(g){let m=g.code;return`${JSON.stringify({systemMessage:us(u,n.now,m==="ENOSPC"||m==="EDQUOT"?"the disk is full: free some space":as(n.paths,n.cli))})}
|
|
33
|
+
`}return nt(n,u,"UserPromptSubmit","claude.prompt","deny",f.id),`${JSON.stringify({decision:"block",reason:Wa(u,n.now,n.cli,f.code)})}
|
|
34
|
+
`}let c=ss(n,a,i,Ke(o));return c?`${JSON.stringify({systemMessage:c})}
|
|
35
|
+
`:null}catch{return null}}function qa(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 ${It(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 Ga(e,n){let t=[],r=[];try{r=Go(ee($e(e),"tasks"))}catch{return t}for(let o of r){if(!o.endsWith(".json"))continue;let s=vn(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 wg=(e,n)=>Wn(Z(e,n));function bg(e,n,t,r){let o=ir(n);if(o.length===0)return[];let s=r??Wn(Z(process.env,ba())),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=es(d,a),f=d.unit==="plan"&&c.used!==null?` \xB7 ${It(c.age??0)}`:"",g;if(et(c))for(let{pass:m,task:p}of u??=Ga(e,t))ls(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?os(c):`${Me(c)}${Ye(c)} \xB7 ${Ve(c,t)}${f}`,short:qa(c),...c.why?{why:c.why}:{},...c.age!==void 0?{age:c.age}:{},...g!==void 0?{okUntil:g}:{}})}return l}import{execFileSync as Va}from"child_process";import{readdirSync as ws,rmSync as cr,statSync as it}from"fs";import{basename as Ya,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,bs=e=>e==="sdk"||e.startsWith("repl_main_thread"),ks=e=>Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.startsWith("context-1m-"));function Cn(e,n){return Za(e,n)?.model??null}function Za(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=J(r,s),a=i?i.split(`
|
|
36
|
+
`):[];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&&!bs(c))continue;let f=B(d.params?.model),g=typeof d.timestamp=="string"?Date.parse(d.timestamp):Number.NaN;if(f)return{model:ks(d.params?.betas)&&!/\[1m\]$/i.test(f)?`${f}[1m]`:f,at:g}}catch{}}if(o<=s)break}return null}var Sn=500,Xa=3e3,Qa="<synthetic>",eu=/"version":"(\d{1,6}\.\d{1,6}\.\d{1,6})"/,vs=e=>typeof e.timestamp=="string"?Date.parse(e.timestamp):Number.NaN;function gs(e,n){try{let t=JSON.parse(e);if(t.type!=="api-request"||!n&&!bs(typeof t.querySource=="string"?t.querySource:""))return null;let r=B(t.params?.model);return r?{model:ks(t.params?.betas)&&!/\[1m\]$/i.test(r)?`${r}[1m]`:r,id:B(t.id),at:vs(t)}:null}catch{return null}}function hs(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===Qa)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:vs(r),fallback:a}}catch{return null}}var nu=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"&&nu.has(n.subtype):n.type!=="user"?!1:typeof n.permissionMode=="string"||typeof n.message?.content=="string"}catch{return!1}}function $s(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=J(e,s),a=i?i.split(`
|
|
37
|
+
`):[],l=null,u=null,d=!1,c=!1,f=null,g=null,m=-1,p=[];for(let x=a.length-1;x>=0;x--){let _=a[x];if(g===null&&_.includes('"version":"')&&(g=eu.exec(_)?.[1]??null),l===null){if(_.includes('"assistant"')){let v=hs(_,t,n);v&&p.push({...v,i:x})}else _.includes('"api-request"')?(l=gs(_,n),l&&(m=x)):p.length===0&&dr(_)&&(c=!0);continue}if(_.includes('"assistant"')){let v=hs(_,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(_.includes('"api-request"')){let v=gs(_,n);if(v){u={model:v.model,at:v.at,reply:!1};break}}else dr(_)&&(d=!0)}let h=null,k=x=>{for(let _=m+1;_<x;_++)if(dr(a[_]))return!0;return!1},y;for(let x of p)x.own&&(y=x);l&&p.some(x=>x.ref!==null&&x.ref!==l.id&&(x===y||k(x.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 ms(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 _s(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=ms(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=ms(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||tu(r)&&!n(s))?{id:s.model,how:"one",version:r}:{id:null,how:"none",version:r}}function tu(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 xs=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 ru(e,n,t=Ze,r=e.wait??xs){let o=$s(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&<(e.env)&&a(i)){let l=e.startedAt??(e.wait?null:Date.now()-process.uptime()*1e3),u=Math.min(Date.now()+Sn,l===null?Number.POSITIVE_INFINITY:l+Xa);for(let d=0;d<Sn/20&&Date.now()<u&&(r(20),i=fr(o,n!==null,s),!!a(i));d++);}return _s(i,l=>n===null&&Ss(e,l.at,t),n!==null)}function Ss(e,n,t){if(!Number.isFinite(n))return!0;let r=Os(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(Ns(e)))return!0;let s=Es(e.env,t);return s!==null&&s.at-1e3>n||o(s?.model)}function ou(e,n,t,r=null,o=!1){let s=B(e.payload.session_id),i=s?vt(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)}:{}})}
|
|
38
|
+
`);for(let l of ws(a)){let u=ae(a,l);l.endsWith(".json")&&e.now-it(u).mtimeMs>kt&&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 su(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 An=(e,n)=>e.model===n.family&&(!e.one_m||n.oneM);function As(e,n=Ze){try{let t=pr(e.table,e.projectDir??null),r=e.kinds??[],o=su(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=ru(e,i,n,o.length>0?e.wait??xs: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=>An(k,u));h&&Pe(e.paths,`model-never|${s}|${h.id}`)&&d.push(`${T("Anvil")} this session runs on ${u.label}, which your rules say never (${st(h.source)})${Ut("Switch it: the model picker, or /model.")}`)}let f,g=(h,k,y,$)=>({action:r.find(x=>h.kinds.includes(x)),decision:{verdict:"hold",policy:"models",origin:null,ruleId:"model",blockedBy:"model_rule",source:h.source},mode:"enforce",floor:null,why:k,said:{user:`${T("Held by Anvil for your OK")} {why}${be("allow it once",`${K(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${T("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(($,x)=>o.findIndex(_=>_.model===$.model)===x),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(`${T("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];Pe(e.paths,`model-unknown|${s}|${i??""}|${h.id}`)&&d.push(`${T("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(x=>An(x,{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&&ou(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(`
|
|
39
|
+
`)}:{}}}catch{return null}}function Pg(e){try{let n=q(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 ys(e,u&&l&&!/\[1m\]$/i.test(u)?`${u}[1m]`:u),null;let d=a?o.never.find(m=>An(m,{family:a.family,oneM:l})):void 0,c=wn(e.paths,n,t).value?.kill_switch===!0;if(!d||c||!a)return ys(e,u&&l&&!/\[1m\]$/i.test(u)?`${u}[1m]`:u),null;let f=`${a.label.replace(/ 1M$/,"")}${l?" 1M":""}`,g=`${T("Anvil")} your rules say ${d.text} \xB7 change it in a terminal: ${K(e.cli)} rules edit`;return Cs(e,d,f,"switch"),`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreModelSwitch",permissionDecision:"deny",permissionDecisionReason:g}})}
|
|
40
|
+
`}catch{return null}}function Cs(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?Ya(s):null,path:"none",ms:0}))}catch{}}var Rs=/^[A-Za-z0-9_-]{1,80}$/,iu=7*864e5;function ys(e,n){let t=B(e.payload.session_id);if(!(!t||!Rs.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})}
|
|
41
|
+
`);for(let o of ws(r)){let s=ae(r,o);o.endsWith(".json")&&e.now-it(s).mtimeMs>iu&&cr(s,{force:!0})}}catch{}}function Os(e,n){if(!n||!Rs.test(n))return null;let t=P(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 Va("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 Es(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 Ns(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=P(r)?.model;if(typeof o=="string"&&o.trim())return o.trim()}return null}function Tg(e,n=Ze){return Ms(e,n).id}function Ms(e,n=Ze){let t=B(e.payload.session_id),r=Es(e.env,n),o=r?r.at-1e3:Number.NEGATIVE_INFINITY,s=c=>Number.isFinite(c)&&c>=o,i=$s(B(e.payload.transcript_path),null),a=i?fr(i,!1,null):null,l=a?.request&&s(a.request.at)?a.request:null,u=Os(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=_s({...a,request:l},f=>Ss(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())??Ns(e)}}var lu=["opus","sonnet","fable","haiku"];function Lg(e,n=Ze){try{if(zn(e.payload))return null;let t=q(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=Ms(e,n),a=i.id?ue(i.id):null,l=i.other?ue(i.other.model):null,u=p=>p?s.never.find(h=>An(h,p)):void 0,d=u(a)??u(l);if(!d)return null;let c=u(a)?a:l,f=lu.find(p=>!(p===c.family&&!c.oneM)&&!s.never.some(h=>An(h,{family:p,oneM:!1}))),g=`${Ut(`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?`${T("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}`:`${T(`This session is on ${c.label}`)} your rules say ${d.text} (${st(d.source)})${g}`;return Cs(e,d,c.label,"message"),`${JSON.stringify({decision:"block",reason:m})}
|
|
42
|
+
`}catch{return null}}import{closeSync as uu,existsSync as du,fstatSync as cu,openSync as fu,readdirSync as pu,readSync as gu,realpathSync as hu,statSync as mu,unlinkSync as yu}from"fs";import{homedir as at}from"os";import{basename as wu,isAbsolute as gr,join as oe,resolve as hr}from"path";import{createHash as bu}from"crypto";var au=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g;function js(e){return e.replace(au,n=>`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}var Ls=(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,Bt),q(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),Is(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 Is(e){let n="";for(let t=e;t.length>1;)try{return hu.native(t)+n}catch{let r=t.lastIndexOf("/");n=t.slice(r)+n,t=t.slice(0,r)||"/"}return e}var ku=(e,n)=>{let t=Rn(e);return t===n.folded||t.startsWith(n.folded.endsWith("/")?n.folded:`${n.folded}/`)};function Ds(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,Is(m)])){let h=t.find(k=>ku(p,k));if(h)return{lock:h,path:m}}}}return null}function Fs(e){let n=[];for(let t of e.split(`
|
|
39
43
|
`)){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
44
|
`):"",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
45
|
`):"",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
|
|
43
|
-
`).filter(s=>s.includes('"tool_result"')).slice(-6).reverse();for(let s of o){let i=
|
|
46
|
+
${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 vu=e=>/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:bu("sha256").update(e).digest("hex").slice(0,24),Ps=(e,n=200)=>{let t=js(e.slice(0,4096).replace(/\s+/g," ").trim());return t.length>n?`${t.slice(0,n-1)}\u2026`:t},Ts=4*1024*1024;function $u(e,n){return oe(e.state,"locks",`${vu(n)}.json`)}function _u(e,n){if(U(e,Number.MAX_SAFE_INTEGER)!==!0)return null;let t=null;try{t=fu(e,"r");let r=cu(t),s=!n||n.ino!==r.ino||n.off>r.size?0:n.off;r.size-s>Ts&&(s=r.size-Ts);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=gu(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&&uu(t)}}function xu(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:Ws(n,r,e.session,e.transcript,t,e.now)}catch{return 0}}function Ws(e,n,t,r,o,s){let i=$u(e,t),a=P(i),l=a&&a.t===r&&typeof a.off=="number"&&typeof a.ino=="number"&&Array.isArray(a.seen)?a:null,u=_u(r,l);if(!u)return 0;let d=new Set(l?.seen??[]),c=0;for(let f of Fs(u.text)){if(d.has(f.call))continue;let g=n.filter(k=>Ls(k,f.ts)&&(k.project===null||f.cwd!==null&&(f.cwd===k.project||f.cwd.startsWith(`${k.project}/`)))),m=Ds(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:Su,verdict:"block",mode:"enforce",delivered:"deny",rule:m.lock.rule,slug:"locked",policy:null,blocked_by:"sandbox_lock",why:Ps(`locked by your rule: ${m.lock.text} \xB7 the sandbox refused a write to ${p}`,300),target:Ps(p),project:f.cwd?wu(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 Su="claude.sandbox.locked";function Au(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=pu(i).slice(0,5e3)}catch{return 0}let l=c=>{try{return mu(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{yu(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=P(oe(i,c));f&&typeof f.t=="string"&&typeof f.session=="string"&&(s+=Ws(r,o,f.session,f.t,t,n))}return s}catch{return 0}}function Cu(e){try{if(!du(oe(e.anvilDir,Bt)))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 xu({anvilDir:e.anvilDir,transcript:n("transcript_path"),session:n("session_id"),now:e.now,...e.home?{home:e.home}:{}})+(e.sessionStart?Au(e.anvilDir,e.now,e.home):0)}catch{return 0}}function Ru(e,n){let t=Ou(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,prod:a,copy:l,...u}=e,d=e.action!=="claude.bash.unclassified"&&e.action!=="claude.tool.other",c=[...new Set([...d?[e.action]:[],...e.also])].filter(_=>_!=="claude.agent.controls"),{environment:f,environment_said:g,repo_dir:m,repo_remote:p,repo_via:h,...k}=e.attributes,y={...f!==void 0?{environment:f,environment_said:g??null}:{},...h!==void 0?{repo_dir:m??null,repo_remote:p??null,repo_via:h}:{},...a?{prod:a}:{}},$=e.findings??(d?[{action:e.action,service:e.service,target:e.attributes.target,why:e.why,...y,...l?{copy:l}:{}}]:[]),x=[{action:"claude.agent.controls",service:null,target:o.target,why:o.why},...$].slice(0,16);return{...u,action:"claude.agent.controls",service:null,attributes:{...k,target:o.target,branch:null,host:null,is_local:!0},why:o.why,also:c,...x.length>1?{findings:x}:{}}}function Ou(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=J(e.transcript,256*1024).split(`
|
|
47
|
+
`).filter(s=>s.includes('"tool_result"')).slice(-6).reverse();for(let s of o){let i=Fs(s)[0];if(!i)continue;let a=r.filter(c=>Ls(c,i.ts)&&(c.project===null||i.cwd!==null&&(i.cwd===c.project||i.cwd.startsWith(`${c.project}/`)))),l=Ds(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 Js,openSync as qs,readdirSync as ut,readSync as Gs,rmSync as Nu,statSync as dt}from"fs";import{homedir as Vs}from"os";import{basename as Mu,isAbsolute as Us,join as z}from"path";import{statSync as Eu}from"fs";function Hs(e){if(!e||!e.endsWith(".jsonl"))return null;for(let n of[256*1024,4*1024*1024]){let t=J(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=Eu(e).size}catch{return null}if(o<=n)break}return null}var de=e=>typeof e=="string"&&e.length>0?e:null,Bs=/^[A-Za-z0-9_-]{1,80}$/,ju=7*864e5;function Ys(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 Zs(e,n=null){let t;try{t=dt(e).size}catch{return null}let r=n?P(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=qs(e,"r")}catch{return null}try{let u=Buffer.alloc(4194304),d="",c=s;for(;c<t;){let f=Gs(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
48
|
`);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=
|
|
46
|
-
`)}catch{}return i?{attached:a}:null}function
|
|
47
|
-
`)){let t=/"timestamp":"([^"]{1,40})"/.exec(n),r=t?Date.parse(t[1]):NaN;if(Number.isFinite(r))return r}return null}function
|
|
48
|
-
`)){if(!n.includes('"api-request-shape"'))continue;let t=
|
|
49
|
-
`)),d.verdict??null}catch{return null}}function
|
|
49
|
+
`)){if(!p.includes('"api-request-shape"'))continue;let h=Ys(p);h!==void 0&&(i=!0,a=h)}d=g.slice(m+1),s=c-Buffer.byteLength(d)}}finally{Js(l)}if(n)try{W(n,`${JSON.stringify({v:1,file:e,at:s,seen:i,attached:a})}
|
|
50
|
+
`)}catch{}return i?{attached:a}:null}function ct(e,n,t,r){return Xs(e,n,t,r)?.value??null}function Xs(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=P(i)?.[e];if(typeof l=="string"&&l.trim())return{value:l.trim(),from:a}}return null}function Pu(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=P(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?Zs(e.transcript,e.cursor??null):null,t=Xs("model",e.env,e.home,e.project);return po({env:e.env,advisorModel:ct("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?Qs(e.transcript):null}:null,since:e.since??null,seen:e.seen??null})}function wr(e,n){let t;try{t=qs(e,"r")}catch{return""}try{let r=Buffer.alloc(n),o=Gs(t,r,0,n,0);return r.toString("utf8",0,o)}catch{return""}finally{Js(t)}}function Qs(e){for(let n of wr(e,256*1024).split(`
|
|
51
|
+
`)){let t=/"timestamp":"([^"]{1,40})"/.exec(n),r=t?Date.parse(t[1]):NaN;if(Number.isFinite(r))return r}return null}function Tu(e){for(let n of wr(e,2*1024*1024).split(`
|
|
52
|
+
`)){if(!n.includes('"api-request-shape"'))continue;let t=Ys(n);if(t!==void 0)return{attached:t}}return null}function br(e){let n=null,t=P(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 zs=e=>z(e.dir,"state","advisor-seen.json"),Lu=8;function Iu(e,n,t,r=!1){let o=Qs(e);if(o===null||o<=n)return null;let s=Tu(e);return s?s.attached?{verdict:"on",started:o}:r||/"entrypoint":"sdk-/.test(wr(e,256*1024))||Kt(Cn(e,null),t)?null:{verdict:"off",started:o}:null}function Du(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=dt(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 ei(e,n,t={}){let r=n===null,o=n??0;try{let s=P(zs(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=Iu(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 Du(t.scan.configDir,Math.max(o,u??o),Lu))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(zs(e),`${JSON.stringify(d)}
|
|
53
|
+
`)),d.verdict??null}catch{return null}}function Fu(e){return!!e&&J(e,256*1024).includes('"entrypoint":"claude-desktop"')}function Wu(e){let n=Wt[e];return n?/^[a-z]+$/.test(n.text)?n.text:`call (${n.text})`:"call"}var Ks=1450,Hu=1700,Uu=19e3;function Bu(e,n){let t=Uu,r=e?J(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
54
|
`,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+
|
|
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)&&
|
|
53
|
-
`),!0}catch{return!1}},N,M=()=>{if(N===void 0){let A=
|
|
54
|
-
`);return Q?{...A,note:Q}:A};if(v.on&&v.seen==="session"&&y!==null&&c!==null&&p!==null&<(e.env)){let A=y.denied[s];if(A)if(
|
|
55
|
-
`),o=t?.stop?{...t.stop,why:`${t.stop.why}; and ${n.stop.why}`}:n.stop;return{...o?{stop:o}:{},...r?{note:r}:{}}}function
|
|
55
|
+
`,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+Hu;return{usd:xe(n,{input:o,output:Ks,write5m:0,write1h:0,read:0}),fresh:o+Ks}}function zu(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 Ku=(e,n)=>z(e.dir,"state","second",`${n}.json`),Ju=(e,n)=>z(e.dir,"state","second",`${n}.shape.json`),ni=/^[A-Za-z0-9_-]{1,120}$/,qu=/^[A-Za-z0-9_.:-]{1,120}$/;function Gu(e,n){try{for(let t of ut(e)){let r=z(e,t);t.endsWith(".json")&&n-dt(r).mtimeMs>ju&&Nu(r,{force:!0})}}catch{}}function Vu(e,n){let t=P(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"&&ni.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 Yu(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 Zu(e,n,t){let r=e.split(`
|
|
56
|
+
`),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)&&Yu(g.content)&&(l=!0)}}return l}function Xu(e,n,t,r){let o=i=>Zu(J(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()+Sn,a===null?Number.POSITIVE_INFINITY:a+3e3);for(let u=0;u<Sn/20&&s===null&&Date.now()<l;u++)i(20),s=o(1024*1024)}return s===!1&&(s=o(8*1024*1024)),s===!0}function Qu(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?Mu(e.projectDir):null,path:"none",ms:0}))}catch{}}function ti(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:`${T("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:`${T("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.`}}}},L=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:`${T("Held by Anvil for your OK")} {why}${be("allow it once",`${K(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${T("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=L;let r=zu(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&&Bs.test(l)?l:null,d=de(e.payload.tool_use_id),c=d&&ni.test(d)?d:null,f=de(e.payload.prompt_id),g=i&&Bs.test(i)?i:null,m=(f&&qu.test(f)?f:null)??Hs(a)??g??"-",p=a&&u?pn(a,u)??null:a,h=g?`${g}${u?`-${u}`:""}`:null,k=h?Ku(e.paths,h):null,y=k?Vu(k,m):null;if(y?.done.includes(s))return null;let $=e.projectDir??null,x=Pu(e.env,e.home,$),_=p?Zs(p,h?Ju(e.paths,h):null):null,v=yr({env:x,home:e.home,project:$,transcript:p,shape:_,model:p?Cn(a,u):null,since:br(e.paths)});Gu(z(e.paths.dir,"state","second"),e.now);let E=Wu(s),C=A=>{try{return O(z(e.paths.dir,"state","second")),W(k,`${JSON.stringify(A)}
|
|
57
|
+
`),!0}catch{return!1}},N,M=()=>{if(N===void 0){let A=_?.attached,Q=A&&A!=="advisor"?A:ct("advisorModel",x,e.home,$)??"opus";N=(e.table?.policies??[]).some(ce=>ce.budgets?.length)?ps({...e,advisor:{...Bu(p,Q),about:E}}):null}return!!N?.stop},R=()=>D({stop:N.stop}),D=A=>{let Q=[N?.note,A.note].filter(Boolean).join(`
|
|
58
|
+
`);return Q?{...A,note:Q}:A};if(v.on&&v.seen==="session"&&y!==null&&c!==null&&p!==null&<(e.env)){let A=y.denied[s];if(A)if(Xu(e,p,A.id,c)){let{[s]:Q,...ce}=y.denied;return C({...y,done:[...y.done,s],denied:ce}),Qu(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 L()}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 j=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",G=v.on?` Ask the advisor about this ${E} and tell the user what it advises.`:"",w=g&&Pe(e.paths,`second-off|${g}|${o.id}`)?`${T("Anvil")} ${v.on?j:j===Jt?`no advisor in this session: ${j}`:`no advisor in this session (${j})`} \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}: ${j}, so you are the second opinion`:`${o.text}: no advisor in this session, so you are the second opinion`,said:{user:`${T("Held by Anvil for your OK")} {why}${be("allow it once",`${K(e.cli)} allow {code}`,"tell Claude to go on")}`,agent:`${T("Held by Anvil")} ${o.text}: ${v.on?`${j}, so the user is the second opinion. Nothing ran.${G}`:"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 ed(e){let n=ti(e);if(n?.stop?.decision.verdict==="block"||n?.stop?.action==="claude.budget")return n;let t=As(e);if(!n)return t;let r=[n.note,t?.note].filter(Boolean).join(`
|
|
59
|
+
`),o=t?.stop?{...t.stop,why:`${t.stop.why}; and ${n.stop.why}`}:n.stop;return{...o?{stop:o}:{},...r?{note:r}:{}}}function nd(e,n,t){return z(Z(e,n),"projects",t.replace(/[^A-Za-z0-9]/g,"-"))}function td(e){let n=null;try{for(let t of ut(e)){if(!t.endsWith(".jsonl"))continue;let r=dt(z(e,t)).mtimeMs;(!n||r>n.t)&&(n={f:z(e,t),t:r})}}catch{return null}return n?.f??null}function ri(e){try{return Re(e,void 0,q(e)).value}catch{return null}}var oi=e=>Ke(e)||(e?.policies??[]).some(n=>(n.model_rules?.second?.length??0)>0);function rd(e,n=Dt()){try{if(!oi(ri(e)))return"";let t=JSON.parse(n??"null"),r=de(t?.transcript_path);if(!r||!Us(r)||!r.endsWith(".jsonl"))return"";let o=de(t?.workspace?.project_dir)??de(t?.cwd),s=Vs(),i=o&&Us(o)?o:null,a=br(e),l=ei(e,a,{file:Jn(process.env)?null:r,advisorModel:ct("advisorModel",process.env,s,i)}),u=yr({env:process.env,home:s,project:i,transcript:r,model:Cn(r,null),since:a,seen:l});return` \xB7 ${qt(u)}`}catch{return""}}function od(e,n){try{let t=ri(e);if(!oi(t))return null;let r=Vs(),o=td(nd(process.env,r,n)),s=o?Cn(o,null):null,i=br(e),a=ei(e,i,{file:Jn(process.env)?null:o,advisorModel:ct("advisorModel",process.env,r,n)}),l=qt(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"&&Fu(o)?`${l} \xB7 the desktop app runs ${u.label} here, its own pick`:l}catch{return null}}export{Sn as ANSWER_WAIT_MS,Ko as COLD_PER_WARM,Rt as FEED_MAX_BYTES,nr as FIRST_HELPER_REPLY_TOKENS,Sa as HELPER_CACHE_MS,Br as HELPER_LIVE_MS,Fe as KEEP_DAYS,Ma as LAUNCH_CLAIM_MS,Ca as LIVE_MS,dn as PLAN_FRESH_MS,Ka as REPORT_ONLY_TOOLS,_a as RESERVE_MAX_SHARE,qr as STATUSLINE_READ_BYTES,xa as UNSEEN_HELPER_SHARE,Ue as accountOf,od as advisorRow,rd as advisorTail,gn as ageWords,ps as budgetAtAction,yg as budgetAtPrompt,bg as budgetStanding,ir as budgetsOf,ff as catchUp,to as catchUpFrom,Ft as catchUpSince,fl as catchUpToday,zn as claudeCodesOwnTurn,Z as claudeConfigDir,Y as dayOf,rl as dollarsWords,lt as eagerFlush,Xr as feedsPlan,cf as feedsSince,Hn as helperFiles,lo as helperStates,pn as helperTranscript,_s as judgeReadings,Be as lastReading,Es as launchOf,Ru as lockHold,Cu as lockRun,ao as megabytes,ll as meterStep,Bn as meterTotals,As as modelAtAction,Tg as modelAtMessage,Lg as modelAtPrompt,Pg as modelAtSwitch,Cn as modelNow,ue as modelOf,ed as modelRulesAt,Kr as money,Tt as offPlan,mg as ownStatusLine,Yr as ownerKeyOf,Gr as parseStatusFeed,ca as probeAccount,Ha as probeFailure,ol as pruneMeter,It as readAgo,Dt as readFeedFromStdin,tl as readLimits,Lt as readSessionAndHelpers,Ot as readSessionFile,ru as readingAtAction,Ms as readingAtMessage,io as recentReplies,Pt as recordFeed,Za as requestNow,aa as runPlanProbe,Pe as sayOnce,wg as screenPlanScope,Wn as screenScope,ti as secondOpinion,so as sessionOpeningPrompt,no as sessionUnread,jt as signedInOwner,zr as spendWords,ar as spentUsd,le as startOfDay,cn as startOfWeek,pf as statusFacts,fr as threadReadings,ze as tokenWords,$t as unheardSessions};
|