SLOPSHOPPER

cost-ledger-probe

Measures how $.model.fork behaves as a prompt-cache keep-alive, to settle the numbers cost-ledger's keep-alive will rely on. Not shipped.

commandtoaststatusmodeltimer
★ 2v0.1.0MITupdated 2026-10-14bobtat/claude-plugins/tests/cost-ledger-probe
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cost-ledger-probe
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /probe ⎿ cost-ledger-probe: Forks (0) ⎿ cost-ledger-probe: none yet ⎿ cost-ledger-probe: ⎿ cost-ledger-probe: First request of each turn ⎿ cost-ledger-probe: none yet ⎿ cost-ledger-probe: ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

cost-ledger probe

A throwaway mod that measures how $.model.fork behaves as a prompt-cache keep-alive, before cost-ledger's keep-alive is built on it. It logs every request's token counts, Claude Code's running cost and the rate-limit readings, and forks the transcript on demand or on a timer while the session is idle.

It lives outside plugins/ so it is never published, and nothing in the marketplace lists it.

What it has to settle

  1. Does a fork sent while the session is idle read the session's cache (cache_read close to the context size)?
  2. With pings, is the next real turn after a gap longer than the cache lifetime still a cache read rather than a re-write?
  3. Is a fork's cost included in Claude Code's running total ($.session.usage().cost)? If it is, cost-ledger must not add it a second time.
  4. How many output tokens does each ping cost? fork takes no max_tokens, and the session's thinking setting applies.
  5. On a subscription, how much does a ping move the 5-hour and 7-day limit percentages?

Running it

Load it next to cost-ledger for one session:

claude --plugin-dir tests/cost-ledger-probe

Every record goes to ~/claude-costs/probe-<date>-<session>.jsonl (%USERPROFILE% on Windows) as it happens. A reload or restart of the same session keeps adding to the same file. Timers still pending are lost on a reload.

CommandDoes
/probe pingForks now
/probe schedule 4 8 12Forks at those minutes after the last turn ended
/probe prompt 110 [text]Sends a prompt (default ok) at that minute after the last turn ended, as if you typed it, so a long run needs no one at the keyboard
/probe burst 20 3020 forks, each started 30 s after the previous one returned
/probe mark <text>Writes a label into the log, such as control start
/probe reportSummarises forks, the first request of each turn, each turn's cost against its tokens at both cache write rates, spend no logged request explains, rate limits and cache lifetime

A prompt you send cancels any pings and any scheduled prompt still pending, and a ping is skipped (and logged as skipped) while a turn is running.

The experiments

Before each one, build a context of at least 50k tokens, for example by asking Claude to read a few large files, so a hit and a miss differ by a clear margin. Use /probe mark before each run so the log is easy to split afterwards. Don't run other Claude sessions during experiment 5.

#StepsRead in the report
1, 4End a turn, wait 2 min, /probe ping. Repeat at your usual effort and at a lower oneFork read close to ctx (above 90%); fork output
2Test: end a turn, /probe schedule 4 8 12, send a one-word prompt 15 min after the turn ended. Control: the same with no scheduleFirst request of the follow-up turn: the test shows a large read, the control a large write
3/probe ping with no turn in betweenFork Δcost against its tokens priced at list rates: about equal means Claude Code counts the fork; zero means cost-ledger has to
5With Claude not in use anywhere else on the account, /probe ping for a fresh reading, then /probe burst 10 30; if the 5-hour reading moved 1% or less, /probe burst 30 30Spend between the steps of the 5-hour reading, set against the pings' cost. A fork's response carries the reading, so no prompt is needed between bursts

For experiment 2, check the reported cache lifetime first. If it is 1h, use /probe schedule 55 110 with the prompt at 115 minutes; the 15-minute version proves nothing on a one-hour cache.

The rate-limit percentages come with one decimal place and are only what the last response reported. That is why experiment 5 uses a burst and takes its readings after a real prompt.

Bring the JSONL file back when you're done. It holds everything the report leaves out.

Results

2026-10-10: personal Pro account, Opus 5.5, ~67k-token context

#Result
1Yes. A fork 2.8 min after a turn read 61,084 of 66,067 tokens from the cache (92%) and wrote 4,981: the tail since the last cached point. Read, write and input add up to the whole context plus the ping prompt.
2Not settled. The pings themselves behaved: +4m read 99% and wrote 790 tokens, +8m and +12m read 100% and wrote 0. But the cache stayed warm without pings too: the first requests after idle gaps of 7.4, 18.3 and 15.2 minutes with no ping in between (the last one the control) all read the whole context. The likeliest cause is that this account uses the one-hour cache. Claude Code never reported the lifetime directly, but its own pricing of the turns agrees (below). The 2026-10-11 run settles it.
3Yes, Claude Code counts it. Each fork's Δcost equals its tokens at list price to the cent: the first fork $0.0374 = 61,084 read × $0.20/M + 4,981 written × $5/M + 49 input × $4/M + 4 output × $20/M. A fork's own writes are priced at the five-minute rate; the main thread's turns at the one-hour rate (below).
44 output tokens per ping, about $0.0001: no noticeable thinking. A ping that writes nothing cost $0.0137 at this context size.
5Not measured. The readings around each fork stayed the same and moved only at real turns. That does not mean forks never update them: in the 2026-10-11 run a fork's response carried a reading that had moved (below). The 5-hour reading went from 3% to 7% over the whole session, about $0.65 of API-equivalent spend, real turns included. Measured on 2026-10-12 (below).
From the JSONL

Claude Code's running total against each interval's tokens at list price:

