SLOPSHOPPER

cache-keeper

Observes prompt-cache usage, keeps the session's and its finished subagents' caches warm, and runs 5m/1h TTL A/B experiments.

bandguardcommandtoaststatusprompt
★ 3v0.5.0MITupdated 2026-10-26wdsewdser-bit/claude-code-mods/cache-keeper
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-keeper
› 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 › /cache-keeper ⎿ cache-keeper: keeper on · 缓存 TTL? · 0k · TTL 未知 ⎿ cache-keeper: anchor off ⎿ cache-keeper: Claude Code 2.1.289 · model claude-opus-5-5 · effort unknown ⎿ cache-keeper: TTL requested: automatic (automatic) · observed in transcript: not yet · scheduling by: unknown ⎿ cache-keeper: cached prefix: 0 tokens (minimum 40000) · no request seen yet ⎿ cache-keeper: keepalives this idle stretch: 0 of 3 · hits 0 · misses 0 ● 保活 · 缓存 TTL? · 0k · TTL 未知 关闭 anchor-toggle ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
● 保活 · 缓存 TTL? · 0k · TTL 未知 关闭 anchor-toggle ⟨Claude Code's own drawing⟩
README

cache-keeper

Claude Code mod(function hooks 插件):观察 prompt cache、在同一进程内保活、跑 5m / 1h TTL 的 A/B 实验并出报告。按《Claude Code 缓存保活与 5 分钟缓存 A/B 测试实施规范》v1.0 实现,针对 Claude Code 2.1.288 的 Mods API,2026-10-08 在 2.1.293 上复验(validate、test、transcript 解析)。

保活只能用 $.model.fork:缓存按模型和前缀存,换成 Haiku 或 $.model.complete({ cache: true }) 的请求是另一条 5 分钟缓存,续不了主会话的 1 小时条目。

安装

/plugin install cache-keeper --marketplace wdsewdser-bit/claude-code-mods

命令

命令作用
/cache-keeper status版本、模型、TTL(请求值 / 日志实测值)、缓存前缀、idle、meter
/cache-keeper start / stop开 / 关保活。默认开;stop 只关当前 session
`/cache-keeper anchor [onoff]`查看 / 设置当前会话是否为锚点(见「锚点会话」);on 会顺带开启保活,off 不动保活开关
/cache-keeper probe立刻做一次 $.model.fork 探测,报告命中情况与 meter 前后值
/cache-keeper agents子代理的 TTL、被跟踪的子代理和保活计数;agents ping 立刻给每个都保活一次
/cache-keeper experiment preflight不花 token 的实验前检查
/cache-keeper experiment <plan>在当前 session 跑一个实验 cell(见下)
/cache-keeper experiment abort中止当前实验
/cache-keeper report生成 cache-events.csv、experiment-summary.json、cache-report.md

保活规则

保活默认开启,只在全部成立时发一次 $.model.fork({ prompt: 'Reply with OK only.' }):没有被 stop;没有 turn 在跑;最近一次主线程请求的缓存前缀(read + write)≥ minCacheReadTokens;距该请求开始已到阈值(5m:245 s,1h:3120 s)但未超过 TTL;meter 未到 maxRateLimitPercent;没有处于"待重建基线"。

  • TTL 已过就不再发:那只会是一次整段重写,等下一次真实请求。
  • 一段 idle 内的保活次数有上限 maxIdleKeepalives,默认 3(1h TTL 下约覆盖 4 小时闲置),之后任缓存过期;设 0 = 按 API 单价的 break-even(Opus 5.5:5m 24 次、1h 39 次;Sonnet 5.5:5m 24 次)。这是 API 口径的启发式,不是套餐额度结论。
  • 连续 maxConsecutiveProbeFailures 次 miss / 失败,或 5 小时额度超阈值:自动停止并提示。周额度不参与:它没用完时停保活只会换来一次整段重写,用完后请求失败,按失败次数停。
  • 模型或 effort 变化、compact 之后:暂停,直到下一次真实请求再次命中缓存。/clear 后等待新基线。
  • 不启动第二个 claude --resume 进程,不碰认证 token,不调用私有接口。

子代理保活

子代理的缓存和主会话是两套:前缀不同,互相不续期;TTL 也分开,引擎默认给主会话以外的请求(子代理、workflow、后台请求)5 分钟。要 1 小时,在 ~/.claude/settings.json 里写 "subagentPromptCacheTtl": "1h",或设环境变量 CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL=1h(优先于设置)。settings.json 只要有一处语法错误,整个文件都不生效,引擎不报错。

一个子代理跑完后,mod 按它最后一次请求计时,到阈值(1h:3120 s,5m:245 s)就用 $.session.send 把它唤起一次,只让它回 OK:这次请求读它自己的缓存前缀,TTL 重新计。每个子代理最多 subagentKeepalives 次(默认 2,1h 下约覆盖 2.7 小时;0 = 关),主模型再给它派活后重新计数。

  • 只保 minCacheReadTokens 以上的前缀;主保活被 stop、或 meter 到 maxRateLimitPercent 时不发。
  • 保活的那一轮结束时引擎会给主会话发完成通知,mod 在 prompt.submit 把它丢掉,主模型不会被叫起来。transcript 里留一行 "Prompt dropped by a hook: cache-keeper kept subagent … warm"。
  • 子代理的对话里会多出保活的一问一答,各几十个 token。
  • 某次保活没命中(实际 TTL 比设想的短):不再保那个子代理;连续 maxConsecutiveProbeFailures 次就整个停掉子代理保活。
  • 后台子代理按引擎的列表认,前台子代理按 session 存下的 subagents/agent-<id>.meta.json 认;引擎自己的 fork(compact 等)两处都没有,不会被唤起。agent 定义里单独写的 cacheTtl 这里看不到。

TTL 的来源与验证

请求值按引擎自己的优先级读取:FORCE_PROMPT_CACHING_5M > CLAUDE_CODE_PROMPT_CACHE_TTL > 设置项 promptCacheTtl > 自动(订阅内 1h)。

Mods API 的 usage 只有四个 token 计数,没有 5m/1h 拆分。所以实测值来自 transcript:每个 turn 结束后读 message.usage.cache_creation.ephemeral_5m/1h_input_tokens 和 message.diagnostics.cache_miss_reason,按"四个计数相同 + 时间最近"配到在线记录上。请求值与实测值不符时标 TTL_CONFIG_MISMATCH,该 run 不进入成本比较。没有请求值时,保活按实测值排程;两者都没有就不保活。

实验

无人值守跑一组(CLI 需先 claude auth login 登录一次):

node "$HOME/.claude/skills/cache-keeper/scripts/run-experiments.ts" --dry-run

去掉 --dry-run 即开跑。默认组是 A、B 各一次加 C1 每个 TTL 三次(约 3.8 小时);--set smoke 只跑 A@5m(2 分钟),--set full 再加 C2 和 D(约 11.6 小时);--cells keeper:5m,keeper-control:1h --reps 3 自选。它为每个 cell 起一个全新的无头 session、设好 TTL、等 mod 写出 run 记录后关掉,第一个 cell 失败或 meter 到 85% 就停,最后生成报告。

手动跑单个 cell:每个 cell 用一个全新 session,TTL 在启动前定好:

& "$HOME\.claude\skills\cache-keeper\scripts\run-cell.ps1" -Ttl 5m

session 内先 /cache-keeper experiment preflight,再跑一个 plan:

plan实验时长内容
ttlA1.5 min建缓存,90 s 后 probe。5m 和 1h 各跑一次
renewB12 min5m:4:00、8:00 保活,12:00 probe
renew-controlB 对照6.5 min5m:不保活,6:30 probe
activeC133 min每 3 分钟一次 probe,共 11 次。5m 和 1h 各 3 次
intermittentC250 min每 10 分钟一次 probe,共 5 次。5m 和 1h 各 3 次
keeperD218 min5m:每 4:05 保活,18:00 probe
keeper-controlD118 min不保活,18:00 probe。5m 是对照,1h 是"直接用 1h"基线

"建缓存"是提交一条带约 60k token 静态填充的消息(tokens=N 可调),填充以本次 run 的 nonce 开头,所以不同 run 不会读到彼此的缓存。benchmark probe 是真实 turn(写进 transcript,能拿到 5m/1h 拆分),keeper 步骤是 fork。

实验期间不要用这个账号做别的事:本 session 的 subagent、实验外的 turn、其他装了本 mod 的 Claude Code session 的请求都会让该 run 标记为 contaminated 并排除出主统计。网页和手机端的使用从这里看不到,需要自己保证。

数据

所有 session 共用一个目录,默认 ~/.claude/cache-keeper/(dataDir 可改;写相对路径就落在各 session 的工作目录下):

~/.claude/cache-keeper/
  cache-events.csv           每个请求一行(规范 §13 的字段,另加 result、cost_basis)
  experiment-summary.json    按 cell 汇总 + 对比 + 结论
  cache-report.md
  raw/
    events-<session>-<n>.jsonl   在线记录,含 meter 前后值
    run-<实验>-<ttl>-r<n>-<session>.json

报告把两种成本分开:API 等价成本按官方单价(2026-10-08 核对,含 Haiku 5.5 按 prompt 长度的两档)由日志算;套餐额度只看 $.session.usage().rateLimits 的百分比增量。meter 判定要求每侧至少 3 次干净重复、且增量至少 2 个百分点,否则写"无法判断"。

离线工具(Node 24+,只读 transcript):

node scripts/analyze-transcript.ts <session.jsonl>
node scripts/analyze-transcript.ts --report <dataDir>

解释一次缓存未命中(CACHE-01)

node scripts/explain-cache.ts <session.jsonl>            # 或 --session <id> 在 ~/.claude/projects 下找
node scripts/explain-cache.ts <session.jsonl> --json     # 机器可读
node scripts/explain-cache.ts <session.jsonl> --tail 20  # 只看最后 20 个请求

逐个请求列出:工具清单 hash、系统提示 hash / 字符数、插件集 hash(MCP + skills,能拿到多少算多少)、cache_read / cache_creation、缓存是否命中、距上次请求的间隔、TTL,以及未命中的原因。原因分三级:

  • observed:transcript 里直接可见。message.diagnostics.cache_miss_reason、工具清单 hash 变化、系统提示 hash 变化、插件集 hash 变化、previous_message_not_found(服务端驱逐)、两次请求之间的 compact_boundary(compaction,带 trigger)。
  • inferred:只能推断。距上次请求超过 TTL、模型变化、客户端版本变化、空闲压缩(idle_compact)。
  • 空闲压缩(idle_compact):引擎在缓存过期前按 TTL 的 0.9(1h 缓存约 54 分钟)给空闲的大会话做压缩。transcript 的 compactMetadata 只写 trigger(manual / auto)和 token 数,引擎内部标记 precomputed 目前不落盘(2.1.299–2.1.306 的 469 条边界里一条都没有),所以:边界带 precomputed: true 时记 observed;否则只有 trigger 为 auto 且压缩前空闲 ≥ 50 分钟时记 inferred。同一段空闲后因上下文超限触发的 auto 压缩看起来一模一样,无法区分;manual 压缩即使空闲很久也仍是普通 compaction。
  • unknown:没有可见原因,或该会话的 transcript 根本没带前缀信息。拿不到的字段标 unknown,不猜。

hash 的输入是 transcript 里的 prompt_snapshot、deferred_tools_record / deferred_tools_delta、mcp_instructions_delta、skill_listing。没有工具定义时工具 hash 按名字算(toolHashBasis: names),两者都没有就是 none;插件集同理(mcp+skills / mcp / skills / none)。系统提示只存 hash 和长度,不存正文。

影子模式与净收益(CACHE-02)

shadowMode(默认 false):不发送任何保活请求,只把"这次本该保活"记成 kind: shadow / result: would_have_keepalive 的事件;用户下一次请求到来时再记一行 kind: recovery,带 shadow_recovery_sec(距上一次请求的真实间隔)。影子模式不改动真实保活的状态(lastActivityAt、idleKeepalives、失败计数、暂停原因),关掉开关后行为与原来一致;子代理的 would-have 也会记录(带 agent_id)。

统计脚本(Node 24+,只读 transcript,可选读事件目录):

node scripts/keepalive-net.ts                                   # 最近 200 个转录
node scripts/keepalive-net.ts --sort size --max-files 40        # 最长的会话
node scripts/keepalive-net.ts --events ~/.claude/cache-keeper   # 附带影子事件统计
node scripts/keepalive-net.ts --prices '[["opus-5-5",{"input":4,"write5m":5,"write1h":8,"read":0.2,"output":20}]]'

对每一对相邻请求:间隔超过 TTL、前缀 ≥ --min-prefix(默认 40000)才计入;按 keeper 的阈值(5m 245 s / 1h 3120 s)模拟最多 --max-idle 次保活。省下的钱 = 下一次请求实际写入的 cache_creation_input_tokens ×(写价 − 读价),且只在下一次请求没有命中缓存时计;成本 = 每次保活按读价读整段前缀 + 少量输入/输出。价格是 API 等价 USD / 百万 token,默认值在脚本顶部,来源 platform.claude.com/docs/en/about-claude/pricing(2026-10-08 读取),可用 --prices 覆盖。

大转录默认按 --max-bytes(12 MB)和 --max-total-bytes(200 MB)跳过,跳过的数量会打印出来;要覆盖更多就调大这两个值。--ttl auto 用线程里最后一次可见的 5m/1h 拆分,mixed 按 1h;没有拆分时按 5m,并在输出里给出 ttlDefaultedGaps。

已知限制

  • fork 请求不写进 transcript,所以 keeper 行拿不到 5m/1h 拆分;它极少写缓存,写了就按该 session 的 TTL 计价(cost_basis 会标 assumed-*)。
  • 前台子代理运行期间主会话的 turn 还没结束,主保活不发;单个子代理连续跑过主会话的 TTL,回来那一步会整段重写。
  • system prompt / 工具定义的变化没有直接事件,只能通过随后请求的 miss 和 cache_miss_reason 看出来。
  • transcript 超过 4 MiB 时改用 node scripts/analyze-transcript.ts --tail 读尾部;没有 node 就拿不到拆分。
  • Mods API 仍是 early access,升级 Claude Code 后先跑 claude plugin validate 和 claude plugin test。

额度桥接(v0.4.0)

5 小时额度到 bridgeAtPercent(默认 90)时:给主会话发一条收尾消息(只完成当前一步、写交接、停下);之后按 TTL 持续保活到额度重置(不受 maxIdleKeepalives 限制,不设百分比停止线(额度再高也保,直到重置);距重置够近、缓存撑得到重置后的「继续」就不再多 ping);重置后约 20 秒自动发「继续」。

  • 只有最近 10 分钟(取它与缓存 TTL 中更短的一个)内有用户或助手消息、或仍在跑回合、或仍有后台任务的会话才会被唤醒;久未动的旧会话不会被叫起来。保活 fork 不算活动,不刷新计数。
  • 不给子代理发任何消息。每个窗口只收尾一次。
  • 收尾后你自己又发了消息 = 接管,重置后不再自动继续。stop(命令或按钮)取消桥接。
  • 输入框上方有一条状态栏,带「开启保活」「关闭保活」两个按钮,等同 /cache-keeper start|stop,只作用于当前会话。
  • 周额度到 weeklyHandoffAtPercent(默认 98,0 = 关)时,给最近 10 分钟内有用户消息、或仍在跑回合、或仍有后台任务的主会话发一条通知:写一份交接检查点(更新已有台账,没有就新建 HANDOFF.md),然后继续干活。每个周窗口只发一次;不叫停、不保活到重置、重置后不自动继续,由新对话按文档接手。与保活开关无关。
  • 选项:bridgeEnabled、bridgeAtPercent、weeklyHandoffAtPercent。逻辑在 hooks/lib/bridge.ts,测试在 tests/bridge.test.ts。

给其他 mod 读的缓存状态(v0.4.1)

  • $.state 里发布 cache-keeper.cache:{ lastActivityAt, ttl, expiresAt, cachedPrefixTokens, isEnabled, pausedReason, bridgePhase }。expiresAt 之后缓存就是冷的;bridgePhase 为 wrapped 表示已发收尾、正在等 5 小时额度重置。别的 mod 把 cache-keeper 列进 dependencies 后用 $.state.get({ plugin: 'cache-keeper', key: 'cache' }) 读,只读。
  • 别的 mod 回答了压缩(不调 next)时,本 mod 的 session.compact 钩子可能收不到。另加两道判断,任一成立就按"已压缩"暂停保活,直到下一次真实请求再次命中:引擎存下压缩边界行(session.append,door: compaction);或保活前发现当前上下文不到所记前缀的一半。

锚点会话(v0.5.0)

用途:让一个几乎空的会话长期挂着,靠保活让跨会话共享的系统前缀缓存不过期,别的会话开局就能命中它。

  • 开启:/cache-keeper anchor on(保活原本是关的则一并开启),或点输入框上方栏里的「设为锚点」;anchor off 或「取消锚点」只清掉锚点标记,不改保活开关;/cache-keeper anchor 查看当前状态。栏文字在锚点开启时带「锚点」。状态跨重载保存。
  • 与普通保活的差别:不受 maxIdleKeepalives 限制(status 里 budget 显示 unbounded),也没有 5 小时额度的百分比停止线(与额度桥接期间一致)。其余停止条件不变:被 stop、连续失败、压缩暂停、前缀小于 minCacheReadTokens。
  • 缓存一旦过期仍不会补写:弹一次提示「anchor cache expired」,之后要在该会话里手动发一条消息重建;下一次真实请求或保活命中后提示复位。
  • 只有锚点与目标会话的插件 / MCP / 工具集一致,系统前缀才相同、缓存才共享;两边不一致时锚点保的是另一份缓存。
