Refuses SendMessage to a bee past its context line, telling the orchestrator to spawn a fresh bee and brief it from the old one's report

hooks/register.tsx 214 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, Register } from 'claude-code'
3
4import type { CodexLaunch, CodexSession } from '../types'
5
6// Break-even: a 20-step round resumed here reads ~0.2M cache-equivalent, as much as a fresh spawn.
7const CONTINUE_LINE = 100_000
8// A round resumed here costs well over a fresh spawn; bee-context-nudge pauses here.
9const RETIRE_AT = 200_000
10const CLAUDE_TTL_MS = 5 * 60_000
11const CODEX_TTL_MS = 30 * 60_000
12const SHOWN_FOR_MS = 60 * 60_000
13const REFRESH_MS = 15_000
14const HANDOVER = '[bees:handover]'
15const OPENCODE_URL = 'http://127.0.0.1:4096'
16
17const contexts = atom({ plugin: 'bees-budget', key: 'contexts' } as const, {})
18const codex = atom({ plugin: 'bees-budget', key: 'codex' } as const, [])
19const launches = atom({ plugin: 'bees-budget', key: 'launches' } as const, [])
20
21type Row = { vendor: string; model: string; label: string; tokens: number; at: number; ttlMs: number; isRunning: boolean; codex?: CodexSession }
22
23const contextTokens = (u: ModelUsage) =>
24 u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens
25
26const kilo = (n: number) => `${Math.round(n / 1000)}k`
27const isRetired = (tokens: number) => tokens >= RETIRE_AT
28const isCold = (r: Row, now: number) => !r.isRunning && now - r.at > r.ttlMs
29const isPastContinueLine = (tokens: number) => tokens >= CONTINUE_LINE
30const isBlocked = (r: Row) => isPastContinueLine(r.tokens)
31
32const refusal = (r: Row) => {
33 if (isRetired(r.tokens))
34 return `${r.label} is at ${kilo(r.tokens)} context, past the ${kilo(RETIRE_AT)} retire line: spawn a fresh bee and brief it from this one's report; a retirement message may start with ${HANDOVER}.`
35 if (isPastContinueLine(r.tokens))
36 return `${r.label} is at ${kilo(r.tokens)} context, past the ${kilo(CONTINUE_LINE)} continue line: spawn a fresh bee and brief it from this one's report; a retirement message may start with ${HANDOVER}.`
37 return undefined
38}
39
40const modelEffort = (model: string, effort: string | null | undefined) => (effort ? `${model}-${effort}` : model)
41
42const frontmatter = (text: string, key: string) => text.match(new RegExp(`^${key}:\\s*(\\S+)`, 'm'))?.[1]
43
44const agentModels = new Map<string, Promise<string>>()
45
46const readAgentModel = async ($: EngineInterface, type: string) => {
47 const text = await $.fs.read(`${await $.env.get('HOME')}/.claude/agents/${type}.md`).catch(() => '')
48 const model = (frontmatter(text, 'model') ?? '?').replace(/^claude-|-.*$/g, '')
49 return modelEffort(model, frontmatter(text, 'effort'))
50}
51
52const agentModel = ($: EngineInterface, type: string) => {
53 if (!agentModels.has(type)) agentModels.set(type, readAgentModel($, type))
54 return agentModels.get(type)!
55}
56
57const beeRows = async ($: EngineInterface): Promise<(Row & { id: string })[]> => {
58 const recorded = await read($, contexts)
59 const bees = (await $.agent.list()).flatMap(a => {
60 const bee = recorded[a.id]
61 return a.type.startsWith('bee-') && bee ? [{ ...a, ...bee }] : []
62 })
63 return Promise.all(bees.map(async a => ({
64 id: a.id, vendor: 'claude', model: await agentModel($, a.type), label: a.name ?? a.description,
65 tokens: a.tokens, at: a.at, ttlMs: CLAUDE_TTL_MS, isRunning: a.status === 'running',
66 })))
67}
68
69const assistant = `json_extract(data, '$.role') = 'assistant'`
70
71const codexQuery = (since: number, liveSince: number) => `
72 with touched as (select session_id, max(time_updated) as at from part group by session_id)
73 select s.id, s.title as label, s.directory, s.time_created as createdAt,
74 json_extract(l.data, '$.modelID') as model, json_extract(l.data, '$.variant') as effort,
75 coalesce(json_extract(m.data, '$.tokens.total'),
76 ifnull(json_extract(m.data, '$.tokens.input'), 0) + ifnull(json_extract(m.data, '$.tokens.output'), 0)
77 + ifnull(json_extract(m.data, '$.tokens.reasoning'), 0) + ifnull(json_extract(m.data, '$.tokens.cache.read'), 0)
78 + ifnull(json_extract(m.data, '$.tokens.cache.write'), 0)) as tokens,
79 coalesce(json_extract(m.data, '$.time.completed'), s.time_created) as at,
80 l.id is not null and json_extract(l.data, '$.time.completed') is null
81 and json_extract(l.data, '$.error') is null and t.at > ${liveSince} as isRunning
82 from session s join touched t on t.session_id = s.id
83 left join message m on m.id = (
84 select id from message where session_id = s.id and ${assistant}
85 and json_extract(data, '$.time.completed') is not null
86 and json_extract(data, '$.error') is null order by time_created desc limit 1)
87 left join message l on l.id = (
88 select id from message where session_id = s.id and ${assistant} order by time_created desc limit 1)
89 where s.parent_id is null and t.at > ${since} order by t.at desc limit 20`
90
91const queryOpencode = async <T,>($: EngineInterface, sql: string): Promise<T[]> => {
92 const data = (await $.env.get('XDG_DATA_HOME')) || `${await $.env.get('HOME')}/.local/share`
93 const ran = await $.process.run(['sqlite3', '-json', `${data}/opencode/opencode.db`, sql])
94 return ran.exitCode === 0 && ran.stdout.trim() ? JSON.parse(ran.stdout) : []
95}
96
97const readCodexSessions = async ($: EngineInterface, now: number): Promise<CodexSession[]> =>
98 (await queryOpencode<CodexSession>($, codexQuery(now - SHOWN_FOR_MS, now - CODEX_TTL_MS)))
99 .map(s => ({ ...s, isRunning: Boolean(s.isRunning) }))
100
101const isLaunchedHere = (s: CodexSession, ls: CodexLaunch[]) =>
102 ls.some(l => l.id === s.id || (l.title === s.label && s.createdAt >= l.since))
103
104const refresh = async ($: EngineInterface) => {
105 const sessions = await readCodexSessions($, await $.clock.now())
106 const { startedAt } = await $.session.usage()
107 const ls = await read($, launches)
108 await update($, codex, () => sessions.filter(s => isLaunchedHere(s, ls) && (s.isRunning || s.at >= startedAt)))
109 $.ui.invalidate('ui.render')
110}
111
112const unquote = (arg: string) => arg.replace(/^(['"])(.*)\1$/, '$2')
113const flag = (command: string, name: string) => {
114 const arg = command.match(new RegExp(`(?:^|\\s)${name}\\s+("[^"]*"|'[^']*'|\\S+)`))?.[1]
115 return arg && unquote(arg)
116}
117const basename = (path: string) => path.split('/').pop() ?? path
118
119const launchTitle = (command: string) => {
120 const launch = command.match(/codex-round (implement|run|review|advise)|opencode run/)
121 if (!launch) return undefined
122 const title = flag(command, '--title')
123 const out = flag(command, '-o')
124 if (title || !out) return title
125 return launch[1] === 'review' || launch[1] === 'advise' ? `review ${basename(out)}` : basename(out)
126}
127
128const sessionIds = (text: string) => [...new Set(text.match(/\bses_[A-Za-z0-9]+/g) ?? [])]
129
130const recordLaunches = async ($: EngineInterface, command: string, output: string) => {
131 const since = await $.clock.now()
132 const title = launchTitle(command)
133 const found: CodexLaunch[] = [...sessionIds(`${command}\n${output}`).map(id => ({ id, since })), ...(title ? [{ title, since }] : [])]
134 if (found.length) await update($, launches, all => [...all, ...found])
135}
136
137const attach = async ($: EngineInterface, s: CodexSession) => {
138 const command = ['opencode', 'attach', OPENCODE_URL, '--dir', s.directory, '--session', s.id]
139 const socket = await $.env.get('KITTY_LISTEN_ON')
140 const window = await $.env.get('KITTY_WINDOW_ID')
141 if (!socket || !window) return $.ui.toast(command.join(' '))
142 const ran = await $.process.run(['kitty', '@', '--to', socket, 'launch', '--location=vsplit', `--next-to=id:${window}`,
143 '--cwd', s.directory, '--title', `codex ${s.label}`, ...command])
144 if (ran.exitCode !== 0) $.ui.toast(`kitty launch failed: ${ran.stderr.trim()}`)
145}
146
147const cacheText = (r: Row, now: number) =>
148 r.isRunning ? 'running' : `warm ${Math.ceil((r.ttlMs - (now - r.at)) / 60_000)}m`
149
150const statusColor = (r: Row) => (isBlocked(r) ? 'red' : r.isRunning ? 'green' : undefined)
151
152const tokenColor = (tokens: number) =>
153 isRetired(tokens) ? 'red' : isPastContinueLine(tokens) ? 'yellow' : undefined
154
155export const register: Register = on => {
156 on('session.start', async ($, e, next) => {
157 $.clock.every(REFRESH_MS, () => void refresh($))
158 void refresh($)
159 return next(e)
160 })
161
162 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
163 const ran = await next(e)
164 const output = ran.deny === undefined && !ran.isError ? `${ran.result.stdout}\n${ran.result.stderr}` : ''
165 await recordLaunches($, e.command, output)
166 return ran
167 })
168
169 on('turn.step', async function* ($, e, next) {
170 const step = yield* next(e)
171 const { agentId } = e
172 const { usage } = step
173 if (agentId && usage) {
174 const bee = { tokens: contextTokens(usage), at: await $.clock.now() }
175 await update($, contexts, all => ({ ...all, [agentId]: bee }))
176 }
177 return step
178 })
179
180 on('session.send', async ($, e, next) => {
181 if (e.text.startsWith(HANDOVER)) return next(e)
182 const to = e.to.replace(/ \[[^\]]*\]$/, '')
183 const bee = (await beeRows($)).find(r => r.id === to || r.label === to)
184 const reason = bee && refusal(bee)
185 return reason ? { isDelivered: false, reason } : next(e)
186 })
187
188 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
189 if (e.props.hasSurvey) return next(e)
190 const now = await $.clock.now()
191 const codexRows = (await read($, codex)).map(s => ({
192 ...s, vendor: 'codex', model: modelEffort(s.model?.split('-').pop() ?? '?', s.effort), ttlMs: CODEX_TTL_MS, codex: s,
193 }))
194 const rows = codexRows.filter(r => !isCold(r, now))
195 if (rows.length === 0) return next(e)
196
197 const { Box, Button, Text } = $.ui.resolve(e)
198 return (
199 <Box flexDirection="column">
200 {rows.map(r => (
201 <Box key={r.codex.id} gap={2}>
202 <Text dimColor>{r.vendor} {r.model}</Text>
203 <Button key={r.codex.id} plain onPress={() => void attach($, r.codex)}>{r.label}</Button>
204 <Text color={tokenColor(r.tokens)}>{kilo(r.tokens)}</Text>
205 <Text dimColor={!statusColor(r)} color={statusColor(r)}>
206 {cacheText(r, now)}{isBlocked(r) ? ' · spawn fresh' : ''}
207 </Text>
208 </Box>
209 ))}
210 </Box>
211 )
212 })
213}
214types/index.d.ts 13 lines1export type BeeContext = { tokens: number; at: number }
2export type CodexSession = {
3 id: string; label: string; directory: string; createdAt: number; model: string | null; effort: string | null
4 tokens: number; at: number; isRunning: boolean
5}
6export type CodexLaunch = { id?: string; title?: string; since: number }
7
8declare module 'claude-code' {
9 interface PluginState {
10 'bees-budget': { contexts: Record<string, BeeContext>; codex: CodexSession[]; launches: CodexLaunch[] }
11 }
12}
13