SLOPSHOPPER

keepwarm

Idle-session guard for Claude Code's 1-hour prompt cache (macOS): about 50 idle minutes after the last turn of a large session it notifies you, optionally…

panebandguardcommandtoaststatus
v0.9.13MITupdated 2026-10-26luwux/keepwarm
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · keepwarm
│ ┃ keepwarm ✕ › fix the failing auth test and add an audit log call │ ┃ 缓存还剩 1h00m │ ┃ 没在保温 ⏺ Read(src/auth.ts) │ ┃ 上下文 97K · 过期重写 $0.78 · 保温 $0.02/h ⎿ Read 6 lines │ ┃ [ compact ] [ 保温 8h ] [ 收起 ] ⏺ 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 │ │ › /keepwarm │ ⎿ keepwarm: app(项目策略 ask) │ ⎿ keepwarm: │ ⎿ keepwarm: 缓存 热,还剩 1h00m · 上下文 97K / 200K · claude-opus-5-5 │ ⎿ keepwarm: 保温 关 │ ⎿ keepwarm: 提醒 不提醒(上下文不到 200K,或缓存已冷) │ ⎿ keepwarm: 价格 过期后重写一次约 $0.78,保温约 $0.02/小时 │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · keepwarm
缓存还剩 1h00m 没在保温 上下文 97K · 过期重写 $0.78 · 保温 $0.02/h [ compact ] [ 保温 8h ] [ 收起 ]
README

keepwarm

English · 中文

An idle-session guard for Claude Code's 1-hour prompt cache, written as a Claude Code mod (a hooks-module plugin). macOS only. The interface text is Chinese for now.

Install

In a terminal session of Claude Code (tested on 2.1.296):

/plugin install keepwarm --marketplace luwux/keepwarm

Answer y to add the marketplace, then pick the user scope. Installed at the user scope it also loads in the desktop app's Code tab.

Why

On a Claude subscription the main conversation's prompt cache lives for an hour after the last request. Come back later and the whole context is written again: a 300K-token Opus 5.5 session costs about $2.4 to rewrite, against about $0.06 to read it warm. keepwarm watches each session and speaks up before the hour runs out.

What it does

  • Idle check, handled without asking (~50 minutes after the last turn, only for sessions above remindMinContext, 200K by default; smaller ones get no judge, no ping and no compaction). If background work the session started (a shell, a subagent, a monitor) is still running, nothing is judged: that work wakes the session when it reports, so the cache is kept warm until then, at most 12 hours after the last turn (then the session is compacted); in fifteen days of the author's sessions 80% of such waits reported within 6 hours and 92% within
  • A watch on a published artifact and an idle teammate do not count (they wake nobody), nor, after the app restarts, the work of the process before (it died with it). Otherwise, with idleCheck: judge a fork of the session decides whether to compact, keep warm or leave it; the fork reads the cache (about $0.03–0.10 at 100–400K tokens) and refreshes it. If the judge finds the cache already gone (the server sometimes drops it within the hour), nothing more is done: keeping warm or compacting would pay the rewrite a second time. Otherwise, with no notification:
  • compact: the session is compacted about 55 minutes later, when the hour the judge's own read bought is nearly over; it costs the same, and coming back before then keeps the full context;
  • keep warm: the cache is kept warm until 6 hours after the last turn, then the session is compacted; any turn in the session ends this (yours, or background work reporting), and the next quiet stretch is checked afresh. Night is no exception: an idle Mac is no sign you have gone to bed, and coming back within hours, the pings cost less than compacting and rewriting the cache;
  • leave it: nothing.

Six hours comes from two weeks of the author's sessions: daytime returns came within six hours or the next day, and up to six hours the pings cost about what the compactions they spare save. A session that scheduled its own wakeup before the cache lapses (ScheduleWakeup, /loop, a cron of its own, or a background shell that starts with sleep N) gets no idle check and no pings, unless the wakeup does not come; so the model need not wake itself to keep the cache warm. Nor does a session with no project, which runs in a folder the app made for it (the + beside This computer; skipScratch), or one filed under a desktop sidebar group named in skipGroups (default Chat). With idleCheck: notify you get a free desktop reminder instead. Claude Code's own idle compaction does the same without judging; turn it off with "idleCompaction": false if you use this.

  • Nothing under the prompt: no status line, warm or cold; /keepwarm shows the state.
  • Keep-warm windows: /keepwarm on 8h pings the cache whenever 55 minutes have passed since the last request, for 8 hours, whatever the session is doing. Only /keepwarm off ends it. A window opened from a reminder's button or by the model covers an absence, so it ends when you write in that session. At most pingLimit pings per session in any pingLimitHours.
  • Buttons on the phone (optional, via ntfy): when you are away from the Mac, the reminder is pushed to your phone with buttons: compact, keep warm N hours, leave it. A tap posts a one-time token to reply_topic; the session polls that topic every 20 seconds while it has buttons out, does what was tapped and pushes a confirmation. The three buttons of one notification share one token group: the first tap voids them all, so a second tap does nothing. Tokens expire after 3 hours; a tap after the cache has lapsed is answered, not acted on.
  • Cold-write notice: whenever the whole context is written again, a notice in Claude says how many tokens, what it cost and why: the cache had lapsed, it lapsed while a keep-warm window was open, the model changed, or the prompt prefix changed unexpectedly; and whether a background task's report set it off. Not for a new session's first message or right after a compaction; nothing goes to the Mac's notifications or the phone (the opt-in alerts below aside).
  • Alerts (/keepwarm alert on, off by default): only for what should not happen: a window whose pings could not go out, the cache rewritten within the hour on the same model, the ping limit reached, or keepwarm's own daily budget (dailyBudgetUsd, $30) exceeded.
  • Leaving: /keepwarm leave 2h asks every live, warm session for its own verdict and shows one summary.
  • Not while the Mac sleeps: with the lid closed the Mac wakes for seconds now and then; no judge, ping or compaction goes out then, since the sleep that follows cuts it and it is sent again after the cache has lapsed. Timers keep wall-clock time: one that came due during the sleep runs on the full wake, unless the cache has under half a minute left (or is gone), when nothing is sent.
  • Not while the server drops caches: when two sessions have had their cache written again unexpectedly within the hour, the server is evicting caches early (idle sessions first) or every prefix just changed; for that hour no automatic judge or ping goes out, since each would mostly find its cache gone and write it whole for nothing.
  • Never blocks a prompt unless you turn guard refuse on.

Every request is accounted for

All requests (forks, pings) and changes (notifications, compact, files it writes) go through one audit layer that records the real usage returned by the API and its dollar cost. /keepwarm log shows it; python3 tests/check-audit.py fails if any effectful call bypasses it.

Commands

CommandWhat it does
/keepwarm or statuscurrent state
on 8h / off / autokeep warm for 8 hours / stop and forbid the model to start one / allow it again
checkjudge now: compact, keep warm or leave it
`leave 2h on\off`tell all sessions you are away (Mac on / lid closed)
`idle off\notify\judge`what the 50-minute idle check does
`alert on\off\test`alerts
`policy auto\warm\off`per-project idle policy: handle as judged / always keep warm / nothing
`guard refuse\warn\off`when you write to a session whose cache is already cold
log, ledgeraudit log, cold-write ledger
push, paneltest push with buttons, button pane on the Mac

Settings

In /config, or pluginConfigs.keepwarm.options in ~/.claude/settings.json: idleCheck (notify | judge | off), remindMinContext, skipScratch, skipGroups, pingLimit, pingLimitHours, dailyBudgetUsd, awayMinutes, ntfyConfigFile.

ntfyConfigFile points to a JSON file:

{ "server": "https://ntfy.sh", "topic": "<push topic>", "reply_topic": "<button topic>" }

Without reply_topic the pushes carry no buttons; an empty path disables phone pushes. On the public ntfy.sh server anyone who knows a topic name can read it, so use long random names: the push carries session titles and summaries. A forged tap cannot act, since tokens are random. Desktop notifications use terminal-notifier when it is installed.

Cost and risk

keepwarm spends your quota to save it. Each fork or ping is a real request billed at the cache-read rate; a 3-hour window on a 300K session costs about $0.20, which pays off only if you come back within it. Defaults are conservative: idleCheck is notify (free), nothing is automatic, and pings stop at the cap or when the cache is found cold. Anthropic can change cache behaviour at any time; check /keepwarm log against your usage. Prices are list prices of September 2026, hard-coded in hooks/register.tsx.

Development

claude --plugin-dir .
claude plugin validate .
claude plugin test .
python3 tests/check-audit.py

Credits

Keep-warm pings are derived from cache-tax (MIT, Karan Bansal); see LICENSE.cache-tax. keepwarm itself is MIT; see LICENSE.