Source 10 files
hooks/register.tsx 2232 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, Timer } from 'claude-code'
3
4import {
5  describeBridge,
6  fiveHour,
7  handoffText,
8  initialBridge,
9  countInFlight,
10  isBackgroundBusy,
11  needsPing,
12  resetMs,
13  resumeText,
14  resumeVerdict,
15  sevenDay,
16  shouldHandoff,
17  shouldWrap,
18  windowKey,
19  wrapText,
20} from './lib/bridge.ts'
21import type { Bridge } from './lib/bridge.ts'
22
23import {
24  classifyUsage,
25  effectiveTtl,
26  isTtlMismatch,
27  observedTtl,
28  requestedSubagentTtl,
29  requestedTtl,
30} from './lib/classify.ts'
31import type { ObservedTtl, SubagentTtlRequest, TtlRequest } from './lib/classify.ts'
32import {
33  buildPrompt,
34  marker,
35  planDurationSec,
36  planNamed,
37  PLANS,
38  probePromptFor,
39} from './lib/experiment.ts'
40import type { Plan, StepKind } from './lib/experiment.ts'
41import {
42  cacheStateOf,
43  decide,
44  decideAgent,
45  describeKeeper,
46  hasShrunk,
47  initialKeeperState,
48  isOverStopLine,
49  unboundedView,
50} from './lib/keeper.ts'
51import type {
52  AgentTrack,
53  Decision,
54  KeeperConfig,
55  KeeperState,
56  RateLimit,
57} from './lib/keeper.ts'
58import { matchSplits, parseTranscript } from './lib/parser.ts'
59import {
60  apiEquivalentCost,
61  breakEvenKeepalives,
62  ZERO_USAGE,
63} from './lib/pricing.ts'
64import type { CacheSplit, Ttl, Usage } from './lib/pricing.ts'
65import { parseJsonl, renderReport, summarize, toCsv } from './lib/report.ts'
66import type { EventRow, RunRecord, RunStep } from './lib/report.ts'
67
68const COMMAND = 'cache-keeper'
69const TICK_MS = 5_000
70const CHUNK_ROWS = 1_000
71const MIN_VERSION = [2, 1, 242] as const
72const DEFAULT_FIXTURE_TOKENS = 60_000
73const STALE_MS = 14 * 24 * 3_600_000
74// One place for every session, whatever project it runs in.
75const DEFAULT_DATA_DIR = '~/.claude/cache-keeper'
76const METER_KEY = 'meter:last'
77// What the bar above the prompt reads: a write redraws it.
78const barAtom = atom({ plugin: 'cache-keeper', key: 'bar' } as const, '')
79// What another mod reads to tell a warm cache from a cold one.
80const cacheAtom = atom(
81  { plugin: 'cache-keeper', key: 'cache' } as const,
82  cacheStateOf(initialKeeperState(false), 'idle'),
83)
84const METER_CARRY_MS = 120_000
85// What a finished subagent is resumed with to have its cached prefix read
86// again. It answers in its own loop; the notice of that never reaches the model.
87const AGENT_PING =
88  'Cache keepalive from the cache-keeper plugin. Nothing has changed and nothing is asked of you: reply with OK only and call no tools.'
89const PING_TIMEOUT_MS = 120_000
90const QUIET_MS = 600_000
91
92type Config = KeeperConfig & {
93  enabled: boolean
94  dataDir: string
95  maxIdleKeepalives: number
96  subagentKeepalives: number
97  bridgeEnabled: boolean
98  bridgeAtPercent: number
99  weeklyHandoffAtPercent: number
100  probePrompt: string
101  writeCsv: boolean
102  writeJson: boolean
103  showStatus: boolean
104  /** Record keepalives instead of sending them. Off by default. */
105  shadowMode: boolean
106}
107
108type Tag = {
109  experimentId: string
110  replicate: number
111  note: StepKind
112  stepIndex: number
113}
114
115type Run = {
116  plan: string
117  experimentId: string
118  replicate: number
119  nonce: string
120  requestedAt: number
121  /** When the build request started; the plan's steps count from it. */
122  startedAt: number | null
123  next: number
124  isInFlight: boolean
125  meterStart: RateLimit[]
126  contamination: string[]
127  warnings: string[]
128  steps: RunStep[]
129  fixtureTokens: number
130}
131
132type Session = {
133  id: string
134  version: string
135  model: string
136  effort: string
137  requested: TtlRequest
138  subagent: SubagentTtlRequest
139  /** The subagents whose cache is worth keeping, by agent id. */
140  agents: Map<string, AgentTrack>
141  agentHits: number
142  agentMisses: number
143  agentFailures: number
144  agentStopNote: string | null
145  /** Pinged subagents whose notice of finishing is not for the model: id, when. */
146  quiet: Map<string, number>
147  observed: ObservedTtl
148  keeper: KeeperState
149  baseline: { model: string; effort: string } | null
150  transcriptPath: string | null
151  rows: EventRow[]
152  chunk: number
153  keeperHits: number
154  keeperMisses: number
155  run: Run | null
156  pending: (Tag & { marker: string; since: number }) | null
157  tags: Map<string, Tag>
158  stopNote: string | null
159  /** Whether the person, or an automatic stop, set the keeper on or off here. */
160  isEnabledDecided: boolean
161  lastStatus: string | undefined
162  heartbeatAt: number
163  /** The last user or assistant message of the main thread, in ms. */
164  lastRealAt: number | null
165  bridge: Bridge
166  /** No keepalive before this: the fork found no request of this process to share yet. */
167  forkRetryAt: number
168  /** Background tasks this main thread launched whose task-notification has not come back. */
169  backgroundPending: number
170  /** When the last of them was launched, in ms. */
171  backgroundSeenAt: number | null
172  /** An anchor session is kept warm without the idle cap, to hold a shared prefix. */
173  isAnchor: boolean
174  /** The expiry of an anchor's cache was already announced; not saved. */
175  isAnchorExpiryNoted: boolean
176  /** Shadow mode: the simulated last request, advanced by would-have keepalives. */
177  shadowLastAt: number | null
178  /** Shadow mode: would-have keepalives in the current idle stretch. */
179  shadowKeepalives: number
180  /** Shadow mode: when the last would-have keepalive was due. */
181  shadowWouldHaveAt: number | null
182  /** Shadow mode: would-have keepalives recorded this session. */
183  shadowWouldHave: number
184}
185
186const isRecord = (value: unknown): value is Record<string, unknown> =>
187  typeof value === 'object' && value !== null && !Array.isArray(value)
188
189const numberOf = (value: unknown, fallback: number): number =>
190  typeof value === 'number' && Number.isFinite(value) ? value : fallback
191
192const stringOf = (value: unknown, fallback: string): string =>
193  typeof value === 'string' && value !== '' ? value : fallback
194
195const booleanOf = (value: unknown, fallback: boolean): boolean =>
196  typeof value === 'boolean' ? value : fallback
197
198const messageOf = (error: unknown): string =>
199  error instanceof Error ? error.message : String(error)
200
201const attempt = async <T,>(run: () => Promise<T>, fallback: T): Promise<T> => {
202  try {
203    return await run()
204  } catch {
205    return fallback
206  }
207}
208
209const iso = (ms: number): string => new Date(ms).toISOString()
210
211const minutes = (ms: number): string => {
212  const seconds = Math.max(0, Math.round(ms / 1000))
213
214  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
215}
216
217const readConfig = (options: PluginOptions): Config => ({
218  enabled: booleanOf(options.enabled, true),
219  dataDir: stringOf(options.dataDir, DEFAULT_DATA_DIR).replace(/[\\/]+$/, ''),
220  minCacheReadTokens: numberOf(options.minCacheReadTokens, 40_000),
221  ttl5mKeepaliveAtSec: numberOf(options.ttl5mKeepaliveAtSec, 245),
222  ttl1hKeepaliveAtSec: numberOf(options.ttl1hKeepaliveAtSec, 3_120),
223  maxRateLimitPercent: numberOf(options.maxRateLimitPercent, 90),
224  maxConsecutiveProbeFailures: numberOf(options.maxConsecutiveProbeFailures, 2),
225  maxIdleKeepalives: numberOf(options.maxIdleKeepalives, 3),
226  bridgeEnabled: booleanOf(options.bridgeEnabled, true),
227  bridgeAtPercent: numberOf(options.bridgeAtPercent, 90),
228  weeklyHandoffAtPercent: numberOf(options.weeklyHandoffAtPercent, 98),
229  subagentKeepalives: numberOf(options.subagentKeepalives, 2),
230  probePrompt: stringOf(options.probePrompt, 'Reply with OK only.'),
231  writeCsv: booleanOf(options.writeCsv, true),
232  writeJson: booleanOf(options.writeJson, true),
233  showStatus: booleanOf(options.showStatus, false), // 按钮栏已实时显示保活信息,状态行默认不再重复
234  shadowMode: booleanOf(options.shadowMode, false),
235})
236
237const usageOf = (row: EventRow): Usage => ({
238  input_tokens: row.input_tokens,
239  output_tokens: row.output_tokens,
240  cache_read_input_tokens: row.cache_read_input_tokens,
241  cache_creation_input_tokens: row.cache_creation_input_tokens,
242})
243
244const splitOf = (row: EventRow): CacheSplit | null =>
245  row.ephemeral_5m_input_tokens === null
246    ? null
247    : {
248        ephemeral_5m_input_tokens: row.ephemeral_5m_input_tokens,
249        ephemeral_1h_input_tokens: row.ephemeral_1h_input_tokens ?? 0,
250      }
251
252const isAtLeast = (version: string, floor: readonly number[]): boolean => {
253  const parts = version.split(/[.-]/).map(Number)
254  for (const [index, wanted] of floor.entries()) {
255    const have = parts[index] ?? 0
256    if (Number.isNaN(have)) return false
257    if (have !== wanted) return have > wanted
258  }
259
260  return true
261}
262
263// Module state: one session per load. register() resets it, as a reload does.
264let config: Config = readConfig({})
265let booting: Promise<Session> | undefined
266let carriedEnabled: boolean | undefined
267let timer: Timer | undefined
268let isTicking = false
269
270const debug = ($: EngineInterface, error: unknown): void => {
271  $.ui.log(`error: ${messageOf(error)}`, { to: 'debug' })
272}
273
274const eventsPath = (s: Session): string =>
275  `${config.dataDir}/raw/events-${s.id}-${s.chunk}.jsonl`
276
277const limitsNow = async ($: EngineInterface): Promise<RateLimit[]> =>
278  attempt(async () => [...(await $.session.usage()).rateLimits], [])
279
280const boot = async ($: EngineInterface): Promise<Session> => {
281  if (config.dataDir.startsWith('~')) {
282    const home =
283      (await attempt(() => $.env.get('USERPROFILE'), undefined)) ??
284      (await attempt(() => $.env.get('HOME'), undefined))
285    const under = `${home?.replace(/[\\/]+$/, '')}${config.dataDir.slice(1)}`
286    config = {
287      ...config,
288      dataDir:
289        home === undefined
290          ? '.cache-keeper'
291          : home.includes('\\')
292            ? under.replaceAll('/', '\\')
293            : under,
294    }
295  }
296  const id = await attempt(() => $.session.id(), 'unknown')
297  const version = await attempt(
298    async () => (await $.session.version()).version,
299    'unknown',
300  )
301  const settings = await attempt(
302    async () => (await $.settings.read()) as unknown as Record<string, unknown>,
303    {},
304  )
305  const force5m = await attempt(() => $.env.get('FORCE_PROMPT_CACHING_5M'), undefined)
306  const s: Session = {
307    id,
308    version,
309    model: await attempt(() => $.session.model(), 'unknown'),
310    effort: '',
311    requested: requestedTtl({
312      force5m,
313      envTtl: await attempt(() => $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'), undefined),
314      settingTtl: settings.promptCacheTtl,
315    }),
316    subagent: requestedSubagentTtl({
317      force5m,
318      envTtl: await attempt(
319        () => $.env.get('CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL'),
320        undefined,
321      ),
322      settingTtl: settings.subagentPromptCacheTtl,
323      enable1h: await attempt(() => $.env.get('ENABLE_PROMPT_CACHING_1H'), undefined),
324    }),
325    agents: new Map(),
326    agentHits: 0,
327    agentMisses: 0,
328    agentFailures: 0,
329    agentStopNote: null,
330    quiet: new Map(),
331    observed: null,
332    keeper: initialKeeperState(carriedEnabled ?? config.enabled),
333    baseline: null,
334    transcriptPath: null,
335    rows: [],
336    chunk: 0,
337    keeperHits: 0,
338    keeperMisses: 0,
339    run: null,
340    pending: null,
341    tags: new Map(),
342    stopNote: null,
343    isEnabledDecided: false,
344    lastStatus: undefined,
345    heartbeatAt: 0,
346    lastRealAt: null,
347    bridge: initialBridge(),
348    forkRetryAt: 0,
349    backgroundPending: 0,
350    backgroundSeenAt: null,
351    isAnchor: false,
352    isAnchorExpiryNoted: false,
353    shadowLastAt: null,
354    shadowKeepalives: 0,
355    shadowWouldHaveAt: null,
356    shadowWouldHave: 0,
357  }
358  carriedEnabled = undefined
359
360  const saved = await attempt(() => $.store.get(`s:${id}`), undefined)
361  if (isRecord(saved)) {
362    // The default decides until someone has: a session saved before a change
363    // of default follows the new one.
364    s.isEnabledDecided = saved.isEnabledDecided === true
365    if (s.isEnabledDecided) {
366      s.keeper.enabled = booleanOf(saved.enabled, s.keeper.enabled)
367    }
368    s.keeper.lastActivityAt =
369      typeof saved.lastActivityAt === 'number' ? saved.lastActivityAt : null
370    s.keeper.cachedPrefixTokens = numberOf(saved.cachedPrefixTokens, 0)
371    s.lastRealAt = typeof saved.lastRealAt === 'number' ? saved.lastRealAt : null
372    s.isAnchor = saved.isAnchor === true
373    s.backgroundPending = numberOf(saved.backgroundPending, 0)
374    s.backgroundSeenAt =
375      typeof saved.backgroundSeenAt === 'number' ? saved.backgroundSeenAt : null
376    s.shadowLastAt =
377      typeof saved.shadowLastAt === 'number' ? saved.shadowLastAt : null
378    s.shadowKeepalives = numberOf(saved.shadowKeepalives, 0)
379    s.shadowWouldHaveAt =
380      typeof saved.shadowWouldHaveAt === 'number' ? saved.shadowWouldHaveAt : null
381    s.shadowWouldHave = numberOf(saved.shadowWouldHave, 0)
382    if (isRecord(saved.bridge)) {
383      const b = saved.bridge
384      s.bridge = {
385        phase: b.phase === 'wrapped' ? 'wrapped' : 'idle',
386        window: typeof b.window === 'string' ? b.window : null,
387        resetAtMs: typeof b.resetAtMs === 'number' ? b.resetAtMs : null,
388        wrapAt: typeof b.wrapAt === 'number' ? b.wrapAt : null,
389        isTakenOver: b.isTakenOver === true,
390        wrappedAtPercent:
391          typeof b.wrappedAtPercent === 'number' ? b.wrappedAtPercent : null,
392        weeklyWindow: typeof b.weeklyWindow === 'string' ? b.weeklyWindow : null,
393      }
394    }
395    s.keeper.consecutiveFailures = numberOf(saved.consecutiveFailures, 0)
396    s.keeper.idleKeepalives = numberOf(saved.idleKeepalives, 0)
397    s.keeper.pausedReason =
398      typeof saved.pausedReason === 'string' ? saved.pausedReason : null
399    s.observed =
400      saved.observed === '5m' || saved.observed === '1h' || saved.observed === 'mixed'
401        ? saved.observed
402        : null
403    s.baseline = isRecord(saved.baseline)
404      ? {
405          model: stringOf(saved.baseline.model, ''),
406          effort: stringOf(saved.baseline.effort, ''),
407        }
408      : null
409    s.transcriptPath =
410      typeof saved.transcriptPath === 'string' ? saved.transcriptPath : null
411    s.chunk = numberOf(saved.chunk, 0)
412    s.keeperHits = numberOf(saved.keeperHits, 0)
413    s.keeperMisses = numberOf(saved.keeperMisses, 0)
414    s.model = stringOf(saved.model, s.model)
415    s.effort = stringOf(saved.effort, '')
416    s.stopNote = typeof saved.stopNote === 'string' ? saved.stopNote : null
417    s.agentHits = numberOf(saved.agentHits, 0)
418    s.agentMisses = numberOf(saved.agentMisses, 0)
419    s.agentFailures = numberOf(saved.agentFailures, 0)
420    s.agentStopNote =
421      typeof saved.agentStopNote === 'string' ? saved.agentStopNote : null
422    // A keepalive still in flight across a reload keeps its id, so the
423    // task-notification that answers it is still dropped.
424    for (const pair of Array.isArray(saved.quiet) ? saved.quiet : []) {
425      if (!Array.isArray(pair) || typeof pair[0] !== 'string') continue
426      s.quiet.set(pair[0], numberOf(pair[1], 0))
427    }
428    for (const one of Array.isArray(saved.agents) ? saved.agents : []) {
429      if (!isRecord(one) || typeof one.id !== 'string') continue
430      // A reload forgets what was in flight: the loop's next event says.
431      s.agents.set(one.id, {
432        lastActivityAt: numberOf(one.lastActivityAt, 0),
433        prefixTokens: numberOf(one.prefixTokens, 0),
434        model: stringOf(one.model, ''),
435        keepalives: numberOf(one.keepalives, 0),
436        isRunning: false,
437        pingAt: null,
438        isPingAnswered: false,
439        isPingMissed: false,
440      })
441    }
442    if (isRecord(saved.run)) {
443      // The step a reload interrupted is asked again; the run says so.
444      const run = saved.run as unknown as Run
445      s.run = {
446        ...run,
447        isInFlight: false,
448        warnings: run.isInFlight
449          ? [...run.warnings, 'the mod reloaded mid-step']
450          : run.warnings,
451      }
452    }
453    s.rows = parseJsonl<EventRow>(await attempt(() => $.fs.read(eventsPath(s)), ''))
454  }
455
456  const now = await attempt(() => $.clock.now(), 0)
457  for (const key of await attempt(() => $.store.keys(), [])) {
458    if (!key.startsWith('s:') && !key.startsWith('hb:')) continue
459    if (key === `s:${id}`) continue
460    const value = await attempt(() => $.store.get(key), undefined)
461    const at = isRecord(value) ? numberOf(value.at, 0) : 0
462    if (now - at > STALE_MS) await attempt(() => $.store.delete(key), undefined)
463  }
464
465  return s
466}
467
468const ensure = ($: EngineInterface): Promise<Session> => (booting ??= boot($))
469
470const save = async ($: EngineInterface, s: Session): Promise<void> => {
471  await attempt(
472    async () =>
473      $.store.set(`s:${s.id}`, {
474        at: await $.clock.now(),
475        enabled: s.keeper.enabled,
476        isEnabledDecided: s.isEnabledDecided,
477        lastActivityAt: s.keeper.lastActivityAt,
478        lastRealAt: s.lastRealAt,
479        isAnchor: s.isAnchor,
480        backgroundPending: s.backgroundPending,
481        backgroundSeenAt: s.backgroundSeenAt,
482        shadowLastAt: s.shadowLastAt,
483        shadowKeepalives: s.shadowKeepalives,
484        shadowWouldHaveAt: s.shadowWouldHaveAt,
485        shadowWouldHave: s.shadowWouldHave,
486        bridge: s.bridge,
487        cachedPrefixTokens: s.keeper.cachedPrefixTokens,
488        consecutiveFailures: s.keeper.consecutiveFailures,
489        idleKeepalives: s.keeper.idleKeepalives,
490        pausedReason: s.keeper.pausedReason,
491        observed: s.observed,
492        baseline: s.baseline,
493        transcriptPath: s.transcriptPath,
494        chunk: s.chunk,
495        keeperHits: s.keeperHits,
496        keeperMisses: s.keeperMisses,
497        model: s.model,
498        effort: s.effort,
499        stopNote: s.stopNote,
500        agentHits: s.agentHits,
501        agentMisses: s.agentMisses,
502        agentFailures: s.agentFailures,
503        agentStopNote: s.agentStopNote,
504        agents: [...s.agents].map(([id, agent]) => ({ id, ...agent })),
505        quiet: [...s.quiet],
506        run: s.run,
507      }),
508    undefined,
509  )
510}
511
512const flush = async ($: EngineInterface, s: Session): Promise<void> => {
513  if (s.rows.length === 0) return
514  await $.fs.write(
515    eventsPath(s),
516    `${s.rows.map(row => JSON.stringify(row)).join('\n')}\n`,
517  )
518}
519
520// Moves to a new chunk only between turns: the rows of the turn that just
521// ended must still be in memory for reconcile and stepDone, and rows already
522// moved to a finished chunk can no longer be filled in. Not during an
523// experiment, whose run is read back from the rows of its own steps.
524const rotateChunkIfNeeded = async ($: EngineInterface, s: Session): Promise<void> => {
525  if (s.run !== null || s.rows.length < CHUNK_ROWS) return
526  await flush($, s)
527  s.chunk += 1
528  s.rows = []
529}
530
531const syncKeeper = (s: Session): void => {
532  s.keeper.ttl = effectiveTtl(s.requested.ttl, s.observed)
533  s.keeper.isRunActive = s.run !== null
534  if (config.maxIdleKeepalives > 0) {
535    s.keeper.idleKeepaliveBudget = config.maxIdleKeepalives
536  } else {
537    s.keeper.idleKeepaliveBudget =
538      s.keeper.ttl === null
539        ? null
540        : (breakEvenKeepalives(s.model, s.keeper.ttl) ?? null)
541  }
542}
543
544const contaminate = (run: Run, cause: string): void => {
545  if (!run.contamination.includes(cause)) run.contamination.push(cause)
546}
547
548const rowOf = (
549  s: Session,
550  fields: Pick<EventRow, 'kind' | 'timestamp' | 'source'> & Partial<EventRow>,
551  usage: Usage,
552  tag: Tag | undefined,
553): EventRow => {
554  const isSubagent = fields.source === 'subagent'
555  const split: CacheSplit | null =
556    usage.cache_creation_input_tokens === 0
557      ? { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 0 }
558      : null
559  const model = fields.model ?? s.model
560  const cost = apiEquivalentCost(
561    model,
562    usage,
563    split,
564    isSubagent ? s.subagent.ttl : effectiveTtl(s.requested.ttl, s.observed),
565  )
566
567  return {
568    experiment_id: tag?.experimentId ?? '',
569    replicate: tag?.replicate ?? null,
570    session_id: s.id,
571    model,
572    effort: s.effort,
573    claude_code_version: s.version,
574    ttl_requested: s.requested.ttl ?? 'automatic',
575    ttl_observed: isSubagent ? '' : (s.observed ?? ''),
576    ...usage,
577    ephemeral_5m_input_tokens: split?.ephemeral_5m_input_tokens ?? null,
578    ephemeral_1h_input_tokens: split?.ephemeral_1h_input_tokens ?? null,
579    cache_miss_reason: '',
580    context_tokens: null,
581    context_window: null,
582    rate_limits_before: [],
583    rate_limits_after: [],
584    api_equivalent_usd: fields.kind === 'meter' ? null : cost.usd,
585    cost_basis: fields.kind === 'meter' ? '' : cost.basis,
586    contaminated: false,
587    notes: tag?.note ?? '',
588    result: '',
589    turn_id: '',
590    step_index: null,
591    agent_id: '',
592    duration_ms: null,
593    ...fields,
594  }
595}
596
597const readTranscript = async (
598  $: EngineInterface,
599  path: string,
600): Promise<string | null> => {
601  try {
602    return await $.fs.read(path)
603  } catch {
604    // over the read limit, or not written yet: the script reads its tail
605  }
606  const ran = await attempt(
607    () =>
608      $.process.run([
609        'node',
610        `${$.plugin.root}/scripts/analyze-transcript.ts`,
611        path,
612        '--tail',
613        '600',
614      ]),
615    undefined,
616  )
617
618  return ran !== undefined && ran.exitCode === 0 ? ran.stdout : null
619}
620
621// Fills in what only the transcript has: each cache write's 5m/1h split and
622// the API's cache-miss reason, matched to the rows recorded live.
623const reconcile = async ($: EngineInterface, s: Session): Promise<void> => {
624  if (s.transcriptPath === null) return
625  // matchSplits pairs a row only within 600 s of its request: an older row that is
626  // still open never will be, so it is not worth re-reading the transcript for.
627  const now = await $.clock.now()
628  const open = s.rows.filter(
629    row =>
630      row.kind === 'step' &&
631      row.source !== 'subagent' &&
632      row.ephemeral_5m_input_tokens === null &&
633      now - Date.parse(row.timestamp) <= 600_000,
634  )
635  if (open.length === 0) return
636  const jsonl = await readTranscript($, s.transcriptPath)
637  if (jsonl === null) return
638  const parsed = parseTranscript(jsonl)
639  const matches = matchSplits(
640    open.map(row => ({
641      timestamp: row.timestamp,
642      isSubagent: false,
643      usage: usageOf(row),
644    })),
645    parsed.requests,
646  )
647  for (const [index, row] of open.entries()) {
648    const match = matches[index]
649    if (match === null || match === undefined) continue
650    row.ephemeral_5m_input_tokens = match.split.ephemeral_5m_input_tokens
651    row.ephemeral_1h_input_tokens = match.split.ephemeral_1h_input_tokens
652    row.ttl_observed = observedTtl(match.split) ?? row.ttl_observed
653    row.cache_miss_reason = match.cacheMissReason ?? ''
654    const cost = apiEquivalentCost(row.model, usageOf(row), match.split, null)
655    row.api_equivalent_usd = cost.usd
656    row.cost_basis = cost.basis
657    if (!match.isSplitConsistent) {
658      row.notes = `${row.notes} SPLIT_INCONSISTENT`.trim()
659    }
660  }
661  const lastWrite = parsed.requests
662    .filter(request => !request.isSidechain)
663    .findLast(request => observedTtl(request.split) !== null)
664  if (lastWrite !== undefined) s.observed = observedTtl(lastWrite.split)
665  await flush($, s)
666}
667
668const stopKeeper = ($: EngineInterface, s: Session, reason: string): void => {
669  s.keeper.enabled = false
670  s.isEnabledDecided = true
671  s.stopNote = reason
672  s.bridge.phase = 'idle'
673  $.ui.toast(`cache-keeper stopped: ${reason}`)
674  $.ui.log(`keeper stopped: ${reason}`)
675}
676
677// One cache-sharing fork over the session's own transcript: the keepalive,
678// a manual probe, or an experiment's keeper step.
679const probe = async (
680  $: EngineInterface,
681  s: Session,
682  tag: Tag | undefined,
683  note: string,
684): Promise<EventRow> => {
685  s.keeper.isProbing = true
686  try {
687    const before = await limitsNow($)
688    const startedAt = await $.clock.now()
689    const reply = await $.model.fork({ prompt: config.probePrompt })
690    const endedAt = await $.clock.now()
691    const after = await attempt(() => $.session.usage(), undefined)
692    const usage: Usage = 'usage' in reply ? { ...reply.usage } : ZERO_USAGE
693    const result = classifyUsage(usage)
694    const failure = reply.isAnswered
695      ? ''
696      : reply.reason === 'api-error'
697        ? `api-error ${reply.status ?? ''} ${reply.error}`.trim()
698        : reply.reason
699    const refreshed =
700      usage.cache_read_input_tokens + usage.cache_creation_input_tokens
701    if (result === 'hit' || result === 'partial_hit') {
702      s.keeper.lastActivityAt = startedAt
703      s.keeper.cachedPrefixTokens = Math.max(s.keeper.cachedPrefixTokens, refreshed)
704      s.keeper.consecutiveFailures = 0
705      s.keeper.idleKeepalives += 1
706      s.keeperHits += 1
707      s.isAnchorExpiryNoted = false
708    } else if (!reply.isAnswered && reply.reason === 'nothing-to-fork') {
709      // A resumed or just-started process has no request of its own to fork yet: wait, never count it as a failure.
710      s.forkRetryAt = endedAt + 30_000
711    } else {
712      s.keeper.consecutiveFailures += 1
713      s.keeperMisses += 1
714      if (usage.cache_creation_input_tokens > 0) {
715        // The miss rewrote the prefix, so the entry is fresh from here.
716        s.keeper.lastActivityAt = startedAt
717        s.keeper.cachedPrefixTokens = refreshed
718        s.keeper.idleKeepalives += 1
719      }
720    }
721    const row = rowOf(
722      s,
723      {
724        kind: 'keeper',
725        timestamp: iso(startedAt),
726        source: 'keeper',
727        result,
728        notes: [note, failure].filter(Boolean).join(': '),
729        rate_limits_before: before,
730        rate_limits_after: after === undefined ? [] : [...after.rateLimits],
731        context_tokens: after?.context.tokens ?? null,
732        context_window: after?.context.window ?? null,
733        duration_ms: endedAt - startedAt,
734      },
735      usage,
736      tag,
737    )
738    s.rows.push(row)
739    await flush($, s)
740    await rememberMeter($, endedAt, after?.rateLimits ?? [])
741    await save($, s)
742
743    return row
744  } finally {
745    s.keeper.isProbing = false
746  }
747}
748
749// Shadow mode: a keepalive the keeper would have sent, recorded instead of
750// sent. Nothing here touches the real keeper state, so turning shadow mode off
751// resumes the keeper exactly where it was.
752const recordWouldHave = async (
753  $: EngineInterface,
754  s: Session,
755  now: number,
756  ttl: Ttl | null,
757  agentId: string,
758  prefixTokens: number,
759  index: number,
760): Promise<void> => {
761  s.rows.push(
762    rowOf(
763      s,
764      {
765        kind: 'shadow',
766        timestamp: iso(now),
767        source: 'shadow',
768        result: 'would_have_keepalive',
769        notes:
770          agentId === ''
771            ? 'shadow mode: no request sent'
772            : `shadow mode: subagent ${agentId}, no request sent`,
773        agent_id: agentId,
774        api_equivalent_usd: null,
775        cost_basis: '',
776        shadow_would_have: true,
777        shadow_prefix_tokens: prefixTokens,
778        shadow_keepalive_index: index,
779        shadow_ttl: ttl ?? '',
780        shadow_last_would_have_at: null,
781      },
782      ZERO_USAGE,
783      undefined,
784    ),
785  )
786  await flush($, s)
787  await save($, s)
788  $.ui.log(
789    `shadow: would have kept the ${ttl ?? 'unknown'} cache warm (${prefixTokens} tokens)${
790      agentId === '' ? '' : ` for subagent ${agentId}`
791    }`,
792  )
793}
794
795// A subagent's request, as its turn.step showed it: the cache it left behind is
796// the one a later SendMessage to it reads. Answers the row's note.
797const agentStepped = (
798  s: Session,
799  id: string,
800  startedAt: number,
801  model: string,
802  usage: Usage,
803): string => {
804  const agent: AgentTrack = s.agents.get(id) ?? {
805    lastActivityAt: startedAt,
806    prefixTokens: 0,
807    model,
808    keepalives: 0,
809    isRunning: true,
810    pingAt: null,
811    isPingAnswered: false,
812    isPingMissed: false,
813  }
814  agent.lastActivityAt = startedAt
815  agent.prefixTokens =
816    usage.cache_read_input_tokens + usage.cache_creation_input_tokens
817  agent.model = model
818  agent.isRunning = true
819  s.agents.set(id, agent)
820  if (agent.pingAt === null) {
821    // A real run: its idle stretch starts over.
822    agent.keepalives = 0
823    return ''
824  }
825  if (!agent.isPingAnswered) {
826    agent.isPingAnswered = true
827    if (classifyUsage(usage) === 'miss') {
828      agent.isPingMissed = true
829      s.agentMisses += 1
830      s.agentFailures += 1
831    } else {
832      s.agentHits += 1
833      s.agentFailures = 0
834    }
835  }
836
837  return 'subagent keepalive'
838}
839
840const agentFinished = ($: EngineInterface, s: Session, id: string): void => {
841  const agent = s.agents.get(id)
842  if (agent === undefined) return
843  agent.isRunning = false
844  if (agent.pingAt === null) return
845  agent.pingAt = null
846  agent.isPingAnswered = false
847  if (!agent.isPingMissed) return
848  // The keepalive rewrote the entry instead of reading it: the TTL assumed for
849  // this subagent is wrong, and another keepalive would cost the same again.
850  s.agents.delete(id)
851  if (s.agentFailures >= config.maxConsecutiveProbeFailures) {
852    s.agentStopNote = `${s.agentFailures} consecutive subagent keepalives missed`
853    $.ui.toast(`cache-keeper stopped keeping subagents: ${s.agentStopNote}`)
854    $.ui.log(`subagent keeper stopped: ${s.agentStopNote}`)
855  }
856}
857
858// Whether the session saved a subagent under this id. The engine lists the
859// subagents it ran in the background; one that ran in the foreground is on no
860// list, and neither are the engine's own forks, which save nothing here.
861const isSavedSubagent = async (
862  $: EngineInterface,
863  s: Session,
864  id: string,
865): Promise<boolean> => {
866  if (s.transcriptPath === null) return false
867  const path = `${s.transcriptPath.replace(/.jsonl$/, '')}/subagents/agent-${id}.meta.json`
868  const meta = await attempt(
869    async () => JSON.parse(await $.fs.read(path)) as unknown,
870    undefined,
871  )
872
873  return isRecord(meta) && typeof meta.agentType === 'string'
874}
875
876// Resumes one finished subagent with the keepalive message: one the engine
877// lists as completed, or one it does not list whose transcript the session
878// saved. A running one waits; a failed or killed one is not resumed.
879const pingAgent = async (
880  $: EngineInterface,
881  s: Session,
882  id: string,
883  now: number,
884): Promise<string> => {
885  const agent = s.agents.get(id)
886  if (agent === undefined) return 'not tracked'
887  const listed = await attempt(() => $.agent.list(), [])
888  const status = listed.find(one => one.id === id)?.status
889  const isResumable =
890    status === 'completed' ||
891    (status === undefined && (await isSavedSubagent($, s, id)))
892  if (!isResumable) {
893    if (status !== 'running') s.agents.delete(id)
894    return status ?? 'not a subagent of this session'
895  }
896  agent.pingAt = now
897  agent.isPingAnswered = false
898  agent.isPingMissed = false
899  agent.keepalives += 1
900  s.quiet.set(id, now)
901  const sent = await attempt(
902    () => $.session.send({ to: { agentId: id }, text: AGENT_PING }),
903    undefined,
904  )
905  if (sent === undefined || !sent.isDelivered) {
906    s.agents.delete(id)
907    s.quiet.delete(id)
908    const why = sent?.reason ?? 'the send failed'
909    $.ui.log(`subagent ${id} keepalive not delivered: ${why}`)
910    return `not delivered (${why})`
911  }
912  await save($, s)
913
914  return 'sent'
915}
916
917const keepAgents = async (
918  $: EngineInterface,
919  s: Session,
920  now: number,
921): Promise<void> => {
922  for (const [id, at] of s.quiet) {
923    if (now - at > QUIET_MS) s.quiet.delete(id)
924  }
925  let due: string | undefined
926  for (const [id, agent] of s.agents) {
927    if (agent.pingAt !== null) {
928      // Delivered and never run: nothing will clear it.
929      if (!agent.isRunning && now - agent.pingAt > PING_TIMEOUT_MS) s.agents.delete(id)
930      continue
931    }
932    const decision = decideAgent(
933      agent,
934      now,
935      s.subagent.ttl,
936      config,
937      config.subagentKeepalives,
938    )
939    if (decision === 'forget') s.agents.delete(id)
940    else if (decision === 'fire') due ??= id
941  }
942  if (due === undefined || !s.keeper.enabled || s.agentStopNote !== null) return
943  const limits = await limitsNow($)
944  if (limits.some(limit => isOverStopLine(limit, config))) return
945  if (config.shadowMode) {
946    const agent = s.agents.get(due)
947    if (agent === undefined) return
948    // Advance its simulated clock so the next would-have waits a full
949    // threshold again, exactly as a delivered ping would have.
950    agent.keepalives += 1
951    agent.lastActivityAt = now
952    s.shadowWouldHave += 1
953    await recordWouldHave($, s, now, s.subagent.ttl, due, agent.prefixTokens, agent.keepalives)
954    return
955  }
956  await pingAgent($, s, due, now)
957}
958
959const agentsText = (s: Session, now: number): string => {
960  const stopped = s.agentStopNote === null ? '' : ` (stopped: ${s.agentStopNote})`
961  const head = `subagents: TTL ${s.subagent.ttl} (${s.subagent.reason}) · keepalives per subagent ${config.subagentKeepalives}${stopped} · tracked ${s.agents.size} · hits ${s.agentHits} · misses ${s.agentMisses}`
962  const rows = [...s.agents].map(([id, agent]) => {
963    const state = agent.isRunning
964      ? 'running'
965      : `idle ${minutes(now - agent.lastActivityAt)}`
966    const flight = agent.pingAt === null ? '' : ' · keepalive in flight'
967
968    return `  ${id} · ${agent.model} · prefix ${agent.prefixTokens} · ${state} · keepalives ${agent.keepalives}${flight}`
969  })
970
971  return [head, ...rows].join('\n')
972}
973
974const otherSessionsSince = async (
975  $: EngineInterface,
976  s: Session,
977  since: number,
978): Promise<string[]> => {
979  const others: string[] = []
980  for (const key of await attempt(() => $.store.keys(), [])) {
981    if (!key.startsWith('hb:') || key === `hb:${s.id}`) continue
982    const value = await attempt(() => $.store.get(key), undefined)
983    if (isRecord(value) && numberOf(value.at, 0) >= since) {
984      others.push(key.slice(3, 11))
985    }
986  }
987
988  return others
989}
990
991const finishRun = async (
992  $: EngineInterface,
993  s: Session,
994  run: Run,
995): Promise<void> => {
996  await reconcile($, s)
997  const now = await $.clock.now()
998  const mine = s.rows.filter(
999    row =>
1000      row.experiment_id === run.experimentId && row.replicate === run.replicate,
1001  )
1002  const build = mine.find(row => row.notes.startsWith('build'))
1003  const observed = build === undefined ? null : observedTtl(splitOf(build))
1004  if (isTtlMismatch(s.requested.ttl, observed)) {
1005    run.warnings.push('TTL_CONFIG_MISMATCH')
1006  }
1007  if (build !== undefined && build.ephemeral_5m_input_tokens === null) {
1008    run.warnings.push('TTL_UNVERIFIED: no transcript split for the build request')
1009  }
1010  if (
1011    build !== undefined &&
1012    build.cache_creation_input_tokens + build.cache_read_input_tokens <
1013      run.fixtureTokens / 2
1014  ) {
1015    run.warnings.push('FIXTURE_SMALLER_THAN_ASKED')
1016  }
1017  for (const other of await otherSessionsSince($, s, run.requestedAt)) {
1018    contaminate(run, `session ${other} made requests meanwhile`)
1019  }
1020  const isContaminated = run.contamination.length > 0
1021  if (isContaminated) {
1022    for (const row of mine) row.contaminated = true
1023  }
1024  const ttl = s.requested.ttl ?? 'automatic'
1025  const record: RunRecord = {
1026    experiment_id: run.experimentId,
1027    plan: run.plan,
1028    replicate: run.replicate,
1029    ttl_requested: ttl,
1030    ttl_reason: s.requested.reason,
1031    ttl_observed: observed ?? '',
1032    session_id: s.id,
1033    model: s.model,
1034    effort: s.effort,
1035    claude_code_version: s.version,
1036    started_at: iso(run.startedAt ?? run.requestedAt),
1037    ended_at: iso(now),
1038    meter_start: run.meterStart,
1039    meter_end: await limitsNow($),
1040    contaminated: isContaminated,
1041    contamination: run.contamination,
1042    warnings: run.warnings,
1043    transcript_path: s.transcriptPath,
1044    fixture_tokens: run.fixtureTokens,
1045    steps: run.steps,
1046  }
1047  const path = `${config.dataDir}/raw/run-${run.experimentId}-${ttl}-r${run.replicate}-${s.id.slice(0, 8)}.json`
1048  await $.fs.write(path, `${JSON.stringify(record, null, 2)}\n`)
1049  s.run = null
1050  await flush($, s)
1051  await save($, s)
1052  const verdict = isContaminated ? 'contaminated' : 'clean'
1053  $.ui.toast(`cache-keeper: ${run.experimentId} r${run.replicate} finished (${verdict})`)
1054  $.ui.log(
1055    `${run.experimentId} r${run.replicate} finished (${verdict}); wrote ${path}. /cache-keeper report builds the report.`,
1056  )
1057}
1058
1059const abortRun = async (
1060  $: EngineInterface,
1061  s: Session,
1062  why: string,
1063): Promise<void> => {
1064  const run = s.run
1065  if (run === null) return
1066  s.run = null
1067  s.pending = null
1068  await save($, s)
1069  $.ui.toast(`cache-keeper: ${run.experimentId} aborted (${why})`)
1070  $.ui.log(`${run.experimentId} r${run.replicate} aborted: ${why}`)
1071}
1072
1073const advanceRun = async (
1074  $: EngineInterface,
1075  s: Session,
1076  run: Run,
1077  now: number,
1078): Promise<void> => {
1079  const plan = planNamed(run.plan)
1080  if (plan === undefined) {
1081    await abortRun($, s, 'unknown plan')
1082    return
1083  }
1084  if (run.isInFlight) {
1085    if (s.pending !== null && now - s.pending.since > 120_000) {
1086      await abortRun($, s, 'the step never started a turn')
1087    }
1088    return
1089  }
1090  if (s.keeper.isTurnRunning || s.keeper.isProbing) return
1091  const step = plan.steps[run.next]
1092  if (step === undefined) {
1093    await finishRun($, s, run)
1094    return
1095  }
1096  if (step.kind !== 'build') {
1097    if (run.startedAt === null) return
1098    if (now < run.startedAt + step.atSec * 1000) return
1099  }
1100  const tag: Tag = {
1101    experimentId: run.experimentId,
1102    replicate: run.replicate,
1103    note: step.kind,
1104    stepIndex: run.next,
1105  }
1106  run.isInFlight = true
1107  if (step.kind === 'keeper') {
1108    const row = await probe($, s, tag, 'keeper')
1109    run.steps.push({
1110      kind: 'keeper',
1111      plannedSec: step.atSec,
1112      actualSec: (Date.parse(row.timestamp) - (run.startedAt ?? now)) / 1000,
1113      result: row.result,
1114      cacheRead: row.cache_read_input_tokens,
1115      cacheCreation: row.cache_creation_input_tokens,
1116    })
1117    run.next += 1
1118    run.isInFlight = false
1119    await save($, s)
1120    return
1121  }
1122  const isBuild = step.kind === 'build'
1123  s.pending = {
1124    ...tag,
1125    marker: marker(step.kind, run.nonce, isBuild ? 0 : run.next),
1126    since: now,
1127  }
1128  await save($, s)
1129  const entered = await attempt(
1130    () =>
1131      $.prompt.submit({
1132        text: isBuild
1133          ? buildPrompt(run.nonce, run.fixtureTokens, config.probePrompt)
1134          : probePromptFor(run.nonce, run.next, config.probePrompt),
1135        asUser: true,
1136      }),
1137    undefined,
1138  )
1139  if (entered === undefined || 'drop' in entered) {
1140    await abortRun($, s, 'the prompt was not accepted')
1141  }
1142}
1143
1144const stepDone = async (
1145  $: EngineInterface,
1146  s: Session,
1147  run: Run,
1148  tag: Tag,
1149  turnId: string,
1150  reason: string,
1151): Promise<void> => {
1152  const plan = planNamed(run.plan)
1153  const rows = s.rows.filter(row => row.turn_id === turnId)
1154  const first = rows[0]
1155  const last = rows.at(-1)
1156  if (first === undefined || last === undefined) {
1157    await abortRun($, s, `the ${tag.note} turn got no response (${reason})`)
1158    return
1159  }
1160  if (reason !== 'answer') {
1161    run.warnings.push(`step ${tag.stepIndex} (${tag.note}) ended: ${reason}`)
1162  }
1163  if (rows.length > 1) {
1164    run.warnings.push(`step ${tag.stepIndex} (${tag.note}) took ${rows.length} requests`)
1165  }
1166  const at = Date.parse(first.timestamp)
1167  if (tag.note === 'build') run.startedAt = at
1168  run.steps.push({
1169    kind: tag.note,
1170    plannedSec: plan?.steps[tag.stepIndex]?.atSec ?? 0,
1171    actualSec: (at - (run.startedAt ?? at)) / 1000,
1172    result: last.result,
1173    cacheRead: last.cache_read_input_tokens,
1174    cacheCreation: last.cache_creation_input_tokens,
1175  })
1176  run.next = tag.stepIndex + 1
1177  run.isInFlight = false
1178}
1179
1180const runStatus = (s: Session, run: Run, now: number): string => {
1181  const plan = planNamed(run.plan)
1182  const step = plan?.steps[run.next]
1183  const total = plan?.steps.length ?? 0
1184  if (step === undefined) return `${run.experimentId} r${run.replicate} · finishing`
1185  const wait =
1186    run.startedAt === null
1187      ? ''
1188      : ` · next ${step.kind} in ${minutes(
1189          Math.ceil((run.startedAt + step.atSec * 1000 - now) / 15_000) * 15_000,
1190        )}`
1191
1192  return `${run.experimentId} r${run.replicate} · step ${run.next + 1}/${total}${wait}`
1193}
1194
1195const showStatus = ($: EngineInterface, s: Session, now: number): void => {
1196  if (!config.showStatus) return
1197  syncKeeper(s)
1198  let text: string
1199  if (s.run !== null) {
1200    text = runStatus(s, s.run, now)
hooks/lib/bridge.ts 243 lines
1import type { RateLimit } from './keeper.ts'
2import { TTL_MS } from './keeper.ts'
3import type { Ttl } from './pricing.ts'
4
5/**
6 * The quota bridge: when the 5-hour window nears its end, the main session is
7 * told to wrap up, its cache is kept warm until the window resets, and it is
8 * told to carry on afterwards. Pure decisions live here; register.tsx acts.
9 */
10export type BridgePhase = 'idle' | 'wrapped'
11
12export type Bridge = {
13  phase: BridgePhase
14  /** The window (its resetsAt) the bridge last wrapped for: one wrap per window. */
15  window: string | null
16  resetAtMs: number | null
17  wrapAt: number | null
18  /** The person typed after the wrap-up: no automatic resume. */
19  isTakenOver: boolean
20  /** Percent when the wrap-up was sent. */
21  wrappedAtPercent: number | null
22  /** The weekly window (windowKey of its reset) the handoff notice was sent for. */
23  weeklyWindow: string | null
24}
25
26export const initialBridge = (): Bridge => ({
27  phase: 'idle',
28  window: null,
29  resetAtMs: null,
30  wrapAt: null,
31  isTakenOver: false,
32  wrappedAtPercent: null,
33  weeklyWindow: null,
34})
35
36/** Only a session worked in this recently counts as being worked: older ones are never woken. */
37export const ACTIVE_MS = 600_000
38
39/**
40 * Background work out for longer than this since the last sign of it (a launch,
41 * or a Stop hook's list that still named it) is taken as lost: a task whose
42 * notice never came back must not keep an idle session "worked in" forever.
43 */
44export const BACKGROUND_MAX_MS = 24 * 3_600_000
45
46/**
47 * How many background tasks the Stop hook's list still names as in flight. That
48 * list is the session's own: it includes tasks a Bash call moved to the
49 * background by itself, which no tool input shows.
50 */
51export const countInFlight = (tasks: readonly unknown[]): number => tasks.length
52
53/**
54 * Whether background work this session started is still out: some task has not
55 * sent its task-notification back, and it was last seen recently enough to
56 * trust. While it is out the session is waiting on that work, not idle, even
57 * though no message has come from the main thread for a while.
58 */
59export const isBackgroundBusy = (
60  pending: number,
61  seenAt: number | null,
62  now: number,
63): boolean => pending > 0 && seenAt !== null && now - seenAt < BACKGROUND_MAX_MS
64
65/** Wait this long after resetsAt before resuming, for the meter to move. */
66export const RESUME_DELAY_MS = 20_000
67/** If the meter still reads high this long after the reset, resume anyway. */
68export const RESUME_GRACE_MS = 300_000
69/** A cache this close to expiring at resume time still wants its last keepalive. */
70export const RESUME_SAFETY_MS = 90_000
71
72export const fiveHour = (limits: readonly RateLimit[]): RateLimit | undefined =>
73  limits.find(limit => limit.kind === 'five_hour')
74
75export const resetMs = (limit: RateLimit | undefined): number | null => {
76  if (limit?.resetsAt === undefined) return null
77  const at = Date.parse(limit.resetsAt)
78
79  return Number.isFinite(at) ? at : null
80}
81
82export const sevenDay = (limits: readonly RateLimit[]): RateLimit | undefined =>
83  limits.find(limit => limit.kind === 'seven_day')
84
85/** One window, by its reset to the minute: a reading's milliseconds may wander. */
86export const windowKey = (resetAtMs: number): string =>
87  String(Math.round(resetAtMs / 60_000))
88
89export type HandoffInput = {
90  isRunActive: boolean
91  bridge: Bridge
92  limits: readonly RateLimit[]
93  now: number
94  /** The last user or assistant message of the main thread, in ms. */
95  lastRealAt: number | null
96  ttl: Ttl | null
97  /** Weekly percent that asks for the handoff; 0 never asks. */
98  atPercent: number
99  /** Background work this session started is still out (see isBackgroundBusy). */
100  isBackgroundBusy: boolean
101  /** A main-thread turn is running now, however long it has been going. */
102  isTurnRunning: boolean
103}
104
105/**
106 * Whether the session is being worked in: background work is out, a turn is
107 * running, or the main thread spoke within the active window (never longer
108 * than the cache TTL). A session idle for longer than that is left alone.
109 */
110const isWorkedIn = (
111  lastRealAt: number,
112  ttl: Ttl | null,
113  now: number,
114  isBackgroundBusy: boolean,
115  isTurnRunning: boolean,
116): boolean =>
117  isBackgroundBusy ||
118  isTurnRunning ||
119  now - lastRealAt < Math.min(ACTIVE_MS, TTL_MS[ttl ?? '1h'])
120
121/**
122 * Whether to ask for a handoff document now: the weekly window is nearly
123 * spent, so the work will be picked up after its reset, days away, by a new
124 * conversation rather than by this one's long-expired cache. Once per weekly
125 * window, and only for a session being worked in, by the wrap-up's rule.
126 */
127export const shouldHandoff = (input: HandoffInput): boolean => {
128  if (input.atPercent <= 0 || input.isRunActive) return false
129  const limit = sevenDay(input.limits)
130  const reset = resetMs(limit)
131  if (limit === undefined || reset === null || reset <= input.now) return false
132  if (limit.percentUsed < input.atPercent) return false
133  if (windowKey(reset) === input.bridge.weeklyWindow) return false
134  if (input.lastRealAt === null) return false
135
136  return isWorkedIn(input.lastRealAt, input.ttl, input.now, input.isBackgroundBusy, input.isTurnRunning)
137}
138
139export type WrapInput = {
140  isEnabled: boolean
141  isBridgeOn: boolean
142  isRunActive: boolean
143  bridge: Bridge
144  limits: readonly RateLimit[]
145  now: number
146  /** The last user or assistant message of the main thread, in ms. */
147  lastRealAt: number | null
148  ttl: Ttl | null
149  atPercent: number
150  /** Background work this session started is still out (see isBackgroundBusy). */
151  isBackgroundBusy: boolean
152  /** A main-thread turn is running now (see isWorkedIn). */
153  isTurnRunning: boolean
154}
155
156/**
157 * Whether to send the wrap-up now: the window is at the threshold, resets in
158 * the future, this session was worked in within ACTIVE_MS or still has background
159 * work out (an idle session is never woken), and the window was not wrapped for already.
160 */
161export const shouldWrap = (input: WrapInput): boolean => {
162  if (!input.isEnabled || !input.isBridgeOn || input.isRunActive) return false
163  if (input.bridge.phase !== 'idle') return false
164  const limit = fiveHour(input.limits)
165  const reset = resetMs(limit)
166  if (limit === undefined || reset === null || reset <= input.now) return false
167  if (limit.percentUsed < input.atPercent) return false
168  if (limit.resetsAt === input.bridge.window) return false
169  if (input.lastRealAt === null) return false
170
171  return isWorkedIn(input.lastRealAt, input.ttl, input.now, input.isBackgroundBusy, input.isTurnRunning)
172}
173
174/**
175 * Whether a keepalive would still be needed before the resume message: the
176 * resume is itself a request, so a cache that outlives it needs no more pings.
177 */
178export const needsPing = (
179  bridge: Bridge,
180  lastActivityAt: number,
181  ttl: Ttl,
182): boolean => {
183  if (bridge.resetAtMs === null) return true
184
185  return (
186    bridge.resetAtMs + RESUME_DELAY_MS - lastActivityAt >=
187    TTL_MS[ttl] - RESUME_SAFETY_MS
188  )
189}
190
191export type ResumeVerdict = 'wait' | 'resume' | 'skip'
192
193/** What to do about the resume message at `now`. */
194export const resumeVerdict = (
195  bridge: Bridge,
196  now: number,
197  limits: readonly RateLimit[],
198  atPercent: number,
199): ResumeVerdict => {
200  if (bridge.phase !== 'wrapped' || bridge.resetAtMs === null) return 'wait'
201  if (now < bridge.resetAtMs + RESUME_DELAY_MS) return 'wait'
202  if (bridge.isTakenOver) return 'skip'
203  const limit = fiveHour(limits)
204  const isStillHigh = limit !== undefined && limit.percentUsed >= atPercent
205  if (isStillHigh && now < bridge.resetAtMs + RESUME_GRACE_MS) return 'wait'
206
207  return 'resume'
208}
209
210export const clockOf = (ms: number): string => {
211  const at = new Date(ms)
212  const two = (n: number): string => String(n).padStart(2, '0')
213
214  return `${two(at.getHours())}:${two(at.getMinutes())}`
215}
216
217export const spanOf = (ms: number): string => {
218  const minutes = Math.max(0, Math.round(ms / 60_000))
219  const hours = Math.floor(minutes / 60)
220
221  return hours === 0 ? `${minutes} 分钟` : `${hours} 小时 ${minutes % 60} 分钟`
222}
223
224export const wrapText = (percent: number, resetAtMs: number, now: number): string =>
225  `【cache-keeper 自动通知】5 小时额度已用 ${percent}%,约 ${spanOf(resetAtMs - now)}后(${clockOf(resetAtMs)})重置。请只快速完成当前这一步并收尾(保存进度、写好交接说明),不要开始新任务、不要再派子代理,然后停下等待。额度重置后会自动通知你继续。`
226
227const dayOf = (ms: number): string => {
228  const at = new Date(ms)
229
230  return `${at.getMonth() + 1} 月 ${at.getDate()} 日 ${clockOf(ms)}`
231}
232
233export const handoffText = (percent: number, resetAtMs: number, now: number): string =>
234  `【cache-keeper 自动通知】周额度已用 ${percent}%,约 ${spanOf(resetAtMs - now)}后(${dayOf(resetAtMs)})重置。请现在写一份交接检查点:更新已有的台账或交接文档,没有就在工作目录新建 HANDOFF.md,写清目标与授权范围、已完成并验证的结果、进行中的步骤和当前状态、下一步、关键文件位置和要跑的命令,让一个没有本对话上下文的新会话能直接接手。写完把文件路径告诉用户,然后继续手头的工作,之后每完成一个阶段就更新它。额度重置后由新对话按这份文档接手,不续用本对话。`
235
236export const resumeText = (): string =>
237  '【cache-keeper 自动通知】5 小时额度已重置。请接着刚才收尾的地方继续之前的工作。'
238
239export const describeBridge = (bridge: Bridge, now: number): string =>
240  bridge.phase === 'wrapped' && bridge.resetAtMs !== null
241    ? `bridge: waiting for reset in ${spanOf(bridge.resetAtMs - now)} (${clockOf(bridge.resetAtMs)})${bridge.isTakenOver ? ' · you took over: no auto-resume' : ''}`
242    : 'bridge: idle'
243
hooks/lib/classify.ts 99 lines
1import type { CacheSplit, Ttl, Usage } from './pricing.ts'
2
3export type ProbeResult = 'hit' | 'partial_hit' | 'miss' | 'cold'
4
5/**
6 * How much of a request's prompt the cache served. `cold` is a request that
7 * carried no prompt tokens at all (none was made, or it failed).
8 */
9export const classifyUsage = (usage: Usage): ProbeResult => {
10  const prompt =
11    usage.input_tokens +
12    usage.cache_read_input_tokens +
13    usage.cache_creation_input_tokens
14  if (prompt === 0) return 'cold'
15  const share = usage.cache_read_input_tokens / prompt
16  if (share >= 0.9) return 'hit'
17
18  return share <= 0.1 ? 'miss' : 'partial_hit'
19}
20
21export type TtlReason = 'force_5m_env' | 'env' | 'setting' | 'automatic'
22
23export type TtlRequest = { ttl: Ttl | null; reason: TtlReason }
24
25const isTtl = (value: unknown): value is Ttl => value === '5m' || value === '1h'
26
27const isOn = (value: string | undefined): boolean =>
28  value !== undefined && /^(1|true|yes|on)$/i.test(value.trim())
29
30/**
31 * The TTL the engine was asked for, in its own order of precedence:
32 * FORCE_PROMPT_CACHING_5M, then the TTL variable, then the `promptCacheTtl`
33 * setting. `automatic` leaves the choice to the engine (ttl null).
34 */
35export const requestedTtl = (source: {
36  force5m?: string
37  envTtl?: string
38  settingTtl?: unknown
39}): TtlRequest => {
40  if (isOn(source.force5m)) return { ttl: '5m', reason: 'force_5m_env' }
41  if (isTtl(source.envTtl)) return { ttl: source.envTtl, reason: 'env' }
42  if (isTtl(source.settingTtl)) {
43    return { ttl: source.settingTtl, reason: 'setting' }
44  }
45
46  return { ttl: null, reason: 'automatic' }
47}
48
49export type SubagentTtlRequest = {
50  ttl: Ttl
51  reason: Exclude<TtlReason, 'automatic'> | 'enable_1h_env' | 'default'
52}
53
54/**
55 * The TTL the engine uses outside the main conversation (subagents, workflows,
56 * helper requests): the same order with its own variable and setting, then
57 * ENABLE_PROMPT_CACHING_1H, and five minutes when nothing asks for more. An
58 * agent definition's own `cacheTtl` sits between the two and is not seen here.
59 */
60export const requestedSubagentTtl = (source: {
61  force5m?: string
62  envTtl?: string
63  settingTtl?: unknown
64  enable1h?: string
65}): SubagentTtlRequest => {
66  if (isOn(source.force5m)) return { ttl: '5m', reason: 'force_5m_env' }
67  if (isTtl(source.envTtl)) return { ttl: source.envTtl, reason: 'env' }
68  if (isTtl(source.settingTtl)) {
69    return { ttl: source.settingTtl, reason: 'setting' }
70  }
71  if (isOn(source.enable1h)) return { ttl: '1h', reason: 'enable_1h_env' }
72
73  return { ttl: '5m', reason: 'default' }
74}
75
76export type ObservedTtl = Ttl | 'mixed' | null
77
78/** Which cache a request wrote to, read off its transcript row's split. */
79export const observedTtl = (split: CacheSplit | null): ObservedTtl => {
80  if (split === null) return null
81  const wrote5m = split.ephemeral_5m_input_tokens > 0
82  const wrote1h = split.ephemeral_1h_input_tokens > 0
83  if (wrote5m && wrote1h) return 'mixed'
84  if (wrote5m) return '5m'
85
86  return wrote1h ? '1h' : null
87}
88
89/** The TTL to schedule by: what the log showed, else what was asked for. */
90export const effectiveTtl = (
91  requested: Ttl | null,
92  observed: ObservedTtl,
93): Ttl | null => (isTtl(observed) ? observed : requested)
94
95export const isTtlMismatch = (
96  requested: Ttl | null,
97  observed: ObservedTtl,
98): boolean => requested !== null && isTtl(observed) && observed !== requested
99
hooks/lib/experiment.ts 160 lines
1import type { Ttl } from './pricing.ts'
2
3export type StepKind = 'build' | 'probe' | 'keeper'
4
5export type PlanStep = {
6  /** Seconds after the build request started. */
7  atSec: number
8  kind: StepKind
9}
10
11export type Plan = {
12  /** What `/cache-keeper experiment <name>` takes. */
13  name: string
14  /** The experiment id rows and run records carry. */
15  id: string
16  title: string
17  /** The TTL the session must have been started with, when the plan needs one. */
18  requiresTtl: Ttl | null
19  steps: readonly PlanStep[]
20}
21
22const BUILD: PlanStep = { atSec: 0, kind: 'build' }
23
24const every = (
25  kind: StepKind,
26  periodSec: number,
27  times: number,
28): PlanStep[] =>
29  Array.from({ length: times }, (_, index) => ({
30    atSec: periodSec * (index + 1),
31    kind,
32  }))
33
34export const PLANS: readonly Plan[] = [
35  {
36    name: 'ttl',
37    id: 'A-ttl',
38    title: 'TTL takes effect: build the cache, probe after 90 s',
39    requiresTtl: null,
40    steps: [BUILD, { atSec: 90, kind: 'probe' }],
41  },
42  {
43    name: 'renew',
44    id: 'B-renew',
45    title: 'A 5m hit renews the TTL: keepalives at 4:00 and 8:00, probe at 12:00',
46    requiresTtl: '5m',
47    steps: [BUILD, ...every('keeper', 240, 2), { atSec: 720, kind: 'probe' }],
48  },
49  {
50    name: 'renew-control',
51    id: 'B-control',
52    title: 'Control for B: no keepalive, probe at 6:30',
53    requiresTtl: '5m',
54    steps: [BUILD, { atSec: 390, kind: 'probe' }],
55  },
56  {
57    name: 'active',
58    id: 'C1-active',
59    title: 'Active coding: 11 probes, 3 minutes apart',
60    requiresTtl: null,
61    steps: [BUILD, ...every('probe', 180, 11)],
62  },
63  {
64    name: 'intermittent',
65    id: 'C2-intermittent',
66    title: 'Intermittent coding: 5 probes, 10 minutes apart',
67    requiresTtl: null,
68    steps: [BUILD, ...every('probe', 600, 5)],
69  },
70  {
71    name: 'keeper',
72    id: 'D2-keeper',
73    title: '18 minutes idle with a keepalive every 4:05, then a probe',
74    requiresTtl: '5m',
75    steps: [BUILD, ...every('keeper', 245, 4), { atSec: 1080, kind: 'probe' }],
76  },
77  {
78    name: 'keeper-control',
79    id: 'D1-idle',
80    title: '18 minutes idle with no keepalive, then a probe',
81    requiresTtl: null,
82    steps: [BUILD, { atSec: 1080, kind: 'probe' }],
83  },
84]
85
86export const planNamed = (name: string): Plan | undefined =>
87  PLANS.find(plan => plan.name === name)
88
89export const planDurationSec = (plan: Plan): number =>
90  Math.max(...plan.steps.map(step => step.atSec))
91
92const WORDS = (
93  'the of and to in is that for it as was with be by on not he this are or ' +
94  'his from at which but have an had they you were their one all we can her ' +
95  'has there been if more when will would who so no out up into than them ' +
96  'time only some could these two may then do first any my now such like ' +
97  'our over man me even most made after also did many before must through ' +
98  'years where much your way well down should because each just those people ' +
99  'how too little state good very make world still own see men work long get ' +
100  'here between both life being under never day same another know while last ' +
101  'might us great old year off come since against go came right used take three'
102).split(' ')
103
104const seedOf = (text: string): number => {
105  let hash = 2166136261
106  for (let index = 0; index < text.length; index += 1) {
107    hash = Math.imul(hash ^ text.charCodeAt(index), 16777619)
108  }
109
110  return hash >>> 0 || 1
111}
112
113/**
114 * Static filler of about `targetTokens` tokens (one common word is about one
115 * token), the same for the same nonce and different from the first word on
116 * for another, so no two runs can be served each other's cache entry.
117 */
118export const buildFiller = (nonce: string, targetTokens: number): string => {
119  let state = seedOf(nonce)
120  const lines: string[] = []
121  let line: string[] = []
122  for (let index = 0; index < targetTokens; index += 1) {
123    state ^= state << 13
124    state ^= state >>> 17
125    state ^= state << 5
126    line.push(WORDS[(state >>> 0) % WORDS.length] ?? 'the')
127    if (line.length === 16) {
128      lines.push(line.join(' '))
129      line = []
130    }
131  }
132  if (line.length > 0) lines.push(line.join(' '))
133
134  return lines.join('\n')
135}
136
137export const marker = (kind: StepKind, nonce: string, index: number): string =>
138  `[cache-keeper:${kind}:${nonce}:${index}]`
139
140export const buildPrompt = (
141  nonce: string,
142  targetTokens: number,
143  probePrompt: string,
144): string =>
145  [
146    `${marker('build', nonce, 0)} The block below is static filler for a prompt-cache benchmark. Do not analyze, summarize or act on it, and do not call any tool.`,
147    '',
148    '<filler>',
149    buildFiller(nonce, targetTokens),
150    '</filler>',
151    '',
152    probePrompt,
153  ].join('\n')
154
155export const probePromptFor = (
156  nonce: string,
157  index: number,
158  probePrompt: string,
159): string => `${marker('probe', nonce, index)} ${probePrompt}`
160
hooks/lib/keeper.ts 266 lines
1import type { Ttl } from './pricing.ts'
2
3export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
4
5export type KeeperConfig = {
6  minCacheReadTokens: number
7  ttl5mKeepaliveAtSec: number
8  ttl1hKeepaliveAtSec: number
9  maxRateLimitPercent: number
10  maxConsecutiveProbeFailures: number
11}
12
13export type KeeperState = {
14  enabled: boolean
15  isTurnRunning: boolean
16  isProbing: boolean
17  isRunActive: boolean
18  /** When the last request that touched the main cache STARTED, in ms. */
19  lastActivityAt: number | null
20  /** Cache read + written by that request: the prefix worth keeping. */
21  cachedPrefixTokens: number
22  consecutiveFailures: number
23  /** Keepalives since the last real request. */
24  idleKeepalives: number
25  /** Keepalives allowed per idle stretch; null when nothing bounds them. */
26  idleKeepaliveBudget: number | null
27  /** Set by a cache-invalidating change until a real request hits again. */
28  pausedReason: string | null
29  ttl: Ttl | null
30}
31
32export const TTL_MS: Record<Ttl, number> = { '5m': 300_000, '1h': 3_600_000 }
33
34export type WaitReason =
35  | 'disabled'
36  | 'experiment'
37  | 'busy'
38  | 'paused'
39  | 'ttl-unknown'
40  | 'no-baseline'
41  | 'prefix-too-small'
42  | 'expired'
43  | 'break-even'
44  | 'not-due'
45
46export type Decision =
47  | { action: 'fire' }
48  | { action: 'wait'; reason: WaitReason; dueInMs?: number }
49  | { action: 'stop'; reason: string }
50
51export const initialKeeperState = (enabled: boolean): KeeperState => ({
52  enabled,
53  isTurnRunning: false,
54  isProbing: false,
55  isRunActive: false,
56  lastActivityAt: null,
57  cachedPrefixTokens: 0,
58  consecutiveFailures: 0,
59  idleKeepalives: 0,
60  idleKeepaliveBudget: null,
61  pausedReason: null,
62  ttl: null,
63})
64
65export const keepaliveAtMs = (ttl: Ttl, config: KeeperConfig): number =>
66  (ttl === '5m' ? config.ttl5mKeepaliveAtSec : config.ttl1hKeepaliveAtSec) *
67  1000
68
69/**
70 * Whether a window stops the keeper. Only the 5-hour window does: the weekly
71 * one resets too far away to wait out, and while it still has room a stopped
72 * keeper costs a full rewrite of the prefix, the dearer way to spend it. Once
73 * it is spent the keepalives fail and the failure count stops the keeper.
74 */
75export const isOverStopLine = (limit: RateLimit, config: KeeperConfig): boolean =>
76  limit.kind === 'five_hour' && limit.percentUsed >= config.maxRateLimitPercent
77
78/**
79 * The keeper and config `decide` should see when pings are not capped: no idle
80 * budget, and, past the stop line, no 5-hour percent limit either. Every other
81 * stop condition, and the TTL expiry, stay as they were.
82 */
83export const unboundedView = (
84  state: KeeperState,
85  config: KeeperConfig,
86  { isUnboundedBudget, isPastStopLine }: {
87    isUnboundedBudget: boolean
88    isPastStopLine: boolean
89  },
90): { keeper: KeeperState; config: KeeperConfig } => ({
91  keeper: isUnboundedBudget ? { ...state, idleKeepaliveBudget: null } : state,
92  config: isPastStopLine
93    ? { ...config, maxRateLimitPercent: Number.POSITIVE_INFINITY }
94    : config,
95})
96
97/**
98 * Whether to refresh the cache now. A keepalive is only ever a read of a
99 * live entry: once the TTL has run out it would be a full rewrite, so the
100 * keeper waits for a real request instead.
101 */
102export const decide = (
103  state: KeeperState,
104  now: number,
105  config: KeeperConfig,
106  rateLimits: readonly RateLimit[],
107): Decision => {
108  if (!state.enabled) return { action: 'wait', reason: 'disabled' }
109  if (state.isRunActive) return { action: 'wait', reason: 'experiment' }
110  if (state.consecutiveFailures >= config.maxConsecutiveProbeFailures) {
111    return {
112      action: 'stop',
113      reason: `${state.consecutiveFailures} consecutive keepalives failed or missed`,
114    }
115  }
116  if (state.isTurnRunning || state.isProbing) {
117    return { action: 'wait', reason: 'busy' }
118  }
119  if (state.pausedReason !== null) return { action: 'wait', reason: 'paused' }
120  if (state.ttl === null) return { action: 'wait', reason: 'ttl-unknown' }
121  if (state.lastActivityAt === null) {
122    return { action: 'wait', reason: 'no-baseline' }
123  }
124  if (state.cachedPrefixTokens < config.minCacheReadTokens) {
125    return { action: 'wait', reason: 'prefix-too-small' }
126  }
127  const over = rateLimits.find(limit => isOverStopLine(limit, config))
128  if (over !== undefined) {
129    return {
130      action: 'stop',
131      reason: `${over.kind} is at ${over.percentUsed}% (limit ${config.maxRateLimitPercent}%)`,
132    }
133  }
134  const idle = now - state.lastActivityAt
135  if (idle >= TTL_MS[state.ttl]) return { action: 'wait', reason: 'expired' }
136  if (
137    state.idleKeepaliveBudget !== null &&
138    state.idleKeepalives >= state.idleKeepaliveBudget
139  ) {
140    return { action: 'wait', reason: 'break-even' }
141  }
142  const dueInMs = keepaliveAtMs(state.ttl, config) - idle
143  if (dueInMs > 0) return { action: 'wait', reason: 'not-due', dueInMs }
144
145  return { action: 'fire' }
146}
147
148/** The main cache as another mod reads it under `$.state`'s `cache`. */
149export type CacheState = {
150  lastActivityAt: number | null
151  ttl: Ttl | null
152  expiresAt: number | null
153  cachedPrefixTokens: number
154  isEnabled: boolean
155  pausedReason: string | null
156  bridgePhase: 'idle' | 'wrapped'
157}
158
159export const cacheStateOf = (
160  state: KeeperState,
161  bridgePhase: 'idle' | 'wrapped',
162): CacheState => ({
163  lastActivityAt: state.lastActivityAt,
164  ttl: state.ttl,
165  expiresAt:
166    state.lastActivityAt === null || state.ttl === null
167      ? null
168      : state.lastActivityAt + TTL_MS[state.ttl],
169  cachedPrefixTokens: state.cachedPrefixTokens,
170  isEnabled: state.enabled,
171  pausedReason: state.pausedReason,
172  bridgePhase,
173})
174
175/**
176 * Whether the conversation is now far smaller than the prefix the keeper
177 * tracks: it was compacted without the keeper's `session.compact` hook being
178 * reached (another mod answered the compaction), so a keepalive would only
179 * read a prefix nothing will ask for again.
180 */
181export const hasShrunk = (
182  contextTokens: number | undefined,
183  cachedPrefixTokens: number,
184): boolean =>
185  contextTokens !== undefined && contextTokens < cachedPrefixTokens / 2
186
187/** One subagent's cache, as its own requests showed it. */
188export type AgentTrack = {
189  /** When its last request STARTED, in ms. */
190  lastActivityAt: number
191  /** Cache read + written by that request. */
192  prefixTokens: number
193  model: string
194  /** Keepalives since its last real run. */
195  keepalives: number
196  isRunning: boolean
197  /** When a keepalive was sent that its loop has not finished answering. */
198  pingAt: number | null
199  isPingAnswered: boolean
200  /** That keepalive rewrote the entry instead of reading it. */
201  isPingMissed: boolean
202}
203
204export type AgentDecision = 'fire' | 'wait' | 'forget'
205
206/**
207 * Whether to refresh a finished subagent's cache now, by the main keeper's
208 * rule: only ever a read of a live entry, and `budget` times at most between
209 * two real runs. An entry past its TTL is forgotten.
210 */
211export const decideAgent = (
212  agent: AgentTrack,
213  now: number,
214  ttl: Ttl,
215  config: KeeperConfig,
216  budget: number,
217): AgentDecision => {
218  if (agent.isRunning || agent.pingAt !== null) return 'wait'
219  const idle = now - agent.lastActivityAt
220  if (idle >= TTL_MS[ttl]) return 'forget'
221  if (agent.prefixTokens < config.minCacheReadTokens) return 'wait'
222  if (agent.keepalives >= budget) return 'wait'
223
224  return idle >= keepaliveAtMs(ttl, config) ? 'fire' : 'wait'
225}
226
227const clock = (ms: number): string => {
228  const seconds = Math.max(0, Math.round(ms / 1000))
229
230  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
231}
232
233const thousands = (tokens: number): string => `${Math.round(tokens / 1000)}k`
234
235/** The status line entry for a keeper outside an experiment. */
236/** 等待原因的中文说明;没列出的原样显示。 */
237const WAIT_TEXT: Record<string, string> = {
238  disabled: '只观察',
239  experiment: '实验中',
240  busy: '对话进行中',
241  'ttl-unknown': 'TTL 未知',
242  'no-baseline': '还没有基线',
243  'prefix-too-small': '前缀太小',
244  expired: '已过期',
245  'break-even': '保活不划算',
246}
247
248export const describeKeeper = (
249  state: KeeperState,
250  decision: Decision,
251): string => {
252  const ttl = state.ttl ?? 'TTL?'
253  const prefix = thousands(state.cachedPrefixTokens)
254  if (decision.action === 'stop') return '保活已停止'
255  if (decision.action === 'fire') return `缓存 ${ttl} · ${prefix} · 保活中`
256  if (decision.reason === 'not-due' && decision.dueInMs !== undefined) {
257    return `缓存 ${ttl} · ${prefix} · ${clock(decision.dueInMs)} 后保活`
258  }
259  const why =
260    decision.reason === 'paused'
261      ? `暂停(${state.pausedReason})`
262      : WAIT_TEXT[decision.reason] ?? decision.reason
263
264  return `缓存 ${ttl} · ${prefix} · ${why}`
265}
266
hooks/lib/parser.ts 362 lines
1import type { CacheSplit, Usage } from './pricing.ts'
2import {
3  applyPrefixRow,
4  initialPrefix,
5  prefixSnapshot,
6} from './prefix.ts'
7import type { PrefixSnapshot } from './prefix.ts'
8
9/** One model request, as the transcript's rows for it agree on it. */
10export type TranscriptRequest = {
11  key: string
12  messageId: string | null
13  requestId: string | null
14  timestamp: string | null
15  sessionId: string | null
16  model: string
17  isSidechain: boolean
18  agentId: string | null
19  version: string | null
20  effort: string | null
21  usage: Usage
22  split: CacheSplit | null
23  isSplitConsistent: boolean
24  cacheMissReason: string | null
25  /** Tokens the engine says this miss cost, when it said so. */
26  cacheMissedTokens: number | null
27  /** Order of the request's first assistant row in the transcript. */
28  order: number
29  /** Position of the request's first row among the transcript's non-empty lines. */
30  line: number
31  /** The prefix as it stood just before the request. */
32  prefix: PrefixSnapshot
33  rowCount: number
34}
35
36/** A `system`/`compact_boundary` row: the engine rewrote the conversation. */
37export type TranscriptCompaction = {
38  /** Position of the boundary row among the transcript's non-empty lines. */
39  line: number
40  timestamp: string | null
41  /** `compactMetadata.trigger` as written: manual, auto, or something newer. */
42  trigger: string | null
43  preTokens: number | null
44  postTokens: number | null
45  isSidechain: boolean
46  /**
47   * The engine's own mark for a summary written ahead of time (idle
48   * compaction). Current builds keep it out of the transcript, so this is
49   * false unless a build starts writing it.
50   */
51  isPrecomputed: boolean
52}
53
54export type ParseResult = {
55  requests: TranscriptRequest[]
56  /** The engine's compaction boundaries, in transcript order. */
57  compactions: TranscriptCompaction[]
58  assistantRows: number
59  parseErrors: number
60  /** Requests whose duplicate rows disagreed on usage. */
61  dedupeWarningCount: number
62  /** Requests whose usage contradicted its own cache split. */
63  inconsistentUsageCount: number
64}
65
66type Row = Record<string, unknown>
67
68const isRecord = (value: unknown): value is Row =>
69  typeof value === 'object' && value !== null && !Array.isArray(value)
70
71const count = (value: unknown): number =>
72  typeof value === 'number' && Number.isFinite(value) ? value : 0
73
74const text = (value: unknown): string | null =>
75  typeof value === 'string' && value !== '' ? value : null
76
77type Candidate = {
78  order: number
79  line: number
80  row: Row
81  message: Row
82  usage: Usage
83  split: CacheSplit | null
84  isTopNonZero: boolean
85  isConsistent: boolean
86  signature: string
87  prefix: PrefixSnapshot
88}
89
90const readCandidate = (
91  row: Row,
92  order: number,
93  line: number,
94  prefix: PrefixSnapshot,
95): Candidate | undefined => {
96  const message = row.message
97  if (!isRecord(message) || !isRecord(message.usage)) return undefined
98  if (message.model === '<synthetic>') return undefined
99  const raw = message.usage
100  const usage: Usage = {
101    input_tokens: count(raw.input_tokens),
102    output_tokens: count(raw.output_tokens),
103    cache_read_input_tokens: count(raw.cache_read_input_tokens),
104    cache_creation_input_tokens: count(raw.cache_creation_input_tokens),
105  }
106  const nested = raw.cache_creation
107  const split: CacheSplit | null = isRecord(nested)
108    ? {
109        ephemeral_5m_input_tokens: count(nested.ephemeral_5m_input_tokens),
110        ephemeral_1h_input_tokens: count(nested.ephemeral_1h_input_tokens),
111      }
112    : null
113  const splitTotal =
114    split === null
115      ? 0
116      : split.ephemeral_5m_input_tokens + split.ephemeral_1h_input_tokens
117  const isTopNonZero =
118    usage.input_tokens +
119      usage.output_tokens +
120      usage.cache_read_input_tokens +
121      usage.cache_creation_input_tokens >
122    0
123
124  return {
125    order,
126    line,
127    row,
128    message,
129    usage,
130    split,
131    isTopNonZero,
132    isConsistent:
133      split === null ||
134      Math.abs(usage.cache_creation_input_tokens - splitTotal) <= 1,
135    signature: JSON.stringify([usage, split]),
136    prefix,
137  }
138}
139
140// The most complete row of a request: one with usage at all, then one whose
141// split adds up, then the furthest along the stream, then the last written.
142const better = (a: Candidate, b: Candidate): Candidate => {
143  if (a.isTopNonZero !== b.isTopNonZero) return a.isTopNonZero ? a : b
144  if (a.isConsistent !== b.isConsistent) return a.isConsistent ? a : b
145  if (a.usage.output_tokens !== b.usage.output_tokens) {
146    return a.usage.output_tokens > b.usage.output_tokens ? a : b
147  }
148
149  return a.order > b.order ? a : b
150}
151
152const numberOrNull = (value: unknown): number | null =>
153  typeof value === 'number' && Number.isFinite(value) ? value : null
154
155const isCompactBoundary = (row: Row): boolean =>
156  row.type === 'system' && row.subtype === 'compact_boundary'
157
158/**
159 * What a compaction boundary says about itself. The engine writes
160 * `trigger` (manual | auto) plus token counts; whether the summary was
161 * written while the session sat idle is not among them today.
162 */
163const readCompaction = (row: Row, line: number): TranscriptCompaction => {
164  const meta = isRecord(row.compactMetadata) ? row.compactMetadata : {}
165
166  return {
167    line,
168    timestamp: text(row.timestamp),
169    trigger: text(meta.trigger),
170    preTokens: numberOrNull(meta.preTokens),
171    postTokens: numberOrNull(meta.postTokens),
172    isSidechain: row.isSidechain === true,
173    isPrecomputed: meta.precomputed === true,
174  }
175}
176
177type MissInfo = { type: string | null; missedTokens: number | null }
178
179const missReasonOf = (candidate: Candidate): MissInfo => {
180  const diagnostics = candidate.message.diagnostics
181  if (isRecord(diagnostics)) {
182    const raw = diagnostics.cache_miss_reason
183    const found = text(raw)
184    if (found !== null) return { type: found, missedTokens: null }
185    // Newer engines write an object here: { type, cache_missed_input_tokens }.
186    if (isRecord(raw)) {
187      const type = text(raw.type)
188      const missed = raw.cache_missed_input_tokens
189      if (type !== null) {
190        return {
191          type,
192          missedTokens:
193            typeof missed === 'number' && Number.isFinite(missed) ? missed : null,
194        }
195      }
196    }
197  }
198
199  const top =
200    text(candidate.row.cache_miss_reason) ?? text(candidate.row.cacheMissReason)
201  if (top !== null) return { type: top, missedTokens: null }
202
203  return { type: null, missedTokens: null }
204}
205
206/**
207 * Reads a session transcript (JSONL) into one entry per model request. The
208 * engine writes a row per content block, each repeating the request's usage,
209 * so rows are grouped by message id and request id and never summed.
210 */
211export const parseTranscript = (jsonl: string): ParseResult => {
212  const groups = new Map<string, Candidate[]>()
213  let assistantRows = 0
214  let parseErrors = 0
215  let order = 0
216  let line = 0
217  let prefix = initialPrefix()
218  const compactions: TranscriptCompaction[] = []
219  for (const raw of jsonl.split('\n')) {
220    if (raw.trim() === '') continue
221    let row: unknown
222    try {
223      row = JSON.parse(raw)
224    } catch {
225      parseErrors += 1
226      continue
227    }
228    if (!isRecord(row)) continue
229    const rowLine = line
230    line += 1
231    prefix = applyPrefixRow(prefix, row)
232    if (isCompactBoundary(row)) {
233      compactions.push(readCompaction(row, rowLine))
234      continue
235    }
236    if (row.type !== 'assistant') continue
237    const candidate = readCandidate(row, order, rowLine, prefixSnapshot(prefix))
238    order += 1
239    if (candidate === undefined) continue
240    assistantRows += 1
241    const messageId = text(candidate.message.id)
242    const requestId = text(row.requestId)
243    const key =
244      messageId !== null || requestId !== null
245        ? `${messageId ?? ''}|${requestId ?? ''}`
246        : `row|${text(row.uuid) ?? String(candidate.order)}`
247    const group = groups.get(key)
248    if (group === undefined) groups.set(key, [candidate])
249    else group.push(candidate)
250  }
251
252  const requests: TranscriptRequest[] = []
253  let dedupeWarningCount = 0
254  let inconsistentUsageCount = 0
255  for (const [key, group] of groups) {
256    const chosen = group.reduce(better)
257    const first = group[0] ?? chosen
258    const miss = missReasonOf(chosen)
259    const informative = group.filter(one => one.isTopNonZero)
260    if (new Set(informative.map(one => one.signature)).size > 1) {
261      dedupeWarningCount += 1
262    }
263    const splitTotal =
264      chosen.split === null
265        ? 0
266        : chosen.split.ephemeral_5m_input_tokens +
267          chosen.split.ephemeral_1h_input_tokens
268    // A row whose top-level counts are all zero while its split is not was
269    // not a free request: the split is the write.
270    const isZeroedWrite = !chosen.isTopNonZero && splitTotal > 0
271    if (!chosen.isConsistent || isZeroedWrite) inconsistentUsageCount += 1
272    requests.push({
273      key,
274      messageId: text(chosen.message.id),
275      requestId: text(chosen.row.requestId),
276      timestamp: text(chosen.row.timestamp),
277      sessionId: text(chosen.row.sessionId),
278      model: text(chosen.message.model) ?? 'unknown',
279      isSidechain: chosen.row.isSidechain === true,
280      agentId: text(chosen.row.agentId),
281      version: text(chosen.row.version),
282      effort: text(chosen.row.effort),
283      usage: isZeroedWrite
284        ? { ...chosen.usage, cache_creation_input_tokens: splitTotal }
285        : chosen.usage,
286      split: chosen.split,
287      isSplitConsistent: chosen.isConsistent && !isZeroedWrite,
288      cacheMissReason: miss.type,
289      cacheMissedTokens: miss.missedTokens,
290      order: first.order,
291      line: first.line,
292      prefix: first.prefix,
293      rowCount: group.length,
294    })
295  }
296
297  return {
298    requests,
299    compactions,
300    assistantRows,
301    parseErrors,
302    dedupeWarningCount,
303    inconsistentUsageCount,
304  }
305}
306
307export type SplitMatch = {
308  split: CacheSplit
309  cacheMissReason: string | null
310  isSplitConsistent: boolean
311}
312
313type Unresolved = {
314  timestamp: string
315  isSubagent: boolean
316  usage: Usage
317}
318
319/**
320 * Pairs requests the mod saw live (four token counts, no split) with the
321 * transcript's rows for them: same four counts, same thread, at most ten
322 * minutes apart, the closest pairs first and each transcript request once.
323 */
324export const matchSplits = (
325  rows: readonly Unresolved[],
326  requests: readonly TranscriptRequest[],
327): (SplitMatch | null)[] => {
328  const pairs: { row: number; request: TranscriptRequest; gap: number }[] = []
329  for (const [index, row] of rows.entries()) {
330    const at = Date.parse(row.timestamp)
331    for (const request of requests) {
332      if (request.split === null || request.timestamp === null) continue
333      if (request.isSidechain !== row.isSubagent) continue
334      const usage = request.usage
335      const isSame =
336        usage.input_tokens === row.usage.input_tokens &&
337        usage.output_tokens === row.usage.output_tokens &&
338        usage.cache_read_input_tokens === row.usage.cache_read_input_tokens &&
339        usage.cache_creation_input_tokens ===
340          row.usage.cache_creation_input_tokens
341      const gap = Math.abs(Date.parse(request.timestamp) - at)
342      if (isSame && gap <= 600_000) pairs.push({ row: index, request, gap })
343    }
344  }
345  pairs.sort((a, b) => a.gap - b.gap)
346
347  const matches: (SplitMatch | null)[] = rows.map(() => null)
348  const used = new Set<string>()
349  for (const { row, request } of pairs) {
350    if (matches[row] !== null || used.has(request.key)) continue
351    if (request.split === null) continue
352    used.add(request.key)
353    matches[row] = {
354      split: request.split,
355      cacheMissReason: request.cacheMissReason,
356      isSplitConsistent: request.isSplitConsistent,
357    }
358  }
359
360  return matches
361}
362
hooks/lib/pricing.ts 120 lines
1export type Usage = {
2  input_tokens: number
3  output_tokens: number
4  cache_read_input_tokens: number
5  cache_creation_input_tokens: number
6}
7
8export type CacheSplit = {
9  ephemeral_5m_input_tokens: number
10  ephemeral_1h_input_tokens: number
11}
12
13export type Ttl = '5m' | '1h'
14
15export type Price = {
16  input: number
17  write5m: number
18  write1h: number
19  read: number
20  output: number
21}
22
23// USD per million tokens, platform.claude.com/docs/en/about-claude/pricing as
24// read on 2026-10-08. The API's prices: never a subscription's quota weights.
25// A third element is a prompt length the row only applies above: Haiku 5.5 is
26// priced by prompt length, so its long-prompt row comes first.
27const PRICES: readonly (readonly [RegExp, Price, number?])[] = [
28  [/opus-5-5/, { input: 4, write5m: 5, write1h: 8, read: 0.2, output: 20 }],
29  [/sonnet-5-5/, { input: 2, write5m: 2.5, write1h: 4, read: 0.1, output: 10 }],
30  [/haiku-5-5/, { input: 0.5, write5m: 0.625, write1h: 1, read: 0.05, output: 2.5 }, 100_000],
31  [/haiku-5-5/, { input: 0.1, write5m: 0.125, write1h: 0.2, read: 0.01, output: 0.5 }],
32  [/haiku-4-5/, { input: 1, write5m: 1.25, write1h: 2, read: 0.1, output: 5 }],
33]
34
35export const ZERO_USAGE: Usage = {
36  input_tokens: 0,
37  output_tokens: 0,
38  cache_read_input_tokens: 0,
39  cache_creation_input_tokens: 0,
40}
41
42export const priceFor = (model: string, promptTokens = 0): Price | undefined =>
43  PRICES.find(
44    ([pattern, , above]) =>
45      pattern.test(model) && (above === undefined || promptTokens > above),
46  )?.[1]
47
48export type CostBasis =
49  | 'split'
50  | 'assumed-5m'
51  | 'assumed-1h'
52  | 'no-cache-write'
53  | 'unpriced-model'
54
55export type Cost = { usd: number | null; basis: CostBasis }
56
57/**
58 * What the request would cost on the API. Cache writes are priced from the
59 * 5m/1h split when the transcript gave one, and `cache_creation_input_tokens`
60 * is then never added again; without a split the whole write is priced at
61 * `assumedTtl` (1h, the dearer, when even that is unknown).
62 */
63export const apiEquivalentCost = (
64  model: string,
65  usage: Usage,
66  split: CacheSplit | null,
67  assumedTtl: Ttl | null,
68): Cost => {
69  const price = priceFor(
70    model,
71    usage.input_tokens +
72      usage.cache_read_input_tokens +
73      usage.cache_creation_input_tokens,
74  )
75  if (price === undefined) return { usd: null, basis: 'unpriced-model' }
76  const base =
77    usage.input_tokens * price.input +
78    usage.cache_read_input_tokens * price.read +
79    usage.output_tokens * price.output
80  const splitTotal =
81    split === null
82      ? 0
83      : split.ephemeral_5m_input_tokens + split.ephemeral_1h_input_tokens
84  if (split !== null && splitTotal > 0) {
85    const writes =
86      split.ephemeral_5m_input_tokens * price.write5m +
87      split.ephemeral_1h_input_tokens * price.write1h
88    return { usd: (base + writes) / 1_000_000, basis: 'split' }
89  }
90  if (usage.cache_creation_input_tokens === 0) {
91    return { usd: base / 1_000_000, basis: 'no-cache-write' }
92  }
93  const isFiveMinute = assumedTtl === '5m'
94  const writes =
95    usage.cache_creation_input_tokens *
96    (isFiveMinute ? price.write5m : price.write1h)
97  return {
98    usd: (base + writes) / 1_000_000,
99    basis: isFiveMinute ? 'assumed-5m' : 'assumed-1h',
100  }
101}
102
103/**
104 * How many keepalive reads cost as much, on the API, as the one cache rewrite
105 * they avoid: (write - read) / read, whole reads. Undefined for an unpriced
106 * model.
107 */
108export const breakEvenKeepalives = (
109  model: string,
110  ttl: Ttl,
111): number | undefined => {
112  const price = priceFor(model)
113  if (price === undefined) return undefined
114  const write = ttl === '5m' ? price.write5m : price.write1h
115  // whole micro-dollars, so 4.8 / 0.2 is 24 and not 23.999
116  return Math.floor(
117    Math.round((write - price.read) * 1000) / Math.round(price.read * 1000),
118  )
119}
120
hooks/lib/report.ts 736 lines
1import type { RateLimit } from './keeper.ts'
2
3export type EventRow = {
4  kind: 'step' | 'keeper' | 'meter' | 'shadow' | 'recovery'
5  timestamp: string
6  experiment_id: string
7  replicate: number | null
8  session_id: string
9  source: 'user' | 'benchmark' | 'keeper' | 'subagent' | 'meter' | 'shadow' | 'recovery'
10  model: string
11  effort: string
12  claude_code_version: string
13  ttl_requested: string
14  ttl_observed: string
15  input_tokens: number
16  output_tokens: number
17  cache_read_input_tokens: number
18  cache_creation_input_tokens: number
19  ephemeral_5m_input_tokens: number | null
20  ephemeral_1h_input_tokens: number | null
21  cache_miss_reason: string
22  context_tokens: number | null
23  context_window: number | null
24  rate_limits_before: RateLimit[]
25  rate_limits_after: RateLimit[]
26  api_equivalent_usd: number | null
27  cost_basis: string
28  contaminated: boolean
29  notes: string
30  result: string
31  turn_id: string
32  step_index: number | null
33  agent_id: string
34  duration_ms: number | null
35  /** Shadow mode only: this row records a keepalive that was not sent. */
36  shadow_would_have?: boolean
37  /** Shadow mode only: the prefix a would-have keepalive would have read. */
38  shadow_prefix_tokens?: number
39  /** Shadow mode only: seconds from the previous real request to this one. */
40  shadow_recovery_sec?: number | null
41  /** Shadow mode only: the 1-based would-have keepalive in its idle stretch. */
42  shadow_keepalive_index?: number
43  /** Shadow mode only: the TTL the decision was made against. */
44  shadow_ttl?: string
45  /** Shadow mode only: when the last would-have keepalive was due, in ms. */
46  shadow_last_would_have_at?: number | null
47}
48
49export type RunStep = {
50  kind: string
51  plannedSec: number
52  actualSec: number | null
53  result: string
54  cacheRead: number
55  cacheCreation: number
56}
57
58export type RunRecord = {
59  experiment_id: string
60  plan: string
61  replicate: number
62  ttl_requested: string
63  ttl_reason: string
64  ttl_observed: string
65  session_id: string
66  model: string
67  effort: string
68  claude_code_version: string
69  started_at: string
70  ended_at: string
71  meter_start: RateLimit[]
72  meter_end: RateLimit[]
73  contaminated: boolean
74  contamination: string[]
75  warnings: string[]
76  transcript_path: string | null
77  fixture_tokens: number
78  steps: RunStep[]
79}
80
81const CSV_COLUMNS = [
82  'timestamp',
83  'experiment_id',
84  'replicate',
85  'session_id',
86  'source',
87  'model',
88  'effort',
89  'claude_code_version',
90  'ttl_requested',
91  'ttl_observed',
92  'input_tokens',
93  'output_tokens',
94  'cache_read_input_tokens',
95  'cache_creation_input_tokens',
96  'ephemeral_5m_input_tokens',
97  'ephemeral_1h_input_tokens',
98  'cache_miss_reason',
99  'context_tokens',
100  'context_window',
101  'rate_limits_before_json',
102  'rate_limits_after_json',
103  'api_equivalent_usd',
104  'contaminated',
105  'notes',
106  'result',
107  'cost_basis',
108  'shadow_would_have',
109  'shadow_prefix_tokens',
110  'shadow_recovery_sec',
111  'shadow_keepalive_index',
112  'shadow_ttl',
113  'shadow_last_would_have_at',
114] as const
115
116const csvCell = (value: unknown): string => {
117  if (value === null || value === undefined) return ''
118  const cell = String(value)
119
120  return /[",\r\n]/.test(cell) ? `"${cell.replaceAll('"', '""')}"` : cell
121}
122
123export const toCsv = (rows: readonly EventRow[]): string => {
124  const lines = rows.map(row => {
125    const flat: Record<string, unknown> = {
126      ...row,
127      rate_limits_before_json: JSON.stringify(row.rate_limits_before),
128      rate_limits_after_json: JSON.stringify(row.rate_limits_after),
129    }
130
131    return CSV_COLUMNS.map(column => csvCell(flat[column])).join(',')
132  })
133
134  return `${[CSV_COLUMNS.join(','), ...lines].join('\n')}\n`
135}
136
137export const parseJsonl = <T>(jsonl: string): T[] => {
138  const rows: T[] = []
139  for (const line of jsonl.split('\n')) {
140    if (line.trim() === '') continue
141    try {
142      rows.push(JSON.parse(line) as T)
143    } catch {
144      // a row cut short by a crash mid-write
145    }
146  }
147
148  return rows
149}
150
151/**
152 * How far each window moved between two meter readings. A window that reset
153 * in between has no difference worth reading: null.
154 */
155export const meterDelta = (
156  before: readonly RateLimit[],
157  after: readonly RateLimit[],
158): Record<string, number | null> => {
159  const delta: Record<string, number | null> = {}
160  for (const end of after) {
161    const start = before.find(limit => limit.kind === end.kind)
162    if (start === undefined) continue
163    delta[end.kind] =
164      start.resetsAt === end.resetsAt
165        ? Math.round((end.percentUsed - start.percentUsed) * 10) / 10
166        : null
167  }
168
169  return delta
170}
171
172type Spread = {
173  mean: number | null
174  min: number | null
175  max: number | null
176  n: number
177  sum: number
178  /** Sample variance; 0 for fewer than two values. */
179  variance: number
180}
181
182const spread = (values: readonly number[]): Spread => {
183  if (values.length === 0) {
184    return { mean: null, min: null, max: null, n: 0, sum: 0, variance: 0 }
185  }
186  const sum = values.reduce((total, value) => total + value, 0)
187  const mean = sum / values.length
188  const squares = values.reduce((total, value) => total + (value - mean) ** 2, 0)
189
190  return {
191    mean,
192    min: Math.min(...values),
193    max: Math.max(...values),
194    n: values.length,
195    sum,
196    variance: values.length > 1 ? squares / (values.length - 1) : 0,
197  }
198}
199
200export type RunSummary = {
201  replicate: number
202  session_id: string
203  apiEquivalentUsd: number
204  rateLimitDelta: Record<string, number | null>
205  finalStep: string
206  ttlObserved: string
207  status: 'clean' | 'contaminated' | 'ttl-mismatch'
208}
209
210export type CellSummary = {
211  experiment: string
212  ttl: string
213  /** Clean runs: the only ones the totals and the comparisons count. */
214  n: number
215  excludedRuns: number
216  totals: {
217    cacheRead: number
218    cacheWrite5m: number
219    cacheWrite1h: number
220    cacheWriteUnsplit: number
221    input: number
222    output: number
223    apiEquivalentUsd: number
224  }
225  apiEquivalentUsdPerRun: Spread
226  rateLimitDelta: Record<string, Spread>
227  cacheHitRate: number | null
228  runs: RunSummary[]
229  warnings: string[]
230}
231
232const cellTtl = (run: RunRecord): string =>
233  run.ttl_requested === '5m' || run.ttl_requested === '1h'
234    ? run.ttl_requested
235    : run.ttl_observed || 'automatic'
236
237const statusOf = (run: RunRecord): RunSummary['status'] => {
238  if (run.warnings.includes('TTL_CONFIG_MISMATCH')) return 'ttl-mismatch'
239
240  return run.contaminated ? 'contaminated' : 'clean'
241}
242
243const summarizeCell = (
244  experiment: string,
245  ttl: string,
246  runs: readonly RunRecord[],
247  events: readonly EventRow[],
248): CellSummary => {
249  const totals = {
250    cacheRead: 0,
251    cacheWrite5m: 0,
252    cacheWrite1h: 0,
253    cacheWriteUnsplit: 0,
254    input: 0,
255    output: 0,
256    apiEquivalentUsd: 0,
257  }
258  const warnings = new Set<string>()
259  const summaries: RunSummary[] = []
260  const deltas: Record<string, number[]> = {}
261  const costs: number[] = []
262  for (const run of runs) {
263    const status = statusOf(run)
264    const rows = events.filter(
265      row =>
266        row.kind !== 'meter' &&
267        row.session_id === run.session_id &&
268        row.experiment_id === run.experiment_id &&
269        row.replicate === run.replicate,
270    )
271    const usd = rows.reduce((sum, row) => sum + (row.api_equivalent_usd ?? 0), 0)
272    const delta = meterDelta(run.meter_start, run.meter_end)
273    summaries.push({
274      replicate: run.replicate,
275      session_id: run.session_id,
276      apiEquivalentUsd: usd,
277      rateLimitDelta: delta,
278      finalStep: run.steps.at(-1)?.result ?? '',
279      ttlObserved: run.ttl_observed,
280      status,
281    })
282    for (const warning of run.warnings) warnings.add(warning)
283    if (status !== 'clean') {
284      for (const cause of run.contamination) warnings.add(`contaminated: ${cause}`)
285      continue
286    }
287    costs.push(usd)
288    for (const [kind, moved] of Object.entries(delta)) {
289      if (moved === null) warnings.add(`METER_WINDOW_RESET: ${kind}`)
290      else (deltas[kind] ??= []).push(moved)
291    }
292    for (const row of rows) {
293      totals.cacheRead += row.cache_read_input_tokens
294      totals.input += row.input_tokens
295      totals.output += row.output_tokens
296      totals.apiEquivalentUsd += row.api_equivalent_usd ?? 0
297      if (row.api_equivalent_usd === null) warnings.add('UNPRICED_MODEL')
298      if (row.ephemeral_5m_input_tokens === null) {
299        totals.cacheWriteUnsplit += row.cache_creation_input_tokens
300        if (row.cache_creation_input_tokens > 0) {
301          warnings.add('UNSPLIT_CACHE_WRITES: priced at the assumed TTL')
302        }
303      } else {
304        totals.cacheWrite5m += row.ephemeral_5m_input_tokens
305        totals.cacheWrite1h += row.ephemeral_1h_input_tokens ?? 0
306      }
307    }
308  }
309  const prompt =
310    totals.cacheRead +
311    totals.cacheWrite5m +
312    totals.cacheWrite1h +
313    totals.cacheWriteUnsplit +
314    totals.input
315
316  return {
317    experiment,
318    ttl,
319    n: costs.length,
320    excludedRuns: runs.length - costs.length,
321    totals,
322    apiEquivalentUsdPerRun: spread(costs),
323    rateLimitDelta: Object.fromEntries(
324      Object.entries(deltas).map(([kind, values]) => [kind, spread(values)]),
325    ),
326    cacheHitRate: prompt === 0 ? null : totals.cacheRead / prompt,
327    runs: summaries,
328    warnings: [...warnings].sort(),
329  }
330}
331
332export type ApiVerdict = 'a' | 'b' | 'tie' | 'insufficient'
333
334export type MeterVerdict =
335  | 'a'
336  | 'b'
337  | 'unclear'
338  | 'insufficient-replicates'
339  | 'insufficient-resolution'
340
341export type Comparison = {
342  id: string
343  title: string
344  a: { label: string; experiment: string; ttl: string }
345  b: { label: string; experiment: string; ttl: string }
346  api: { verdict: ApiVerdict; a: Spread; b: Spread }
347  meter: {
348    verdict: MeterVerdict
349    byKind: Record<string, { a: Spread; b: Spread }>
350  }
351}
352
353const COMPARISONS = [
354  {
355    id: 'W',
356    title: '只写缓存(建缓存 + 1 次 probe):5m 写入 vs 1h 写入',
357    a: { label: '5m', experiment: 'A-ttl', ttl: '5m' },
358    b: { label: '1h', experiment: 'A-ttl', ttl: '1h' },
359  },
360  {
361    id: 'C1',
362    title: '高频 active coding(约 3 分钟一次请求):5m vs 1h',
363    a: { label: '5m', experiment: 'C1-active', ttl: '5m' },
364    b: { label: '1h', experiment: 'C1-active', ttl: '1h' },
365  },
366  {
367    id: 'C2',
368    title: '间歇 coding(约 10 分钟一次请求):5m vs 1h',
369    a: { label: '5m', experiment: 'C2-intermittent', ttl: '5m' },
370    b: { label: '1h', experiment: 'C2-intermittent', ttl: '1h' },
371  },
372  {
373    id: 'D-keeper',
374    title: 'idle 18 分钟:5m + keeper vs 5m 无 keeper',
375    a: { label: '5m+keeper', experiment: 'D2-keeper', ttl: '5m' },
376    b: { label: '5m 无 keeper', experiment: 'D1-idle', ttl: '5m' },
377  },
378  {
379    id: 'D-1h',
380    title: 'idle 18 分钟:5m + keeper vs 1h 无 keeper',
381    a: { label: '5m+keeper', experiment: 'D2-keeper', ttl: '5m' },
382    b: { label: '1h 无 keeper', experiment: 'D1-idle', ttl: '1h' },
383  },
384] as const
385
386/** The replicates a meter verdict needs on each side. */
387export const MIN_REPLICATES = 3
388/** The percentage points a cell's runs must move a window by, in all, for its meter to say anything. */
389export const MIN_METER_POINTS = 2
390// The meter reports whole points, so one run's delta is off by up to a point
391// either way. Runs that all read the same are not that exact: their variance
392// is held to at least what rounding alone gives a difference of two readings.
393const ROUNDING_VARIANCE = 0.25
394/** How many standard errors apart two cells' mean deltas must be to call one cheaper. */
395const MIN_SEPARATION = 2.5
396
397const EMPTY: Spread = { mean: null, min: null, max: null, n: 0, sum: 0, variance: 0 }
398
399const compare = (
400  spec: (typeof COMPARISONS)[number],
401  cells: readonly CellSummary[],
402): Comparison => {
403  const cellOf = (side: { experiment: string; ttl: string }) =>
404    cells.find(
405      cell => cell.experiment === side.experiment && cell.ttl === side.ttl,
406    )
407  const a = cellOf(spec.a)
408  const b = cellOf(spec.b)
409  const costA = a?.apiEquivalentUsdPerRun ?? EMPTY
410  const costB = b?.apiEquivalentUsdPerRun ?? EMPTY
411  let api: ApiVerdict = 'insufficient'
412  if (costA.mean !== null && costB.mean !== null) {
413    if (costA.mean < costB.mean * 0.97) api = 'a'
414    else if (costB.mean < costA.mean * 0.97) api = 'b'
415    else api = 'tie'
416  }
417
418  const kinds = new Set([
419    ...Object.keys(a?.rateLimitDelta ?? {}),
420    ...Object.keys(b?.rateLimitDelta ?? {}),
421  ])
422  const byKind: Comparison['meter']['byKind'] = {}
423  const decided = new Set<'a' | 'b'>()
424  let hasReplicates = false
425  let hasResolution = false
426  for (const kind of kinds) {
427    const sideA = a?.rateLimitDelta[kind] ?? EMPTY
428    const sideB = b?.rateLimitDelta[kind] ?? EMPTY
429    byKind[kind] = { a: sideA, b: sideB }
430    if (sideA.n < MIN_REPLICATES || sideB.n < MIN_REPLICATES) continue
431    hasReplicates = true
432    if (Math.max(sideA.sum, sideB.sum) < MIN_METER_POINTS) continue
433    hasResolution = true
434    const error = Math.sqrt(
435      Math.max(sideA.variance, ROUNDING_VARIANCE) / sideA.n +
436        Math.max(sideB.variance, ROUNDING_VARIANCE) / sideB.n,
437    )
438    const apart = ((sideB.mean ?? 0) - (sideA.mean ?? 0)) / error
439    if (apart >= MIN_SEPARATION) decided.add('a')
440    else if (apart <= -MIN_SEPARATION) decided.add('b')
441  }
442  let meter: MeterVerdict = 'unclear'
443  if (!hasReplicates) meter = 'insufficient-replicates'
444  else if (!hasResolution) meter = 'insufficient-resolution'
445  else if (decided.size === 1) meter = [...decided][0] ?? 'unclear'
446
447  return {
448    id: spec.id,
449    title: spec.title,
450    a: spec.a,
451    b: spec.b,
452    api: { verdict: api, a: costA, b: costB },
453    meter: { verdict: meter, byKind },
454  }
455}
456
457export type Conclusion = { category: 1 | 2 | 3 | 4 | 5; text: string }
458
459const conclude = (comparisons: readonly Comparison[]): Conclusion => {
460  const rhythm = comparisons.filter(one => one.id === 'C1' || one.id === 'C2')
461  if (rhythm.every(one => one.api.verdict === 'insufficient')) {
462    return {
463      category: 5,
464      text: '数据不足,无法判断:C1/C2 还没有可比较的 5m 与 1h 干净 run。',
465    }
466  }
467  const api = new Set(
468    rhythm.map(one => one.api.verdict).filter(v => v === 'a' || v === 'b'),
469  )
470  const meter = new Set(
471    rhythm.map(one => one.meter.verdict).filter(v => v === 'a' || v === 'b'),
472  )
473  const isMeterBlind = rhythm.every(one =>
474    one.meter.verdict.startsWith('insufficient'),
475  )
476  if (isMeterBlind) {
477    const writes = comparisons.find(one => one.id === 'W')?.meter.verdict
478    const onWrites =
479      writes === 'a'
480        ? '只写缓存的对比(W)里,meter 显示 5m 写入比 1h 写入省。'
481        : writes === 'b'
482          ? '只写缓存的对比(W)里,meter 显示 1h 写入比 5m 写入省。'
483          : writes === 'unclear'
484            ? '只写缓存的对比(W)里,meter 没有显示出 5m 与 1h 写入的显著差异。'
485            : ''
486
487    return {
488      category: 5,
489      text: `C1/C2 上 Pro meter 的分辨率或重复次数不足,暂不能按工作节奏判断哪种 TTL 更省套餐额度;API 等价成本见下表,但不能替代 meter 结论。${onWrites}`,
490    }
491  }
492  if (api.size > 1 || meter.size > 1) {
493    return { category: 4, text: '结果随工作节奏而变化:见各对比的分项结论。' }
494  }
495  if (meter.has('b')) {
496    return { category: 3, text: '1h 更便宜:Pro meter 在已判定的工作节奏下偏向 1h。' }
497  }
498  if (meter.has('a')) {
499    return api.has('b')
500      ? { category: 4, text: 'API 等价成本与 Pro meter 的结论相反:见各对比的分项结论。' }
501      : { category: 1, text: '5m 在 API 等价成本和 Pro meter 两边都更便宜(限已判定的工作节奏)。' }
502  }
503  if (api.has('a')) {
504    return { category: 2, text: '5m 只在 API 等价成本上更便宜,Pro meter 无显著优势。' }
505  }
506
507  return {
508    category: api.has('b') ? 3 : 2,
509    text: api.has('b')
510      ? '1h 在 API 等价成本上更便宜;Pro meter 无显著差异。'
511      : 'API 等价成本与 Pro meter 均无显著差异。',
512  }
513}
514
515export type ObservationRow = {
516  session_id: string
517  source: string
518  ttl: string
519  requests: number
520  cacheRead: number
521  cacheWrite: number
522  input: number
523  output: number
524  apiEquivalentUsd: number
525}
526
527export type Summary = {
528  generatedAt: string
529  counts: { events: number; runs: number }
530  cells: CellSummary[]
531  comparisons: Comparison[]
532  conclusion: Conclusion
533  observation: ObservationRow[]
534}
535
536export const summarize = (
537  events: readonly EventRow[],
538  runs: readonly RunRecord[],
539  generatedAt: string,
540): Summary => {
541  const groups = new Map<string, RunRecord[]>()
542  for (const run of runs) {
543    const key = `${run.experiment_id}\u0000${cellTtl(run)}`
544    const group = groups.get(key)
545    if (group === undefined) groups.set(key, [run])
546    else group.push(run)
547  }
548  const cells = [...groups.entries()]
549    .map(([key, group]) => {
550      const [experiment = '', ttl = ''] = key.split('\u0000')
551
552      return summarizeCell(experiment, ttl, group, events)
553    })
554    .sort((x, y) => `${x.experiment}${x.ttl}`.localeCompare(`${y.experiment}${y.ttl}`))
555  const comparisons = COMPARISONS.map(spec => compare(spec, cells))
556
557  const observed = new Map<string, ObservationRow>()
558  for (const row of events) {
559    if (row.kind === 'meter' || row.kind === 'shadow' || row.kind === 'recovery') continue
560    if (row.experiment_id !== '') continue
561    const ttl = row.ttl_observed || row.ttl_requested
562    const key = `${row.session_id}\u0000${row.source}\u0000${ttl}`
563    const entry = observed.get(key) ?? {
564      session_id: row.session_id,
565      source: row.source,
566      ttl,
567      requests: 0,
568      cacheRead: 0,
569      cacheWrite: 0,
570      input: 0,
571      output: 0,
572      apiEquivalentUsd: 0,
573    }
574    entry.requests += 1
575    entry.cacheRead += row.cache_read_input_tokens
576    entry.cacheWrite += row.cache_creation_input_tokens
577    entry.input += row.input_tokens
578    entry.output += row.output_tokens
579    entry.apiEquivalentUsd += row.api_equivalent_usd ?? 0
580    observed.set(key, entry)
581  }
582
583  return {
584    generatedAt,
585    counts: { events: events.length, runs: runs.length },
586    cells,
587    comparisons,
588    conclusion: conclude(comparisons),
589    observation: [...observed.values()],
590  }
591}
592
593const usd = (value: number | null): string =>
594  value === null ? '-' : `$${value.toFixed(4)}`
595
596const points = (value: Spread): string =>
597  value.mean === null
598    ? '-'
599    : `${value.mean.toFixed(1)} (${value.min}~${value.max}, n=${value.n})`
600
601const API_WORDS: Record<ApiVerdict, string> = {
602  a: 'A 更便宜',
603  b: 'B 更便宜',
604  tie: '差异小于 3%',
605  insufficient: '数据不足',
606}
607
608const METER_WORDS: Record<MeterVerdict, string> = {
609  a: 'A 更省',
610  b: 'B 更省',
611  unclear: '区间重叠,无显著差异',
612  'insufficient-replicates': `每侧不足 ${MIN_REPLICATES} 次干净重复,无法判断`,
613  'insufficient-resolution': `该组各 run 的 meter 累计变化不足 ${MIN_METER_POINTS} 个百分点,分辨率不足`,
614}
615
616const table = (head: readonly string[], rows: readonly (readonly string[])[]): string =>
617  [
618    `| ${head.join(' | ')} |`,
619    `| ${head.map(() => '---').join(' | ')} |`,
620    ...rows.map(row => `| ${row.join(' | ')} |`),
621  ].join('\n')
622
623export const renderReport = (summary: Summary): string => {
624  const parts: string[] = [
625    '# cache-keeper 报告',
626    '',
627    `生成时间:${summary.generatedAt};事件 ${summary.counts.events} 条,实验 run ${summary.counts.runs} 个。`,
628    '',
629    '## 结论',
630    '',
631    `**类型 ${summary.conclusion.category}:${summary.conclusion.text}**`,
632    '',
633    '两种成本分开报告:API 等价成本按官方 API 单价由日志算出;套餐额度只看 `$.session.usage().rateLimits` 的真实百分比增量,不由 API 价格推算。',
634    '',
635    '## 对比',
636    '',
637  ]
638  for (const one of summary.comparisons) {
639    parts.push(
640      `### ${one.id}:${one.title}`,
641      '',
642      `A = ${one.a.label}(${one.a.experiment}),B = ${one.b.label}(${one.b.experiment})`,
643      '',
644      table(
645        ['成本口径', 'A', 'B', '判定'],
646        [
647          [
648            'API 等价 USD / run',
649            `${usd(one.api.a.mean)} (n=${one.api.a.n})`,
650            `${usd(one.api.b.mean)} (n=${one.api.b.n})`,
651            API_WORDS[one.api.verdict],
652          ],
653          ...Object.entries(one.meter.byKind).map(([kind, sides]) => [
654            `套餐 meter ${kind} 增量(百分点)`,
655            points(sides.a),
656            points(sides.b),
657            METER_WORDS[one.meter.verdict],
658          ]),
659          ...(Object.keys(one.meter.byKind).length === 0
660            ? [['套餐 meter', '-', '-', METER_WORDS[one.meter.verdict]]]
661            : []),
662        ],
663      ),
664      '',
665    )
666  }
667
668  parts.push('## 实验 cell', '')
669  if (summary.cells.length === 0) parts.push('还没有完成的实验 run。', '')
670  for (const cell of summary.cells) {
671    parts.push(
672      `### ${cell.experiment} · TTL ${cell.ttl}`,
673      '',
674      `干净 run ${cell.n} 个,排除 ${cell.excludedRuns} 个;cache 命中率 ${
675        cell.cacheHitRate === null ? '-' : `${(cell.cacheHitRate * 100).toFixed(1)}%`
676      };API 等价合计 ${usd(cell.totals.apiEquivalentUsd)}。`,
677      '',
678      table(
679        ['replicate', 'session', '状态', 'TTL 实测', '末步结果', 'API 等价 USD', 'meter 增量'],
680        cell.runs.map(run => [
681          String(run.replicate),
682          run.session_id.slice(0, 8),
683          run.status,
684          run.ttlObserved || '-',
685          run.finalStep || '-',
686          usd(run.apiEquivalentUsd),
687          Object.entries(run.rateLimitDelta)
688            .map(([kind, moved]) => `${kind} ${moved ?? 'reset'}`)
689            .join('; ') || '-',
690        ]),
691      ),
692      '',
693      table(
694        ['cache read', '5m write', '1h write', '未拆分 write', 'input', 'output'],
695        [
696          [
697            String(cell.totals.cacheRead),
698            String(cell.totals.cacheWrite5m),
699            String(cell.totals.cacheWrite1h),
700            String(cell.totals.cacheWriteUnsplit),
701            String(cell.totals.input),
702            String(cell.totals.output),
703          ],
704        ],
705      ),
706      '',
707    )
708    if (cell.warnings.length > 0) {
709      parts.push(...cell.warnings.map(warning => `- 警告:${warning}`), '')
710    }
711  }
712
713  parts.push('## 日常观察(非实验请求)', '')
714  parts.push(
715    summary.observation.length === 0
716      ? '无。'
717      : table(
718          ['session', '来源', 'TTL', '请求数', 'cache read', 'cache write', 'input', 'output', 'API 等价 USD'],
719          summary.observation.map(row => [
720            row.session_id.slice(0, 8),
721            row.source,
722            row.ttl,
723            String(row.requests),
724            String(row.cacheRead),
725            String(row.cacheWrite),
726            String(row.input),
727            String(row.output),
728            usd(row.apiEquivalentUsd),
729          ]),
730        ),
731    '',
732  )
733
734  return parts.join('\n')
735}
736
hooks/lib/prefix.ts 231 lines
1// What of a request's prefix the transcript actually shows. The engine does
2// not write the system prompt, the tool list or the plugin set as such; it
3// writes attachments that carry them (prompt_snapshot, the deferred-tool
4// record and deltas, MCP instruction deltas, the skill listing). This module
5// turns those into stable hashes so a cache miss can be attributed to a
6// prefix change that was observed, instead of guessed at.
7//
8// A hash is a short, stable digest, not a security primitive: 16 hex digits
9// of two independent 32-bit hashes. Equal text always gives equal hashes;
10// different text gives different hashes with overwhelming probability.
11
12type Row = Record<string, unknown>
13
14const isRecord = (value: unknown): value is Row =>
15  typeof value === 'object' && value !== null && !Array.isArray(value)
16
17const text = (value: unknown): string | null =>
18  typeof value === 'string' && value !== '' ? value : null
19
20/** JSON with object keys sorted, so equal values always spell the same. */
21const stable = (value: unknown): string => {
22  if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`
23  if (isRecord(value)) {
24    const keys = Object.keys(value).sort()
25    return `{${keys
26      .map(key => `${JSON.stringify(key)}:${stable(value[key])}`)
27      .join(',')}}`
28  }
29  const json = JSON.stringify(value)
30  return json === undefined ? 'null' : json
31}
32
33/** 16 hex digits: FNV-1a and djb2, both 32-bit. */
34export const digest = (input: string): string => {
35  let a = 0x811c9dc5
36  let b = 5381
37  for (let index = 0; index < input.length; index += 1) {
38    const code = input.charCodeAt(index)
39    a ^= code
40    a = Math.imul(a, 0x01000193)
41    b = Math.imul(b, 33) ^ code
42  }
43  return (
44    (a >>> 0).toString(16).padStart(8, '0') +
45    (b >>> 0).toString(16).padStart(8, '0')
46  )
47}
48
49export type ToolHashBasis = 'definitions' | 'names' | 'none'
50export type PluginHashBasis = 'mcp+skills' | 'mcp' | 'skills' | 'none'
51
52/** The prefix as it stood just before one request. Null means: not visible. */
53export type PrefixSnapshot = {
54  /** Hash of prompt_snapshot.systemPrompt, and its total character count. */
55  systemPromptHash: string | null
56  systemPromptChars: number | null
57  /** The Claude Code version that wrote the snapshot, when the row had one. */
58  systemPromptVersion: string | null
59  /** Hash of the deferred tool set (names, and definitions when recorded). */
60  toolListHash: string | null
61  toolNames: string[] | null
62  toolHashBasis: ToolHashBasis
63  /** Hash of the MCP-server set and the skill listing, as a plugin proxy. */
64  pluginSetHash: string | null
65  pluginSetBasis: PluginHashBasis
66  mcpServers: string[] | null
67  skills: string[] | null
68  claudeCodeVersion: string | null
69}
70
71type PrefixState = PrefixSnapshot & {
72  /** name -> stable serialisation of its last recorded definition. */
73  toolDefinitions: Map<string, string>
74  /** Null until a record or delta names tools at all. */
75  toolNamesSet: Set<string> | null
76  mcpSet: Set<string> | null
77  skillSet: Set<string> | null
78  systemPrompt: string[] | null
79}
80
81export const initialPrefix = (): PrefixState => ({
82  systemPromptHash: null,
83  systemPromptChars: null,
84  systemPromptVersion: null,
85  toolListHash: null,
86  toolNames: null,
87  toolHashBasis: 'none',
88  pluginSetHash: null,
89  pluginSetBasis: 'none',
90  mcpServers: null,
91  skills: null,
92  claudeCodeVersion: null,
93  toolDefinitions: new Map(),
94  toolNamesSet: null,
95  mcpSet: null,
96  skillSet: null,
97  systemPrompt: null,
98})
99
100const cloneSet = (set: Set<string> | null): Set<string> | null =>
101  set === null ? null : new Set(set)
102
103const namesOf = (value: unknown): string[] =>
104  Array.isArray(value)
105    ? value.filter((one): one is string => typeof one === 'string' && one !== '')
106    : []
107
108const recomputeTools = (state: PrefixState): void => {
109  if (state.toolNamesSet === null) {
110    state.toolListHash = null
111    state.toolNames = null
112    state.toolHashBasis = 'none'
113    return
114  }
115  const names = [...state.toolNamesSet].sort()
116  state.toolNames = names
117  if (state.toolDefinitions.size > 0) {
118    const definitions = names
119      .filter(name => state.toolDefinitions.has(name))
120      .map(name => [name, state.toolDefinitions.get(name)] as const)
121    state.toolListHash = digest(stable({ names, definitions }))
122    state.toolHashBasis = 'definitions'
123  } else {
124    state.toolListHash = digest(stable({ names }))
125    state.toolHashBasis = 'names'
126  }
127}
128
129const recomputePlugins = (state: PrefixState): void => {
130  const mcp = state.mcpSet === null ? null : [...state.mcpSet].sort()
131  const skills = state.skillSet === null ? null : [...state.skillSet].sort()
132  state.mcpServers = mcp
133  state.skills = skills
134  if (mcp === null && skills === null) {
135    state.pluginSetHash = null
136    state.pluginSetBasis = 'none'
137    return
138  }
139  state.pluginSetHash = digest(stable({ mcp: mcp ?? [], skills: skills ?? [] }))
140  state.pluginSetBasis =
141    mcp !== null && skills !== null
142      ? 'mcp+skills'
143      : mcp !== null
144        ? 'mcp'
145        : 'skills'
146}
147
148/**
149 * Folds one transcript row into the prefix state. Only attachment rows and
150 * the version field matter; every other row leaves the state unchanged.
151 */
152export const applyPrefixRow = (state: PrefixState, row: Row): PrefixState => {
153  if (typeof row.version === 'string' && row.version !== '') {
154    state.claudeCodeVersion = row.version
155  }
156  const attachment = isRecord(row.attachment) ? row.attachment : undefined
157  if (attachment === undefined) return state
158  const type = text(attachment.type)
159
160  if (type === 'prompt_snapshot') {
161    const prompt = attachment.systemPrompt
162    if (Array.isArray(prompt) && prompt.every(one => typeof one === 'string')) {
163      state.systemPrompt = prompt as string[]
164      state.systemPromptHash = digest(stable(prompt))
165      state.systemPromptChars = (prompt as string[]).reduce(
166        (total, part) => total + part.length,
167        0,
168      )
169      state.systemPromptVersion = text(row.version)
170    }
171    return state
172  }
173
174  if (type === 'deferred_tools_record') {
175    const entries = Array.isArray(attachment.entries) ? attachment.entries : []
176    state.toolNamesSet ??= new Set()
177    state.toolDefinitions = new Map()
178    for (const entry of entries) {
179      if (!isRecord(entry)) continue
180      const name = text(entry.name)
181      if (name === null) continue
182      state.toolNamesSet.add(name)
183      state.toolDefinitions.set(name, stable(entry))
184    }
185    recomputeTools(state)
186    return state
187  }
188
189  if (type === 'deferred_tools_delta') {
190    state.toolNamesSet ??= new Set()
191    for (const name of namesOf(attachment.addedNames)) state.toolNamesSet.add(name)
192    for (const name of namesOf(attachment.readdedNames)) state.toolNamesSet.add(name)
193    for (const name of namesOf(attachment.removedNames)) state.toolNamesSet.delete(name)
194    for (const name of namesOf(attachment.wireHiddenNames)) {
195      state.toolNamesSet.delete(name)
196    }
197    recomputeTools(state)
198    return state
199  }
200
201  if (type === 'mcp_instructions_delta') {
202    state.mcpSet = cloneSet(state.mcpSet) ?? new Set()
203    for (const name of namesOf(attachment.addedNames)) state.mcpSet.add(name)
204    for (const name of namesOf(attachment.removedNames)) state.mcpSet.delete(name)
205    recomputePlugins(state)
206    return state
207  }
208
209  if (type === 'skill_listing') {
210    state.skillSet = new Set(namesOf(attachment.names))
211    recomputePlugins(state)
212  }
213
214  return state
215}
216
217/** A copy safe to keep after later rows have changed the running state. */
218export const prefixSnapshot = (state: PrefixState): PrefixSnapshot => ({
219  systemPromptHash: state.systemPromptHash,
220  systemPromptChars: state.systemPromptChars,
221  systemPromptVersion: state.systemPromptVersion,
222  toolListHash: state.toolListHash,
223  toolNames: state.toolNames === null ? null : [...state.toolNames],
224  toolHashBasis: state.toolHashBasis,
225  pluginSetHash: state.pluginSetHash,
226  pluginSetBasis: state.pluginSetBasis,
227  mcpServers: state.mcpServers === null ? null : [...state.mcpServers],
228  skills: state.skills === null ? null : [...state.skills],
229  claudeCodeVersion: state.claudeCodeVersion,
230})
231
types/index.d.ts 21 lines
1declare module 'claude-code' {
2  interface PluginState {
3    'cache-keeper': {
4      bar: string
5      /** The main conversation's prompt cache as the keeper has it, for other mods to read. */
6      cache: {
7        /** When the last request or keepalive that touched the cache started, in ms. */
8        lastActivityAt: number | null
9        ttl: '5m' | '1h' | null
10        /** `lastActivityAt` plus the TTL: past it the cache is cold. */
11        expiresAt: number | null
12        cachedPrefixTokens: number
13        isEnabled: boolean
14        pausedReason: string | null
15        /** `wrapped`: the wrap-up was sent and the session waits for the 5-hour reset. */
16        bridgePhase: 'idle' | 'wrapped'
17      }
18    }
19  }
20}
21