IntervalTotal movedWrites at $5/MWrites at $8/M
First turn, two requests$0.38143$0.2834$0.3811
11:50 turn, one request$0.07121$0.0550$0.07121
Each of the four forksas loggedmatchestoo high

So Claude Code charges the main thread's cache writes at the one-hour rate and a fork's at the five-minute rate. A fork's read still renews the main thread's one-hour entries: the caching docs say a read renews an entry's timer on either lifetime.

Some spend passed through no hook the probe logs:

WindowTotal movedLogged requests pricedLeft over
12:02 → 12:21, 18 min idle$0.0509$0.0292$0.0217
12:21 → 12:36, 15 min idle$0.0357$0.0146$0.0211
11:44 → 11:50, 7 min idle$0.0712$0.0712none
After the last turn$0.0331none$0.0331

About $0.021 is what one cache read of the 67k context plus a few hundred output tokens costs. That looks like Claude Code making a background request of its own after a long idle gap. If such a request reads the transcript, it renews the cache too. The report now lists this spend with its window, so the next runs show when it happens. The 2026-10-11 run had none in 110 minutes, so what it was is still unknown.

2026-10-11: personal Pro account, Opus 5.5, ~64k-token context

One turn, then /probe schedule 55 and /probe prompt 110, and the session left alone.

After the turn endedEventReadWriteTotal moved
0Context-building turn29,13033,009$0.29908
55.0 min+55m ping62,139 of 63,587 (98%)1,446$0.01993
110.0 min, 55.0 after the pingScheduled ok62,1398,667$0.08424
  • The cache lasted at least 55 minutes, and the ping renewed it: the prompt at 110 minutes read the same 62,139 tokens again. The expiry control below confirms the cache would otherwise have expired.
  • The write rates match exactly again. The first turn comes to $0.29883 with one-hour writes and $0.1998 with five-minute writes. The ok turn comes to $0.08424 with one-hour writes, exactly. The ping comes to $0.01993 with five-minute writes, exactly.
  • The ping wrote only the tail. Its 1,446 written tokens equal the first turn's 1,446 output tokens. That write is priced, and so presumably kept, at the five-minute rate, so it had expired by the ok 55 minutes later, which wrote it again. The other ~7,100 tokens came with the prompt itself: /probe prompt adds that much context where a typed ok added about 120 (below). What they contain is not in the log.
  • No spend went unexplained. Each known total equals the next across the whole 110 minutes.
  • Saving: without the ping, the ok would have re-written about 62k tokens at $8/M, roughly $0.50, against $0.0199 for the ping.
  • A fork can carry a moved rate-limit reading. The ping's response came with the 5-hour reading at 62% (55% before) and the 7-day at 13% (12% before). A $0.02 request cannot account for 7 points when $0.65 moved the reading 4 points in the first run, so this is almost certainly other use on the account in those 55 minutes. The readings cover the whole account, so experiment 5 has to run while Claude is not in use anywhere else on it.
The expiry control, same session

After 438 minutes (7.3 hours) with nothing sent, a typed ok:

ReadWriteContextTotal movedWrites at $8/MWrites at $5/M
29,13041,91971,051$0.341986$0.341986$0.2162
  • The cache had expired. The gap is far past an hour, so on its own it shows only that entries expire within 7.3 hours. But the API offers two lifetimes, five minutes and one hour, the 18-minute hits of the first run rule out five minutes, and Claude Code prices every turn at the one-hour rate. So the lifetime is one hour, and without the +55m ping the 110-minute prompt would have found the cache cold.
  • The shared opening stayed warm. The cold request still read 29,130 tokens, exactly what this session's very first request read before it had written anything (the first run's first request read 28,468). The opening of the prompt, mostly the system prompt and tool definitions by its size, is cached on its own; something else must have used it within the hour, most likely another Claude Code session. Only the conversation, 41,919 tokens, was written again. A cold resume therefore cost (context − shared opening) × write rate: $0.335, where the whole context × $8/M would say $0.568, about 70% too high.
  • No spend went unexplained in 7.3 hours idle, so the first run's ~$0.02 charges are not something Claude Code does whenever a session sits idle.
  • A typed prompt added about 120 tokens of context (71,051 against 70,810 + 123 output before it), where the /probe prompt one added about 7,100.

2026-10-12: experiment 5, personal Pro account, Opus 5.5, ~62k-token context

One context-building turn, /probe ping, /probe burst 10 30, then /probe burst 30 30: 41 pings, with Claude not in use anywhere else on the account.

PointTotal moved to (API-equivalent)5-hour7-day
Session start$0.00003%21%
After the context turn$0.24473%21%
After the first ping$0.26244%21%
After the 10-ping burst$0.38854%21%
After ping 12 of the 30$0.53994%21%
After ping 13 of the 30$0.55265%21%
After all 41 pings$0.76715%21%
  • Each pure-read ping cost exactly $0.0126176: 61,708 read × $0.20/M + 49 input × $4/M + 4 output × $20/M. The first wrote the 1,053-token tail as well, $0.0177.
  • About 23 pings per 1% of the 5-hour window. The step from 4% to 5% took between $0.2775 and $0.3079 of spend, all of it pings, so roughly 22–24 pings: about 0.045% of the 5-hour window per ping at 62k tokens. The 7-day reading did not move.
  • Cache reads are not counted like full input. If they were, a ping would weigh like 61.7k × $4/M ≈ $0.25, and 41 pings would have used something like 35% of the window rather than about 2%. The run fits limits weighted by API-equivalent price, at about $0.29 of spend per 1% of this account's 5-hour window. The first run's rougher figure, about $0.16 per 1%, came from whole-number readings over a session that may have included other use.
  • Forks do carry fresh readings. Every step in the table came with a fork's response; resetsAt stayed at 16:50 UTC throughout.