Source 2 files
hooks/register.tsx 2054 lines
1// keepwarm: an idle-session guard for the 1-hour prompt cache.
2//
3// 1. Context reminder: ~50 minutes after the last request, if the context is
4//    large, a tool-less fork of the session's own transcript (billed at the
5//    cache-read rate, written nowhere, and refreshing the cache as it reads)
6//    judges whether to compact, keep warm or ignore. The verdict shows as a band
7//    above the prompt with buttons, a toast and a macOS notification; per-project
8//    policy can apply it automatically.
9// 2. Keep-warm: the same fork, sent when 55 minutes have passed since the last
10//    request, inside a window. The person's /keepwarm on 8h holds for its hours
11//    whatever happens; the model may also start one with the
12//    mcp__keepwarm__keepwarm tool, and the person's /keepwarm overrides the model.
13//
14// Keep-warm is derived from cache-tax (MIT, Karan Bansal, github.com/karanb192/cache-tax).
15import { atom, read, update } from 'claude-code'
16import type { EngineInterface, Register, TurnUsage } from 'claude-code'
17
18import type { KeepwarmAdvice, KeepwarmLeaveAll, KeepwarmLeaveItem } from '../types'
19
20const TTL_MS = 60 * 60 * 1000
21// Cross-session: every session's keepwarm polls the shared $.store for a leave request.
22const POLL_MS = 10_000
23const LEAVE_COLLECT_MS = 45_000
24const LEAVE_REQ_TTL_MS = 10 * 60 * 1000
25const RT_KEEP_MS = 3 * 24 * 60 * 60 * 1000
26// Settings the person picks in /config (plugin.json userConfig); register() fills them in.
27type Idle = 'off' | 'notify' | 'judge'
28const cfg = {
29  // A JSON file {"server": "https://ntfy.sh", "topic": "..."}; empty means no phone push.
30  ntfyConfigFile: '',
31  // Below this a session is left alone: no judge, no ping, no compaction; it keeps its whole
32  // context and pays a rewrite when the person comes back late. The person's choice (10-16), from
33  // 100K: over fifteen days handling the 100-200K band saved about $107 against 48 compactions.
34  remindMinCtx: 200_000,
35  awayIdleS: 5 * 60,
36  // A safety net against a runaway timer: per session, at most pingLimit pings in any
37  // pingLimitHours (one every 55 minutes is 13 in 12 hours).
38  pingLimit: 15,
39  pingLimitHours: 12,
40  // What keepwarm may spend a day on its own (idle judges, pings of windows the model opened);
41  // past it the idle check falls back to the free notice until midnight. 0: no limit. A busy day
42  // spends $3-10; $10 was hit on 10-19 at 02:46 by cold forks in a cache eviction, and the
43  // nineteen hours without judges that followed cost about $17 in rewrites.
44  dailyBudgetUsd: 30,
45  idleDefault: 'notify' as Idle,
46  // Desktop sidebar groups (lower case) whose sessions get no idle check: chats used once and left.
47  skipGroups: ['chat'],
48  // Nor do sessions with no project, which run in a folder the app made for them (the + beside
49  // "This computer" in the sidebar): the person's real chats (10-14).
50  skipScratch: true,
51}
52// Ping when the hour has five minutes left, whatever the session is doing (working, waiting on
53// background work, waiting on the person): only the time since the last request counts.
54const PING_AFTER_MS = 55 * 60 * 1000
55const CHECK_AFTER_MS = 50 * 60 * 1000
56const MIN_PING_MS = 60 * 1000
57const DEFAULT_WINDOW_MS = 3 * 60 * 60 * 1000
58const MAX_WINDOW_MS = 12 * 60 * 60 * 1000
59const MIN_CTX = 30_000
60const END_WARN_MS = 10 * 60 * 1000
61// Hard brakes on pings, whatever the timers say.
62const PING_MIN_GAP_MS = 40 * 60 * 1000
63// A wakeup the session scheduled itself (ScheduleWakeup, /loop) refreshes the cache with its own
64// request: no idle check and no ping while one is due this long before the cache lapses.
65const WAKE_MARGIN_MS = 3 * 60 * 1000
66// An idle session the judge wants kept warm stays warm until this long after its last turn, then
67// is compacted. Two weeks of history (research/10-keepwarm-backlog.md, 10-14): daytime returns
68// come within six hours or the next day, and up to six hours the pings cost about what the
69// compactions they spare save.
70const KEEP_UNTIL_MS = 6 * 60 * 60 * 1000
71// A session waiting on background work it started (a shell, a subagent, a monitor) is woken by
72// that work when it reports, whoever is around: it stays warm until then, with no judge, at most
73// this long after its last turn, and is then compacted. Fifteen days of history
74// (research/10-keepwarm-backlog.md, 10-14): 80% of such waits report within 6 hours, 92% in 12.
75const BG_KEEP_MS = 12 * 60 * 60 * 1000
76// A background shell that starts by sleeping is the session's own alarm clock: sessions use
77// `sleep 3300` because ScheduleWakeup fires only under /loop.
78const SELF_WAKE = /^\s*sleep\s+(\d+(?:\.\d+)?)\s*(?:$|[;&|\n])/
79// A watch on a published artifact ("live updates for artifact …") is listed as background work but
80// runs until stopped and reports only if someone comments: no sign the session will be woken
81// (10-16: two sessions kept warm twelve hours overnight for one).
82const WATCH = /^live updates for /i
83const ACTIVE = /^(running|pending)$/i
84const GUARD_MIN_CTX = 50_000
85const PING_PROMPT = 'Reply with the single word: warm'
86const TOOL = 'mcp__keepwarm__keepwarm'
87const NOT_THE_PERSON = new Set(['plugin', 'task-notification', 'scheduled-trigger', 'peer', 'peer-send-message', 'coordinator', 'observer', 'observer-activity', 'auto-continuation', 'slack-ping', 'projects-relay', 'channel'])
88const LOG_MAX = 500
89
90// $ per million tokens: [cache read, 1h cache write, output], list prices September 2026.
91// Longer family names first: a model id matches the first row it contains.
92const PRICES: Array<[string, number, number, number]> = [
93  ['fable-5-1', 0.25, 20, 50],
94  ['fable-5', 1, 20, 50],
95  ['opus-5-5', 0.2, 8, 20],
96  ['opus-5', 0.5, 10, 25],
97  ['opus-4', 0.5, 10, 25],
98  ['sonnet-5', 0.2, 4, 10],
99  ['sonnet', 0.3, 6, 15],
100  ['haiku', 0.1, 2, 5],
101]
102
103type Owner = 'user' | 'model'
104type Policy = 'ask' | 'auto' | 'warm' | 'off'
105type Guard = 'refuse' | 'warn' | 'off'
106// Why a request rewrote the cache: the hour lapsed, the model changed, or something else
107// changed the prompt's prefix (system prompt, tool list).
108type MissCause = 'expired' | 'model' | 'other'
109type Miss = { at: number; tokens: number; usd: number | null; cause: MissCause; gapMs: number }
110type Usage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
111type PingRecord = { at: number; read: number; write: number; usd: number | null; warm: boolean }
112type Timer = { cancel: () => void }
113
114type State = {
115  sid: string
116  cwd: string
117  policy: Policy
118  guard: Guard
119  ackedAt: number
120  // What the last main-loop request carried, and on which model: the next one is held to it.
121  stepCtx: number
122  stepModel: string | null
123  // When the cache was last known refreshed, held while main-loop requests go unanswered
124  // (interrupted or failed before any usage came back): those may never have reached it.
125  unansweredFrom: number
126  // The first request after a compaction writes the summary; that is not a miss.
127  skipMiss: boolean
128  // What started the current turn: 'person', or the origin of a turn nobody typed.
129  turnBy: string
130  misses: Miss[]
131  deadline: number
132  every: number
133  owner: Owner | null
134  reason: string
135  wakePrompt: string
136  userOff: boolean
137  // Opened with /keepwarm on: it holds for its hours whatever the person does, and only
138  // /keepwarm off ends it. A window from a reminder or the model covers an absence, so it ends
139  // when the person writes.
140  sticky: boolean
141  lastRequestAt: number
142  lastModel: string | null
143  ctx: number
144  window: number
145  compacted: boolean
146  compactions: number // seen since this load: a command worked when it went up
147  turnError: boolean // the last main turn died on an API error (a usage limit, say)
148  pending: Timer | null
149  check: Timer | null
150  expire: Timer | null
151  endWarn: Timer | null
152  endWarnedFor: number
153  tick: Timer | null
154  caff: AsyncGenerator<unknown, unknown> | null
155  checkedFor: number
156  // Last real turn. Forks refresh lastRequestAt but are not the person coming back.
157  turnAt: number
158  poll: Timer | null
159  collect: Timer | null
160  leaveSeen: string
161  // The 50-minute idle check: off, a free notice, or a judging fork.
162  idle: Idle
163  last: PingRecord | null
164  pings: number
165  pingUsd: number
166  stopped: string | null
167  // The panel (/keepwarm panel) redraws its countdown each minute while open.
168  paneTick: Timer | null
169  // Buttons on a phone push: polling the reply topic while one of them may still be tapped.
170  phonePoll: Timer | null
171  phoneBusy: boolean
172  // The window was opened by the idle judge: when it runs out, compact.
173  thenCompact: boolean
174  // When the session's own scheduled wakeup fires next (ScheduleWakeup, a sleeping background
175  // shell); 0 when none is known.
176  wakeAt: number
177  wakeBySleep: boolean
178  // The background work still running when the main thread last stopped, as the engine lists it:
179  // it wakes the session when it reports.
180  bg: string[]
181}
182
183const advice = atom({ plugin: 'keepwarm', key: 'advice' } as const, null as KeepwarmAdvice | null)
184const leaveAll = atom({ plugin: 'keepwarm', key: 'leaveAll' } as const, null as KeepwarmLeaveAll | null)
185const panel = atom({ plugin: 'keepwarm', key: 'panel' } as const, 0)
186
187type LeaveReq = { id: string; at: number; from: string; hours: number; machineOn: boolean }
188type Runtime = { lastRequestAt: number; turnAt: number; ctx: number; window: number; model: string | null; compacted: boolean }
189
190function priceOf(model: string | null): [number, number, number] | null {
191  const m = (model ?? '').toLowerCase().replace(/[\s.]+/g, '-')
192  for (const [family, r, w, o] of PRICES) if (m.includes(family)) return [r, w, o]
193  return null
194}
195
196function parseDuration(text: string): number | null {
197  const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+)m)?$/.exec(text.trim())
198  if (!m || (m[1] === undefined && m[2] === undefined)) return null
199  return (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60 * 1000
200}
201
202function fmtDuration(ms: number): string {
203  const total = Math.max(0, Math.round(ms / 60000))
204  const h = Math.floor(total / 60)
205  const m = total % 60
206  return h > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m`
207}
208
209const fmtUsd = (usd: number | null) => usd == null ? 'n/a' : '$' + (usd >= 10 ? usd.toFixed(1) : usd.toFixed(2))
210const fmtTok = (n: number) => n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1000 ? Math.round(n / 1000) + 'K' : String(n)
211const coldUsd = (s: State) => { const p = priceOf(s.lastModel); return p ? s.ctx * p[1] / 1e6 : null }
212const hourUsd = (s: State) => { const p = priceOf(s.lastModel); return p ? s.ctx * p[0] / 1e6 * (TTL_MS / s.every) : null }
213const isCold = (s: State, now: number) => s.lastRequestAt > 0 && !s.compacted && now - s.lastRequestAt >= TTL_MS
214// Too late to send: a request takes seconds to reach the cache (a 300K fork, more), so one sent in
215// the hour's last half minute (a lid opened at 59:58) may find it gone and write it all again.
216const SEND_MARGIN_MS = 30_000
217const tooLate = (s: State, now: number) => s.lastRequestAt > 0 && !s.compacted && now - s.lastRequestAt >= TTL_MS - SEND_MARGIN_MS
218const key = (s: State, k: string) => `${k}:${s.sid}`
219const project = (s: State) => s.cwd.split('/').filter(Boolean).pop() ?? s.cwd
220
221function forkUsd(u: Usage, p: [number, number, number] | null): number | null {
222  return p ? (u.cache_read_input_tokens * p[0] + u.cache_creation_input_tokens * p[1] + u.input_tokens * p[1] / 2 + u.output_tokens * p[2]) / 1e6 : null
223}
224
225// A warm fork reads the prefix and writes only its own tail; a big write means the prefix broke.
226const forkWasWarm = (u: Usage) => u.cache_read_input_tokens > 0 && u.cache_creation_input_tokens < 0.1 * u.cache_read_input_tokens
227
228// Nothing under the prompt, warm or cold (10-14): a rewrite is told by a notice when it
229// happens, and /keepwarm shows the rest.
230function statusText(_s: State, _now: number): string | undefined {
231  return undefined
232}
233
234// Each label is two Chinese characters and a full-width space, so the lines stay aligned in the
235// desktop app's proportional font as well as in a terminal.
236async function card($: EngineInterface, s: State, now: number): Promise<string> {
237  const alertOn = (await $.store.get('alert')) === true
238  const spent = await spendToday($, now)
239  const over = await overBudget($)
240  const cache = !s.lastRequestAt ? '本会话还没有请求'
241    : s.compacted ? '刚 compact,等下一轮'
242    : isCold(s, now) ? `已冷(最后请求在 ${fmtDuration(now - s.lastRequestAt)} 前)`
243    : `热,还剩 ${fmtDuration(s.lastRequestAt + TTL_MS - now)}`
244  const warm = s.deadline
245    ? `开,还剩 ${fmtDuration(s.deadline - now)}(${s.sticky ? '/keepwarm on 开的,发消息不会结束' : `${s.owner === 'model' ? '模型' : '你'}开的,你回来发消息就结束`})` +
246      `${s.reason && !s.sticky ? `:${s.reason}` : ''}${s.wakePrompt ? `;唤醒任务:${s.wakePrompt}` : ''}`
247    : s.stopped ? `关(上次停止:${s.stopped})` : '关'
248  const remind = s.policy === 'off' || s.idle === 'off' ? '关'
249    : wakesItself(s, now) ? `会话定好了 ${fmtDuration(s.wakeAt - now)} 后自己醒来,不用提醒`
250    : s.check && s.bg.length ? `${s.bg.length} 个后台任务在跑:空闲 50 分钟时开始保温到它们回报(最长到空闲 ${fmtDuration(BG_KEEP_MS)})`
251    : s.check ? `空闲 50 分钟时${s.idle === 'judge' && !over ? `判断一次,然后自己 compact、保温到空闲 ${fmtDuration(KEEP_UNTIL_MS)} 后 compact,或不管` : '免费提醒一次'}`
252    : s.deadline ? '保温期间不提醒'
253    : `不提醒(上下文不到 ${fmtTok(cfg.remindMinCtx)},或缓存已冷)`
254  const missUsd = s.misses.reduce((a, m) => a + (m.usd ?? 0), 0)
255  return [
256    `${project(s)}(项目策略 ${s.policy})`,
257    '',
258    `缓存 ${cache} · 上下文 ${fmtTok(s.ctx)} / ${fmtTok(s.window)} · ${s.lastModel ?? '模型未知'}`,
259    `保温 ${warm}${s.userOff ? ';你已禁止模型开启' : ''}`,
260    `提醒 ${remind}`,
261    `价格 过期后重写一次约 ${fmtUsd(coldUsd(s))},保温约 ${fmtUsd(hourUsd(s))}/小时`,
262    `记账 本会话冷写入 ${s.misses.length} 次 ${fmtUsd(missUsd)} · 本次运行 ping ${s.pings} 次 ${fmtUsd(s.pingUsd)}` +
263      `${s.last ? `(上次读 ${fmtTok(s.last.read)}、写 ${fmtTok(s.last.write)})` : ''}`,
264    `今天 keepwarm 共花 ${fmtUsd(spent.auto + spent.manual)}:自己主动的 ${fmtUsd(spent.auto)}` +
265      `${cfg.dailyBudgetUsd ? `(上限 $${cfg.dailyBudgetUsd}${over ? ',已超,今天不再自动判断' : ''})` : ''},你要求的 ${fmtUsd(spent.manual)}`,
266    `报警 ${alertOn ? '开' : '关'}`,
267    `设置 空闲检查 ${s.idle} · 提醒门槛 ${fmtTok(cfg.remindMinCtx)} · ping 上限 ${cfg.pingLimit} 次/${cfg.pingLimitHours} 小时 · ` +
268      `冷发送${{ refuse: '先拦一次', warn: '只记账', off: '不管' }[s.guard]} · 项目策略 ${s.policy} · 手机推送${cfg.ntfyConfigFile ? `开(离开 ${cfg.awayIdleS / 60} 分钟后)` : '关'}`,
269    '',
270    '常用 /keepwarm on 8h · off · check · alert on · log · help',
271  ].join('\n')
272}
273
274const HELP = [
275  '/keepwarm 的用法',
276  '',
277  'on 8h:保温 8 小时(也可以写 90m),不管会话在干什么、你发什么消息,只有 off 能关',
278  'off:关掉保温,并禁止模型自己开;auto:重新允许模型自己开',
279  'status:看状态(直接输入 /keepwarm 也是)',
280  'check:现在判断一次:compact、保温还是不管',
281  'leave 2h on|off:告诉所有会话你要离开多久(on 电脑开着,off 合盖或关机)',
282  'idle off|notify|judge:空闲 50 分钟时什么都不做 / 免费提醒 / 判断一次',
283  'alert on|off|test:报警开关;test 发一条测试报警',
284  'policy auto|warm|off:本项目空闲时按判断自动处理 / 总是保温 / 不管(ask 同 auto)',
285  'guard refuse|warn|off:缓存已冷还发消息时先拦一次 / 只记账 / 不管',
286  'log [all] [requests|changes]:审计记录;ledger:冷写入账本',
287  'push:发一条带按钮的测试推送到手机(真实提醒在你离开 Mac 时才推,带 compact / 保温 / 不管 按钮)',
288  'panel:打开按钮面板(compact / 保温 / 关保温)',
289].join('\n')
290
291// ---------- audit: every request keepwarm pays for and every change it makes ----------
292// All side effects go through the audited* helpers below; nothing else calls $.model, $.mcp,
293// $.prompt.submit, $.session.compact/append or spawns a process that changes anything.
294const AUDIT_MAX = 3000
295type ForkResult = Awaited<ReturnType<EngineInterface['model']['fork']>>
296type CompleteResult = Awaited<ReturnType<EngineInterface['model']['complete']>>
297const errText = (err: unknown) => (err instanceof Error ? err.message : String(err)).slice(0, 300)
298
299async function audit($: EngineInterface, s: State, kind: 'request' | 'change' | 'notify', what: string, data: Record<string, unknown> = {}) {
300  try {
301    const log = ((await $.store.get('audit')) as unknown[] | undefined) ?? []
302    log.push({ at: await $.clock.now(), sid: s.sid, kind, what, ...data })
303    await $.store.set('audit', log.slice(-AUDIT_MAX))
304  } catch (err) {
305    $.ui.log(`keepwarm:审计记录写入失败 ${errText(err)}`)
306  }
307}
308
309// manual: the person asked for this request (their window's ping, /keepwarm check, a leave);
310// everything else counts against the daily budget.
311async function auditedFork($: EngineInterface, s: State, purpose: string, prompt: string, manual = false): Promise<ForkResult> {
312  let r: ForkResult
313  try {
314    r = await $.model.fork({ prompt })
315  } catch (err) {
316    await audit($, s, 'request', purpose, { via: 'fork', model: s.lastModel, manual, error: errText(err) })
317    throw err
318  }
319  const u = 'usage' in r ? (r.usage as Usage) : null
320  await audit($, s, 'request', purpose, {
321    via: 'fork', model: s.lastModel, manual, answered: r.isAnswered, reason: r.isAnswered ? undefined : r.reason,
322    read: u?.cache_read_input_tokens ?? 0, write: u?.cache_creation_input_tokens ?? 0, in: u?.input_tokens ?? 0, out: u?.output_tokens ?? 0,
323    usd: u ? forkUsd(u, priceOf(s.lastModel)) : 0,
324  })
325  return r
326}
327
328async function auditedComplete($: EngineInterface, s: State, purpose: string, model: string, prompt: string, maxTokens: number, price: [number, number]): Promise<CompleteResult> {
329  let r: CompleteResult
330  try {
331    r = await $.model.complete({ model, prompt, maxTokens })
332  } catch (err) {
333    await audit($, s, 'request', purpose, { via: 'complete', model, error: errText(err) })
334    throw err
335  }
336  const u = 'usage' in r ? (r.usage as { input_tokens: number; output_tokens: number }) : null
337  await audit($, s, 'request', purpose, {
338    via: 'complete', model, answered: r.isAnswered, reason: r.isAnswered ? undefined : r.reason,
339    in: u?.input_tokens ?? 0, out: u?.output_tokens ?? 0, usd: u ? (u.input_tokens * price[0] + u.output_tokens * price[1]) / 1e6 : 0,
340  })
341  return r
342}
343
344async function auditedMcp($: EngineInterface, s: State, purpose: string, server: string, tool: string, args: Record<string, unknown>) {
345  try {
346    const r = await $.mcp.call(server, tool, args)
347    await audit($, s, 'change', purpose, { server, tool, args, ok: !r.isError, result: r.isError ? JSON.stringify(r.content).slice(0, 300) : undefined })
348    return r
349  } catch (err) {
350    await audit($, s, 'change', purpose, { server, tool, args, ok: false, error: errText(err) })
351    throw err
352  }
353}
354
355// A process that changes something (a notification, a push, a file write or delete).
356async function auditedRun($: EngineInterface, s: State, kind: 'change' | 'notify', purpose: string, argv: readonly string[], detail: Record<string, unknown> = {}) {
357  try {
358    const r = await $.process.run(argv)
359    await audit($, s, kind, purpose, { ...detail, exit: r.exitCode })
360    return r
361  } catch (err) {
362    await audit($, s, kind, purpose, { ...detail, ok: false, error: errText(err) })
363    throw err
364  }
365}
366
367async function auditedSubmit($: EngineInterface, s: State, purpose: string, text: string) {
368  try {
369    await $.prompt.submit({ text })
370    await audit($, s, 'change', purpose, { text: text.slice(0, 500) })
371  } catch (err) {
372    await audit($, s, 'change', purpose, { text: text.slice(0, 500), ok: false, error: errText(err) })
373    throw err
374  }
375}
376
377async function auditedCompact($: EngineInterface, s: State) {
378  try {
379    await $.session.compact()
380    await audit($, s, 'change', 'compact', {})
381  } catch (err) {
382    await audit($, s, 'change', 'compact', { ok: false, error: errText(err) })
383    throw err
384  }
385}
386
387// A slash command run as the user would type it (the desktop app compacts only this way).
388async function auditedCommand($: EngineInterface, s: State, purpose: string, command: string, args: string) {
389  const n = s.compactions
390  try {
391    const r = await $.command.run({ command, args })
392    await audit($, s, 'change', purpose, { command, args: args.slice(0, 500), text: r.text?.slice(0, 300), compacted: s.compactions > n })
393    return r
394  } catch (err) {
395    await audit($, s, 'change', purpose, { command, args: args.slice(0, 500), ok: false, error: errText(err) })
396    throw err
397  }
398}
399
400async function appendLog($: EngineInterface, name: string, row: Record<string, unknown>) {
401  const log = ((await $.store.get(name)) as unknown[] | undefined) ?? []
402  log.push(row)
403  await $.store.set(name, log.slice(-LOG_MAX))
404}
405
406// Seconds since the last keyboard or mouse input on this Mac.
407async function idleSeconds($: EngineInterface): Promise<number> {
408  try {
409    const r = await $.process.run(['ioreg', '-c', 'IOHIDSystem', '-d', '4'])
410    const m = /"HIDIdleTime" = (\d+)/.exec(r.stdout)
411    return m ? Number(m[1]) / 1e9 : 0
412  } catch {
413    return 0
414  }
415}
416
417// A dark wake: the lid is closed and the Mac wakes for a few seconds of maintenance, then sleeps
418// again. A request sent then is cut by the sleep and retried on the next full wake, maybe after
419// the cache has lapsed (10-15: a judge sent at 12:23 went out again at 12:54 and wrote 404K
420// tokens, $3.25). A full wake has graphics; a display that is merely off keeps them.
421async function darkWake($: EngineInterface): Promise<boolean> {
422  try {
423    const r = await $.process.run(['pmset', '-g', 'systemstate'])
424    return /Capabilities are:/.test(r.stdout) && !/Graphics/.test(r.stdout)
425  } catch {
426    return false
427  }
428}
429
430// A desktop notification always; the phone too when nobody is at the Mac.
431async function alert($: EngineInterface, s: State, title: string, message: string, buttons: PhoneButton[] = []) {
432  await notify($, s, title, message)
433  if ((await idleSeconds($)) < cfg.awayIdleS) return
434  const c = await ntfyConfig($)
435  const actions = c ? await phoneActions($, s, buttons, c) : []
436  // The phone shows the session's own title (as the desktop sidebar does), not the folder.
437  await push($, s, `${await sessionName($, s)} · ${title}`,
438    message + (actions.length ? '\n\n点下面的按钮,Mac 上的这个会话约半分钟内照做,做完再推一条确认。' : '\n\n要处理请回到会话里。'), actions)
439}
440
441const sessionName = async ($: EngineInterface, s: State) => (await desktopSession($, s))?.title || project(s)
442
443// ---------- the panel (/keepwarm panel): the same buttons as the band, in a pane ----------
444
445const PANE = 'keepwarm'
446
447async function openPanel($: EngineInterface, s: State) {
448  const r = await $.ui.open({ id: PANE, title: 'keepwarm' })
449  // The countdown moves with the clock, not with any value the drawing reads.
450  if (s.paneTick) s.paneTick.cancel()
451  s.paneTick = $.clock.every(60_000, () => { void update($, panel, n => n + 1) })
452  return r
453}
454
455type PanelChoice = 'compact' | 'advised' | 'warm8' | 'off' | 'ignore'
456
457async function panelPress($: EngineInterface, s: State, choice: PanelChoice) {
458  const now = await $.clock.now()
459  const stored = await read($, advice)
460  const a = stored && !adviceStale(stored, now) ? stored : null
461  await audit($, s, 'change', '面板按钮', { choice, advised: a?.action ?? null })
462  if (choice === 'compact') {
463    await apply($, s, a ?? { action: 'compact', reason: '面板上手动 compact', topic: '', hours: 3, ctx: s.ctx, coldUsd: coldUsd(s), hourUsd: hourUsd(s), judgeUsd: null, at: now, auto: false }, 'compact', 'user')
464  } else if (choice === 'advised' && a) {
465    await apply($, s, a, 'keepwarm', 'user')
466  } else if (choice === 'ignore' && a) {
467    await apply($, s, a, 'ignore', 'user')
468  } else if (choice === 'warm8') {
469    // The same as /keepwarm on 8h: it holds whatever happens, until off.
470    if (a) {
471      await appendLog($, 'decisions', { sid: s.sid, cwd: s.cwd, at: now, ctx: a.ctx, advised: a.action, reason: a.reason, chosen: 'keepwarm', by: 'user' })
472      await update($, advice, () => null)
473    }
474    s.userOff = false
475    await startWindow($, s, 8 * 3_600_000, 'user', '面板:保温 8h', '', true)
476  } else if (choice === 'off') {
477    await stop($, s, '你在面板上关了保温')
478  }
479  $.ui.status(statusText(s, await $.clock.now()))
480  await update($, panel, n => n + 1)
481}
482
483// ---------- buttons on a phone push ----------
484// Each button is an ntfy http action that posts a one-time token to the reply topic. Only this
485// session honours its tokens, each notification once (one tap spends all its buttons), and only
486// for PHONE_KEEP_MS; the session polls the topic (a GET) while any of its tokens is live.
487
488type PhoneChoice = { kind: 'compact' } | { kind: 'warm'; hours: number } | { kind: 'ignore' }
489type PhoneButton = { label: string; choice: PhoneChoice }
490type PhoneToken = { token: string; group: string; choice: PhoneChoice; at: number; exp: number }
491type NtfyAction = { action: 'http'; label: string; url: string; method: 'POST'; body: string; clear: true }
492
493const PHONE_POLL_MS = 20_000
494const PHONE_KEEP_MS = 3 * 3_600_000
495
496const warmButton = (hours: number, verb = '保温'): PhoneButton => ({ label: `${verb} ${hours}h`, choice: { kind: 'warm', hours } })
497const COMPACT_BUTTON: PhoneButton = { label: 'compact', choice: { kind: 'compact' } }
498const IGNORE_BUTTON: PhoneButton = { label: '不管', choice: { kind: 'ignore' } }
499
500async function phoneTokens($: EngineInterface, s: State): Promise<PhoneToken[]> {
501  const v = await $.store.get(key(s, 'phone'))
502  return Array.isArray(v) ? (v as PhoneToken[]) : []
503}
504
505async function setPhoneTokens($: EngineInterface, s: State, list: PhoneToken[]) {
506  if (list.length) await $.store.set(key(s, 'phone'), list)
507  else await $.store.delete(key(s, 'phone'))
508}
509
510async function phoneActions($: EngineInterface, s: State, buttons: PhoneButton[], c: Ntfy): Promise<NtfyAction[]> {
511  if (!c.reply || !buttons.length) return []
512  const now = await $.clock.now()
513  const group = crypto.randomUUID()
514  const fresh = buttons.slice(0, 3).map(b => ({ label: b.label, t: { token: crypto.randomUUID().replace(/-/g, ''), group, choice: b.choice, at: now, exp: now + PHONE_KEEP_MS } }))
515  await setPhoneTokens($, s, [...(await phoneTokens($, s)).filter(t => t.exp > now), ...fresh.map(f => f.t)])
516  armPhonePoll($, s)
517  return fresh.map(({ label, t }) => ({ action: 'http', label, url: `${c.server}/${c.reply}`, method: 'POST', body: JSON.stringify({ keepwarm: t.token }), clear: true }))
518}
519
520function armPhonePoll($: EngineInterface, s: State) {
521  if (!s.phonePoll) s.phonePoll = $.clock.every(PHONE_POLL_MS, () => { void pollPhone($, s) })
522}
523
524// The taps since the oldest live token was handed out: a GET on the reply topic, nothing written.
525async function readReplies($: EngineInterface, c: Ntfy, since: number): Promise<{ id: string; token: string }[]> {
526  const r = await $.process.run(['curl', '-s', '-m', '10', `${c.server}/${c.reply}/json?poll=1&since=${since}`])
527  const out: { id: string; token: string }[] = []
528  for (const line of r.stdout.split('\n')) {
529    try {
530      const m = JSON.parse(line) as { id?: string; event?: string; message?: string }
531      const b = JSON.parse(m.message ?? '') as { keepwarm?: unknown }
532      if (m.event === 'message' && m.id && typeof b.keepwarm === 'string') out.push({ id: m.id, token: b.keepwarm })
533    } catch {
534      // another sender's message on the topic, or a partial line
535    }
536  }
537  return out
538}
539
540async function pollPhone($: EngineInterface, s: State) {
541  if (s.phoneBusy) return
542  s.phoneBusy = true
543  try {
544    const now = await $.clock.now()
545    const live = (await phoneTokens($, s)).filter(t => t.exp > now)
546    if (!live.length) {
547      if (s.phonePoll) s.phonePoll.cancel()
548      s.phonePoll = null
549      await setPhoneTokens($, s, [])
550      return
551    }
552    const c = await ntfyConfig($)
553    if (!c?.reply) return
554    const since = Math.floor(Math.min(...live.map(t => t.at)) / 1000) - 5
555    for (const r of await readReplies($, c, since)) {
556      const tokens = await phoneTokens($, s)
557      const t = tokens.find(x => x.token === r.token && x.exp > now)
558      if (!t) continue
559      await setPhoneTokens($, s, tokens.filter(x => x.group !== t.group))
560      await phoneDo($, s, t.choice)
561    }
562  } catch (err) {
563    $.ui.log(`keepwarm:读手机按钮失败 ${errText(err)}`, { to: 'debug' })
564  } finally {
565    s.phoneBusy = false
566  }
567}
568
569async function phoneDo($: EngineInterface, s: State, choice: PhoneChoice) {
570  const now = await $.clock.now()
571  const stored = await read($, advice)
572  const a = stored && !adviceStale(stored, now) ? stored : null
573  await audit($, s, 'change', '手机通知按钮', { choice, advised: a?.action ?? null })
574  const name = await sessionName($, s)
575  if (choice.kind === 'ignore') {
576    if (a) await apply($, s, a, 'ignore', 'user')
577    return
578  }
579  if (s.compacted) {
580    await push($, s, `${name} · 已经 compact 过了`, '这次按钮没有执行。')
581    return
582  }
583  if (isCold(s, now)) {
584    const late = `缓存在 ${fmtDuration(now - s.lastRequestAt - TTL_MS)} 前已经过期,`
585    await push($, s, `${name} · 缓存已过期,没执行`, choice.kind === 'compact'
586      ? `${late}现在 compact 要重新读整段上下文(约 ${fmtUsd(coldUsd(s))}),回到会话里再决定。`
587      : `${late}保温已经没有意义。`)
588    return
589  }
590  if (choice.kind === 'compact') {
591    const before = s.ctx
592    const n = s.compactions
593    await apply($, s, a ?? { action: 'compact', reason: '手机通知上的 compact', topic: '', hours: 3, ctx: s.ctx, coldUsd: coldUsd(s), hourUsd: hourUsd(s), judgeUsd: null, at: now, auto: false }, 'compact', 'user')
594    const done = s.compactions > n
595    await push($, s, `${name} · ${done ? '已 compact' : 'compact 没成功'}`,
596      done ? `原来上下文 ${fmtTok(before)},下一轮从摘要开始。` : '回到会话里手动 /compact。')
597    return
598  }
599  if (a) {
600    await appendLog($, 'decisions', { sid: s.sid, cwd: s.cwd, at: now, ctx: a.ctx, advised: a.action, reason: a.reason, chosen: 'keepwarm', by: 'user' })
601    await update($, advice, () => null)
602  }
603  s.userOff = false
604  // Like a reminder's button: it covers the absence, so it ends when you write in the session.
605  await startWindow($, s, choice.hours * 3_600_000, 'user', `手机通知:保温 ${choice.hours}h`)
606  await push($, s, `${name} · 已保温 ${choice.hours}h`, `约 ${fmtUsd(hourUsd(s))}/小时;你回来在这个会话里发消息,保温就结束。`)
607}
608
609// ---------- alerts: only what should not have happened, opt-in (/keepwarm alert on) ----------
610
611type AlarmKind = 'lapsed' | 'unexplained' | 'budget' | 'pinglimit' | 'compactfail'
612const ALARM_GAP_MS = 60 * 60 * 1000
613
614const dayStart = (now: number) => {
615  const d = new Date(now)
616  return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
617}
618
619// To the Mac (and the phone when you are away), at most once an hour per kind and session.
620async function alarm($: EngineInterface, s: State, kind: AlarmKind, title: string, message: string) {
621  if ((await $.store.get('alert')) !== true) return
622  const now = await $.clock.now()
623  const seen = ((await $.store.get('alarms')) as Record<string, number> | undefined) ?? {}
624  const k = `${kind}:${kind === 'budget' ? '' : s.sid}`
625  if (now - (seen[k] ?? 0) < ALARM_GAP_MS) return
626  const kept: Record<string, number> = {}
627  for (const [key, at] of Object.entries(seen)) if (now - at < 24 * 3_600_000) kept[key] = at
628  kept[k] = now
629  await $.store.set('alarms', kept)
630  await alert($, s, `⚠️ ${title}`, message)
631}
632
633// What keepwarm spent today, split into what it chose to spend and what the person asked for.
634// Only the first has a budget: pausing the second would undo what they asked for, and with many
635// sessions each kept warm on purpose the total grows past any fixed line. The person's own
636// windows are bounded per session by pingLimit instead.
637async function spendToday($: EngineInterface, now: number): Promise<{ auto: number; manual: number }> {
638  const from = dayStart(now)
639  const log = ((await $.store.get('audit')) as Array<{ at: number; kind: string; usd?: number; manual?: boolean }> | undefined) ?? []
640  const out = { auto: 0, manual: 0 }
641  for (const r of log) if (r.at >= from && r.kind === 'request') out[r.manual ? 'manual' : 'auto'] += r.usd ?? 0
642  return out
643}
644
645// Counted afresh each time, against this process's own limit: a mark left by another process,
646// or by a lower limit before an update, does not hold this one back.
647async function overBudget($: EngineInterface): Promise<boolean> {
648  return cfg.dailyBudgetUsd > 0 && (await spendToday($, await $.clock.now())).auto > cfg.dailyBudgetUsd
649}
650
651async function checkBudget($: EngineInterface, s: State) {
652  if (!cfg.dailyBudgetUsd) return
653  const now = await $.clock.now()
654  if ((await $.store.get('budgetHit')) === dayStart(now)) return // told once a day
655  const spent = (await spendToday($, now)).auto
656  if (spent <= cfg.dailyBudgetUsd) return
657  await $.store.set('budgetHit', dayStart(now))
658  await audit($, s, 'change', '今日自动花费超过上限', { spent, budget: cfg.dailyBudgetUsd })
659  const msg = `keepwarm 今天自己花了 ${fmtUsd(spent)}(上限 $${cfg.dailyBudgetUsd}),午夜前空闲检查改为免费提醒;你开的保温照常。`
660  $.ui.toast(msg)
661  await alarm($, s, 'budget', '自动花费超过上限', msg)
662}
663
664// The server evicting caches before the hour is out (10-19: nine sessions in forty minutes; 10-15:
665// an app update changed every session's prefix at once). Idle sessions go first, so a ping or a
666// judge then mostly finds the cache gone and writes it whole for nothing ($2-3 each). Two sessions
667// written again unexpectedly within the hour mark one; 17 days had three.
668const STORM_MS = 60 * 60_000
669async function storm($: EngineInterface, now: number): Promise<boolean> {
670  type Rec = { sid: string; at: number; cause?: string; gapMs?: number; read?: number; write?: number }
671  const get = async (k: string) => (((await $.store.get(k)) as Rec[] | undefined) ?? []).filter(r => now - r.at < STORM_MS)
672  const hit = new Set<string>()
673  // A rewrite seconds after the last request is the client changing the prefix (a test forking
674  // one base many ways, 10-25), not the server: evictions found idle sessions, 2.7 min and up.
675  for (const r of await get('misses')) if (r.cause === 'other' && (r.gapMs ?? 0) >= 2 * 60_000) hit.add(r.sid)
676  for (const r of [...(await get('pings')), ...(await get('judgements'))]) {
677    if (!forkWasWarm({ cache_read_input_tokens: r.read ?? 0, cache_creation_input_tokens: r.write ?? 0 } as Usage)) hit.add(r.sid)
678  }
679  return hit.size >= 2
680}
681
682async function alertLine($: EngineInterface, now: number): Promise<string> {
683  const on = (await $.store.get('alert')) === true
684  const spent = await spendToday($, now)
685  const over = await overBudget($)
686  return `alerts      报警${on ? '开' : '关'}(/keepwarm alert on|off|test)\n` +
687    `today       keepwarm 今天共花 ${fmtUsd(spent.auto + spent.manual)}:自己主动的 ${fmtUsd(spent.auto)}${cfg.dailyBudgetUsd ? `(上限 $${cfg.dailyBudgetUsd}${over ? ',已超,今天不再自动判断' : ''})` : ''},` +
688    `你要求的 ${fmtUsd(spent.manual)}(你开的保温、check、离开判断;不设上限,每会话 ${cfg.pingLimitHours} 小时最多 ping ${cfg.pingLimit} 次)`
689}
690
691// The desktop app names its sessions local_<uuid>; its deep link wants that id, and
692// its record maps it to the CLI session id this mod knows.
693const DESKTOP_SESSIONS = '$HOME/Library/Application Support/Claude/claude-code-sessions'
694
695async function desktopSession($: EngineInterface, s: State): Promise<{ id: string; title: string } | null> {
696  try {
697    // The pattern goes in as an argument: quotes written inside this template literal would be
698    // eaten by JS and then by sh, and grep would search for cliSessionId:<id> and never match.
699    const r = await $.process.run(['sh', '-c', `f=$(grep -rl --include='local_*.json' -F -e "$1" "${DESKTOP_SESSIONS}" 2>/dev/null | head -1) && [ -n "$f" ] && cat "$f"`, 'kw', `"cliSessionId":"${s.sid}"`])
700    const d = JSON.parse(r.stdout) as { sessionId?: string; cliSessionId?: string; title?: string }
701    return d.cliSessionId === s.sid && d.sessionId?.startsWith('local_') ? { id: d.sessionId, title: d.title ?? '' } : null
702  } catch {
703    return null
704  }
705}
706
707// The folder the desktop app makes for a session started with no project.
708const SCRATCH = /\/Library\/Application Support\/Claude\/scratch-workspaces\//
709const DESKTOP_CONFIG = '$HOME/Library/Application Support/Claude/claude_desktop_config.json'
710
711// The desktop sidebar group this session is filed under, by name; '' when none (or not the app).
712async function sidebarGroup($: EngineInterface, s: State): Promise<string> {
713  const ds = await desktopSession($, s)
714  if (!ds) return ''
715  try {
716    const r = await $.process.run(['sh', '-c', `cat "${DESKTOP_CONFIG}"`])
717    type Scope = { groups?: Array<{ id: string; name: string }>; assignments?: Record<string, string> }
718    const scopes = ((JSON.parse(r.stdout) as { preferences?: { epitaxyPrefs?: Record<string, unknown> } })
719      .preferences?.epitaxyPrefs?.['dframe-group-scopes'] ?? {}) as Record<string, Scope>
720    for (const scope of Object.values(scopes)) {
721      const id = scope.assignments?.[`code:${ds.id}`]
722      const group = id ? scope.groups?.find(g => g.id === id) : undefined
723      if (group) return group.name
724    }
725  } catch { /* no desktop app config */ }
726  return ''
727}
728
729async function notify($: EngineInterface, s: State, title: string, message: string) {
730  $.ui.toast(`${title}:${message}`)
731  try {
732    // The desktop app runs sessions headless, so surfaces() may not say 'desktop':
733    // the app's own record of this session is the test.
734    const ds = await desktopSession($, s)
735    $.ui.log(`keepwarm notify: surfaces=${(await $.session.surfaces()).join(',') || '-'} desktop=${ds?.id ?? 'none'}`, { to: 'debug' })
736    const argv = ['terminal-notifier', '-title', 'Claude Code', '-subtitle', `${ds?.title || project(s)} · ${title}`, '-message', message, '-group', `keepwarm-${s.sid}`]
737    // Clicking opens this very session in the desktop app.
738    // Bring the app forward first: a link to the session already on screen changes nothing by itself.
739    if (ds) argv.push('-execute', `open -b com.anthropic.claudefordesktop && open 'claude://code/continue?session=${ds.id}&source=desktop_action'`)
740    await auditedRun($, s, 'notify', 'Mac 通知', argv, { title, message: message.slice(0, 200), jump: ds?.id ?? null })
741  } catch {
742    // terminal-notifier missing or refused: the toast and band still show.
743  }
744}
745
746// ---------- cold-send guard (from cache-tax) ----------
747
748function guardText(s: State, now: number): string {
749  const p = priceOf(s.lastModel)
750  const warm = p ? s.ctx * p[0] / 1e6 : null
751  return `缓存已冷 ${fmtDuration(now - s.lastRequestAt - TTL_MS)}(最后请求在 ${fmtDuration(now - s.lastRequestAt)} 前)。` +
752    `这次发送要重写约 ${fmtTok(s.ctx)} tokens,约 ${fmtUsd(coldUsd(s))}(热的话只要 ${fmtUsd(warm)})。`
753}
754
755const MISS_ZH = { expired: '缓存过期', model: '换了模型', other: '缓存提前没了' } as const
756
757// Judged per request, not per turn: a long turn whose context grows step by step writes a lot
758// in total and is not a miss, while a rewrite in the middle of a turn (after a foreground
759// subagent that ran past the hour) is one.
760async function checkMiss($: EngineInterface, s: State, u: TurnUsage, prevAt: number) {
761  const prev = s.stepCtx || s.ctx
762  const read = u.cache_read_input_tokens
763  const write = u.cache_creation_input_tokens
764  const prevModel = s.stepModel ?? s.lastModel
765  s.stepCtx = read + write + u.input_tokens
766  s.stepModel = u.model
767  // The summary of a compaction is written afresh by design.
768  if (s.skipMiss) {
769    s.skipMiss = false
770    return
771  }
772  // Nothing was cached yet (a new session's first message, prev is 0), or no rewrite.
773  if (prev <= 20000 || read >= 0.5 * prev || write < 0.5 * prev) return
774  const now = await $.clock.now()
775  const gapMs = prevAt ? now - prevAt : 0
776  // No last request known: an old session reopened after its record was dropped.
777  const cause: MissCause = prevModel && prevModel !== u.model ? 'model' : !prevAt || gapMs > TTL_MS ? 'expired' : 'other'
778  const p = priceOf(u.model)
779  const miss: Miss = { at: now, tokens: write, usd: p ? write * p[1] / 1e6 : null, cause, gapMs }
780  s.misses.push(miss)
781  await appendLog($, 'misses', { sid: s.sid, cwd: s.cwd, model: u.model, ...miss })
782  // Every real rewrite gets a notice in Claude, nothing outside it (asked for 10-14).
783  const by = s.turnBy === 'person' ? '' : s.turnBy === 'task-notification' ? ',后台任务回报时' : `,${s.turnBy} 触发`
784  const what = `${fmtTok(write)} tokens,约 ${fmtUsd(miss.usd)}`
785  $.ui.toast(
786    cause === 'other' ? `意外整段重写 ${what}:同一模型、距上次请求只有 ${fmtDuration(gapMs)},可能是服务端提前清掉了缓存,或系统提示、工具列表变了${by}`
787    : cause === 'expired' && s.deadline ? `保温期间缓存过期,重写 ${what}(距上次请求 ${fmtDuration(gapMs)}${by})`
788    : `冷写入 ${what}(${MISS_ZH[cause]}${prevAt ? `,距上次请求 ${fmtDuration(gapMs)}` : ''}${by})`,
789  )
790  if (cause === 'other') {
791    await alarm($, s, 'unexplained', '缓存被意外整段重写', `同一模型、距上次请求只有 ${fmtDuration(gapMs)},仍整段重写了 ${fmtTok(write)} tokens(约 ${fmtUsd(miss.usd)})。可能是系统提示或工具列表变了,或者回退、编辑了历史消息。`)
792  } else if (cause === 'expired' && s.deadline) {
793    await alarm($, s, 'lapsed', '保温期间缓存过期', `保温窗口开着,缓存还是过期了:重写 ${fmtTok(write)} tokens(约 ${fmtUsd(miss.usd)})。看 /keepwarm log 找原因。`)
794  }
795}
796
797const hhmm = (ms: number) => new Date(ms).toTimeString().slice(0, 5)
798
799// A window whose pings could not go out (the Mac slept, or this session's process was not
800// running after an app restart): the cache lapsed an hour after the last request, inside the
801// window. Record it and end the window rather than let it run out silently.
802async function lapsedWindow($: EngineInterface, s: State, deadline: number, cause: string) {
803  const lostAt = s.lastRequestAt + TTL_MS
804  const why = `保温本该到 ${hhmm(deadline)},但${cause},缓存约 ${hhmm(lostAt)} 已过期`
805  await audit($, s, 'change', '保温中断', { why, deadline, lastRequestAt: s.lastRequestAt, lostAt })
806  await alarm($, s, 'lapsed', '保温失效', why)
807  if (s.deadline) await stop($, s, why)
808  else $.ui.toast(`keepwarm:${why}`)
809}
810
811async function missesTotal($: EngineInterface): Promise<{ n: number; usd: number }> {
812  const log = ((await $.store.get('misses')) as Array<{ usd: number | null }> | undefined) ?? []
813  return { n: log.length, usd: log.reduce((a, m) => a + (m.usd ?? 0), 0) }
814}
815
816// ---------- keep-warm window ----------
817
818function disarm(s: State) {
819  if (s.pending) s.pending.cancel()
820  s.pending = null
821}
822
823function disarmCheck(s: State) {
824  if (s.check) s.check.cancel()
825  s.check = null
826}
827
828async function save($: EngineInterface, s: State) {
829  if (s.deadline) {
830    await $.store.set(key(s, 'deadline'), s.deadline)
831    await $.store.set(key(s, 'owner'), s.owner ?? 'user')
832    await $.store.set(key(s, 'reason'), s.reason)
833    await $.store.set(key(s, 'wake'), s.wakePrompt)
834    await $.store.set(key(s, 'sticky'), s.sticky)
835    await $.store.set(key(s, 'thenCompact'), s.thenCompact)
836  } else {
837    for (const k of ['deadline', 'owner', 'reason', 'wake', 'sticky', 'thenCompact']) await $.store.delete(key(s, k))
838  }
839  if (s.userOff) await $.store.set(key(s, 'userOff'), true)
840  else await $.store.delete(key(s, 'userOff'))
841}
842
843async function stop($: EngineInterface, s: State, why: string | null) {
844  if (s.deadline) await audit($, s, 'change', '停止保温', { why: why ?? '(无提示)', owner: s.owner, left: s.deadline - (await $.clock.now()) })
845  s.deadline = 0
846  s.owner = null
847  s.reason = ''
848  s.wakePrompt = ''
849  s.sticky = false
850  s.thenCompact = false
851  s.stopped = why
852  disarm(s)
853  stopCaffeinate($, s)
854  await save($, s)
855  $.ui.status(statusText(s, await $.clock.now()))
856  if (why) $.ui.toast(`keepwarm 停止:${why}`)
857  await arm($, s)
858}
859
860async function arm($: EngineInterface, s: State) {
861  disarm(s)
862  disarmCheck(s)
863  const now = await $.clock.now()
864  if (s.deadline && now >= s.deadline) {
865    const compact = s.thenCompact && !s.compacted && !tooLate(s, now)
866    if (compact && (await darkWake($))) {
867      // The compaction is a request too (10-20: due at 08:45 with the lid closed, it went out on
868      // the full wake at 08:58, seven minutes before the cache lapsed): wait for the full wake.
869      s.pending = $.clock.after(60_000, () => { void arm($, s) })
870      return
871    }
872    await audit($, s, 'change', '保温到期结束', { owner: s.owner })
873    s.deadline = 0
874    s.owner = null
875    s.thenCompact = false
876    await save($, s)
877    if (compact) return autoCompact($, s, `空闲 ${fmtDuration(now - s.turnAt)} 没人回来,保温结束`)
878  }
879  const live = s.lastRequestAt > 0 && !s.compacted && !isCold(s, now)
880  if (s.deadline) {
881    if (live) {
882      const delay = Math.min(s.deadline - now, Math.max(1000, s.lastRequestAt + s.every - now))
883      s.pending = $.clock.after(delay, () => { void ping($, s) })
884      if (s.endWarnedFor !== s.deadline && s.deadline - now > 1000) {
885        if (s.endWarn) s.endWarn.cancel()
886        s.endWarn = $.clock.after(Math.max(1000, s.deadline - END_WARN_MS - now), () => { void endWarn($, s) })
887      }
888    } else {
889      // Cold or just compacted: never ping (it would pay the rewrite); only expire the window.
890      s.pending = $.clock.after(s.deadline - now, () => { void arm($, s) })
891    }
892  } else if (live && s.policy !== 'off' && s.idle !== 'off' && s.ctx >= cfg.remindMinCtx && s.checkedFor !== s.turnAt) {
893    // One reminder per idle stretch, before the cache lapses.
894    s.check = $.clock.after(Math.max(1000, s.lastRequestAt + CHECK_AFTER_MS - now), () => { void idleCheck($, s) })
895  }
896  $.ui.status(statusText(s, now))
897  await saveRuntime($, s)
898}
899
900// Module variables start over on a hot reload; the store does not.
901async function saveRuntime($: EngineInterface, s: State) {
902  if (!s.sid) return
903  const rt: Runtime = { lastRequestAt: s.lastRequestAt, turnAt: s.turnAt, ctx: s.ctx, window: s.window, model: s.lastModel, compacted: s.compacted }
904  await $.store.set(`rt:${s.sid}`, rt)
905}
906
907// The last read of this conversation's cache that keepwarm knows of: this session's own record,
908// or, for a fork (a rewind starts one under a new id), the record of the session it came from:
909// the same last turn and the same context. The engine dates a resumed cache from the transcript's
910// last response and knows nothing of the pings and judges since (10-16: a rewound session was told
911// 417K would be rewritten; it read all 417K). Context size alone is no proof: on 10-17 a resumed
912// session took another's ping, 50 minutes after its own cache had lapsed, for its own.
913async function lastKnownRead($: EngineInterface, s: State, ctx: number, turnAt: number, fork: boolean): Promise<number> {
914  let at = 0
915  for (const k of await $.store.keys()) {
916    if (!k.startsWith('rt:')) continue
917    const rt = (await $.store.get(k)) as Runtime | undefined
918    if (!rt || rt.compacted) continue
919    const parent = fork && Math.abs(rt.ctx - ctx) <= ctx * 0.01 && Math.abs(rt.turnAt - turnAt) <= 2 * 60_000
920    if ((k === `rt:${s.sid}` || parent) && rt.lastRequestAt > at) at = rt.lastRequestAt
921  }
922  return at
923}
924
925async function loadRuntime($: EngineInterface, s: State, now: number) {
926  for (const k of await $.store.keys()) {
927    if (!k.startsWith('rt:') || k === `rt:${s.sid}`) continue
928    const old = (await $.store.get(k)) as Runtime | undefined
929    if (!old || now - old.lastRequestAt > RT_KEEP_MS) await $.store.delete(k)
930  }
931  const rt = (await $.store.get(`rt:${s.sid}`)) as Runtime | undefined
932  if (!rt || s.lastRequestAt) return
933  s.lastRequestAt = rt.lastRequestAt
934  s.turnAt = rt.turnAt
935  s.ctx = rt.ctx
936  s.window = rt.window
937  s.lastModel = rt.model
938  s.compacted = rt.compacted
939}
940
941// ---------- leave: every live session at once ----------
942
943// The sessions are separate processes; they talk through small JSON files, each
944// written whole and renamed into place, so a reader never sees half a file.
945const BUS = '$HOME/.claude/keepwarm-bus'
946
947async function busGet<T>($: EngineInterface, name: string): Promise<T | undefined> {
948  try {
949    const r = await $.process.run(['sh', '-c', `cat "${BUS}/$1" 2>/dev/null`, 'kw', name])
950    return r.stdout.trim() ? JSON.parse(r.stdout) as T : undefined
951  } catch {
952    return undefined
953  }
954}
955
956async function busSet($: EngineInterface, s: State, name: string, value: unknown) {
957  await auditedRun($, s, 'change', '写离开广播文件', ['sh', '-c', `mkdir -p "${BUS}" && printf '%s\\n' "$2" > "${BUS}/$1.$$" && mv "${BUS}/$1.$$" "${BUS}/$1"`, 'kw', name, JSON.stringify(value)], { file: name })
958}
959
960async function busAll<T>($: EngineInterface, prefix: string): Promise<T[]> {
961  const r = await $.process.run(['sh', '-c', `cat "${BUS}/$1"* 2>/dev/null; true`, 'kw', prefix])
962  const out: T[] = []
963  for (const line of r.stdout.split('\n')) { try { if (line.trim()) out.push(JSON.parse(line) as T) } catch { /* partial */ } }
964  return out
965}
966
967function leaveSkip(s: State, now: number): string | null {
968  if (!s.lastRequestAt) return '还没有请求'
969  if (s.compacted) return '刚 compact'
970  if (isCold(s, now)) return '缓存已冷'
971  if (s.ctx < MIN_CTX) return '上下文很小'
972  return null
973}
974
975async function broadcastLeave($: EngineInterface, s: State, hours: number, machineOn: boolean, id?: string) {
976  const now = await $.clock.now()
977  const req: LeaveReq = { id: id ?? `${now}-${s.sid.slice(0, 8)}`, at: now, from: s.sid, hours, machineOn }
978  const cur = await busGet<LeaveReq>($, 'leave-req')
979  if (cur?.id === req.id) return
980  await auditedRun($, s, 'change', '清理一天前的离开广播回复', ['sh', '-c', `find "${BUS}" -name 'leave-res-*' -mtime +1 -delete 2>/dev/null; true`])
981  await busSet($, s, 'leave-req', req)
982  await update($, leaveAll, () => ({ id: req.id, hours, machineOn, startedAt: now, items: [], collecting: true }))
983  if (s.collect) s.collect.cancel()
984  s.collect = $.clock.every(3000, () => { void collect($, s, req.id) })
985  void poll($, s)
986}
987
988async function collect($: EngineInterface, s: State, id: string) {
989  const la = await read($, leaveAll)
990  if (!la || la.id !== id) { if (s.collect) s.collect.cancel(); s.collect = null; return }
991  const items: KeepwarmLeaveItem[] = []
992  for (const r of await busAll<{ id: string } & KeepwarmLeaveItem>($, 'leave-res-')) {
993    if (r.id === id) items.push({ sid: r.sid, project: r.project, topic: r.topic ?? '', ctx: r.ctx, action: r.action, reason: r.reason, keepUsd: r.keepUsd, compactUsd: r.compactUsd, coldUsd: r.coldUsd })
994  }
995  const now = await $.clock.now()
996  const done = now - la.startedAt >= LEAVE_COLLECT_MS
997  await update($, leaveAll, v => v && v.id === id ? { ...v, items, collecting: !done } : v)
998  if (done) {
999    if (s.collect) s.collect.cancel()
1000    s.collect = null
1001    await pushLeaveSummary($, s, { ...la, items, collecting: false })
1002  }
1003}
1004
1005async function poll($: EngineInterface, s: State) {
1006  const now = await $.clock.now()
1007  const req = await busGet<LeaveReq>($, 'leave-req')
1008  if (!req || req.id === s.leaveSeen || now - req.at >= LEAVE_REQ_TTL_MS) return
1009  s.leaveSeen = req.id
1010  if (leaveSkip(s, now) !== null) return
1011  const a = await leaveCheck($, s, req.hours, req.machineOn)
1012  const L = a.leave
1013  await busSet($, s, `leave-res-${s.sid}`, { id: req.id, sid: s.sid, project: project(s), topic: a.topic ?? '', ctx: a.ctx, action: a.action, reason: a.reason, keepUsd: L?.keepUsd ?? null, compactUsd: L?.compactUsd ?? null, coldUsd: a.coldUsd })
1014  // The advice waits in this session's own band; acting on it is done here, by hand.
1015  if (a.action !== 'ignore') {
1016    await offerAdvice($, s, a)
1017  }
1018}
1019
1020// ---------- phone (ntfy): notifications, with buttons when a reply topic is set ----------
1021
1022// reply_topic: where the buttons on a push post their one-time token; without it pushes carry none.
1023type Ntfy = { server: string; topic: string; reply: string | null }
1024
1025async function ntfyConfig($: EngineInterface): Promise<Ntfy | null> {
1026  try {
1027    if (!cfg.ntfyConfigFile) return null
1028    const r = await $.process.run(['sh', '-c', 'f=$1; case $f in "~/"*) f="$HOME/${f#??}";; esac; cat "$f"', 'kw', cfg.ntfyConfigFile])
1029    const c = JSON.parse(r.stdout) as { server?: string; topic?: string; reply_topic?: string }
1030    return c.server && c.topic ? { server: c.server.replace(/\/$/, ''), topic: c.topic, reply: c.reply_topic || null } : null
1031  } catch {
1032    return null
1033  }
1034}
1035
1036async function push($: EngineInterface, s: State, title: string, markdown: string, actions: NtfyAction[] = []) {
1037  const c = await ntfyConfig($)
1038  if (!c) return
1039  const body = { topic: c.topic, title, message: markdown.slice(0, 4000), markdown: true, priority: 3, tags: ['hourglass'], ...(actions.length ? { actions } : {}) }
1040  try {
1041    await auditedRun($, s, 'notify', '手机推送', ['curl', '-s', '-m', '15', '-H', 'Content-Type: application/json', '-d', JSON.stringify(body), c.server + '/'], { title })
1042  } catch {
1043    // offline: the desktop notification and band still show
1044  }
1045}
1046
1047const ACTION_ZH = { compact: 'compact', keepwarm: '保温', ignore: '不管' } as const
1048
1049async function pushLeaveSummary($: EngineInterface, s: State, la: KeepwarmLeaveAll) {
1050  if (!la.items.length) return
1051  const lines = la.items.map(i => `- **${i.project}**${i.topic ? `(${i.topic})` : ''} ${fmtTok(i.ctx)} → **${ACTION_ZH[i.action]}**:${i.reason}`)
1052  await push($, s, `离开 ${fmtDuration(la.hours * 3_600_000)}:${la.items.length} 个会话`, lines.join('\n') + '\n\n建议已显示在各会话的输入框上方,到会话里自己处理。')
1053}
1054
1055// Ten minutes before a keep-warm window ends: offer to extend it, once per window.
1056async function endWarn($: EngineInterface, s: State) {
1057  s.endWarn = null
1058  // A window the idle judge opened ends in a compaction by design: nothing to tell.
1059  if (s.thenCompact) return
1060  const now = await $.clock.now()
1061  if (!s.deadline || s.endWarnedFor === s.deadline || s.deadline - now > END_WARN_MS + 1000 || isCold(s, now)) return
1062  s.endWarnedFor = s.deadline
1063  const a: KeepwarmAdvice = {
1064    action: 'keepwarm', topic: '', reason: `保温约 ${fmtDuration(s.deadline - now)} 后结束,之后缓存会在 1 小时内过期。要续的话选保温`,
1065    hours: DEFAULT_WINDOW_MS / 3_600_000, ctx: s.ctx, coldUsd: coldUsd(s), hourUsd: hourUsd(s), judgeUsd: 0, at: now, auto: false,
1066  }
1067  await offerAdvice($, s, a)
1068  await alert($, s, '保温快结束了', `${a.reason}(上下文 ${fmtTok(s.ctx)},过期重写 ${fmtUsd(coldUsd(s))})`, [warmButton(a.hours, '续'), IGNORE_BUTTON])
1069}
1070
1071async function ping($: EngineInterface, s: State) {
1072  s.pending = null
1073  if (!s.deadline) return
1074  const now = await $.clock.now()
1075  // A window that ends while the last request's cache still holds needs no ping, only its end.
1076  // A judged compaction's window ends 55 minutes after the judge, and the judge's own fork
1077  // takes seconds, so the end can fall a little after this ping is due (10-15: one wasted ping).
1078  if (now >= s.deadline - 1000) return arm($, s)
1079  if (s.deadline <= s.lastRequestAt + PING_AFTER_MS + 60_000) {
1080    s.pending = $.clock.after(s.deadline - now, () => { void arm($, s) })
1081    return
1082  }
1083  if (now - s.lastRequestAt < s.every - 1000) return arm($, s) // a turn re-armed meanwhile
1084  if (wakesItself(s, now)) {
1085    // Its own wakeup will refresh the cache; ping only if that wakeup does not come.
1086    s.pending = $.clock.after(s.wakeAt + WAKE_MARGIN_MS / 2 - now, () => { void ping($, s) })
1087    return
1088  }
1089  if (tooLate(s, now)) return lapsedWindow($, s, s.deadline, '电脑睡眠或进程暂停到快满 1 小时,ping 没能按时发出')
1090  if (await darkWake($)) {
1091    // Asleep but for a moment: try again; on the full wake the timer fires late and finds out.
1092    s.pending = $.clock.after(60_000, () => { void ping($, s) })
1093    return
1094  }
1095  if (s.last && now - s.last.at < PING_MIN_GAP_MS) {
1096    s.pending = $.clock.after(s.last.at + PING_MIN_GAP_MS - now, () => { void ping($, s) })
1097    return
1098  }
1099  const recent = (((await $.store.get('pings')) as Array<{ sid: string; at: number }> | undefined) ?? [])
1100    .filter(p => p.sid === s.sid && now - p.at < cfg.pingLimitHours * 3_600_000).length
1101  if (recent >= cfg.pingLimit) {
1102    const why = `${cfg.pingLimitHours} 小时内已 ping ${recent} 次,达到上限 ${cfg.pingLimit}`
1103    await alarm($, s, 'pinglimit', 'ping 次数到了上限', `${why},保温已停。正常每 55 分钟一次,到上限多半是哪里出了问题,看 /keepwarm log。`)
1104    return stop($, s, why)
1105  }
1106  if (s.owner !== 'user' && (await storm($, now))) return stop($, s, '这一小时里服务端在提前清缓存,ping 多半碰上已清掉的缓存、白写一次')
1107  const reply = await auditedFork($, s, s.wakePrompt ? '保温 ping(带唤醒判断)' : '保温 ping', s.wakePrompt ? wakeJudgePrompt(s, now) : PING_PROMPT, s.owner === 'user')
1108  if (s.owner !== 'user') await checkBudget($, s)
1109  if (!reply.isAnswered && reply.reason === 'nothing-to-fork') return stop($, s, '没有可以 fork 的对话')
1110  if (!reply.isAnswered && reply.reason !== 'empty-reply') return stop($, s, `ping 失败(${reply.reason})`)
1111  const u = reply.usage
1112  const usd = forkUsd(u, priceOf(s.lastModel))
1113  const warm = forkWasWarm(u)
1114  s.last = { at: now, read: u.cache_read_input_tokens, write: u.cache_creation_input_tokens, usd, warm }
1115  s.pings += 1
1116  s.pingUsd += usd ?? 0
1117  await appendLog($, 'pings', { sid: s.sid, cwd: s.cwd, model: s.lastModel, ctx: s.ctx, owner: s.owner, ...s.last })
1118  if (warm && s.wakePrompt && reply.isAnswered) await wakeDecision($, s, reply.text, now)
1119  // Seen once (Taskline, 10-11): after a turn that died on a usage limit the fork no longer
1120  // replays what the main thread sent, so it misses a cache that may still be warm.
1121  const got = `ping 读 ${fmtTok(u.cache_read_input_tokens)}、写 ${fmtTok(u.cache_creation_input_tokens)}`
1122  if (!warm) return stop($, s, s.turnError ? `${got}:上一轮因 API 错误(如额度用完)中断后,ping 对不上主对话的缓存` : `${got},缓存已经丢了`)
1123  s.lastRequestAt = now
1124  s.unansweredFrom = 0
1125  await arm($, s)
1126}
1127
1128// With a wake task, the fork (which sees the whole conversation and the time) decides first,
1129// so a wake that needs nothing leaves the conversation untouched and only tool work becomes a turn.
1130function wakeJudgePrompt(s: State, now: number): string {
1131  return [
1132    '[keepwarm 定时唤醒,不是用户消息;不要调用工具,只输出一行 JSON]',
1133    `现在是 ${new Date(now).toString()},用户已离开 ${fmtDuration(now - s.lastRequestAt)},保温还剩 ${fmtDuration(s.deadline - now)}。`,
1134    `唤醒任务:${s.wakePrompt}`,
1135    '决定这次唤醒怎么处理:',
1136    '- skip:现在不需要做任何事(时间未到、无新情况),这次唤醒不留痕迹。',
1137    '- note:不需要工具,但有一句值得记入对话、供之后参考的话。',
1138    '- act:需要用工具真正检查或处理(看日志、查服务、跑命令),将运行一整轮对话并保留在对话里。',
1139    '- stop:任务已无必要,结束保温。',
1140    '输出格式:{"decision":"skip|note|act|stop","note":"<note 时的一句话,否则空>","task":"<act 时要做的具体事情,否则空>"}',
1141  ].join('\n')
1142}
1143
1144async function wakeDecision($: EngineInterface, s: State, text: string, now: number) {
1145  let v: { decision?: string; note?: string; task?: string } = {}
1146  try {
1147    v = JSON.parse(/\{[\s\S]*\}/.exec(text)?.[0] ?? '{}')
1148  } catch {
1149    v = {}
1150  }
1151  const decision = v.decision === 'note' || v.decision === 'act' || v.decision === 'stop' ? v.decision : 'skip'
1152  await appendLog($, 'wakes', { sid: s.sid, cwd: s.cwd, at: now, decision, note: v.note ?? '', task: v.task ?? '' })
1153  if (decision === 'note' && v.note) {
1154    const text = `[keepwarm 唤醒记录 ${new Date(now).toLocaleString()}] ${String(v.note).slice(0, 500)}`
1155    try {
1156      await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
1157      await audit($, s, 'change', '往对话里插入唤醒记录', { text })
1158    } catch (err) {
1159      await audit($, s, 'change', '往对话里插入唤醒记录', { text, ok: false, error: errText(err) })
1160    }
1161    $.ui.toast(`keepwarm 记录:${String(v.note).slice(0, 80)}`)
1162  } else if (decision === 'act') {
1163    await auditedSubmit($, s, '唤醒后发起一轮真实对话',
1164      `[keepwarm 定时唤醒,保温剩 ${fmtDuration(s.deadline - now)}] ${v.task || s.wakePrompt}\n` +
1165        '做完后简短汇报;一切正常且无需用户处理就只回一行。保温会自动继续,任务已无必要时调用 keepwarm stop。')
1166  } else if (decision === 'stop') {
1167    await stop($, s, null)
1168  }
1169}
1170
1171async function startWindow($: EngineInterface, s: State, windowMs: number, owner: Owner, reason: string, wakePrompt = '', sticky = false) {
1172  const now = await $.clock.now()
1173  const deadline = now + Math.min(windowMs, MAX_WINDOW_MS)
1174  // The model may extend the person's window, never shorten it.
1175  if (owner === 'model' && s.deadline && s.owner === 'user') {
1176    s.deadline = Math.max(s.deadline, deadline)
1177  } else {
1178    s.deadline = deadline
1179    s.owner = owner
1180    s.sticky = sticky
1181  }
1182  s.reason = reason
1183  s.wakePrompt = wakePrompt
1184  s.stopped = null
1185  await audit($, s, 'change', '开启保温', { by: owner, owner: s.owner, until: s.deadline, reason, wake: wakePrompt || undefined, sticky: s.sticky })
1186  await save($, s)
1187  await arm($, s)
1188}
1189
1190// Keeps the Mac from idle sleep while a leave window runs; lid-close on battery still sleeps.
1191// The child dies with the module too (a reload), which only ends the stay-awake, not the window.
1192function caffeinate($: EngineInterface, s: State, ms: number) {
1193  stopCaffeinate($, s)
1194  const it = $.process.spawn({ argv: ['caffeinate', '-i', '-t', String(Math.ceil(ms / 1000))] })
1195  void audit($, s, 'change', '启动 caffeinate 防闲置睡眠', { seconds: Math.ceil(ms / 1000) })
1196  s.caff = it
1197  void (async () => {
1198    try { for await (const _ of it) { /* no output */ } } catch { /* not on macOS, or killed */ }
1199    if (s.caff === it) s.caff = null
1200  })()
types/index.d.ts 44 lines
1export type KeepwarmAdvice = {
2  action: 'compact' | 'keepwarm' | 'ignore'
3  reason: string
4  // What the session is about, in a few words (for notifications).
5  topic?: string
6  hours: number
7  ctx: number
8  coldUsd: number | null
9  hourUsd: number | null
10  judgeUsd: number | null
11  at: number
12  auto: boolean
13  // Set when the person said they are leaving (/keepwarm leave).
14  leave?: { hours: number; machineOn: boolean; keepUsd: number | null; compactUsd: number | null }
15}
16
17export type KeepwarmLeaveItem = {
18  sid: string
19  project: string
20  topic: string
21  ctx: number
22  action: 'compact' | 'keepwarm' | 'ignore'
23  reason: string
24  keepUsd: number | null
25  compactUsd: number | null
26  coldUsd: number | null
27}
28
29export type KeepwarmLeaveAll = {
30  id: string
31  hours: number
32  machineOn: boolean
33  startedAt: number
34  items: KeepwarmLeaveItem[]
35  collecting: boolean
36}
37
38declare module 'claude-code' {
39  interface PluginState {
40    // panel: a counter bumped to redraw the panel (its countdown, a window started or stopped).
41    keepwarm: { advice: KeepwarmAdvice | null; leaveAll: KeepwarmLeaveAll | null; panel: number }
42  }
43}
44