For keep-alive on this account: hourly pings across a three-hour idle stretch cost about 0.13% of the 5-hour window, against about 1% for one cold re-cache of a conversation this size (33–42k tokens at the one-hour write rate, $0.27–0.34).

Nothing is left to run for the keep-alive.

What this changes for cost-ledger's keep-alive

  • The ping interval comes from the cache lifetime, not a fixed ~4.5 minutes. On a one-hour cache that means one ping about every 55 minutes, about $0.014–0.02 each at 62–67k tokens, against a cold re-cache of 67k × $8/M ≈ $0.54 at the one-hour write rate. That is about 40 hours of pings before they cost more than one re-cache, so the limit that matters is the maximum idle time, not break-even.
  • cost-ledger should learn the lifetime from what it observes. With cacheTtl on auto and nothing reported, it assumes five minutes. That shows "cache cold" and the re-cache warning too early, and prices writes too low, on an account like this one. The reliable signal is Claude Code's own pricing: price each request with five-minute and one-hour writes and see which matches the running total's change, as the probe's report now does.
  • Keep-alive cost goes into the category breakdown only. Claude Code's running total already includes forks, and cost-ledger's totals come from it, so adding forks to the totals would count them twice. Forks don't pass through turn.step, so the breakdown must record their usage itself.
  • A ping only has to protect the conversation, not the shared opening while something else keeps that opening warm. In the expiry run that is 41,919 tokens × ($8 − $0.20)/M ≈ $0.33 per re-cache avoided, so hourly pings at $0.014–0.02 cover 16–23 hours.
  • The cold-resume estimate should subtract the shared opening, learned from a session's first request, and still show the whole context as the worst case, since the opening stays warm only if something else used it within the hour.
  • On a subscription, pings are cheap against the limits. About 0.045% of the 5-hour window each at 62k tokens on Pro, so keepAlive can stay off by default as an opt-in for something that spends while the person is away, without the limits being the reason.
  • Only the first ping after a turn writes anything. It writes the tail; later pings are pure cache reads. That tail is written at the five-minute rate, so on a one-hour cache it has expired by the next ping or prompt and is written again: about $0.01 an hour at this size, not worth working around.

Development

claude plugin validate tests/cost-ledger-probe
claude plugin test tests/cost-ledger-probe
Source 3 files
hooks/register.ts 308 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import type { ProbeRecord, Snapshot, Tokens } from './probe'
4import { contextOf, fromJsonl, logFileName, parseCommand, PING_PROMPT, report, scheduleDelays, toJsonl, USAGE } from './probe'
5
6type Usage = {
7  input_tokens: number
8  output_tokens: number
9  cache_read_input_tokens: number
10  cache_creation_input_tokens: number
11}
12
13const tokensOf = (u: Usage): Tokens => ({
14  input: u.input_tokens,
15  output: u.output_tokens,
16  cacheRead: u.cache_read_input_tokens,
17  cacheWrite: u.cache_creation_input_tokens,
18})
19
20// Module state starts over on a reload; the log itself is read back from its
21// file, so a reload mid-experiment loses only pending timers.
22type TimerKind = 'ping' | 'prompt'
23
24const state = {
25  records: [] as ProbeRecord[],
26  logPath: undefined as string | undefined,
27  runningTurn: null as string | null,
28  lastTurnEnd: undefined as number | undefined,
29  contextTokens: null as number | null,
30  lastMeasured: '',
31  pending: [] as { cancel: () => void; kind: TimerKind }[],
32  queue: Promise.resolve() as Promise<void>,
33}
34
35function serially(task: () => Promise<void>) {
36  const run = state.queue.then(task)
37  state.queue = run.catch(() => undefined)
38  return run
39}
40
41async function writeLog($: EngineInterface) {
42  const path = state.logPath
43  if (path === undefined) return
44  try {
45    await $.fs.write(path, toJsonl(state.records))
46  } catch (err) {
47    $.ui.toast(`cost-ledger-probe: could not write ${path}: ${String(err)}`)
48  }
49}
50
51function add($: EngineInterface, record: ProbeRecord) {
52  return serially(async () => {
53    state.records.push(record)
54    await writeLog($)
55  })
56}
57
58async function snapshot($: EngineInterface): Promise<Snapshot> {
59  const usage = await $.session.usage()
60  return { costUsd: usage.cost?.usd ?? null, rateLimits: usage.rateLimits.map(l => ({ ...l })) }
61}
62
63async function ping($: EngineInterface, label: string) {
64  if (state.runningTurn !== null) {
65    await add($, { at: await $.clock.now(), kind: 'skip', label, why: 'a turn is running' })
66    return
67  }
68  const before = await snapshot($)
69  const startedAt = await $.clock.now()
70  const result = await $.model.fork({ prompt: PING_PROMPT })
71  const after = await snapshot($)
72  const at = await $.clock.now()
73  const common = { at, kind: 'fork' as const, label, startedAt, contextTokens: state.contextTokens, before, after }
74  let record: ProbeRecord
75  if (result.isAnswered) record = { ...common, result: 'answered', tokens: tokensOf(result.usage) }
76  else if (result.reason === 'nothing-to-fork') record = { ...common, result: result.reason }
77  else if (result.reason === 'api-error')
78    record = { ...common, result: `api-error ${result.error}`, status: result.status, tokens: tokensOf(result.usage) }
79  else record = { ...common, result: result.reason, tokens: tokensOf(result.usage) }
80  await add($, record)
81  const read = record.tokens?.cacheRead ?? 0
82  const ctx = state.contextTokens ? ` of ~${state.contextTokens}` : ''
83  $.ui.status(`probe ${label}: ${record.result}, cache read ${read}${ctx}`)
84}
85
86// A timer's ping has no caller to reject to: a fork the engine refuses is
87// logged as a skip instead of surfacing as an unhandled rejection.
88async function pingFromTimer($: EngineInterface, label: string) {
89  try {
90    await ping($, label)
91  } catch (err) {
92    await add($, { at: await $.clock.now(), kind: 'skip', label, why: String(err) })
93  }
94}
95
96// A pending timer leaves the list as it fires, so a prompt cancels, and
97// reports, only the timers still to come.
98function later($: EngineInterface, ms: number, run: () => Promise<void>, kind: TimerKind = 'ping') {
99  const timer = $.clock.after(ms, () => {
100    state.pending = state.pending.filter(t => t !== entry)
101    void run()
102  })
103  const entry = { cancel: () => timer.cancel(), kind }
104  state.pending.push(entry)
105}
106
107// A scheduled prompt stands in for the person typing one: the same turn, so
108// its first request shows whether the cache was still warm when it ran.
109async function submitScheduled($: EngineInterface, label: string, text: string) {
110  try {
111    await add($, { at: await $.clock.now(), kind: 'mark', text: `prompt ${label} submitted: ${text}` })
112    const result = await $.prompt.submit({ text })
113    if (result.drop !== undefined) {
114      await add($, { at: await $.clock.now(), kind: 'skip', label: `prompt ${label}`, why: `refused: ${result.drop}` })
115    }
116  } catch (err) {
117    await add($, { at: await $.clock.now(), kind: 'skip', label: `prompt ${label}`, why: String(err) })
118  }
119}
120
121// Each fork of a burst starts only after the previous one returned, so slow
122// replies stretch the spacing rather than overlapping.
123async function burst($: EngineInterface, i: number, count: number, seconds: number) {
124  await pingFromTimer($, `burst ${i}/${count}`)
125  if (i < count && state.runningTurn === null) {
126    later($, seconds * 1000, () => burst($, i + 1, count, seconds))
127  }
128}
129
130// Without a kind, every pending timer; with one, only that kind, so setting
131// up pings leaves a scheduled prompt in place and the other way round.
132function cancelPending(kind?: TimerKind) {
133  const cancelled = state.pending.filter(t => kind === undefined || t.kind === kind)
134  for (const timer of cancelled) timer.cancel()
135  state.pending = state.pending.filter(t => !cancelled.includes(t))
136  return cancelled.length
137}
138
139export const register: Register = on => {
140  Object.assign(state, {
141    records: [],
142    logPath: undefined,
143    runningTurn: null,
144    lastTurnEnd: undefined,
145    contextTokens: null,
146    lastMeasured: '',
147    pending: [],
148    queue: Promise.resolve(),
149  })
150
151  on('session.start', async ($, e, next) => {
152    await $.command.register({
153      name: 'probe',
154      description: 'cost-ledger-probe: ping (fork now), schedule <minutes...>, prompt <minutes> [text], burst <count> <seconds>, mark <text>, report',
155      argumentHint: 'ping | schedule <min...> | prompt <min> [text] | burst <n> <s> | mark <text> | report',
156    })
157    const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
158    const sessionId = await $.session.id()
159    const now = await $.clock.now()
160    if (home !== undefined) {
161      const path = `${home}/claude-costs/${logFileName(now, sessionId)}`
162      state.logPath = path
163      if (await $.fs.exists(path)) state.records = fromJsonl(String(await $.fs.read(path)))
164    } else {
165      $.ui.toast('cost-ledger-probe: no home folder found; records are kept in memory only')
166    }
167    await add($, { at: now, kind: 'session', sessionId, version: (await $.session.version()).version })
168    return next(e)
169  })
170
171  on('classic.SessionStart', async ($, e, next) => {
172    if (e.source === 'resume' || e.source === 'fork' || e.source === 'clear' || e.source === 'compact') {
173      await add($, {
174        at: await $.clock.now(),
175        kind: 'resume',
176        source: e.source,
177        secondsSinceLastResponse: e.seconds_since_last_response,
178        contextTokens: e.context_tokens,
179        likelyExpired: e.prompt_cache_likely_expired,
180        estimatedCacheWriteUsd: e.estimated_cache_write_usd,
181      })
182    }
183    if (e.source === 'clear' || e.source === 'compact') state.contextTokens = null
184    else if (e.context_tokens !== undefined) state.contextTokens = e.context_tokens
185    return next(e)
186  })
187
188  on('classic.PreModelSwitch', async ($, e, next) => {
189    await add($, { at: await $.clock.now(), kind: 'ttl', source: 'PreModelSwitch', ttl: e.cache_ttl })
190    return next(e)
191  })
192
193  on('classic.PostModelSwitch', async ($, e, next) => {
194    await add($, { at: await $.clock.now(), kind: 'ttl', source: 'PostModelSwitch', ttl: e.cache_ttl })
195    return next(e)
196  })
197
198  on('turn.start', async ($, e, next) => {
199    state.runningTurn = e.turnId
200    // A real prompt ends whatever schedule, burst or scheduled prompt was
201    // waiting: the gap it was meant to measure no longer exists.
202    const cancelled = cancelPending()
203    const at = await $.clock.now()
204    if (cancelled > 0) await add($, { at, kind: 'mark', text: `turn started; ${cancelled} pending timer(s) cancelled` })
205    const { costUsd } = await snapshot($)
206    await add($, { at, kind: 'turn', phase: 'start', turnId: e.turnId, costUsd })
207    return next(e)
208  })
209
210  on('turn.step', async function* ($, e, next) {
211    const startedAt = await $.clock.now()
212    const result = yield* next(e)
213    const usage = result.usage
214    if (usage) {
215      const tokens = tokensOf(usage)
216      if (e.agentId === undefined) state.contextTokens = contextOf(tokens)
217      await add($, {
218        at: await $.clock.now(),
219        kind: 'step',
220        turnId: e.turnId,
221        agentId: e.agentId,
222        model: usage.model,
223        startedAt,
224        tokens,
225      })
226    }
227    return result
228  })
229
230  on('turn.complete', async ($, e, next) => {
231    const result = await next(e)
232    if (e.agentId === undefined) {
233      state.runningTurn = null
234      const at = await $.clock.now()
235      state.lastTurnEnd = at
236      const { costUsd } = await snapshot($)
237      await add($, { at, kind: 'turn', phase: 'end', turnId: e.turnId, costUsd })
238    }
239    return result
240  })
241
242  on('session.measure', async ($, e, next) => {
243    const snap: Snapshot = { costUsd: e.cost?.usd ?? null, rateLimits: e.rateLimits.map(l => ({ ...l })) }
244    const key = JSON.stringify(snap)
245    if (key !== state.lastMeasured) {
246      state.lastMeasured = key
247      await add($, { at: await $.clock.now(), kind: 'measure', snapshot: snap })
248    }
249    return next(e)
250  })
251
252  on('command.run', { command: 'probe' }, async ($, e) => {
253    const command = parseCommand(e.args)
254    const now = await $.clock.now()
255    switch (command.kind) {
256      case 'help':
257        return { text: `${command.error ? `${command.error}\n` : ''}${USAGE}` }
258      case 'report':
259        return { text: `${report(state.records)}\n\nLog: ${state.logPath ?? '(memory only)'}` }
260      case 'mark':
261        await add($, { at: now, kind: 'mark', text: command.text })
262        return { text: `Marked: ${command.text}` }
263      case 'ping':
264        // Not awaited: the command returns at once and the fork's record lands
265        // when it finishes, as a scheduled ping's would.
266        void pingFromTimer($, 'ping')
267        return { text: 'Forking now; /probe report shows the result.' }
268      case 'schedule': {
269        const anchor = state.lastTurnEnd
270        if (anchor === undefined) return { text: 'No turn has finished in this session yet; send a prompt first.' }
271        cancelPending('ping')
272        const lines: string[] = []
273        for (const { minutes, delayMs } of scheduleDelays(anchor, now, command.minutes)) {
274          if (delayMs <= 0) {
275            lines.push(`  +${minutes}m: already past, skipped`)
276            continue
277          }
278          later($, delayMs, () => pingFromTimer($, `+${minutes}m`))
279          lines.push(`  +${minutes}m: in ${(delayMs / 60_000).toFixed(1)} min`)
280        }
281        await add($, { at: now, kind: 'mark', text: `schedule ${command.minutes.join(' ')} after turn end` })
282        return { text: `Pings after the last turn's end:\n${lines.join('\n')}\nA new prompt cancels any still pending.` }
283      }
284      case 'prompt': {
285        const anchor = state.lastTurnEnd
286        if (anchor === undefined) return { text: 'No turn has finished in this session yet; send a prompt first.' }
287        const [{ minutes, delayMs }] = scheduleDelays(anchor, now, [command.minutes]) as [{ minutes: number; delayMs: number }]
288        if (delayMs <= 0) return { text: `+${minutes}m after the last turn's end is already past.` }
289        cancelPending('prompt')
290        later($, delayMs, () => submitScheduled($, `+${minutes}m`, command.text), 'prompt')
291        await add($, { at: now, kind: 'mark', text: `prompt "${command.text}" at +${minutes}m after turn end` })
292        return {
293          text:
294            `Will send "${command.text}" at +${minutes}m after the last turn's end, in ${(delayMs / 60_000).toFixed(1)} min.\n` +
295            'Leave the session idle until then: a prompt you type first cancels it.',
296        }
297      }
298      case 'burst': {
299        cancelPending('ping')
300        const { count, seconds } = command
301        await add($, { at: now, kind: 'mark', text: `burst ${count} x ${seconds}s` })
302        void burst($, 1, count, seconds)
303        return { text: `Burst of ${count} pings, ${seconds}s apart, started. A new prompt stops it.` }
304      }
305    }
306  })
307}
308
hooks/probe.ts 325 lines
1// The probe's records and the arithmetic over them, free of engine calls so the
2// tests can check it directly. Each record is one line of the JSONL log.
3
4import { ratesFor } from './pricing'
5
6export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
7
8export type Snapshot = { costUsd: number | null; rateLimits: Limit[] }
9
10export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number }
11
12export type ProbeRecord = { at: number } & (
13  | { kind: 'session'; sessionId: string; version: string }
14  // costUsd is Claude Code's running total as the turn starts and ends, so a
15  // turn's cost can be set against its tokens; absent from older logs.
16  | { kind: 'turn'; phase: 'start' | 'end'; turnId: string; costUsd?: number | null }
17  | { kind: 'step'; turnId: string; agentId?: string; model: string; startedAt: number; tokens: Tokens }
18  | { kind: 'measure'; snapshot: Snapshot }
19  | {
20      kind: 'fork'
21      label: string
22      startedAt: number
23      contextTokens: number | null
24      result: 'answered' | string
25      status?: number | null
26      tokens?: Tokens
27      before: Snapshot
28      after: Snapshot
29    }
30  | { kind: 'skip'; label: string; why: string }
31  | { kind: 'ttl'; source: string; ttl: string }
32  | { kind: 'resume'; source: string; secondsSinceLastResponse?: number; contextTokens?: number; likelyExpired?: boolean; estimatedCacheWriteUsd?: number }
33  | { kind: 'mark'; text: string }
34)
35
36// Short, tool-free and asking for one word, so each ping's output stays small;
37// the output tokens it still costs are one of the things being measured.
38export const PING_PROMPT =
39  'This is an automated prompt-cache keep-alive check, not a request from the user. ' +
40  'Do not use any tools. Reply with exactly: ok'
41
42export type Command =
43  | { kind: 'ping' }
44  | { kind: 'schedule'; minutes: number[] }
45  | { kind: 'burst'; count: number; seconds: number }
46  | { kind: 'prompt'; minutes: number; text: string }
47  | { kind: 'mark'; text: string }
48  | { kind: 'report' }
49  | { kind: 'help'; error?: string }
50
51export const USAGE =
52  'Usage: /probe ping | schedule <minutes...> | prompt <minutes> [text] | burst <count> <seconds> | mark <text> | report'
53
54const isPositive = (n: number) => Number.isFinite(n) && n > 0
55
56export function parseCommand(args: string): Command {
57  const [verb = '', ...rest] = args.trim().split(/\s+/).filter(Boolean)
58  switch (verb) {
59    case 'ping':
60      return { kind: 'ping' }
61    case 'schedule': {
62      const minutes = rest.map(Number)
63      if (minutes.length === 0 || !minutes.every(isPositive)) {
64        return { kind: 'help', error: 'schedule takes one or more positive minute offsets, e.g. schedule 4 8 12' }
65      }
66      return { kind: 'schedule', minutes: [...minutes].sort((a, b) => a - b) }
67    }
68    case 'burst': {
69      const [count, seconds] = rest.map(Number)
70      if (count === undefined || seconds === undefined || !Number.isInteger(count) || !isPositive(count) || !isPositive(seconds)) {
71        return { kind: 'help', error: 'burst takes a whole count and a spacing in seconds, e.g. burst 20 30' }
72      }
73      return { kind: 'burst', count, seconds }
74    }
75    case 'prompt': {
76      const [first, ...words] = rest
77      const minutes = Number(first)
78      if (first === undefined || !isPositive(minutes)) {
79        return { kind: 'help', error: 'prompt takes a positive minute offset and optional text, e.g. prompt 110 ok' }
80      }
81      return { kind: 'prompt', minutes, text: words.join(' ') || 'ok' }
82    }
83    case 'mark': {
84      const text = rest.join(' ')
85      return text === '' ? { kind: 'help', error: 'mark takes a label, e.g. mark control start' } : { kind: 'mark', text }
86    }
87    case 'report':
88    case '':
89      return { kind: 'report' }
90    default:
91      return { kind: 'help', error: `unknown subcommand "${verb}"` }
92  }
93}
94
95// The context the next request sends, counted as cost-ledger counts it: the
96// last response's input, cache read, cache write and output together.
97export const contextOf = (t: Tokens) => t.input + t.cacheRead + t.cacheWrite + t.output
98
99export function dayKey(ms: number): string {
100  const d = new Date(ms)
101  const pad = (n: number) => String(n).padStart(2, '0')
102  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
103}
104
105export const logFileName = (ms: number, sessionId: string) => `probe-${dayKey(ms)}-${sessionId.slice(0, 8)}.jsonl`
106
107export const toJsonl = (records: readonly ProbeRecord[]) => records.map(r => JSON.stringify(r)).join('\n') + '\n'
108
109export function fromJsonl(text: string): ProbeRecord[] {
110  const records: ProbeRecord[] = []
111  for (const line of text.split('\n')) {
112    if (line.trim() === '') continue
113    try {
114      records.push(JSON.parse(line) as ProbeRecord)
115    } catch {
116      // a line cut short by a crash mid-write is dropped, not fatal
117    }
118  }
119  return records
120}
121
122// Delays for `schedule`: each offset counts from the end of the last main
123// turn. Offsets already past are reported rather than fired late, since a late
124// ping would measure a different idle gap from the one asked for.
125export function scheduleDelays(anchor: number, now: number, minutes: readonly number[]) {
126  return minutes.map(m => ({ minutes: m, delayMs: anchor + m * 60_000 - now }))
127}
128
129// Below this many tokens written, a turn's other charges swamp the write and
130// the implied rate says nothing.
131const MIN_WRITE_FOR_RATE = 1_000
132// Spend under this is rounding in Claude Code's total, not a request.
133const MIN_UNATTRIBUTED_USD = 0.0005
134
135export type TurnCost = {
136  turnId: string
137  startedAt: number
138  endedAt: number
139  deltaUsd: number
140  writeTokens: number
141  // The turn's tokens priced at list rates, with writes at each lifetime.
142  at5m: number
143  at1h: number
144  // What one written million tokens must have cost for the rest to add up.
145  impliedWriteRate: number | null
146  matches: '5m' | '1h' | '?'
147  hasUnpriced: boolean
148}
149
150// Each turn whose start and end both carry Claude Code's running total, its
151// cost set against its requests (subagents' included) priced both ways: the
152// lifetime whose write rate makes them add up is the one Claude Code charged.
153export function turnCosts(records: readonly ProbeRecord[]): TurnCost[] {
154  const turns: TurnCost[] = []
155  let open: { turnId: string; at: number; costUsd: number; steps: Tokens[]; models: string[] } | undefined
156  for (const r of records) {
157    if (r.kind === 'turn' && r.phase === 'start') {
158      open = typeof r.costUsd === 'number' ? { turnId: r.turnId, at: r.at, costUsd: r.costUsd, steps: [], models: [] } : undefined
159    } else if (r.kind === 'step' && open && r.turnId === open.turnId) {
160      open.steps.push(r.tokens)
161      open.models.push(r.model)
162    } else if (r.kind === 'turn' && r.phase === 'end' && open && r.turnId === open.turnId) {
163      if (typeof r.costUsd === 'number') {
164        let base = 0
165        let w5 = 0
166        let w1 = 0
167        let writeTokens = 0
168        let hasUnpriced = false
169        open.steps.forEach((t, i) => {
170          const rates = ratesFor(open?.models[i] ?? '')
171          if (rates === undefined) {
172            hasUnpriced = true
173            return
174          }
175          base += (t.input * rates.input + t.cacheRead * rates.cacheRead + t.output * rates.output) / 1e6
176          w5 += (t.cacheWrite * rates.cacheWrite5m) / 1e6
177          w1 += (t.cacheWrite * rates.cacheWrite1h) / 1e6
178          writeTokens += t.cacheWrite
179        })
180        const deltaUsd = r.costUsd - open.costUsd
181        const at5m = base + w5
182        const at1h = base + w1
183        const impliedWriteRate = writeTokens >= MIN_WRITE_FOR_RATE && !hasUnpriced ? ((deltaUsd - base) / writeTokens) * 1e6 : null
184        const near = (a: number, b: number) => Math.abs(a - b) <= Math.max(0.0005, Math.abs(b) * 0.02)
185        const matches = impliedWriteRate === null ? '?' : near(deltaUsd, at1h) ? '1h' : near(deltaUsd, at5m) ? '5m' : '?'
186        turns.push({ turnId: open.turnId, startedAt: open.at, endedAt: r.at, deltaUsd, writeTokens, at5m, at1h, impliedWriteRate, matches, hasUnpriced })
187      }
188      open = undefined
189    }
190  }
191  return turns
192}
193
194export type Unattributed = { from: number; to: number; usd: number }
195
196// Spend between one known total and the next that no logged request explains:
197// the totals come from turn starts and ends and from either side of each fork,
198// so whatever the running total gained between them was spent by something
199// else (a background request Claude Code made on its own).
200export function unattributedSpend(records: readonly ProbeRecord[]): Unattributed[] {
201  const found: Unattributed[] = []
202  let last: { at: number; costUsd: number } | undefined
203  const reach = (at: number, costUsd: number | null | undefined) => {
204    if (typeof costUsd !== 'number') return
205    if (last && costUsd - last.costUsd >= MIN_UNATTRIBUTED_USD) found.push({ from: last.at, to: at, usd: costUsd - last.costUsd })
206    last = { at, costUsd }
207  }
208  for (const r of records) {
209    if (r.kind === 'turn' && r.phase === 'start') reach(r.at, r.costUsd)
210    else if (r.kind === 'turn' && r.phase === 'end') last = typeof r.costUsd === 'number' ? { at: r.at, costUsd: r.costUsd } : undefined
211    else if (r.kind === 'fork') {
212      reach(r.startedAt, r.before.costUsd)
213      last = typeof r.after.costUsd === 'number' ? { at: r.at, costUsd: r.after.costUsd } : undefined
214    }
215  }
216  return found
217}
218
219const time = (ms: number) => new Date(ms).toTimeString().slice(0, 8)
220const minutes = (ms: number) => `${(ms / 60_000).toFixed(1)}m`
221const pct = (part: number, whole: number | null) => (whole ? `${Math.round((part / whole) * 100)}%` : '?')
222const usd = (n: number | null) => (n === null ? '?' : `$${n.toFixed(4)}`)
223
224function costDelta(before: Snapshot, after: Snapshot): string {
225  if (before.costUsd === null || after.costUsd === null) return '?'
226  return usd(after.costUsd - before.costUsd)
227}
228
229function limitsText(limits: readonly Limit[]): string {
230  return limits.length === 0 ? 'none reported' : limits.map(l => `${l.kind} ${l.percentUsed}%`).join(', ')
231}
232
233// What the five Phase 0 questions read from the log: each fork's cache hit and
234// cost, the first request of each turn after an idle gap, and how the
235// rate-limit readings moved. The raw JSONL holds everything else.
236export function report(records: readonly ProbeRecord[]): string {
237  const lines: string[] = []
238  let lastRequest: number | undefined
239  let lastTurnStart: number | undefined
240  let awaitingFirstStep = false
241  const forks: string[] = []
242  const firstSteps: string[] = []
243  const limits: Limit[][] = []
244  const ttls = new Set<string>()
245  const marks: string[] = []
246
247  for (const r of records) {
248    switch (r.kind) {
249      case 'turn':
250        if (r.phase === 'start') {
251          lastTurnStart = r.at
252          awaitingFirstStep = true
253        }
254        break
255      case 'step': {
256        if (r.agentId === undefined && awaitingFirstStep && lastTurnStart !== undefined) {
257          const idle = lastRequest === undefined ? '-' : minutes(r.startedAt - lastRequest)
258          firstSteps.push(
259            `  ${time(r.startedAt)}  idle ${idle.padStart(6)}  read ${String(r.tokens.cacheRead).padStart(8)}` +
260              `  write ${String(r.tokens.cacheWrite).padStart(8)}  input ${r.tokens.input}  ${r.model}`,
261          )
262          awaitingFirstStep = false
263        }
264        if (r.agentId === undefined) lastRequest = r.startedAt
265        break
266      }
267      case 'fork': {
268        const idle = lastRequest === undefined ? '-' : minutes(r.startedAt - lastRequest)
269        const t = r.tokens
270        forks.push(
271          t
272            ? `  ${time(r.startedAt)}  ${r.label.padEnd(10)}  idle ${idle.padStart(6)}  ctx ${String(r.contextTokens ?? '?').padStart(8)}` +
273                `  read ${String(t.cacheRead).padStart(8)} (${pct(t.cacheRead, r.contextTokens)})  write ${t.cacheWrite}` +
274                `  input ${t.input}  output ${t.output}  Δcost ${costDelta(r.before, r.after)}  ${r.result}`
275            : `  ${time(r.startedAt)}  ${r.label.padEnd(10)}  ${r.result}${r.status ? ` (${r.status})` : ''}`,
276        )
277        if (t) lastRequest = r.startedAt
278        if (r.after.rateLimits.length > 0) limits.push(r.after.rateLimits)
279        break
280      }
281      case 'measure':
282        if (r.snapshot.rateLimits.length > 0) limits.push(r.snapshot.rateLimits)
283        break
284      case 'ttl':
285        ttls.add(`${r.ttl} (${r.source})`)
286        break
287      case 'mark':
288        marks.push(`  ${time(r.at)}  ${r.text}`)
289        break
290      case 'skip':
291        forks.push(`  ${time(r.at)}  ${r.label.padEnd(10)}  skipped: ${r.why}`)
292        break
293    }
294  }
295
296  lines.push(`Forks (${forks.length})`, ...(forks.length ? forks : ['  none yet']))
297  lines.push('', 'First request of each turn', ...(firstSteps.length ? firstSteps : ['  none yet']))
298  const turns = turnCosts(records)
299  lines.push(
300    '',
301    'Turn cost against its tokens (writes priced at the 5-minute and 1-hour rates)',
302    ...(turns.length
303      ? turns.map(
304          t =>
305            `  ${time(t.startedAt)}  write ${String(t.writeTokens).padStart(8)}  Δcost ${usd(t.deltaUsd)}` +
306            `  5m ${usd(t.at5m)}  1h ${usd(t.at1h)}` +
307            `  implied ${t.impliedWriteRate === null ? '-' : `$${t.impliedWriteRate.toFixed(2)}/M`}  matches ${t.matches}` +
308            (t.hasUnpriced ? '  (a model with no list price)' : ''),
309        )
310      : ['  none recorded (turns logged before this version carry no totals)']),
311  )
312  const other = unattributedSpend(records)
313  lines.push(
314    '',
315    'Spend no logged request explains',
316    ...(other.length ? other.map(u => `  ${time(u.from)} → ${time(u.to)}  ${usd(u.usd)}`) : ['  none']),
317  )
318  const first = limits[0]
319  const last = limits[limits.length - 1]
320  lines.push('', `Rate limits: first ${first ? limitsText(first) : 'none reported'}; last ${last ? limitsText(last) : 'none reported'}`)
321  lines.push(`Cache lifetime reported: ${ttls.size ? [...ttls].join(', ') : 'not yet'}`)
322  if (marks.length) lines.push('', 'Marks', ...marks)
323  return lines.join('\n')
324}
325
hooks/pricing.ts 49 lines
1// List prices in USD per million tokens, copied from cost-ledger's
2// hooks/pricing.ts: the probe sits outside that plugin and cannot import it.
3// Only what the report needs to compare a turn's cost against its tokens.
4
5export type Rates = { input: number; output: number; cacheRead: number; cacheWrite5m: number; cacheWrite1h: number }
6
7const listRates = (input: number, output: number, cacheRead: number): Rates => ({
8  input,
9  output,
10  cacheRead,
11  cacheWrite5m: input * 1.25,
12  cacheWrite1h: input * 2,
13})
14
15const LIST_RATES: readonly [string, Rates][] = [
16  ['mythos-5-1', listRates(10, 50, 0.25)],
17  ['mythos-5', listRates(10, 50, 1)],
18  ['fable-5-1', listRates(10, 50, 0.25)],
19  ['fable-5', listRates(10, 50, 1)],
20  ['opus-5-5', listRates(4, 20, 0.2)],
21  ['opus-5', listRates(5, 25, 0.5)],
22  ['opus-4-8', listRates(5, 25, 0.5)],
23  ['opus-4-7', listRates(5, 25, 0.5)],
24  ['opus-4-6', listRates(5, 25, 0.5)],
25  ['sonnet-5-5', listRates(2, 10, 0.2)],
26  ['sonnet-5', listRates(2, 10, 0.2)],
27  ['sonnet-4-6', listRates(3, 15, 0.3)],
28  ['haiku-4-5', listRates(1, 5, 0.1)],
29]
30
31// A family matches where the id does not continue with another version
32// number, so "opus-5" does not claim "claude-opus-5-5".
33function matchesFamily(model: string, family: string): boolean {
34  let at = model.indexOf(family)
35  while (at !== -1) {
36    if (!/^(\d|-\d{1,2}(?!\d))/.test(model.slice(at + family.length))) return true
37    at = model.indexOf(family, at + 1)
38  }
39  return false
40}
41
42export function ratesFor(model: string): Rates | undefined {
43  let best: [string, Rates] | undefined
44  for (const entry of LIST_RATES) {
45    if (matchesFamily(model, entry[0]) && (best === undefined || entry[0].length > best[0].length)) best = entry
46  }
47  return best?.[1]
48}
49