Clawd, a token-saving assistant: trims noisy tool output and pasted logs before they fill your context, tells you when to compact (and does it in one click)…

A Claude Code mod that puts Clawd, Claude Code's pixel mascot, to work as your token-saving assistant.
Most token waste in a long session isn't the work itself. It's noise that piles up in the context and is re-sent with every request: install logs, progress bars, colour codes, a test runner printing the same warning 400 times. On top of that, a big context gets re-cached at full price after the prompt cache expires. Clawd goes after both:
Everything except routing works on its own, every turn: none of it depends on Claude choosing to delegate. It works in the Claude Code CLI and in the Code tab of the desktop app.
<sub>Drawn by npm run preview with the mod's real renderers over sample figures, exactly as the desktop app receives them. They animate on GitHub too. They are not screenshots of a live session.</sub>
Measured by npm run bench on the realistic outputs in tests/fixtures/outputs.ts. Every error line in every fixture survives the trim, and CI fails if one ever doesn't.
| Output | Tokens | After full | Saved | After lossless | | :- | -: | -: | -: | -: | | npm install with deprecation spam and progress frames | 4,337 | 221 | 95% | 3,977 | | A jest run: 260 passes, 1 failure | 3,759 | 160 | 96% | 3,106 | | cargo build with 340 crates and a type error | 2,809 | 102 | 96% | 2,809 | | docker build progress | 2,228 | 983 | 56% | 2,228 | | A 2,400-line server log with one error | 42,808 | 145 | ~100% | 42,808 | | git diff --stat (clean output) | 353 | 353 | 0% | 353 |
Trimming a megabyte of mixed noise takes about 30 ms.
In a Claude Code session:
/plugin install tokensaver --marketplace AGregDev/claude-tokensaver
Or from your shell:
claude plugin install tokensaver --marketplace AGregDev/claude-tokensaver
Answer y to add the marketplace and pick a scope. The mod is active at once. tokensaver needs Claude Code v2.1.299 or later.
In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with AGregDev/claude-tokensaver, then Add plugin.
To update to a new release:
claude plugin marketplace update claude-tokensaver
claude plugin update tokensaver@claude-tokensaver
Then start a new session (or run /reload-plugins). /tokensaver doctor says what loaded.
A mod is code that runs with your permissions. Before you install any mod, you can list what it hooks and calls without running it: clone the repository and run claude plugin validate . in it. What it can reach has tokensaver's list.
Every Bash and PowerShell result (and background shell output) passes through Clawd on its way into the conversation. That happens before the model reads it and before it is written to the transcript. The trims, in order:
| Trim | What it removes | Level | | :- | :- | :- | | Colour codes | ANSI escape sequences | lossless | | Progress bars | frames a carriage return overwrote; only the last one was ever visible | lossless | | Blank runs | trailing spaces, and runs of blank lines folded to one | lossless | | Repeated lines | 3 or more identical lines in a row become one line plus a count | lossless | | Look-alike lines | 6 or more lines that differ only in numbers or hashes keep the first two, a count and the last one. Error and warning lines are never folded | full | | Huge outputs | past maxOutputLines (300 by default), the head and tail are kept, plus every error or warning line from the middle, with a note saying what was cut and how to see it | full |
File reads, searches, errors and anything a tool marks as failed are never touched. A trim that would save fewer than about 40 tokens is skipped. In the transcript, a trimmed row gets a line saying how much Clawd ate.
Why this matters more than it looks: the context is re-sent with every request. A 4k-token log trimmed to 400 tokens saves 3.6k on that request and 3.6k again on each request after it, until the next compaction. Clawd counts both numbers: noise eaten, and re-sends avoided (the trimmed tokens times the main-loop requests made since).
When a prompt you type contains something that looks like a log (colour codes, or many lines with the same shape), Clawd applies only the lossless trims to it and shows a toast saying how much it saved. A slash command, a hidden prompt, or prose you wrote is left as typed.
Claude Code reports the context fill after each turn. As the fill crosses 70% and then 85%, Clawd says so once per level (in a toast, in the band above the prompt, and in the pane), with an estimate of how much a compaction would take off every request. Compact now (in the band, the pane, or /tokensaver compact) runs a normal compaction with focus instructions: keep the goal, the decisions, the changed files, open TODOs and your last few requests; drop raw tool output and dead ends.
Auto-compact is off by default. Set autoCompactAt (or run /tokensaver autocompact 80) and Clawd compacts by itself once the fill passes that mark, only between turns, never in the middle of one.
The prompt cache lives for a few minutes (5 by default; set cacheTtlMinutes to match your plan). After you have been idle that long with a context worth caching, Clawd falls asleep. The band, the status line and a toast then say that your next message re-writes the whole context to the cache, with the cost now and after a compaction. Compacting first is often the cheaper way back in.
When Claude starts a sub-agent, tokensaver scores the sub-agent's task and picks its model:
| Tier | Used for | | :- | :- | | Haiku | Simple, mechanical work: searches, bulk reads, repetitive edits | | Sonnet | Medium work, and anything Haiku-sized that the heuristics are unsure about | | Opus | Hard reasoning, architecture, and every risky task |
The score comes from five signals read off the task text with regular expressions and counts: scope (how broad), files touched, ambiguity, reasoning depth, and risk. No model is called to classify anything, so scoring costs no tokens.
Every adjustment after the first pick moves up, never down:
An agent type can name its own model in its definition, and a spawn does not say whether it does. So tokensaver leaves the first spawn of each agent type in a session untouched and watches which model Claude Code resolves for it:
model: in its definition does, and tokensaver never reroutes it.Forks, teammates and workflow agents are left alone, and so is any session whose model family tokensaver does not recognise.
The main conversation's own model is not switched. Changing models mid-session invalidates the prompt cache, which costs more than routing would save.
You do not have to ask for sub-agents. For each prompt you type, tokensaver works out whether handing the reading to a sub-agent would cost less than Claude doing it inline, and when it would, it tells Claude to delegate.
The comparison uses measured numbers, not guesses:
How much reading a task means is estimated from the files the prompt names and, for a broad task, from the size of the repository, which tokensaver samples once per session (file names only, never contents). So "find every usage across the repo" earns a suggestion in a 600-file repository and none in a 40-file one, where a single search is cheaper than any sub-agent.
When delegating wins by a clear margin, tokensaver adds one line to the prompt: about how many files, and to use one Explore sub-agent or up to three in parallel. Claude makes the final call, because it can see the code and tokensaver cannot. That line is the only thing tokensaver ever adds to the model's context for a prompt, and its cost is subtracted from the savings counter.
tokensaver never starts a sub-agent itself. A sub-agent that a mod starts has not been through the safety review Claude's own actions get, and Claude Code refuses it in auto mode. Delegation stays Claude's own action.
When a sub-agent's result fails its checks on a tier tokensaver picked, the same call is retried once on the next tier up, and Claude only sees the retry's result. The checks are:
If your next prompt opens by rejecting the result ("no, that's wrong", "try again"), every sub-agent that turn is routed one tier up.
A denied call is never retried, and neither is a turn you interrupted.
Clawd lives in three places, and its mood follows the session:
| Mood | When | What Clawd does | | :- | :- | :- | | idle | nothing to report | bobs and blinks | | chomp | it just trimmed output or a paste | chews, with tokens flying into its mouth | | happy | a compaction or a routing win | jumps, with sparkles | | busy | a turn or a helper is running | walks, eyes darting | | worried | context past 70% | trembles, with a sweat drop | | sleepy | the prompt cache went cold | eyes shut, Zzz | | alert | a helper failed and was escalated | shakes, with a red ! |
/tokensaver dashboard): animated Clawd with a speech bubble, a context meter whose hatched segment shows what the context would hold without the trims, four savings tiles, buttons (Compact now, Trimming on/off, Paste tidy on/off, power), and an activity feed. In the terminal, Clawd is drawn in block glyphs.Animation is CSS inside the picture, so it costs nothing while idle. reducedMotion (or /tokensaver motion off) stills everything, and NO_COLOR removes every colour from the text views.
All of them are estimates (about 4 characters to a token). They are kept apart because adding them up would count the same tokens twice.
| Command | What it does | | :- | :- | | /tokensaver | Status: what Clawd ate, re-sends avoided, context, routing | | /tokensaver compact | Compact now, with focus instructions from your recent asks | | /tokensaver trim [on\|off] | Trim noisy shell output before it is stored | | /tokensaver pastes [on\|off] | Tidy pasted logs in your prompts | | /tokensaver autocompact <0-95> | Compact between turns past this fill %; 0 means never | | /tokensaver on / off | Master switch. Off, every event passes through untouched | | /tokensaver dry-run [on\|off] | Only show what would have been trimmed or rerouted | | /tokensaver dashboard | Open Clawd's pane | | /tokensaver motion [on\|off] | Animations | | /tokensaver doctor | What tokensaver knows and what the display reported. Run this first if nothing shows | | /tokensaver export [path] | Write the routing outcome log as JSON to a local file | | /tokensaver reset | Clear the routing log and the learned thresholds | | /tokensaver help | List the commands |
Switches set with a command are remembered across sessions. /tokensaver:status, :compact, :trim, :dashboard, :doctor, :on, :off, :dry-run and :help are listed in the / menu from the very first prompt.
Set these when you install, or later with /plugin configure tokensaver@claude-tokensaver.
| Option | Default | What it does | | :- | :- | :- | | enabled | true | Master switch | | trimOutput | true | Trim noisy shell output before it is stored | | trimLevel | full | lossless only removes what carries no information; full also folds look-alike lines and caps huge outputs | | maxOutputLines | 300 | Under full, longer outputs keep their head, tail and error lines | | trimPastes | true | Tidy logs pasted into prompts (lossless) | | autoCompactAt | 0 | Compact between turns past this fill %; 0 means suggest only | | cacheTtlMinutes | 5 | Prompt cache lifetime, for the cold-cache warning; 0 turns it off | | dryRun | false | Change nothing; show what would have happened | | contextHint | true | Add the one-line delegation hint to prompts where delegating pays | | statusLine | true | Show the status line under the prompt | | reducedMotion | false | Turn off all animation |
Each finished delegation that tokensaver routed is appended to a local outcome log: the kind of task, the tier used, tokens, retries, whether it was escalated, and whether it passed its checks. The log holds counts and labels only. No prompt, file name or answer text is stored.
Routing is driven by two cutoffs per kind of task, and the log tunes them:
The log and the thresholds live in the mod's own store on your machine (Claude Code keeps it under your Claude Code configuration directory). The log is capped at 500 entries. A corrupted log is read entry by entry; whatever does not parse is dropped and the rest is kept.
The bar a delegation suggestion must clear is learned the same lopsided way. When a turn ends, the suggestion made in it is judged by what happened: if Claude declined and then read only a few files, or the sub-agent barely did more than start, the suggestion was not worth making and the bar rises by a quarter at once. If the sub-agent did real work, the bar drops by a few percent.
Nothing is sent anywhere. The mod makes no network call at all. /tokensaver export writes a file on your disk, and /tokensaver reset deletes the log and the thresholds.
Each guarantee below is enforced by a test, and the tests are part of CI.
| Guarantee | How it is held | | :- | :- | | Risky, destructive or production-touching work is never downgraded | A property test over every risky prompt, parent model and named model, under default thresholds and under the loosest thresholds learning could ever produce | | Escalation only moves up | A property test over every tier, check result, retry count and flag: the retry is exactly one tier higher or does not happen | | An agent type's own model is never overridden | A property test over every task and parent model, for a type known to bring its own model and for one not yet seen; a test inside Claude Code confirms it against the real agent.spawn event | | Permission decisions are never overridden | The mod has no tool.check hook, so it cannot approve anything; a test inside Claude Code confirms deny, ask and allow come back unchanged, and that a denied call is returned untouched and not retried | | It stacks with other mods | Every hook passes the event on with next, and every hook that could gate an event has a .catch that passes it on unchanged if the hook fails | | It degrades instead of breaking | A failed store, environment or display call never fails the hook that made it, and a test runs the mod with none of them available. When no per-request usage arrives, the meter falls back to turn totals |
One thing it cannot soften: Claude Code checks a mod's event names when it loads the mod. On a build that lacks one of the events above, Claude Code refuses to load tokensaver and says which event, and your session carries on without it. tokensaver is typed and tested against Claude Code v2.1.299 (the in-engine tests for the output trimmer need 2.1.299's test kit).
tokensaver runs after Claude Code's built-in sec-default guard and after any mod your organization lists ahead of user mods. It does nothing to work around either.
This is the complete list, as claude plugin validate reads it from the source. The build fails if the list changes, so it cannot grow without a reviewed edit to scripts/build.mjs.
| It hooks | To | | :- | :- | | session.start | Load the log and settings, register /tokensaver, sample the repository's size | | session.append on Claude's responses | Note which command each shell call ran (read only), so a search's output is never folded | | session.append on tool results only | Trim shell output before it is stored | | session.compact | Book what a compaction freed, and calm Clawd down | | session.attach | Redraw when an app connects to the session | | prompt.submit | Tidy a pasted log; score the prompt; add the delegation line when it pays | | agent.spawn | Choose the sub-agent's model | | tool.call on Agent only | Read the result; retry once one tier up when it fails | | turn.step, turn.complete, session.measure | Read token usage for the meter, and count how much the main loop reads itself | | command.run for tokensaver | Answer its own command | | ui.render for its own pane, the strip above the prompt, the spinner, and tool rows | Draw Clawd's pane and band; add to the spinner; mark trimmed shell rows and routed sub-agent rows. Every other row is passed on untouched | | ui.close for its own pane | Remember that you closed it |
| It calls | For | | :- | :- | | $.store.get, set, delete | The local log, thresholds and switches | | $.fs.write | /tokensaver export, to the path you give | | $.fs.list | Counting the repository's files once per session: names only, a few folders deep, capped | | $.env.get | Reading NO_COLOR, and nothing else | | $.ui.status, toast, log, open, resolve | Display | | $.state.get, set | Redrawing the pane | | $.clock.every, after | The animation timer; the cold-cache check; starting a compaction once a command has returned | | $.session.compact | Compacting, when you press Compact now or run /tokensaver compact, or past autoCompactAt if you set it | | $.command.register, $.session.surfaces, $.session.model | Its command; telling the CLI from the desktop app; knowing which model the session runs on |
It does not call a model, start a sub-agent or a process, make a network request, read the contents of your files, or change a permission. The only text it changes is shell output and pasted logs on their way into the conversation, as described above.
full, a huge output keeps its head, tail and error lines, and a long run of look-alike lines is folded; if Claude needs a line that was cut, the note in the output tells it to re-run with a filter. Set trimLevel to lossless if you never want lines dropped.cacheTtlMinutes to your plan's cache lifetime.hooks/register.tsx 1196 lines1/**
2 * tokensaver's hooks module: the thin layer between Claude Code's events and
3 * the pure controllers in ../src. Two of them run side by side:
4 *
5 * - the assistant (Clawd): trims noisy shell output and pasted logs before
6 * they are stored, watches the context window and the prompt cache, and
7 * compacts when asked (or, opted in, by itself between turns);
8 * - the router: picks the cheapest capable model for sub-agents Claude starts,
9 * and retries one tier up when a result fails its checks.
10 *
11 * None of it approves a tool call (there is no `tool.check` hook), and it
12 * never starts a sub-agent itself.
13 */
14import { atom, read, update } from 'claude-code'
15import type { EngineInterface, Register, Timer, ToolCallResult, TurnUsage } from 'claude-code'
16
17import { isRecord } from '../src/core/log.ts'
18import {
19 createAssistant,
20 fillOf,
21 hasFlare,
22 moodOf,
23 noteEvent,
24 onCompacted,
25 onContext,
26 onIdleCheck,
27 onMainRequest,
28 onPromptText,
29 onToolOutput,
30 onTurnEnd,
31 parseAssistantOptions,
32 parseAssistantOverrides,
33 requestCompact,
34 speechOf,
35 withAssistantConfig,
36} from '../src/runtime/assistant.ts'
37import type { Assistant, AssistantOverrides, AssistantStep } from '../src/runtime/assistant.ts'
38import {
39 hydrate,
40 isAnimating,
41 onAgentResult,
42 onCommand,
43 onDiagnostic,
44 onFacts,
45 onMeasure,
46 onPrompt,
47 onSpawn,
48 onSpawned,
49 onStepUsage,
50 onTick,
51 onTurnComplete,
52} from '../src/runtime/session.ts'
53import type { AgentResultInput, Effect, Session, Step, Usage } from '../src/runtime/session.ts'
54import { BAND_HEIGHT, bandSvg, isBandVisible, routedBadge, spinnerSuffix } from '../src/ui/band.ts'
55import {
56 bandLineOf,
57 bandSvgOf,
58 bubbleRows,
59 clawdArt,
60 heroSvg,
61 tilesSvg,
62} from '../src/ui/clawd.ts'
63import type { ClawdView } from '../src/ui/clawd.ts'
64import { bar, formatTokens, spinner } from '../src/ui/format.ts'
65import type { Span, Tone } from '../src/ui/theme.ts'
66import { toView } from '../src/ui/view.ts'
67
68const NAME = 'tokensaver'
69const TICK_MS = 250
70const STORE_LOG = 'log'
71const STORE_THRESHOLDS = 'thresholds'
72const STORE_SETTINGS = 'settings'
73const STORE_DELEGATION = 'delegation'
74const STORE_ASSISTANT = 'assistant'
75const STORE_LIFETIME = 'lifetime'
76
77/** Tools that read the repository; counted to see how much the main loop reads for itself. */
78const READING_TOOLS = ['Read', 'Grep', 'Glob']
79
80/** Folders that hold no source of the project's own. */
81const SKIPPED_FOLDERS = [
82 'node_modules',
83 '.git',
84 'dist',
85 'build',
86 'out',
87 'coverage',
88 'target',
89 'vendor',
90 '.next',
91 '.venv',
92 '__pycache__',
93]
94const MAX_LISTINGS = 40
95const MAX_COUNTED = 2000
96const MAX_MARKED_ROWS = 200
97
98/** About how wide one text cell is in the desktop app, to size a picture to its slot. */
99const CELL_PX = 7.4
100
101const revision = atom({ plugin: 'tokensaver', key: 'revision' } as const, 0)
102
103type TextStyle = { color?: Tone; weight?: 'semibold'; dimColor?: true }
104
105/** A colour prop only where colour is on. */
106const tint = (hasColor: boolean, tone: Tone): { color?: Tone } => (hasColor ? { color: tone } : {})
107
108const styleOf = (part: Span): TextStyle => ({
109 ...(part.tone === undefined ? {} : { color: part.tone }),
110 ...(part.isBold === true ? { weight: 'semibold' as const } : {}),
111 ...(part.isDim === true ? { dimColor: true } : {}),
112})
113
114const usageOf = (usage: TurnUsage): Usage => ({
115 model: usage.model,
116 input: usage.input_tokens,
117 output: usage.output_tokens,
118 cacheWrite: usage.cache_creation_input_tokens,
119})
120
121/** The Agent tool's own token total. A denial, an error and a background launch carry none. */
122const totalTokensOf = (result: unknown): number | undefined => {
123 const total = isRecord(result) ? result['totalTokens'] : undefined
124
125 return typeof total === 'number' ? total : undefined
126}
127
128const resultOf = (toolUseId: string, result: ToolCallResult<'Agent'>): AgentResultInput => ({
129 toolUseId,
130 isDenied: result.deny !== undefined,
131 isError: result.isError === true,
132 text: result.text ?? '',
133 totalTokens: totalTokensOf(result.result),
134 now: Date.now(),
135})
136
137/** A call that falls back instead of failing its hook when it is not available. */
138const attempt = async <Value,>(call: () => Promise<Value>, fallback: Value): Promise<Value> => {
139 try {
140 return await call()
141 } catch {
142 return fallback
143 }
144}
145
146const reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
147
148/** A tool_result block's text, whether it came as a string or as text blocks; undefined for anything else. */
149const resultText = (block: Record<string, unknown>): string | undefined => {
150 const content = block['content']
151
152 if (typeof content === 'string') {
153 return content
154 }
155
156 if (!Array.isArray(content) || content.length === 0) {
157 return undefined
158 }
159
160 const texts = content.map(part => (isRecord(part) && part['type'] === 'text' ? part['text'] : undefined))
161
162 return texts.every(text => typeof text === 'string') ? texts.join('\n') : undefined
163}
164
165type Lifetime = { eaten: number; freed: number }
166
167const parseLifetime = (value: unknown): Lifetime => ({
168 eaten: isRecord(value) && typeof value['eaten'] === 'number' ? value['eaten'] : 0,
169 freed: isRecord(value) && typeof value['freed'] === 'number' ? value['freed'] : 0,
170})
171
172// Module state: a session's worth of bookkeeping. A reload starts it over, and
173// `session.start` then rebuilds it from the store.
174let session: Session = hydrate({
175 options: {},
176 storedLog: undefined,
177 storedThresholds: undefined,
178 storedSettings: undefined,
179 noColor: undefined,
180}).session
181let assistant: Assistant = createAssistant(parseAssistantOptions({}))
182let assistantOverrides: AssistantOverrides = {}
183let lifetime: Lifetime = { eaten: 0, freed: 0 }
184let timer: Timer | undefined
185let idleTimer: Timer | undefined
186let shownStatus: string | undefined
187let isPaneOpen = false
188let wasPaneClosedByPerson = false
189/** Shell rows Clawd trimmed, by tool_use_id, for their badge in the transcript. */
190let markedRows = new Map<string, number>()
191/** The command each shell call ran, by tool_use_id, so the trimmer knows a search from a build. */
192let commands = new Map<string, string>()
193
194const clawdView = (now = Date.now()): ClawdView => {
195 const view = toView(session)
196 const state = { now, isEnabled: session.config.isEnabled, activeAgents: view.activeCount }
197
198 return {
199 mood: moodOf(assistant, state),
200 speech: speechOf(assistant, state),
201 mode: view.mode,
202 hasMotion: !session.config.hasReducedMotion,
203 hasColor: !session.hasNoColor,
204 context: { ...assistant.context, percent: fillOf(assistant) },
205 ghost: assistant.live,
206 stats: {
207 eaten: assistant.trimmed + assistant.pasteTrimmed,
208 reReads: assistant.reReads,
209 compactFreed: assistant.compactFreed,
210 routed: Math.max(0, session.saved),
211 keptOut: session.keptOut,
212 trims: assistant.trims + assistant.pastes,
213 compactions: assistant.compactions,
214 },
215 feed: assistant.feed,
216 activeAgents: view.activeCount,
217 frame: session.frame,
218 }
219}
220
221/** The status line: one glance at what Clawd is doing for the session. Plain text, no colour codes. */
222const statusText = (): string | undefined => {
223 if (!session.config.isEnabled || !session.config.hasStatusLine) {
224 return undefined
225 }
226
227 const view = clawdView()
228 const routing = toView(session)
229 const glyph = view.activeAgents > 0 ? spinner(session.frame, view.hasMotion) : '●'
230 const parts = [
231 `${glyph} ${session.config.isDryRun ? 'tokensaver [dry-run]' : 'tokensaver'} ${formatTokens(routing.total)} tok`,
232 `Clawd ate ${formatTokens(view.stats.eaten)}`,
233 `~${formatTokens(view.stats.reReads)} re-sends avoided`,
234 ]
235
236 if (view.context.window > 0) {
237 parts.push(`ctx ${bar(view.context.percent / 100, 6)} ${String(view.context.percent)}%`)
238 }
239
240 if (view.mood === 'sleepy') {
241 parts.push('cache cold: /tokensaver compact')
242 }
243
244 if (view.activeAgents > 0) {
245 parts.push(`${String(view.activeAgents)} helper${view.activeAgents === 1 ? '' : 's'}`)
246 }
247
248 return parts.join(' · ')
249}
250
251/** Opens the pane and keeps what Claude Code answered, for `/tokensaver doctor`. */
252const openPane = async ($: EngineInterface, why: string): Promise<void> => {
253 try {
254 const opened = await $.ui.open({ id: NAME, title: 'Clawd · tokensaver' })
255
256 isPaneOpen = opened.isPlaced
257 session = onDiagnostic(
258 session,
259 opened.isPlaced ? `pane opened (${why})` : `pane waiting (${why}): ${opened.reason}`,
260 ).session
261 } catch (error) {
262 isPaneOpen = false
263 session = onDiagnostic(session, `pane did not open (${why}): ${reasonOf(error)}`).session
264 }
265}
266
267const saveLifetime = ($: EngineInterface): Promise<void> =>
268 attempt(() => $.store.set(STORE_LIFETIME, lifetime), undefined)
269
270const run = async ($: EngineInterface, effect: Effect): Promise<void> => {
271 switch (effect.kind) {
272 case 'toast':
273 $.ui.toast(effect.text)
274 break
275 case 'log':
276 $.ui.log(effect.text)
277 break
278 case 'save-log':
279 await $.store.set(STORE_LOG, session.outcomes)
280 await $.store.set(STORE_THRESHOLDS, session.thresholds)
281 await $.store.set(STORE_DELEGATION, { minSaving: session.minSaving })
282 break
283 case 'save-settings':
284 await $.store.set(STORE_SETTINGS, session.overrides)
285 break
286 case 'clear-log':
287 await $.store.delete(STORE_LOG)
288 await $.store.delete(STORE_THRESHOLDS)
289 await $.store.delete(STORE_DELEGATION)
290 break
291 case 'open-dashboard':
292 wasPaneClosedByPerson = false
293 await openPane($, 'asked')
294 break
295 case 'export':
296 await $.fs.write(effect.path, effect.json)
297 break
298 }
299}
300
301/** True while something on screen moves or must be taken down on time. */
302const needsClock = (): boolean =>
303 isAnimating(session) || (session.config.isEnabled && hasFlare(assistant, Date.now()))
304
305/** Redraws the status line and everything the mod draws. Display only: nothing here reaches the model. */
306const refresh = ($: EngineInterface): void => {
307 const status = statusText()
308
309 if (status !== shownStatus) {
310 shownStatus = status
311 $.ui.status(status)
312 }
313
314 void attempt(() => update($, revision, count => count + 1), undefined)
315
316 if (timer === undefined && needsClock()) {
317 timer = $.clock.every(TICK_MS, () => {
318 session = onTick(session, Date.now()).session
319
320 if (!needsClock()) {
321 timer?.cancel()
322 timer = undefined
323 // One last frame without the passing mood.
324 void attempt(() => update($, revision, count => count + 1), undefined)
325 return
326 }
327
328 refresh($)
329 })
330 }
331}
332
333/**
334 * Puts the display back in step with the session. What is sent while no
335 * surface is attached is dropped, so this runs again whenever one may have
336 * appeared: when an app attaches, and at the start of every turn.
337 */
338const sync = async ($: EngineInterface, why: string): Promise<void> => {
339 const surfaces = await attempt(() => $.session.surfaces(), [])
340
341 // Send the status line again even when its text has not changed.
342 shownStatus = undefined
343
344 // A surface with room beside the transcript gets the pane; the terminal gets the status line and strip.
345 if (
346 session.config.isEnabled &&
347 !isPaneOpen &&
348 !wasPaneClosedByPerson &&
349 surfaces.some(surface => surface !== 'terminal')
350 ) {
351 await openPane($, why)
352 }
353
354 refresh($)
355}
356
357/** Applies a router transition: keeps its session, carries out its effects, redraws. */
358const commit = async <Reply,>($: EngineInterface, step: Step<Reply>): Promise<Reply> => {
359 const before = session.notes
360 session = { ...step.session, now: Math.max(step.session.now, Date.now()) }
361
362 // What the router did shows in Clawd's feed too.
363 for (const note of session.notes.filter(note => !before.includes(note))) {
364 assistant = noteEvent(assistant, {
365 kind: note.includes('escalated') || note.includes('failed') ? 'escalate' : note.includes('→') ? 'route' : 'info',
366 text: note,
367 now: Date.now(),
368 })
369 }
370
371 for (const effect of step.effects) {
372 // A display or storage effect that fails must never fail the hook that caused it.
373 await attempt(() => run($, effect), undefined)
374 }
375
376 refresh($)
377
378 return step.reply
379}
380
381/** Runs a compaction for Clawd and books what it freed. */
382const compactNow = async ($: EngineInterface, instructions: string): Promise<string> => {
383 try {
384 const result = await $.session.compact({ instructions })
385
386 assistant = onCompacted(assistant, {
387 before: result.skip === undefined ? result.tokensBefore : undefined,
388 after: result.skip === undefined ? result.tokensAfter : undefined,
389 isSkipped: result.skip !== undefined,
390 now: Date.now(),
391 })
392
393 return result.skip === undefined ? 'Compacted.' : `Compaction skipped: ${result.skip}`
394 } catch (error) {
395 assistant = { ...assistant, isCompacting: false }
396
397 const text = `Clawd could not compact now: ${reasonOf(error)}`
398
399 $.ui.toast(text)
400
401 return text
402 } finally {
403 refresh($)
404 }
405}
406
407/** Applies an assistant transition: keeps it, carries out its effects, redraws. */
408const commitAssistant = async <Reply,>($: EngineInterface, step: AssistantStep<Reply>): Promise<Reply> => {
409 assistant = step.assistant
410
411 for (const effect of step.effects) {
412 if (effect.kind === 'toast') {
413 $.ui.toast(effect.text)
414 } else if (effect.kind === 'compact') {
415 // Never awaited by the hook that noticed the need: it compacts once the turn has let go.
416 void compactNow($, effect.instructions)
417 } else {
418 await attempt(() => $.store.set(STORE_ASSISTANT, assistantOverrides), undefined)
419 }
420 }
421
422 refresh($)
423
424 return step.reply
425}
426
427const applyAssistantOverrides = (options: Readonly<Record<string, unknown>>): void => {
428 assistant = withAssistantConfig(assistant, { ...parseAssistantOptions(options), ...assistantOverrides })
429}
430
431/** Watches the idle session so Clawd can say when the prompt cache has expired. */
432const armIdleCheck = ($: EngineInterface): void => {
433 idleTimer?.cancel()
434 idleTimer = undefined
435
436 const ttl = assistant.config.cacheTtlMinutes * 60_000
437
438 if (ttl <= 0) {
439 return
440 }
441
442 const firesAt = Date.now() + ttl + 1000
443
444 idleTimer = $.clock.after(ttl + 1000, () => {
445 idleTimer = undefined
446
447 const wasCold = assistant.isCold
448 // The timer firing is the proof that the idle time passed, whatever clock drives it.
449 assistant = onIdleCheck(assistant, { now: Math.max(Date.now(), firesAt), isEnabled: session.config.isEnabled })
450
451 if (assistant.isCold && !wasCold) {
452 $.ui.toast(`Clawd: ${speechOf(assistant, { now: Date.now(), isEnabled: true, activeAgents: 0 })}`)
453 refresh($)
454 }
455 })
456}
457
458/**
459 * Counts the project's files, a few folders deep, to judge how much reading a
460 * broad task means. A sample with a ceiling: it reads names only, never contents.
461 */
462const countFiles = async ($: EngineInterface): Promise<number | undefined> => {
463 const queue: { path: string; depth: number }[] = [{ path: '.', depth: 0 }]
464 let listings = 0
465 let files = 0
466
467 while (queue.length > 0 && listings < MAX_LISTINGS && files < MAX_COUNTED) {
468 const folder = queue.shift()
469
470 if (folder === undefined) {
471 break
472 }
473
474 const entries = await attempt(() => $.fs.list(folder.path), undefined)
475
476 if (entries === undefined) {
477 // The first listing failing means the count is unknown, not zero.
478 if (listings === 0) {
479 return undefined
480 }
481
482 continue
483 }
484
485 listings += 1
486
487 for (const entry of entries) {
488 if (entry.kind === 'file') {
489 files += 1
490 } else if (entry.kind === 'dir' && folder.depth < 3 && !SKIPPED_FOLDERS.includes(entry.name)) {
491 queue.push({
492 path: folder.path === '.' ? entry.name : `${folder.path}/${entry.name}`,
493 depth: folder.depth + 1,
494 })
495 }
496 }
497 }
498
499 return files
500}
501
502const ASSISTANT_HELP = [
503 '/tokensaver compact compact now, with focus instructions from your recent asks',
504 '/tokensaver trim [on|off] trim noisy shell output before it is stored',
505 '/tokensaver pastes [on|off] tidy pasted logs in your prompts (lossless)',
506 '/tokensaver autocompact <0-95> compact by itself past this fill % (0 = never)',
507].join('\n')
508
509const switchOf = (word: string | undefined, isOn: boolean): boolean =>
510 word === 'on' ? true : word === 'off' ? false : !isOn
511
512/** The assistant's own commands; undefined for a word the router answers. */
513const assistantCommand = async ($: EngineInterface, args: string): Promise<string | undefined> => {
514 const [first = '', second] = args.trim().toLowerCase().split(/\s+/)
515
516 switch (first) {
517 case 'compact': {
518 const step = requestCompact(assistant)
519
520 assistant = step.assistant
521
522 if (step.reply.instructions === undefined) {
523 return `Clawd: ${step.reply.why ?? 'not now'}`
524 }
525
526 const instructions = step.reply.instructions
527
528 // A command holds its own turn, under which the engine refuses to compact: start once it has let go.
529 $.clock.after(50, () => {
530 void compactNow($, instructions)
531 })
532
533 return 'Clawd is compacting the conversation, keeping your current task in focus.'
534 }
535 case 'trim': {
536 const isTrimming = switchOf(second, assistant.config.isTrimming)
537
538 assistantOverrides = { ...assistantOverrides, isTrimming }
539 await commitAssistant($, {
540 assistant: withAssistantConfig(assistant, { ...assistant.config, isTrimming }),
541 effects: [{ kind: 'save-assistant' }],
542 reply: undefined,
543 })
544
545 return `Clawd: output trimming is ${isTrimming ? 'on' : 'off'}`
546 }
547 case 'pastes': {
548 const isTrimmingPastes = switchOf(second, assistant.config.isTrimmingPastes)
549
550 assistantOverrides = { ...assistantOverrides, isTrimmingPastes }
551 await commitAssistant($, {
552 assistant: withAssistantConfig(assistant, { ...assistant.config, isTrimmingPastes }),
553 effects: [{ kind: 'save-assistant' }],
554 reply: undefined,
555 })
556
557 return `Clawd: paste tidying is ${isTrimmingPastes ? 'on' : 'off'}`
558 }
559 case 'autocompact': {
560 const value = Number(second)
561
562 if (!Number.isFinite(value) || value < 0 || value > 95) {
563 return 'Clawd: give a fill percentage from 0 (never) to 95, e.g. /tokensaver autocompact 80'
564 }
565
566 const autoCompactAt = Math.round(value)
567
568 assistantOverrides = { ...assistantOverrides, autoCompactAt }
569 await commitAssistant($, {
570 assistant: withAssistantConfig(assistant, { ...assistant.config, autoCompactAt }),
571 effects: [{ kind: 'save-assistant' }],
572 reply: undefined,
573 })
574
575 return autoCompactAt === 0
576 ? 'Clawd: auto-compact is off; I will only suggest it'
577 : `Clawd: I will compact between turns once the context passes ${String(autoCompactAt)}%`
578 }
579 default:
580 return undefined
581 }
582}
583
584const assistantReport = (): string => {
585 const view = clawdView()
586
587 return [
588 `Clawd ate ${formatTokens(view.stats.eaten)} tokens of noise this session (${String(view.stats.trims)} trims; ${formatTokens(lifetime.eaten)} all-time)`,
589 `~${formatTokens(view.stats.reReads)} tokens not re-sent on later requests; ${formatTokens(view.stats.compactFreed)} freed by ${String(view.stats.compactions)} compaction(s)`,
590 `context ${view.context.window > 0 ? `${String(view.context.percent)}% (${formatTokens(view.context.tokens)} of ${formatTokens(view.context.window)})` : 'not measured yet'}`,
591 `trim ${assistant.config.isTrimming ? `on (${assistant.config.trimLevel}, cap ${String(assistant.config.maxOutputLines)} lines)` : 'off'} · pastes ${assistant.config.isTrimmingPastes ? 'on' : 'off'} · auto-compact ${assistant.config.autoCompactAt === 0 ? 'off' : `at ${String(assistant.config.autoCompactAt)}%`} · cache coach ${assistant.config.cacheTtlMinutes === 0 ? 'off' : `${String(assistant.config.cacheTtlMinutes)} min`}`,
592 ].join('\n')
593}
594
595/** Runs `/tokensaver <args>`: the assistant's words first, then the router's. */
596const runCommand = async ($: EngineInterface, args: string): Promise<string> => {
597 const own = await assistantCommand($, args)
598
599 if (own !== undefined) {
600 return own
601 }
602
603 const reply = await commit($, onCommand(session, args, Date.now()))
604 const word = args.trim().split(/\s+/)[0]?.toLowerCase() ?? ''
605
606 if (word === '' || word === 'status') {
607 return `${assistantReport()}\n${reply.text}`
608 }
609
610 return word === 'help' ? `${ASSISTANT_HELP}\n${reply.text}` : reply.text
611}
612
613/** Presses on Clawd's buttons, from the pane or the strip. */
614const press = ($: EngineInterface, args: string) => async (): Promise<void> => {
615 const text = await runCommand($, args)
616
617 $.ui.toast(text.split('\n')[0] ?? text)
618}
619
620export const register: Register = (on, options) => {
621 session = hydrate({
622 options,
623 storedLog: undefined,
624 storedThresholds: undefined,
625 storedSettings: undefined,
626 noColor: undefined,
627 }).session
628 assistant = createAssistant(parseAssistantOptions(options))
629 assistantOverrides = {}
630 markedRows = new Map()
631 commands = new Map()
632 isPaneOpen = false
633 wasPaneClosedByPerson = false
634
635 on('session.start', async ($, e, next) => {
636 const [storedLog, storedThresholds, storedSettings, storedDelegation, storedAssistant, storedLifetime, noColor] =
637 await Promise.all([
638 attempt(() => $.store.get(STORE_LOG), undefined),
639 attempt(() => $.store.get(STORE_THRESHOLDS), undefined),
640 attempt(() => $.store.get(STORE_SETTINGS), undefined),
641 attempt(() => $.store.get(STORE_DELEGATION), undefined),
642 attempt(() => $.store.get(STORE_ASSISTANT), undefined),
643 attempt(() => $.store.get(STORE_LIFETIME), undefined),
644 attempt(() => $.env.get('NO_COLOR'), undefined),
645 ])
646
647 assistantOverrides = parseAssistantOverrides(storedAssistant)
648 lifetime = parseLifetime(storedLifetime)
649 applyAssistantOverrides(options)
650
651 await commit(
652 $,
653 hydrate({ options, storedLog, storedThresholds, storedSettings, storedDelegation, noColor }),
654 )
655 await attempt(
656 () =>
657 $.command.register({
658 name: 'tokensaver',
659 description: 'Clawd, your token saver: status, compact, trim, on/off, dashboard, doctor',
660 argumentHint: '[compact|trim|pastes|autocompact|on|off|dry-run|dashboard|doctor|motion|export|reset|help]',
661 immediate: true,
662 }),
663 undefined,
664 )
665
666 const [model, repoFiles] = await Promise.all([
667 attempt(() => $.session.model(), undefined),
668 countFiles($),
669 ])
670
671 await commit($, onFacts(session, { model, repoFiles }))
672 await sync($, 'session start')
673
674 return next(e)
675 })
676
677 on('session.attach', async ($, e, next) => {
678 const attached = await next(e)
679
680 session = onDiagnostic(session, `${e.surface} attached`).session
681 await sync($, `${e.surface} attached`)
682
683 return attached
684 })
685
686 on('ui.close', { id: 'tokensaver' }, async (_$, e, next) => {
687 const closed = await next(e)
688
689 isPaneOpen = false
690
691 // A pane the person closed stays closed until they ask for it again.
692 if (e.origin.kind === 'person') {
693 wasPaneClosedByPerson = true
694 }
695
696 return closed
697 }).catch((_$, e, next) => next(e))
698
699 on('command.run', { command: 'tokensaver' }, async ($, e) => ({ text: await runCommand($, e.args) }))
700
701 // The same commands, declared as files in commands/ so the menu lists them before this
702 // module has run: `/tokensaver:doctor` is `/tokensaver doctor`. Answered here, they
703 // never reach the model; their file text is only what Claude reads if this hook is absent.
704 on(
705 'command.run',
706 {
707 command: [
708 'tokensaver:status',
709 'tokensaver:dashboard',
710 'tokensaver:doctor',
711 'tokensaver:on',
712 'tokensaver:off',
713 'tokensaver:dry-run',
714 'tokensaver:help',
715 'tokensaver:compact',
716 'tokensaver:trim',
717 ],
718 },
719 async ($, e) => ({ text: await runCommand($, `${e.command.slice('tokensaver:'.length)} ${e.args}`) }),
720 ).catch((_$, e, next) => next(e))
721
722 on('prompt.submit', async ($, e, next) => {
723 const kind = e.origin.kind
724 const isFromUser = kind === 'composer' || kind === 'bridge' || kind === 'sdk'
725 const model = await attempt(() => $.session.model(), undefined)
726
727 if (model !== undefined) {
728 session = onFacts(session, { model }).session
729 }
730
731 idleTimer?.cancel()
732 idleTimer = undefined
733 await sync($, 'turn start')
734
735 const tidied = await commitAssistant(
736 $,
737 onPromptText(assistant, {
738 text: e.text,
739 // A slash command's line and a hidden prompt take no rewrite of their text.
740 isFromUser: isFromUser && e.command === undefined && e.isMeta !== true,
741 isEnabled: session.config.isEnabled,
742 isDryRun: session.config.isDryRun,
743 now: Date.now(),
744 }),
745 )
746 const text = tidied.text ?? e.text
747 const reply = await commit($, onPrompt(session, { text, isFromUser, now: Date.now() }))
748 const passed = tidied.text === undefined ? e : { ...e, text }
749
750 if (tidied.text !== undefined) {
751 lifetime = { ...lifetime, eaten: lifetime.eaten + (e.text.length - text.length) / 4 }
752 void saveLifetime($)
753 }
754
755 return reply.context === undefined
756 ? next(passed)
757 : next({ ...passed, context: [...(passed.context ?? []), reply.context] })
758 }).catch((_$, e, next) => next(e))
759
760 // The output trimmer: a shell's result is shrunk before it is stored, so the
761 // model reads (and every later request re-sends) the tidy form only.
762 // Claude's own tool calls arrive as response rows just before their results: note each shell command.
763 on('session.append', { door: 'response' }, (_$, e, next) => {
764 for (const block of e.message.content) {
765 const input = block['input']
766 const command = isRecord(input) ? input['command'] : undefined
767
768 if (block.type === 'tool_use' && typeof block['id'] === 'string' && typeof command === 'string') {
769 commands.set(block['id'], command)
770 }
771 }
772
773 if (commands.size > MAX_MARKED_ROWS) {
774 commands = new Map([...commands].slice(-MAX_MARKED_ROWS))
775 }
776
777 return next(e)
778 }).catch((_$, e, next) => next(e))
779
780 on('session.append', { door: 'tool-result' }, async ($, e, next) => {
781 const tool = e.origin.kind === 'tool' ? e.origin.tool : ''
782 let cutTotal = 0
783 const content = e.message.content.map(block => {
784 if (block.type !== 'tool_result' || block['is_error'] === true) {
785 return block
786 }
787
788 const text = resultText(block)
789
790 if (text === undefined) {
791 return block
792 }
793
794 const callId = block['tool_use_id']
795 const step = onToolOutput(assistant, {
796 tool,
797 command: typeof callId === 'string' ? commands.get(callId) : undefined,
798 text,
799 isEnabled: session.config.isEnabled,
800 isDryRun: session.config.isDryRun,
801 now: Date.now(),
802 })
803
804 assistant = step.assistant
805
806 if (step.reply.text === undefined) {
807 return block
808 }
809
810 const cut = Math.round((text.length - step.reply.text.length) / 4)
811 const id = block['tool_use_id']
812
813 if (typeof id === 'string') {
814 markedRows.set(id, cut)
815
816 if (markedRows.size > MAX_MARKED_ROWS) {
817 markedRows = new Map([...markedRows].slice(-MAX_MARKED_ROWS))
818 }
819 }
820
821 cutTotal += cut
822
823 return { ...block, content: step.reply.text }
824 })
825
826 if (content.every((block, index) => block === e.message.content[index])) {
827 return next(e)
828 }
829
830 lifetime = { ...lifetime, eaten: lifetime.eaten + cutTotal }
831 void saveLifetime($)
832 refresh($)
833
834 return next({ ...e, message: { ...e.message, content } })
835 }).catch((_$, e, next) => next(e))
836
837 on('session.compact', async ($, e, next) => {
838 const result = await next(e)
839
840 // The main conversation's own compactions, whoever asked; Clawd's own calls book theirs.
841 if (e.agentId === undefined && e.trigger !== 'precompute' && e.trigger !== 'plugin') {
842 assistant = onCompacted(assistant, {
843 before: result.skip === undefined ? result.tokensBefore : undefined,
844 after: result.skip === undefined ? result.tokensAfter : undefined,
845 isSkipped: result.skip !== undefined,
846 now: Date.now(),
847 })
848
849 if (result.skip === undefined) {
850 lifetime = { ...lifetime, freed: lifetime.freed + Math.max(0, (result.tokensBefore ?? 0) - (result.tokensAfter ?? 0)) }
851 void saveLifetime($)
852 }
853
854 refresh($)
855 }
856
857 return result
858 }).catch((_$, e, next) => next(e))
859
860 let unnamed = 0
861
862 on('agent.spawn', async ($, e, next) => {
863 unnamed += 1
864
865 const toolUseId = e.tool_use_id === '' ? `spawn-${String(unnamed)}` : e.tool_use_id
866 const reply = await commit(
867 $,
868 onSpawn(session, {
869 toolUseId,
870 prompt: e.prompt,
871 description: e.description,
872 subagentType: e.subagentType,
873 explicitModel: e.model,
874 parentModel: e.parentModel,
875 parentAgentId: e.parentAgentId,
876 isBackground: e.background,
877 isPinned: e.fork || e.isTeammate === true || e.workflow !== undefined,
878 now: Date.now(),
879 }),
880 )
881 const started = await next(reply.model === undefined ? e : { ...e, model: reply.model })
882
883 await commit(
884 $,
885 onSpawned(session, {
886 toolUseId,
887 agentId: started.agentId,
888 isDenied: started.deny !== undefined,
889 resolvedModel: started.model,
890 }),
891 )
892
893 return started
894 }).catch((_$, e, next) => next(e))
895
896 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
897 const first = await next(e)
898 const reply = await commit($, onAgentResult(session, resultOf(e.tool_use_id, first)))
899
900 // A denied call, a passing result and a dry run all come back with nothing to retry.
901 if (reply.retryWith === undefined) {
902 return first
903 }
904
905 const second = await next({ ...e, model: reply.retryWith })
906
907 await commit($, onAgentResult(session, resultOf(e.tool_use_id, second)))
908
909 return second
910 }).catch((_$, e, next) => next(e))
911
912 on('turn.step', async function* ($, e, next) {
913 const result = yield* next(e)
914
915 if (e.agentId === undefined) {
916 assistant = onMainRequest(assistant)
917 }
918
919 if (result.usage !== null) {
920 await commit(
921 $,
922 onStepUsage(session, {
923 turnId: e.turnId,
924 agentId: e.agentId,
925 usage: usageOf(result.usage),
926 reads: result.toolUses.filter(use => READING_TOOLS.includes(use.name)).length,
927 }),
928 )
929 }
930
931 return result
932 })
933
934 on('turn.complete', async ($, e, next) => {
935 if (e.agentId === undefined) {
936 assistant = onTurnEnd(assistant, Date.now())
937 armIdleCheck($)
938 }
939
940 await commit(
941 $,
942 onTurnComplete(session, {
943 turnId: e.turnId,
944 agentId: e.agentId,
945 usage: e.usage === undefined ? undefined : usageOf(e.usage),
946 isFailed: e.reason === 'error' || e.reason === 'refusal',
947 isAborted: e.isAborted,
948 answer: e.answer,
949 now: Date.now(),
950 }),
951 )
952
953 return next(e)
954 }).catch((_$, e, next) => next(e))
955
956 on('session.measure', async ($, e, next) => {
957 await commit($, onMeasure(session, { tokens: e.context.tokens, window: e.context.window }))
958 await commitAssistant(
959 $,
960 onContext(assistant, {
961 tokens: e.context.tokens,
962 window: e.context.window,
963 isEnabled: session.config.isEnabled,
964 now: Date.now(),
965 }),
966 )
967
968 return next(e)
969 }).catch((_$, e, next) => next(e))
970
971 // --- Drawing ---------------------------------------------------------------
972
973 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
974 // Reading the revision subscribes the strip to every later change.
975 await read($, revision)
976
977 const view = clawdView()
978 const routing = toView(session)
979 const hasAgents = isBandVisible(routing) && routing.band.agents.length > 0
980 const shouldOffer = view.mood === 'sleepy' || (view.mood === 'worried' && view.context.percent >= 70)
981 const isVisible =
982 view.mode !== 'off' &&
983 (hasFlare(assistant, Date.now()) || shouldOffer || hasAgents || (isBandVisible(routing) && routing.band.flash !== undefined))
984
985 if (!isVisible || e.props.hasSurvey) {
986 return next(e)
987 }
988
989 const { Box, Text, Button } = $.ui.resolve(e)
990 // Whatever another mod draws in the strip stays, beneath tokensaver's.
991 const beneath = await next(e)
992 const buttons = shouldOffer ? (
993 <Box gap={1}>
994 <Button key="band-compact" variant="primary" label="Compact now" onPress={press($, 'compact')} />
995 </Box>
996 ) : null
997
998 if (e.surface === 'desktop') {
999 const { Svg } = $.ui.resolve({ ...e, surface: 'desktop' as const })
1000 const width = Math.round(Math.max(40, e.props.bodyColumns) * CELL_PX)
1001
1002 return (
1003 <Box flexDirection="column">
1004 <Box gap={1} alignItems="center">
1005 <Svg source={bandSvgOf(view, shouldOffer ? width - 130 : width)} alt={view.speech} width={shouldOffer ? width - 130 : width} height={46} />
1006 {buttons}
1007 </Box>
1008 {hasAgents ? (
1009 <Svg source={bandSvg(routing, width)} alt={`${String(routing.activeCount)} helpers running`} width={width} height={BAND_HEIGHT} />
1010 ) : null}
1011 {beneath}
1012 </Box>
1013 )
1014 }
1015
1016 return (
1017 <Box flexDirection="column">
1018 <Box gap={1}>
1019 <Box>
1020 {bandLineOf(view, e.props.bodyColumns - (shouldOffer ? 16 : 0)).map(part => (
1021 <Text {...styleOf(part)}>{part.text}</Text>
1022 ))}
1023 </Box>
1024 {buttons}
1025 </Box>
1026 {beneath}
1027 </Box>
1028 )
1029 })
1030
1031 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
1032 await read($, revision)
1033
1034 const suffix = spinnerSuffix(toView(session))
1035
1036 return suffix === undefined
1037 ? next(e)
1038 : next({ ...e, props: { ...e.props, suffix: `${e.props.suffix}${suffix}` } })
1039 })
1040
1041 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
1042 // A shell row Clawd trimmed says so, and by how much.
1043 if (e.props.tool !== 'Agent') {
1044 const cut = markedRows.get(e.props.tool_use_id)
1045
1046 if (cut === undefined) {
1047 return next(e)
1048 }
1049
1050 const { Box, Text } = $.ui.resolve(e)
1051 const row = await next(e)
1052
1053 return (
1054 <Box flexDirection="column">
1055 {row}
1056 <Text {...tint(!session.hasNoColor, 'success')} dimColor>
1057 {` ▐▛█▜▌ Clawd ate ${formatTokens(cut)} tokens of noise from this output`}
1058 </Text>
1059 </Box>
1060 )
1061 }
1062
1063 // Only a running call is kept in step: its model is decided just after its row appears.
1064 if (e.props.isRunning) {
1065 await read($, revision)
1066 }
1067
1068 const badge = routedBadge(toView(session), e.props.tool_use_id)
1069 const row = await next(e)
1070
1071 if (badge === undefined) {
1072 return row
1073 }
1074
1075 const { Box, Text } = $.ui.resolve(e)
1076
1077 return (
1078 <Box flexDirection="column">
1079 <Box>
1080 {badge.map(part => (
1081 <Text {...styleOf(part)}>{part.text}</Text>
1082 ))}
1083 </Box>
1084 {row}
1085 </Box>
1086 )
1087 })
1088
1089 on('ui.render', { component: 'Pane', requestId: 'tokensaver' }, async ($, e) => {
1090 await read($, revision)
1091 isPaneOpen = true
1092
1093 const { Box, Text, Button } = $.ui.resolve(e)
1094 const view = clawdView()
1095 const columns = e.props.bodyColumns
1096 const isOff = view.mode === 'off'
1097 const feed = [...view.feed].reverse().slice(0, 6)
1098 const ago = (at: number): string => {
1099 const seconds = Math.max(0, Math.round((Date.now() - at) / 1000))
1100
1101 return seconds < 60 ? `${String(seconds)}s` : `${String(Math.round(seconds / 60))}m`
1102 }
1103 const controls = (
1104 <Box gap={1} flexWrap="wrap">
1105 <Button key="compact" variant="primary" label="Compact now" onPress={press($, 'compact')} />
1106 <Button
1107 key="trim"
1108 label={assistant.config.isTrimming ? 'Trimming: on' : 'Trimming: off'}
1109 onPress={press($, 'trim')}
1110 />
1111 <Button
1112 key="pastes"
1113 label={assistant.config.isTrimmingPastes ? 'Paste tidy: on' : 'Paste tidy: off'}
1114 onPress={press($, 'pastes')}
1115 />
1116 <Button key="power" label={isOff ? 'Wake Clawd' : 'Turn off'} onPress={press($, isOff ? 'on' : 'off')} />
1117 </Box>
1118 )
1119
1120 if (e.surface === 'desktop') {
1121 const { Svg } = $.ui.resolve({ ...e, surface: 'desktop' as const })
1122 const width = Math.round(Math.max(44, columns) * CELL_PX)
1123
1124 return (
1125 <Box flexDirection="column" gap={1}>
1126 <Svg source={heroSvg(view, width)} alt={`Clawd: ${view.speech}`} width={width} />
1127 <Svg
1128 source={tilesSvg(view, width)}
1129 alt={`${formatTokens(view.stats.eaten)} tokens eaten, ${formatTokens(view.stats.reReads)} re-sends avoided, ${formatTokens(view.stats.compactFreed)} freed by compacting`}
1130 width={width}
1131 />
1132 {controls}
1133 <Text weight="semibold">Activity</Text>
1134 {feed.length === 0 ? (
1135 <Text dimColor>Nothing yet. Run something noisy (a build, a test suite, an install) and watch me eat.</Text>
1136 ) : (
1137 feed.map(item => (
1138 <Box gap={1}>
1139 <Text {...tint(view.hasColor, (item.kind === 'warn' ? 'warning' : item.kind === 'escalate' ? 'error' : 'success'))}>
1140 {item.kind === 'trim' || item.kind === 'paste' ? '✂' : item.kind === 'compact' ? '⇣' : item.kind === 'cold' ? '❄' : item.kind === 'warn' ? '▲' : '•'}
1141 </Text>
1142 <Text>{item.text}</Text>
1143 <Text dimColor>{ago(item.at)}</Text>
1144 </Box>
1145 ))
1146 )}
1147 <Text dimColor>
1148 {`All-time: ${formatTokens(lifetime.eaten)} eaten · ${formatTokens(lifetime.freed)} freed by compacting`}
1149 </Text>
1150 </Box>
1151 )
1152 }
1153
1154 const art = clawdArt(view)
1155 const bubble = bubbleRows(view, columns)
1156 const meter = view.context.window > 0
1157 ? `${bar(view.context.percent / 100, Math.max(10, columns - 30))} ${String(view.context.percent)}% ${formatTokens(view.context.tokens)}/${formatTokens(view.context.window)}`
1158 : 'context: waiting for the first reply'
1159
1160 return (
1161 <Box flexDirection="column">
1162 {art.map((row, index) => (
1163 <Box>
1164 <Text {...tint(view.hasColor, (view.mood === 'off' ? 'inactive' : 'claude'))}>{row}</Text>
1165 <Text>{` ${bubble[index] ?? ''}`}</Text>
1166 </Box>
1167 ))}
1168 <Text> </Text>
1169 <Text weight="semibold">Context</Text>
1170 <Text {...tint(view.hasColor, (view.context.percent >= 85 ? 'error' : view.context.percent >= 70 ? 'warning' : 'claude'))}>{meter}</Text>
1171 {view.ghost > 0 ? <Text dimColor>{`without Clawd it would hold ${formatTokens(view.ghost)} more`}</Text> : null}
1172 <Text> </Text>
1173 <Text>
1174 <Text {...tint(view.hasColor, 'success')} weight="semibold">{formatTokens(view.stats.eaten)}</Text>
1175 <Text dimColor> eaten </Text>
1176 <Text {...tint(view.hasColor, 'suggestion')} weight="semibold">{formatTokens(view.stats.reReads)}</Text>
1177 <Text dimColor> re-sends avoided </Text>
1178 <Text {...tint(view.hasColor, 'claude')} weight="semibold">{formatTokens(view.stats.compactFreed)}</Text>
1179 <Text dimColor> freed </Text>
1180 <Text {...tint(view.hasColor, 'warning')} weight="semibold">{formatTokens(view.stats.routed + view.stats.keptOut)}</Text>
1181 <Text dimColor> routing</Text>
1182 </Text>
1183 <Text> </Text>
1184 {controls}
1185 <Text> </Text>
1186 <Text weight="semibold">Activity</Text>
1187 {feed.length === 0 ? (
1188 <Text dimColor>Nothing yet.</Text>
1189 ) : (
1190 feed.map(item => <Text>{`${item.kind === 'warn' ? '▲' : item.kind === 'cold' ? '❄' : item.kind === 'compact' ? '⇣' : '✂'} ${item.text} ${ago(item.at)}`}</Text>)
1191 )}
1192 </Box>
1193 )
1194 })
1195}
1196src/core/log.ts 177 lines1import { isCheckSignal } from './escalate.ts'
2import type { CheckSignal } from './escalate.ts'
3import { DEFAULT_THRESHOLDS } from './route.ts'
4import type { Cutoffs, Thresholds } from './route.ts'
5import { TASK_TYPES, isTaskType } from './score.ts'
6import type { TaskType } from './score.ts'
7import { TIERS, isTier } from './tiers.ts'
8import type { Tier } from './tiers.ts'
9
10/** One finished delegation, as the local outcome log keeps it. No prompt text is stored. */
11export type Outcome = {
12 seq: number
13 at: number
14 taskType: TaskType
15 tier: Tier
16 tokens: number
17 retries: number
18 wasEscalated: boolean
19 isSuccess: boolean
20 signal: CheckSignal
21}
22
23/** The log is capped so it stays far below the store's size limit. */
24export const MAX_OUTCOMES = 500
25
26export const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
27 typeof value === 'object' && value !== null && !Array.isArray(value)
28
29const isCount = (value: unknown): value is number =>
30 typeof value === 'number' && Number.isFinite(value) && value >= 0
31
32/** Reads one stored entry, or undefined when it is not a well-formed outcome. */
33export const parseOutcome = (value: unknown): Outcome | undefined => {
34 if (!isRecord(value)) {
35 return undefined
36 }
37
38 const { seq, at, taskType, tier, tokens, retries, wasEscalated, isSuccess, signal } = value
39
40 if (
41 !isCount(seq) ||
42 !isCount(at) ||
43 !isTaskType(taskType) ||
44 !isTier(tier) ||
45 !isCount(tokens) ||
46 !isCount(retries) ||
47 typeof wasEscalated !== 'boolean' ||
48 typeof isSuccess !== 'boolean' ||
49 !isCheckSignal(signal)
50 ) {
51 return undefined
52 }
53
54 return { seq, at, taskType, tier, tokens, retries, wasEscalated, isSuccess, signal }
55}
56
57export type ParsedLog = {
58 outcomes: readonly Outcome[]
59 /** Entries that were present but unreadable, including a log that was not a list at all. */
60 dropped: number
61}
62
63/**
64 * Reads the stored log defensively. A missing log is empty; a corrupted one
65 * keeps every entry that still parses and counts the rest as dropped.
66 */
67export const parseLog = (value: unknown): ParsedLog => {
68 if (value === undefined || value === null) {
69 return { outcomes: [], dropped: 0 }
70 }
71
72 if (!Array.isArray(value)) {
73 return { outcomes: [], dropped: 1 }
74 }
75
76 const entries: readonly unknown[] = value
77 const outcomes = entries
78 .map(parseOutcome)
79 .filter(outcome => outcome !== undefined)
80 .slice(-MAX_OUTCOMES)
81
82 return { outcomes, dropped: entries.length - outcomes.length }
83}
84
85export const nextSeq = (outcomes: readonly Outcome[]): number =>
86 outcomes.reduce((highest, outcome) => Math.max(highest, outcome.seq), 0) + 1
87
88export const appendOutcome = (outcomes: readonly Outcome[], outcome: Outcome): readonly Outcome[] =>
89 [...outcomes, outcome].slice(-MAX_OUTCOMES)
90
91/** A clean outcome is the only evidence that counts toward loosening a rule. */
92export const isCleanSuccess = (outcome: Outcome): boolean =>
93 outcome.isSuccess && !outcome.wasEscalated && outcome.retries === 0
94
95const clampCutoff = (value: unknown, fallback: number): number =>
96 typeof value === 'number' && Number.isFinite(value)
97 ? Math.min(100, Math.max(0, Math.round(value)))
98 : fallback
99
100const parseCutoffs = (value: unknown, fallback: Cutoffs): Cutoffs => {
101 if (!isRecord(value)) {
102 return fallback
103 }
104
105 const haikuMax = clampCutoff(value['haikuMax'], fallback.haikuMax)
106 const sonnetMax = Math.max(haikuMax, clampCutoff(value['sonnetMax'], fallback.sonnetMax))
107 const tunedAtSeq = isCount(value['tunedAtSeq']) ? value['tunedAtSeq'] : 0
108
109 return { haikuMax, sonnetMax, tunedAtSeq }
110}
111
112/** Reads stored thresholds, falling back to the default for anything missing or malformed. */
113export const parseThresholds = (value: unknown): Thresholds => {
114 const stored = isRecord(value) ? value : {}
115
116 return {
117 search: parseCutoffs(stored['search'], DEFAULT_THRESHOLDS.search),
118 'bulk-read': parseCutoffs(stored['bulk-read'], DEFAULT_THRESHOLDS['bulk-read']),
119 'repetitive-edit': parseCutoffs(
120 stored['repetitive-edit'],
121 DEFAULT_THRESHOLDS['repetitive-edit'],
122 ),
123 summarize: parseCutoffs(stored['summarize'], DEFAULT_THRESHOLDS.summarize),
124 edit: parseCutoffs(stored['edit'], DEFAULT_THRESHOLDS.edit),
125 reasoning: parseCutoffs(stored['reasoning'], DEFAULT_THRESHOLDS.reasoning),
126 general: parseCutoffs(stored['general'], DEFAULT_THRESHOLDS.general),
127 }
128}
129
130export type LogSummary = {
131 count: number
132 cleanRate: number
133 escalations: number
134 failures: number
135 byTier: Readonly<Record<Tier, number>>
136}
137
138export const summarizeLog = (outcomes: readonly Outcome[]): LogSummary => {
139 const clean = outcomes.filter(isCleanSuccess).length
140 const countAt = (tier: Tier): number => outcomes.filter(outcome => outcome.tier === tier).length
141
142 return {
143 count: outcomes.length,
144 cleanRate: outcomes.length === 0 ? 1 : clean / outcomes.length,
145 escalations: outcomes.filter(outcome => outcome.wasEscalated).length,
146 failures: outcomes.filter(outcome => !outcome.isSuccess).length,
147 byTier: { haiku: countAt('haiku'), sonnet: countAt('sonnet'), opus: countAt('opus') },
148 }
149}
150
151export type ExportBundle = {
152 format: 'tokensaver-export'
153 version: 1
154 exportedAt: number
155 taskTypes: readonly TaskType[]
156 tiers: readonly Tier[]
157 thresholds: Thresholds
158 summary: LogSummary
159 outcomes: readonly Outcome[]
160}
161
162/** Everything `/tokensaver export` writes: the log, the tuned thresholds and a summary. */
163export const buildExport = (
164 outcomes: readonly Outcome[],
165 thresholds: Thresholds,
166 exportedAt: number,
167): ExportBundle => ({
168 format: 'tokensaver-export',
169 version: 1,
170 exportedAt,
171 taskTypes: TASK_TYPES,
172 tiers: TIERS,
173 thresholds,
174 summary: summarizeLog(outcomes),
175 outcomes,
176})
177src/runtime/assistant.ts 526 lines1/**
2 * Clawd, the assistant: the savers that act on their own (the output and
3 * paste trimmers, the context guardian, the cold-cache coach) and the mood
4 * and words the mascot shows for them. Pure transitions, like session.ts:
5 * `(assistant, input) -> { assistant, effects, reply }`.
6 */
7import { formatTokens } from '../ui/format.ts'
8import {
9 afterCompact,
10 coldCost,
11 compactInstructions,
12 compactSaving,
13 isCacheCold,
14 levelOf,
15 MIN_WORTHWHILE_TOKENS,
16 percentOf,
17 rankOfLevel,
18} from '../core/guardian.ts'
19import type { GuardLevel } from '../core/guardian.ts'
20import { ACTION_WORDS, isInspecting, looksLikeLog, trimOutput } from '../core/trim.ts'
21import type { TrimLevel } from '../core/trim.ts'
22import { isRecord } from '../core/log.ts'
23
24export type AssistantConfig = {
25 isTrimming: boolean
26 trimLevel: TrimLevel
27 maxOutputLines: number
28 isTrimmingPastes: boolean
29 /** Fill percentage at which Clawd compacts between turns by itself; 0 is never. */
30 autoCompactAt: number
31 /** How long the prompt cache lives, in minutes; 0 turns the cold-cache coach off. */
32 cacheTtlMinutes: number
33}
34
35export const DEFAULT_ASSISTANT: AssistantConfig = {
36 isTrimming: true,
37 trimLevel: 'full',
38 maxOutputLines: 300,
39 isTrimmingPastes: true,
40 autoCompactAt: 0,
41 cacheTtlMinutes: 5,
42}
43
44/** The tools whose output the trimmer may shrink: shells and their background output, never file reads. */
45export const TRIMMED_TOOLS: readonly string[] = ['Bash', 'PowerShell', 'BashOutput', 'TaskOutput', 'Monitor']
46
47export type Mood = 'idle' | 'chomp' | 'happy' | 'worried' | 'sleepy' | 'busy' | 'alert' | 'off'
48
49export type FeedKind = 'trim' | 'paste' | 'compact' | 'cold' | 'warn' | 'route' | 'escalate' | 'info'
50
51export type FeedItem = { at: number; kind: FeedKind; text: string; tokens: number }
52
53export type Assistant = {
54 config: AssistantConfig
55 /** Outputs trimmed, and the tokens cut from them. */
56 trims: number
57 trimmed: number
58 /** Tokens cut since the last compaction: still absent from every request that follows. */
59 live: number
60 /** Re-sends avoided: `live` summed over every main-loop request since it was cut. */
61 reReads: number
62 pastes: number
63 pasteTrimmed: number
64 compactions: number
65 /** Tokens compactions took off the context. */
66 compactFreed: number
67 context: { tokens: number; window: number }
68 isTurnRunning: boolean
69 lastTurnEndAt: number | undefined
70 warnedLevel: GuardLevel
71 isCold: boolean
72 isCompacting: boolean
73 feed: readonly FeedItem[]
74 /** A passing mood (chomping, cheering) and when it ends. */
75 flare: { mood: Mood; until: number; text: string } | undefined
76 prompts: readonly string[]
77}
78
79export type AssistantEffect =
80 | { kind: 'toast'; text: string }
81 | { kind: 'compact'; instructions: string }
82 | { kind: 'save-assistant' }
83
84export type AssistantStep<Reply> = {
85 assistant: Assistant
86 effects: readonly AssistantEffect[]
87 reply: Reply
88}
89
90const MAX_FEED = 12
91const MAX_PROMPTS = 6
92const FLARE_MS = 5000
93
94const still = <Reply>(assistant: Assistant, reply: Reply): AssistantStep<Reply> => ({
95 assistant,
96 effects: [],
97 reply,
98})
99
100const number = (value: unknown, preset: number, min: number, max: number): number =>
101 typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : preset
102
103const flag = (value: unknown, isOnByDefault: boolean): boolean => (typeof value === 'boolean' ? value : isOnByDefault)
104
105/** Reads the manifest's options for the savers. */
106export const parseAssistantOptions = (options: Readonly<Record<string, unknown>>): AssistantConfig => ({
107 isTrimming: flag(options['trimOutput'], DEFAULT_ASSISTANT.isTrimming),
108 trimLevel: options['trimLevel'] === 'lossless' ? 'lossless' : 'full',
109 maxOutputLines: number(options['maxOutputLines'], DEFAULT_ASSISTANT.maxOutputLines, 40, 5000),
110 isTrimmingPastes: flag(options['trimPastes'], DEFAULT_ASSISTANT.isTrimmingPastes),
111 autoCompactAt: number(options['autoCompactAt'], DEFAULT_ASSISTANT.autoCompactAt, 0, 95),
112 cacheTtlMinutes: number(options['cacheTtlMinutes'], DEFAULT_ASSISTANT.cacheTtlMinutes, 0, 120),
113})
114
115export type AssistantOverrides = Partial<Pick<AssistantConfig, 'isTrimming' | 'isTrimmingPastes' | 'autoCompactAt'>>
116
117export const parseAssistantOverrides = (value: unknown): AssistantOverrides => {
118 if (!isRecord(value)) {
119 return {}
120 }
121
122 const { isTrimming, isTrimmingPastes, autoCompactAt } = value
123
124 return {
125 ...(typeof isTrimming === 'boolean' ? { isTrimming } : {}),
126 ...(typeof isTrimmingPastes === 'boolean' ? { isTrimmingPastes } : {}),
127 ...(typeof autoCompactAt === 'number' ? { autoCompactAt: number(autoCompactAt, 0, 0, 95) } : {}),
128 }
129}
130
131export const createAssistant = (config: AssistantConfig): Assistant => ({
132 config,
133 trims: 0,
134 trimmed: 0,
135 live: 0,
136 reReads: 0,
137 pastes: 0,
138 pasteTrimmed: 0,
139 compactions: 0,
140 compactFreed: 0,
141 context: { tokens: 0, window: 0 },
142 isTurnRunning: false,
143 lastTurnEndAt: undefined,
144 warnedLevel: 'calm',
145 isCold: false,
146 isCompacting: false,
147 feed: [],
148 flare: undefined,
149 prompts: [],
150})
151
152const withFeed = (assistant: Assistant, item: FeedItem): Assistant => ({
153 ...assistant,
154 feed: [...assistant.feed, item].slice(-MAX_FEED),
155})
156
157const withFlare = (assistant: Assistant, mood: Mood, text: string, now: number): Assistant => ({
158 ...assistant,
159 flare: { mood, text, until: now + FLARE_MS },
160})
161
162/** Records something the routing side did, so it shows in Clawd's feed. */
163export const noteEvent = (
164 assistant: Assistant,
165 input: { kind: FeedKind; text: string; tokens?: number; now: number },
166): Assistant => {
167 const mood: Mood = input.kind === 'escalate' ? 'alert' : 'happy'
168
169 return withFlare(
170 withFeed(assistant, { at: input.now, kind: input.kind, text: input.text, tokens: input.tokens ?? 0 }),
171 mood,
172 input.text,
173 input.now,
174 )
175}
176
177const listOf = (words: readonly string[]): string =>
178 words.length <= 1 ? (words[0] ?? '') : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1] ?? ''}`
179
180/**
181 * A shell's output is about to be stored: trims it when that saves enough.
182 * Answers the text to store instead, or undefined to store it as it came.
183 */
184export const onToolOutput = (
185 assistant: Assistant,
186 input: {
187 tool: string
188 /** The shell command that produced the output, when known. */
189 command?: string | undefined
190 text: string
191 isEnabled: boolean
192 isDryRun: boolean
193 now: number
194 },
195): AssistantStep<{ text: string | undefined }> => {
196 if (!input.isEnabled || !assistant.config.isTrimming || !TRIMMED_TOOLS.includes(input.tool)) {
197 return still(assistant, { text: undefined })
198 }
199
200 // A search or a listing printed what was asked for: nothing is folded or cut from it.
201 const isAsked = isInspecting(input.command)
202 const result = trimOutput(input.text, {
203 level: isAsked ? 'lossless' : assistant.config.trimLevel,
204 maxLines: isAsked ? Number.MAX_SAFE_INTEGER : assistant.config.maxOutputLines,
205 })
206 const cut = result.beforeTokens - result.afterTokens
207
208 if (result.actions.length === 0) {
209 return still(assistant, { text: undefined })
210 }
211
212 const what = listOf(result.actions.map(action => ACTION_WORDS[action]))
213
214 if (input.isDryRun) {
215 return still(
216 withFeed(assistant, {
217 at: input.now,
218 kind: 'info',
219 text: `dry-run: would trim ${formatTokens(cut)} from ${input.tool} output (${what})`,
220 tokens: 0,
221 }),
222 { text: undefined },
223 )
224 }
225
226 const text = `Ate ${formatTokens(cut)} tokens of ${input.tool} noise: ${what}`
227
228 return still(
229 withFlare(
230 withFeed(
231 {
232 ...assistant,
233 trims: assistant.trims + 1,
234 trimmed: assistant.trimmed + cut,
235 live: assistant.live + cut,
236 },
237 { at: input.now, kind: 'trim', text, tokens: cut },
238 ),
239 'chomp',
240 text,
241 input.now,
242 ),
243 { text: result.text },
244 )
245}
246
247/**
248 * A prompt the person typed: remembers it for compaction instructions, wakes
249 * Clawd, and cleans a pasted log in it, losslessly. Prose is never touched.
250 */
251export const onPromptText = (
252 assistant: Assistant,
253 input: { text: string; isFromUser: boolean; isEnabled: boolean; isDryRun: boolean; now: number },
254): AssistantStep<{ text: string | undefined }> => {
255 const woken: Assistant = {
256 ...assistant,
257 isTurnRunning: true,
258 isCold: false,
259 prompts: input.isFromUser ? [...assistant.prompts, input.text].slice(-MAX_PROMPTS) : assistant.prompts,
260 }
261
262 if (
263 !input.isEnabled ||
264 !input.isFromUser ||
265 input.isDryRun ||
266 !assistant.config.isTrimmingPastes ||
267 !looksLikeLog(input.text)
268 ) {
269 return still(woken, { text: undefined })
270 }
271
272 const result = trimOutput(input.text, { level: 'lossless', maxLines: Number.MAX_SAFE_INTEGER })
273 const cut = result.beforeTokens - result.afterTokens
274
275 if (result.actions.length === 0) {
276 return still(woken, { text: undefined })
277 }
278
279 const text = `Tidied your pasted log: −${formatTokens(cut)} tokens (${listOf(result.actions.map(action => ACTION_WORDS[action]))})`
280
281 return {
282 assistant: withFlare(
283 withFeed(
284 {
285 ...woken,
286 pastes: woken.pastes + 1,
287 pasteTrimmed: woken.pasteTrimmed + cut,
288 live: woken.live + cut,
289 },
290 { at: input.now, kind: 'paste', text, tokens: cut },
291 ),
292 'chomp',
293 text,
294 input.now,
295 ),
296 effects: [{ kind: 'toast', text: `Clawd: ${text}` }],
297 reply: { text: result.text },
298 }
299}
300
301/** One main-loop model request: everything trimmed so far was not re-sent with it. */
302export const onMainRequest = (assistant: Assistant): Assistant => ({
303 ...assistant,
304 reReads: assistant.reReads + assistant.live,
305})
306
307export const onTurnEnd = (assistant: Assistant, now: number): Assistant => ({
308 ...assistant,
309 isTurnRunning: false,
310 lastTurnEndAt: now,
311})
312
313export const fillOf = (assistant: Assistant): number =>
314 percentOf(assistant.context.tokens, assistant.context.window)
315
316/**
317 * The window was measured. Crossing into a fuller level says so once; past
318 * the auto-compact mark, between turns, Clawd compacts by itself.
319 */
320export const onContext = (
321 assistant: Assistant,
322 input: { tokens: number | undefined; window: number; isEnabled: boolean; now: number },
323): AssistantStep<undefined> => {
324 const measured: Assistant = {
325 ...assistant,
326 context: { tokens: input.tokens ?? assistant.context.tokens, window: input.window },
327 }
328 const percent = fillOf(measured)
329 const level = levelOf(percent)
330
331 if (!input.isEnabled) {
332 return still(measured, undefined)
333 }
334
335 // Emptier than warned (a compaction, a /clear): ready to warn again.
336 if (rankOfLevel(level) < rankOfLevel(measured.warnedLevel)) {
337 return still({ ...measured, warnedLevel: level }, undefined)
338 }
339
340 const effects: AssistantEffect[] = []
341 let next = measured
342
343 if (rankOfLevel(level) > rankOfLevel(measured.warnedLevel) && level !== 'filling') {
344 const saving = compactSaving(measured.context.tokens)
345 const text =
346 level === 'critical'
347 ? `Context at ${String(percent)}%: compact now, before Claude Code does it mid-task. Every request carries ${formatTokens(measured.context.tokens)} tokens.`
348 : `Context at ${String(percent)}%. Compacting would take ~${formatTokens(saving)} tokens off every request.`
349
350 next = withFlare(
351 withFeed({ ...next, warnedLevel: level }, { at: input.now, kind: 'warn', text, tokens: 0 }),
352 'worried',
353 text,
354 input.now,
355 )
356 effects.push({ kind: 'toast', text: `Clawd: ${text}` })
357 } else if (level === 'filling' && measured.warnedLevel === 'calm') {
358 next = { ...next, warnedLevel: level }
359 }
360
361 const autoAt = next.config.autoCompactAt
362
363 if (
364 autoAt > 0 &&
365 percent >= autoAt &&
366 !next.isTurnRunning &&
367 !next.isCompacting &&
368 next.context.tokens >= MIN_WORTHWHILE_TOKENS
369 ) {
370 next = { ...next, isCompacting: true }
371 effects.push({ kind: 'compact', instructions: compactInstructions(next.prompts) })
372 }
373
374 return { assistant: next, effects, reply: undefined }
375}
376
377/** The clock checked the idle session: a cache past its life makes the next message expensive. */
378export const onIdleCheck = (assistant: Assistant, input: { now: number; isEnabled: boolean }): Assistant => {
379 if (!input.isEnabled || assistant.isCold || assistant.lastTurnEndAt === undefined) {
380 return assistant
381 }
382
383 const isCold = isCacheCold({
384 idleMs: input.now - assistant.lastTurnEndAt,
385 ttlMs: assistant.config.cacheTtlMinutes * 60_000,
386 tokens: assistant.context.tokens,
387 isTurnRunning: assistant.isTurnRunning,
388 })
389
390 if (!isCold) {
391 return assistant
392 }
393
394 const cost = coldCost(assistant.context.tokens)
395
396 return withFeed(
397 { ...assistant, isCold: true },
398 {
399 at: input.now,
400 kind: 'cold',
401 text: `Cache went cold. Next message re-writes ~${formatTokens(cost.now)} tokens; after a compact, ~${formatTokens(cost.compacted)}.`,
402 tokens: 0,
403 },
404 )
405}
406
407/** Asked to compact (a button, a command): the instructions to send, or why not. */
408export const requestCompact = (
409 assistant: Assistant,
410): AssistantStep<{ instructions: string | undefined; why: string | undefined }> => {
411 if (assistant.isTurnRunning) {
412 return still(assistant, { instructions: undefined, why: 'Claude is mid-turn; compact when it finishes.' })
413 }
414
415 if (assistant.isCompacting) {
416 return still(assistant, { instructions: undefined, why: 'Already compacting.' })
417 }
418
419 return still({ ...assistant, isCompacting: true }, {
420 instructions: compactInstructions(assistant.prompts),
421 why: undefined,
422 })
423}
424
425/** A compaction ended, whoever started it. */
426export const onCompacted = (
427 assistant: Assistant,
428 input: { before: number | undefined; after: number | undefined; isSkipped: boolean; now: number },
429): Assistant => {
430 if (input.isSkipped) {
431 return { ...assistant, isCompacting: false }
432 }
433
434 const before = input.before ?? assistant.context.tokens
435 const after = input.after ?? afterCompact(before)
436 const freed = Math.max(0, before - after)
437 const text = `Compacted: ${formatTokens(before)} → ${formatTokens(after)} tokens. Every request is lighter now.`
438
439 return withFlare(
440 withFeed(
441 {
442 ...assistant,
443 isCompacting: false,
444 isCold: false,
445 live: 0,
446 compactions: assistant.compactions + 1,
447 compactFreed: assistant.compactFreed + freed,
448 context: { ...assistant.context, tokens: after },
449 warnedLevel: 'calm',
450 },
451 { at: input.now, kind: 'compact', text, tokens: freed },
452 ),
453 'happy',
454 text,
455 input.now,
456 )
457}
458
459export const withAssistantConfig = (assistant: Assistant, config: AssistantConfig): Assistant => ({
460 ...assistant,
461 config,
462})
463
464/** True while a passing mood is still showing. */
465export const hasFlare = (assistant: Assistant, now: number): boolean =>
466 assistant.flare !== undefined && now < assistant.flare.until
467
468/** The mood Clawd shows now: a passing one first, then what the session's state calls for. */
469export const moodOf = (
470 assistant: Assistant,
471 input: { now: number; isEnabled: boolean; activeAgents: number },
472): Mood => {
473 if (!input.isEnabled) {
474 return 'off'
475 }
476
477 if (assistant.flare !== undefined && hasFlare(assistant, input.now)) {
478 return assistant.flare.mood
479 }
480
481 if (assistant.isCold) {
482 return 'sleepy'
483 }
484
485 if (rankOfLevel(levelOf(fillOf(assistant))) >= rankOfLevel('heavy')) {
486 return 'worried'
487 }
488
489 return input.activeAgents > 0 || assistant.isTurnRunning ? 'busy' : 'idle'
490}
491
492/** What Clawd says in the speech bubble. */
493export const speechOf = (
494 assistant: Assistant,
495 input: { now: number; isEnabled: boolean; activeAgents: number },
496): string => {
497 const mood = moodOf(assistant, input)
498 const percent = fillOf(assistant)
499
500 switch (mood) {
501 case 'off':
502 return 'Off duty. Turn me on and I start eating noise.'
503 case 'sleepy': {
504 const cost = coldCost(assistant.context.tokens)
505
506 return `Zzz… cache went cold. Your next message re-writes ~${formatTokens(cost.now)} tokens. Compact first and it's ~${formatTokens(cost.compacted)}.`
507 }
508 case 'worried':
509 return assistant.flare !== undefined && hasFlare(assistant, input.now)
510 ? assistant.flare.text
511 : `Context at ${String(percent)}%. Compacting takes ~${formatTokens(compactSaving(assistant.context.tokens))} off every request.`
512 case 'busy':
513 return input.activeAgents > 0
514 ? `${String(input.activeAgents)} helper${input.activeAgents === 1 ? '' : 's'} on cheaper models. I'm watching the output.`
515 : 'Watching tool output for noise to eat…'
516 case 'chomp':
517 case 'happy':
518 case 'alert':
519 return assistant.flare?.text ?? ''
520 case 'idle':
521 return assistant.trimmed > 0
522 ? `${formatTokens(assistant.trimmed + assistant.pasteTrimmed)} tokens eaten so far, ~${formatTokens(assistant.reReads)} re-sends avoided.`
523 : 'Hi! I trim noisy output before it fills your context, and tell you when to compact.'
524 }
525}
526src/runtime/session.ts 1002 lines1/**
2 * The session controller: every mod event becomes one pure transition,
3 * `(session, input) -> { session, effects, reply }`. Nothing here touches
4 * Claude Code; hooks/register.tsx feeds events in and carries effects out.
5 */
6import { checkResult, isUserRejection, planEscalation } from '../core/escalate.ts'
7import type { CheckSignal } from '../core/escalate.ts'
8import {
9 appendOutcome,
10 buildExport,
11 nextSeq,
12 parseLog,
13 parseThresholds,
14 summarizeLog,
15} from '../core/log.ts'
16import type { Outcome } from '../core/log.ts'
17import {
18 DEFAULT_MIN_SAVING,
19 decideDelegation,
20 judgeHint,
21 parseMinSaving,
22 tuneMinSaving,
23} from '../core/delegate.ts'
24import { DEFAULT_THRESHOLDS, resolveSpawnModel, routeTier } from '../core/route.ts'
25import type { Thresholds } from '../core/route.ts'
26import { contextSavings, estimateTokens, routingSavings } from '../core/savings.ts'
27import { scoreTask } from '../core/score.ts'
28import type { TaskType } from '../core/score.ts'
29import { rankOf, rankOfModel, tierOfModel } from '../core/tiers.ts'
30import type { Tier } from '../core/tiers.ts'
31import { learnFromOutcome, tighten, tuneFromLog } from '../core/tune.ts'
32import { DEFAULT_EXPORT_PATH, HELP_TEXT, parseCommand } from './commands.ts'
33import { applyOverrides, isNoColor, parseOptions, parseOverrides } from './config.ts'
34import type { Config, Overrides } from './config.ts'
35import { formatTokens } from '../ui/format.ts'
36
37export type AgentStatus = 'running' | 'retrying' | 'done' | 'failed' | 'planned'
38
39/**
40 * How an agent type gets its model when nobody names one: from its parent, or
41 * from its own definition. Only the first kind is tokensaver's to route.
42 */
43export type AgentTypeModel = 'inherits' | 'own-model'
44
45/** One sub-agent in the delegation tree. */
46export type AgentNode = {
47 /** The Agent tool call it belongs to. */
48 key: string
49 subagentType: string
50 parentModel: string
51 /** True for the first, untouched spawn of an agent type: it shows how the type picks its model. */
52 isProbe: boolean
53 agentId: string | undefined
54 parentAgentId: string | undefined
55 label: string
56 taskType: TaskType
57 /** The tier it runs on; undefined when it inherits a model tokensaver cannot name. */
58 tier: Tier | undefined
59 /** True when tokensaver chose its model. */
60 isRouted: boolean
61 escalatedFrom: Tier | undefined
62 /** Set between a failed attempt and its retry: the tier the retry must use. */
63 pendingTier: Tier | undefined
64 status: AgentStatus
65 tokens: number
66 /** Tokens a failed attempt spent before its retry. */
67 wastedTokens: number
68 answerTokens: number
69 attempts: number
70 isBackground: boolean
71 isDryRun: boolean
72 /** True when tokensaver's hint asked for this delegation. */
73 isHinted: boolean
74 isRecorded: boolean
75 /** The rank of the model it would have run on without tokensaver. */
76 baselineRank: number | undefined
77}
78
79export type Spend = Readonly<Record<Tier | 'other', number>>
80
81export type Session = {
82 config: Config
83 overrides: Overrides
84 hasNoColor: boolean
85 thresholds: Thresholds
86 outcomes: readonly Outcome[]
87 spend: Spend
88 context: { tokens: number; window: number }
89 /**
90 * Estimated saving from running work on cheaper tiers, in tokens of the
91 * model it would otherwise have run on, net of failed attempts and of
92 * tokensaver's own hint. Negative when the overhead outweighs the gain.
93 */
94 saved: number
95 /** Tokens of delegated work the main context never had to hold: the work less its summary. */
96 keptOut: number
97 savedHistory: readonly number[]
98 agents: readonly AgentNode[]
99 /** What this session has seen of each agent type; a type not listed has not been observed yet. */
100 agentTypes: Readonly<Record<string, AgentTypeModel>>
101 /** Delegations of the turn in progress, by key; the next prompt reads them to judge that turn. */
102 turnKeys: readonly string[]
103 /** Tiers to add to every routing decision this turn (after a user rejection). */
104 boost: number
105 isHintActive: boolean
106 /** Turns whose usage arrived step by step, so their totals are not counted twice. */
107 steppedTurns: readonly string[]
108 /** The bar a delegation suggestion must clear, tuned from how suggestions turn out. */
109 minSaving: number
110 /** What the session knows about where it runs. */
111 facts: SessionFacts
112 /** Files the main loop read or searched itself in the turn in progress. */
113 mainReads: number
114 /** The newest event worth showing above the prompt, for a few seconds. */
115 flash: Flash | undefined
116 /** The clock as of the last event or animation frame. */
117 now: number
118 /** What the display layer reported, for `/tokensaver doctor`. */
119 diagnostics: readonly string[]
120 notes: readonly string[]
121 frame: number
122 shownSaved: number
123}
124
125export type SessionFacts = {
126 /** Files under the working directory, sampled once; undefined until counted. */
127 repoFiles: number | undefined
128 /** The session's model id; undefined until Claude Code has said. */
129 model: string | undefined
130}
131
132export type FlashTone = 'route' | 'escalate' | 'done' | 'fail' | 'info'
133
134export type Flash = {
135 text: string
136 tone: FlashTone
137 at: number
138}
139
140/** How long an event stays above the prompt after it happens. */
141export const FLASH_MS = 6000
142
143export type Effect =
144 | { kind: 'toast'; text: string }
145 | { kind: 'log'; text: string }
146 | { kind: 'save-log' }
147 | { kind: 'save-settings' }
148 | { kind: 'clear-log' }
149 | { kind: 'open-dashboard' }
150 | { kind: 'export'; path: string; json: string }
151
152export type Step<Reply> = {
153 session: Session
154 effects: readonly Effect[]
155 reply: Reply
156}
157
158const MAX_AGENTS = 24
159const MAX_HISTORY = 32
160const MAX_NOTES = 4
161const MAX_STEPPED_TURNS = 64
162const MAX_DIAGNOSTICS = 12
163const HINT_NOUNS: Readonly<Record<TaskType, string>> = {
164 search: 'search',
165 'bulk-read': 'read-through',
166 'repetitive-edit': 'repetitive edit',
167 summarize: 'summarising job',
168 edit: 'edit',
169 reasoning: 'problem',
170 general: 'task',
171}
172
173const withFlash = (session: Session, text: string, tone: FlashTone, at: number): Session => ({
174 ...session,
175 flash: { text, tone, at },
176 now: Math.max(session.now, at),
177})
178
179const still = <Reply>(session: Session, reply: Reply): Step<Reply> => ({
180 session,
181 effects: [],
182 reply,
183})
184
185const shorten = (text: string, limit = 40): string => {
186 const line = text.replace(/\s+/g, ' ').trim()
187
188 return line.length <= limit ? line : `${line.slice(0, limit - 1)}…`
189}
190
191const withNote = (session: Session, note: string): Session => ({
192 ...session,
193 notes: [...session.notes, note].slice(-MAX_NOTES),
194})
195
196const replaceAgent = (session: Session, node: AgentNode): Session => ({
197 ...session,
198 agents: session.agents.map(agent => (agent.key === node.key ? node : agent)),
199})
200
201const signalText = (signal: CheckSignal): string => signal.replace('-', ' ')
202
203export type HydrateInput = {
204 options: Readonly<Record<string, unknown>>
205 storedLog: unknown
206 storedThresholds: unknown
207 storedSettings: unknown
208 storedDelegation?: unknown
209 noColor: string | undefined
210}
211
212/** Builds the session from the plugin's options and whatever the local store holds. */
213export const hydrate = (input: HydrateInput): Step<undefined> => {
214 const log = parseLog(input.storedLog)
215 const overrides = parseOverrides(input.storedSettings)
216 const session: Session = {
217 config: applyOverrides(parseOptions(input.options), overrides),
218 overrides,
219 hasNoColor: isNoColor(input.noColor),
220 thresholds: tuneFromLog(parseThresholds(input.storedThresholds), log.outcomes),
221 outcomes: log.outcomes,
222 spend: { haiku: 0, sonnet: 0, opus: 0, other: 0 },
223 context: { tokens: 0, window: 0 },
224 saved: 0,
225 keptOut: 0,
226 savedHistory: [],
227 agents: [],
228 agentTypes: {},
229 turnKeys: [],
230 boost: 0,
231 isHintActive: false,
232 steppedTurns: [],
233 minSaving: parseMinSaving(input.storedDelegation),
234 facts: { repoFiles: undefined, model: undefined },
235 mainReads: 0,
236 flash: undefined,
237 now: 0,
238 diagnostics: [],
239 notes: [],
240 frame: 0,
241 shownSaved: 0,
242 }
243
244 if (log.dropped === 0) {
245 return still(session, undefined)
246 }
247
248 return {
249 session,
250 effects: [
251 {
252 kind: 'log',
253 text: `tokensaver: ${String(log.dropped)} unreadable entr${log.dropped === 1 ? 'y' : 'ies'} dropped from the outcome log`,
254 },
255 { kind: 'save-log' },
256 ],
257 reply: undefined,
258 }
259}
260
261/** What the display layer learned about the session: its model and how big the repository is. */
262export const onFacts = (session: Session, facts: Partial<SessionFacts>): Step<undefined> =>
263 still({ ...session, facts: { ...session.facts, ...facts } }, undefined)
264
265/** Keeps a line for `/tokensaver doctor`: what was asked of the display and what came back. */
266export const onDiagnostic = (session: Session, line: string): Step<undefined> =>
267 still(
268 { ...session, diagnostics: [...session.diagnostics, line].slice(-MAX_DIAGNOSTICS) },
269 undefined,
270 )
271
272export type PromptInput = {
273 text: string
274 /** True for a prompt the person typed; notifications and peers are not scored. */
275 isFromUser: boolean
276 now: number
277}
278
279/** A user rejection counts against every model tokensaver picked in the turn it rejects. */
280const recordRejections = (session: Session, now: number): Session =>
281 session.agents
282 .filter(agent => session.turnKeys.includes(agent.key) && agent.isRouted && !agent.isDryRun)
283 .reduce((current, agent) => {
284 if (agent.tier === undefined) {
285 return current
286 }
287
288 const outcome: Outcome = {
289 seq: nextSeq(current.outcomes),
290 at: now,
291 taskType: agent.taskType,
292 tier: agent.tier,
293 tokens: agent.tokens,
294 retries: agent.attempts,
295 wasEscalated: agent.escalatedFrom !== undefined,
296 isSuccess: false,
297 signal: 'user-rejection',
298 }
299
300 return {
301 ...current,
302 outcomes: appendOutcome(current.outcomes, outcome),
303 thresholds: tighten(current.thresholds, agent.taskType, agent.tier, outcome.seq),
304 }
305 }, session)
306
307/**
308 * A submitted prompt: judges the previous turn if the user rejects it, then
309 * scores the new task and decides whether delegating would save tokens.
310 */
311export const onPrompt = (
312 session: Session,
313 input: PromptInput,
314): Step<{ context: string | undefined }> => {
315 if (!session.config.isEnabled || !input.isFromUser) {
316 return still(session, { context: undefined })
317 }
318
319 const effects: Effect[] = []
320 const hadRouted = session.agents.some(
321 agent => session.turnKeys.includes(agent.key) && agent.isRouted && !agent.isDryRun,
322 )
323 const isRejected = hadRouted && isUserRejection(input.text)
324 let next: Session = isRejected ? recordRejections(session, input.now) : session
325
326 if (isRejected) {
327 effects.push(
328 { kind: 'toast', text: 'tokensaver: result rejected, routing one tier up this turn' },
329 { kind: 'save-log' },
330 )
331 next = withNote(next, 'rejected: one tier up this turn')
332 }
333
334 const score = scoreTask({ text: input.text })
335 const delegation = decideDelegation(score, {
336 repoFiles: session.facts.repoFiles,
337 parentRank: rankOfModel(session.facts.model),
338 minSaving: session.minSaving,
339 })
340 const shouldHint =
341 delegation.shouldDelegate && session.config.hasContextHint && !session.config.isDryRun
342 const helpers =
343 delegation.agents > 1
344 ? `up to ${String(delegation.agents)} Explore sub-agents in parallel, one per independent part,`
345 : 'one Explore sub-agent'
346 // Directive, because Claude only delegates on a clear instruction; with a way out, because
347 // this estimate is made from the wording and Claude can see the code.
348 const hint = `[tokensaver] This ${HINT_NOUNS[score.taskType]} likely means reading about ${String(delegation.estimatedFiles)} files. Before reading them yourself, hand that reading to ${helpers} with the Agent tool, and work from what they report. Skip this only if one or two targeted lookups would answer it.`
349
350 if (delegation.shouldDelegate && session.config.isDryRun) {
351 const text = `tokensaver dry-run: would suggest delegating this ${HINT_NOUNS[score.taskType]} (about ${String(delegation.estimatedFiles)} files, ~${formatTokens(delegation.estimatedSaving)} tokens saved)`
352 effects.push({ kind: 'toast', text })
353 next = withNote(next, text.replace('tokensaver ', ''))
354 }
355
356 if (shouldHint) {
357 next = withFlash(
358 next,
359 `suggested delegating about ${String(delegation.estimatedFiles)} files of reading`,
360 'info',
361 input.now,
362 )
363 }
364
365 return {
366 session: {
367 ...next,
368 turnKeys: [],
369 mainReads: 0,
370 boost: isRejected ? 1 : 0,
371 isHintActive: shouldHint,
372 // The hint is the one thing tokensaver adds to the model's context: count it as a cost.
373 saved: shouldHint ? next.saved - estimateTokens(hint) : next.saved,
374 },
375 effects,
376 reply: { context: shouldHint ? hint : undefined },
377 }
378}
379
380export type SpawnInput = {
381 toolUseId: string
382 prompt: string
383 description: string
384 subagentType: string
385 explicitModel: string | undefined
386 parentModel: string
387 parentAgentId: string | undefined
388 isBackground: boolean
389 /** True for a fork, a teammate or a workflow agent: their model is not tokensaver's to set. */
390 isPinned: boolean
391 now?: number | undefined
392}
393
394/**
395 * A sub-agent is about to start: scores its task and answers with the model
396 * it should run on, or with nothing to leave the spawn untouched.
397 */
398export const onSpawn = (
399 session: Session,
400 input: SpawnInput,
401): Step<{ model: string | undefined }> => {
402 if (!session.config.isEnabled) {
403 return still(session, { model: undefined })
404 }
405
406 const existing = session.agents.find(agent => agent.key === input.toolUseId)
407 const label = shorten(input.description === '' ? input.prompt : input.description)
408 const score = scoreTask({ text: input.prompt, description: input.description })
409 const decision = routeTier(score, session.thresholds, session.boost)
410 const known = session.agentTypes[input.subagentType]
411 // An agent type may name its own model, and a spawn does not say whether it does. So
412 // tokensaver sets a model only where that cannot override the type's choice: on a retry of
413 // its own, on a model the caller named (which it only ever raises), or on a type it has
414 // watched inherit its parent's model.
415 const canRoute =
416 !input.isPinned &&
417 (existing?.pendingTier !== undefined || input.explicitModel !== undefined || known === 'inherits')
418 const routing = canRoute
419 ? resolveSpawnModel(decision, score, {
420 parentModel: input.parentModel,
421 explicitModel: input.explicitModel,
422 forcedTier: existing?.pendingTier,
423 })
424 : { model: undefined, tier: undefined, note: 'the agent type picks its own model' }
425 const isRouted = routing.model !== undefined
426 const isDryRun = session.config.isDryRun
427 const node: AgentNode = {
428 key: input.toolUseId,
429 subagentType: input.subagentType,
430 parentModel: input.parentModel,
431 isProbe:
432 existing === undefined &&
433 known === undefined &&
434 !input.isPinned &&
435 input.explicitModel === undefined,
436 agentId: undefined,
437 parentAgentId: input.parentAgentId,
438 label,
439 taskType: score.taskType,
440 tier: routing.tier,
441 isRouted,
442 escalatedFrom: existing?.escalatedFrom,
443 pendingTier: undefined,
444 status: isDryRun ? 'planned' : 'running',
445 tokens: existing?.tokens ?? 0,
446 wastedTokens: existing?.wastedTokens ?? 0,
447 answerTokens: 0,
448 attempts: existing?.attempts ?? 0,
449 isBackground: input.isBackground,
450 isDryRun,
451 isHinted: existing?.isHinted ?? session.isHintActive,
452 isRecorded: false,
453 // A retry keeps the baseline of the first attempt: what would have run without tokensaver.
454 baselineRank: existing?.baselineRank ?? rankOfModel(input.explicitModel ?? input.parentModel),
455 }
456 const agents =
457 existing === undefined
458 ? [...session.agents, node].slice(-MAX_AGENTS)
459 : session.agents.map(agent => (agent.key === node.key ? node : agent))
460 const tracked: Session = {
461 ...session,
462 agents,
463 turnKeys: session.turnKeys.includes(node.key) ? session.turnKeys : [...session.turnKeys, node.key],
464 }
465
466 if (!isRouted) {
467 return still(tracked, { model: undefined })
468 }
469
470 const target = routing.tier ?? 'the parent model'
471
472 if (isDryRun) {
473 const text = `tokensaver dry-run: would run "${label}" on ${target} (${score.taskType})`
474
475 return {
476 session: withNote(tracked, text.replace('tokensaver ', '')),
477 effects: [{ kind: 'toast', text }],
478 reply: { model: undefined },
479 }
480 }
481
482 const text =
483 existing?.escalatedFrom === undefined
484 ? `tokensaver: "${label}" → ${target} (${score.taskType})`
485 : `tokensaver: escalated "${label}" ${existing.escalatedFrom} → ${target}`
486
487 return {
488 session: withFlash(
489 withNote(tracked, text.replace('tokensaver: ', '')),
490 existing?.escalatedFrom === undefined
491 ? `${label} → ${target}`
492 : `${label} escalated ${existing.escalatedFrom} → ${target}`,
493 existing?.escalatedFrom === undefined ? 'route' : 'escalate',
494 input.now ?? session.now,
495 ),
496 effects: [{ kind: 'toast', text }],
497 reply: { model: routing.model },
498 }
499}
500
501export type SpawnedInput = {
502 toolUseId: string
503 agentId: string | undefined
504 isDenied: boolean
505 /** The model Claude Code resolved for the sub-agent. */
506 resolvedModel?: string | undefined
507}
508
509const isSameModel = (a: string, b: string): boolean => {
510 const rank = rankOfModel(a)
511
512 return a === b || (rank !== undefined && rank === rankOfModel(b))
513}
514
515/**
516 * The spawn settled: remembers the agent's id, and from an untouched first
517 * spawn learns whether its agent type inherits the parent's model. A refused
518 * spawn is dropped.
519 */
520export const onSpawned = (session: Session, input: SpawnedInput): Step<undefined> => {
521 const node = session.agents.find(agent => agent.key === input.toolUseId)
522
523 if (node === undefined) {
524 return still(session, undefined)
525 }
526
527 if (input.isDenied) {
528 return still(replaceAgent(session, { ...node, status: 'failed', isRecorded: true }), undefined)
529 }
530
531 const started: AgentNode = {
532 ...node,
533 agentId: input.agentId,
534 tier: node.isRouted ? node.tier : (tierOfModel(input.resolvedModel) ?? node.tier),
535 }
536
537 if (!node.isProbe || input.resolvedModel === undefined) {
538 return still(replaceAgent(session, started), undefined)
539 }
540
541 const learned: AgentTypeModel = isSameModel(input.resolvedModel, node.parentModel)
542 ? 'inherits'
543 : 'own-model'
544 const note =
545 learned === 'inherits'
546 ? `"${node.subagentType}" agents inherit their model: routing them from now on`
547 : `"${node.subagentType}" agents choose their own model: left alone`
548
549 return still(
550 withNote(
551 {
552 ...replaceAgent(session, started),
553 agentTypes: { ...session.agentTypes, [node.subagentType]: learned },
554 },
555 note,
556 ),
557 undefined,
558 )
559}
560
561/** Books a finished delegation: its outcome, what it teaches, and what it saved. */
562const finalize = (session: Session, node: AgentNode, signal: CheckSignal, now: number): Step<undefined> => {
563 const isSuccess = signal === 'ok'
564 const usefulTokens = Math.max(0, node.tokens - node.wastedTokens)
565 // A dry run changed nothing, so it saved nothing.
566 const routed =
567 node.isRouted && !node.isDryRun && node.tier !== undefined && node.baselineRank !== undefined
568 ? routingSavings(usefulTokens, rankOf(node.tier), node.baselineRank)
569 : 0
570 const kept =
571 node.isHinted && !node.isDryRun && isSuccess
572 ? contextSavings(usefulTokens, node.answerTokens)
573 : 0
574 const done: AgentNode = { ...node, status: isSuccess ? 'done' : 'failed', isRecorded: true }
575 const settled: Session = {
576 ...withFlash(
577 replaceAgent(session, done),
578 `${node.label} ${isSuccess ? 'done' : `failed (${signalText(signal)})`} · ${formatTokens(node.tokens)}${node.tier === undefined ? '' : ` on ${node.tier}`}`,
579 isSuccess ? 'done' : 'fail',
580 now,
581 ),
582 // Two different savings, kept apart: adding them would count the same tokens twice.
583 saved: session.saved + routed - node.wastedTokens,
584 keptOut: session.keptOut + kept,
585 }
586
587 // The log records tokensaver's own decisions; a model it did not pick teaches it nothing.
588 if (!node.isRouted || node.tier === undefined || node.isDryRun) {
589 return still(settled, undefined)
590 }
591
592 const outcome: Outcome = {
593 seq: nextSeq(session.outcomes),
594 at: now,
595 taskType: node.taskType,
596 tier: node.tier,
597 tokens: node.tokens,
598 retries: node.attempts,
599 wasEscalated: node.escalatedFrom !== undefined,
600 isSuccess,
601 signal,
602 }
603 const outcomes = appendOutcome(session.outcomes, outcome)
604
605 return {
606 session: {
607 ...settled,
608 outcomes,
609 thresholds: learnFromOutcome(session.thresholds, outcomes, outcome),
610 },
611 effects: [{ kind: 'save-log' }],
612 reply: undefined,
613 }
614}
615
616export type AgentResultInput = {
617 toolUseId: string
618 isDenied: boolean
619 isError: boolean
620 text: string
621 /** The Agent tool's own token total, used when no step usage was seen. */
622 totalTokens: number | undefined
623 now: number
624}
625
626/**
627 * An Agent call returned. A result that fails its checks on a tier
628 * tokensaver picked is retried once, one tier up; anything else is final.
629 */
630export const onAgentResult = (
631 session: Session,
632 input: AgentResultInput,
633): Step<{ retryWith: Tier | undefined }> => {
634 const found = session.agents.find(agent => agent.key === input.toolUseId)
635
636 if (!session.config.isEnabled || found === undefined || found.isRecorded) {
637 return still(session, { retryWith: undefined })
638 }
639
640 // A background agent's call returns as it starts; its turn.complete settles it.
641 if (found.isBackground && !input.isDenied && !input.isError) {
642 return still(session, { retryWith: undefined })
643 }
644
645 const node: AgentNode =
646 found.tokens === 0 && input.totalTokens !== undefined
647 ? { ...found, tokens: input.totalTokens }
648 : found
649
650 // A denial is a permission decision, not a quality signal: no retry, no outcome.
651 if (input.isDenied) {
652 return still(replaceAgent(session, { ...node, status: 'failed', isRecorded: true }), {
653 retryWith: undefined,
654 })
655 }
656
657 const signal = checkResult({ isError: input.isError, text: input.text })
658 const plan = planEscalation({
659 signal,
660 tier: node.isRouted ? node.tier : undefined,
661 attempts: node.attempts,
662 isDenied: input.isDenied,
663 isDryRun: node.isDryRun,
664 })
665
666 if (!plan.shouldEscalate || node.tier === undefined) {
667 return { ...finalize(session, node, signal, input.now), reply: { retryWith: undefined } }
668 }
669
670 const retrying: AgentNode = {
671 ...node,
672 status: 'retrying',
673 escalatedFrom: node.tier,
674 pendingTier: plan.to,
675 attempts: node.attempts + 1,
676 wastedTokens: node.tokens,
677 }
678 const text = `tokensaver: "${node.label}" failed on ${node.tier} (${signalText(signal)}), retrying on ${plan.to}`
679
680 return {
681 session: withNote(
682 {
683 ...withFlash(
684 replaceAgent(session, retrying),
685 `${node.label} failed on ${node.tier}, retrying on ${plan.to}`,
686 'escalate',
687 input.now,
688 ),
689 // Tighten now, not when the retry finishes: the cheaper tier has already failed.
690 thresholds: tighten(session.thresholds, node.taskType, node.tier, nextSeq(session.outcomes)),
691 },
692 text.replace('tokensaver: ', ''),
693 ),
694 effects: [{ kind: 'toast', text }, { kind: 'save-log' }],
695 reply: { retryWith: plan.to },
696 }
697}
698
699export type Usage = {
700 model: string
701 input: number
702 output: number
703 cacheWrite: number
704}
705
706const applyUsage = (session: Session, agentId: string | undefined, usage: Usage): Session => {
707 // Cache reads are left out: they are re-read context, not new work.
708 const tokens = usage.input + usage.output + usage.cacheWrite
709 const bucket = tierOfModel(usage.model) ?? 'other'
710 const spend = { ...session.spend, [bucket]: session.spend[bucket] + tokens }
711
712 return {
713 ...session,
714 spend,
715 agents:
716 agentId === undefined
717 ? session.agents
718 : session.agents.map(agent =>
719 agent.agentId === agentId ? { ...agent, tokens: agent.tokens + tokens } : agent,
720 ),
721 }
722}
723
724export type StepUsageInput = {
725 turnId: string
726 agentId: string | undefined
727 usage: Usage
728 /** Read, Grep and Glob calls the response asked for. */
729 reads?: number | undefined
730}
731
732/** One model request finished: adds its tokens to the meter and to its agent. */
733export const onStepUsage = (session: Session, input: StepUsageInput): Step<undefined> => {
734 if (!session.config.isEnabled) {
735 return still(session, undefined)
736 }
737
738 const stepKey = `${input.turnId}/${input.agentId ?? 'main'}`
739
740 return still(
741 {
742 ...applyUsage(session, input.agentId, input.usage),
743 mainReads: session.mainReads + (input.agentId === undefined ? (input.reads ?? 0) : 0),
744 steppedTurns: session.steppedTurns.includes(stepKey)
745 ? session.steppedTurns
746 : [...session.steppedTurns, stepKey].slice(-MAX_STEPPED_TURNS),
747 },
748 undefined,
749 )
750}
751
752export type TurnCompleteInput = {
753 turnId: string
754 agentId: string | undefined
755 /** The turn's totals; used only when no step of this turn reported usage. */
756 usage: Usage | undefined
757 isFailed: boolean
758 /** True when the user interrupted the turn. */
759 isAborted: boolean
760 answer: string
761 now: number
762}
763
764/** A turn ended: the main loop's closes the books on the turn, a sub-agent's on itself. */
765export const onTurnComplete = (session: Session, input: TurnCompleteInput): Step<undefined> => {
766 if (!session.config.isEnabled) {
767 return still(session, undefined)
768 }
769
770 const stepKey = `${input.turnId}/${input.agentId ?? 'main'}`
771 const counted =
772 input.usage === undefined || session.steppedTurns.includes(stepKey)
773 ? session
774 : applyUsage(session, input.agentId, input.usage)
775
776 if (input.agentId === undefined) {
777 const closed: Session = {
778 ...counted,
779 savedHistory: [...counted.savedHistory, counted.saved].slice(-MAX_HISTORY),
780 }
781
782 if (!closed.isHintActive || input.isAborted) {
783 return still(closed, undefined)
784 }
785
786 // The suggestion is judged by what the turn then did, and the bar moves with the verdict.
787 const verdict = judgeHint({
788 largestAgentTokens: Math.max(
789 0,
790 ...closed.agents.filter(agent => closed.turnKeys.includes(agent.key)).map(agent => agent.tokens),
791 ),
792 mainReads: closed.mainReads,
793 })
794 const minSaving = tuneMinSaving(closed.minSaving, verdict)
795 const judged: Session = { ...closed, isHintActive: false, minSaving }
796
797 if (minSaving === closed.minSaving) {
798 return still(judged, undefined)
799 }
800
801 return {
802 session: withNote(
803 judged,
804 verdict === 'over-fired'
805 ? 'delegation suggestion was not needed: raising the bar'
806 : 'delegation suggestion paid off',
807 ),
808 effects: [{ kind: 'save-log' }],
809 reply: undefined,
810 }
811 }
812
813 const node = counted.agents.find(agent => agent.agentId === input.agentId)
814
815 if (node === undefined || node.isRecorded) {
816 return still(counted, undefined)
817 }
818
819 // An interrupt is the user's choice, not a quality signal: no outcome, and never a retry.
820 if (input.isAborted) {
821 return still(replaceAgent(counted, { ...node, status: 'failed', isRecorded: true }), undefined)
822 }
823
824 const answered: AgentNode = { ...node, answerTokens: estimateTokens(input.answer) }
825
826 // A foreground agent is settled by its Agent call, which can still retry it.
827 if (!node.isBackground) {
828 return still(replaceAgent(counted, answered), undefined)
829 }
830
831 const signal = checkResult({ isError: input.isFailed, text: input.answer })
832
833 return finalize(replaceAgent(counted, answered), answered, signal, input.now)
834}
835
836/** The context window moved: feeds the live meter. */
837export const onMeasure = (
838 session: Session,
839 input: { tokens: number | undefined; window: number },
840): Step<undefined> =>
841 still({ ...session, context: { tokens: input.tokens ?? session.context.tokens, window: input.window } }, undefined)
842
843export const activeCount = (session: Session): number =>
844 session.agents.filter(agent => agent.status === 'running' || agent.status === 'retrying').length
845
846/** True while an event is recent enough to still be shown above the prompt. */
847export const hasFreshFlash = (session: Session): boolean =>
848 session.flash !== undefined && session.now - session.flash.at < FLASH_MS
849
850/**
851 * True while the animation clock is needed. A fresh event keeps it running
852 * even under reduced motion, because the clock is also what takes the event
853 * down again; reduced motion stops only the movement.
854 */
855export const isAnimating = (session: Session): boolean =>
856 session.config.isEnabled &&
857 (hasFreshFlash(session) ||
858 (!session.config.hasReducedMotion &&
859 (activeCount(session) > 0 || session.shownSaved !== session.saved)))
860
861/** One animation frame: turns the spinner and eases the saved counter toward its value. */
862export const onTick = (session: Session, now = session.now): Step<undefined> => {
863 if (session.config.hasReducedMotion) {
864 return still({ ...session, now, shownSaved: session.saved }, undefined)
865 }
866
867 const gap = session.saved - session.shownSaved
868 const move = Math.abs(gap) <= 3 ? gap : Math.trunc(gap / 3)
869
870 return still(
871 { ...session, now, frame: session.frame + 1, shownSaved: session.shownSaved + move },
872 undefined,
873 )
874}
875
876const modeOf = (config: Config): string => {
877 if (!config.isEnabled) {
878 return 'off'
879 }
880
881 return config.isDryRun ? 'dry-run' : 'on'
882}
883
884const statusReport = (session: Session): string => {
885 const summary = summarizeLog(session.outcomes)
886 const total = session.spend.haiku + session.spend.sonnet + session.spend.opus + session.spend.other
887
888 return [
889 `tokensaver is ${modeOf(session.config)}`,
890 `${formatTokens(total)} tokens this session (haiku ${formatTokens(session.spend.haiku)}, sonnet ${formatTokens(session.spend.sonnet)}, opus ${formatTokens(session.spend.opus)})`,
891 `~${formatTokens(session.saved)} saved by routing (estimate), ${formatTokens(session.keptOut)} kept out of the main context`,
892 `${String(summary.count)} logged outcomes, ${String(Math.round(summary.cleanRate * 100))}% clean, ${String(summary.escalations)} escalations`,
893 ].join('\n')
894}
895
896/** What tokensaver knows and what the display told it: the first thing to read when nothing shows. */
897const doctorReport = (session: Session): string => {
898 const types = Object.entries(session.agentTypes)
899 .map(([name, kind]) => `${name} ${kind === 'inherits' ? 'inherits' : 'has its own model'}`)
900 .join(', ')
901
902 return [
903 `tokensaver is ${modeOf(session.config)}`,
904 `session model: ${session.facts.model ?? 'not reported yet'}`,
905 `repository: ${session.facts.repoFiles === undefined ? 'not counted yet' : `about ${String(session.facts.repoFiles)} files`}`,
906 `agent types seen: ${types === '' ? 'none yet' : types}`,
907 `a delegation suggestion must save at least ${formatTokens(session.minSaving)} tokens`,
908 `colour ${session.hasNoColor ? 'off (NO_COLOR)' : 'on'}, motion ${session.config.hasReducedMotion ? 'off' : 'on'}`,
909 'display:',
910 ...(session.diagnostics.length === 0
911 ? [' nothing reported yet']
912 : session.diagnostics.map(line => ` ${line}`)),
913 ].join('\n')
914}
915
916export type CommandReply = {
917 /** What the command prints. A command's output is a transcript row, so it is kept short. */
918 text: string
919}
920
921const answer = (session: Session, text: string, effects: readonly Effect[] = []): Step<CommandReply> => ({
922 session,
923 effects,
924 reply: { text },
925})
926
927const withOverride = (session: Session, overrides: Overrides, text: string): Step<CommandReply> => {
928 const merged = { ...session.overrides, ...overrides }
929
930 return answer(
931 { ...session, overrides: merged, config: applyOverrides(session.config, merged) },
932 text,
933 [{ kind: 'save-settings' }],
934 )
935}
936
937/**
938 * `/tokensaver <args>`. Every command answers with a line of text, so it is
939 * visible on every surface even where a pane or a toast is not.
940 */
941export const onCommand = (session: Session, args: string, now: number): Step<CommandReply> => {
942 const command = parseCommand(args)
943
944 switch (command.kind) {
945 case 'status':
946 return answer(session, statusReport(session))
947 case 'help':
948 return answer(session, HELP_TEXT)
949 case 'doctor':
950 return answer(session, doctorReport(session))
951 case 'dashboard':
952 return answer(session, 'tokensaver dashboard opened', [{ kind: 'open-dashboard' }])
953 case 'enable':
954 return withOverride(
955 session,
956 { isEnabled: command.value },
957 `tokensaver is ${command.value ? 'on' : 'off'}`,
958 )
959 case 'dry-run': {
960 const isDryRun = command.value ?? !session.config.isDryRun
961
962 return withOverride(session, { isDryRun }, `tokensaver dry-run is ${isDryRun ? 'on' : 'off'}`)
963 }
964 case 'motion': {
965 const hasMotion = command.value ?? session.config.hasReducedMotion
966
967 return withOverride(
968 { ...session, shownSaved: session.saved },
969 { hasReducedMotion: !hasMotion },
970 `tokensaver animations are ${hasMotion ? 'on' : 'off'}`,
971 )
972 }
973 case 'reset':
974 return answer(
975 {
976 ...session,
977 outcomes: [],
978 thresholds: DEFAULT_THRESHOLDS,
979 minSaving: DEFAULT_MIN_SAVING,
980 saved: 0,
981 keptOut: 0,
982 shownSaved: 0,
983 savedHistory: [],
984 },
985 'tokensaver: outcome log and everything learned from it cleared',
986 [{ kind: 'clear-log' }],
987 )
988 case 'export': {
989 const path = command.path ?? DEFAULT_EXPORT_PATH
990 const json = JSON.stringify(buildExport(session.outcomes, session.thresholds, now), null, 2)
991
992 return answer(
993 session,
994 `tokensaver: wrote ${String(session.outcomes.length)} outcomes to ${path} (local file, nothing was sent anywhere)`,
995 [{ kind: 'export', path, json }],
996 )
997 }
998 case 'unknown':
999 return answer(session, `tokensaver: unknown command "${command.word}"\n${HELP_TEXT}`)
1000 }
1001}
1002src/ui/band.ts 226 lines1/**
2 * The strip above the prompt: who is working for whom, right now. It shows
3 * while a sub-agent runs and for a few seconds after an event, and is gone
4 * the rest of the time. Text for the terminal, an animated vector for
5 * surfaces that draw one.
6 */
7import type { Tier } from '../core/tiers.ts'
8import type { FlashTone } from '../runtime/session.ts'
9import { fit, formatTokens, spinner } from './format.ts'
10import { span } from './theme.ts'
11import type { Line, Tone } from './theme.ts'
12import { themeOf } from './view.ts'
13import type { View, ViewAgent } from './view.ts'
14
15const TIER_TONES: Readonly<Record<Tier, Tone>> = {
16 haiku: 'success',
17 sonnet: 'suggestion',
18 opus: 'claude',
19}
20
21const FLASH_TONES: Readonly<Record<FlashTone, Tone>> = {
22 route: 'success',
23 escalate: 'warning',
24 done: 'success',
25 fail: 'error',
26 info: 'suggestion',
27}
28
29const FLASH_GLYPHS: Readonly<Record<FlashTone, string>> = {
30 route: '→',
31 escalate: '↑',
32 done: '✓',
33 fail: '✗',
34 info: '·',
35}
36
37/** Colours that read on a light and on a dark background alike. */
38const HEX: Readonly<Record<Tone, string>> = {
39 success: '#3fa55b',
40 suggestion: '#7b83eb',
41 claude: '#d77757',
42 warning: '#d99a00',
43 error: '#e5484d',
44 inactive: '#8b8b8b',
45}
46
47const MAX_SHOWN = 3
48const LABEL_CHARS = 22
49
50/** True when the strip has something to say. */
51export const isBandVisible = (view: View): boolean =>
52 view.mode !== 'off' && (view.band.agents.length > 0 || view.band.flash !== undefined)
53
54const tierName = (agent: ViewAgent): string => agent.tier ?? 'inherit'
55
56/** The strip as one line of text. */
57export const bandLine = (view: View, columns: number): Line => {
58 const theme = themeOf(view)
59 const { agents, flash } = view.band
60 const isActive = agents.length > 0
61 const parts = [
62 span(theme, `${isActive ? spinner(view.frame, theme.hasMotion) : '●'} `, { tone: 'claude' }),
63 span(theme, 'tokensaver ', { isBold: true }),
64 ]
65
66 if (isActive) {
67 parts.push(span(theme, 'main', { isDim: true }))
68
69 for (const agent of agents.slice(0, MAX_SHOWN)) {
70 parts.push(
71 span(theme, ' ─▸ ', { isDim: true }),
72 span(theme, tierName(agent), agent.tier === undefined ? {} : { tone: TIER_TONES[agent.tier] }),
73 span(theme, ` ${fit(agent.label, LABEL_CHARS)}`),
74 )
75 }
76
77 if (agents.length > MAX_SHOWN) {
78 parts.push(span(theme, ` +${String(agents.length - MAX_SHOWN)}`, { isDim: true }))
79 }
80 } else if (flash !== undefined) {
81 parts.push(
82 span(theme, `${FLASH_GLYPHS[flash.tone]} `, { tone: FLASH_TONES[flash.tone] }),
83 span(theme, fit(flash.text, Math.max(20, columns - 16))),
84 )
85 }
86
87 return parts
88}
89
90const escapeXml = (text: string): string =>
91 text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
92
93const STYLE =
94 '<style>' +
95 'text{font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;font-size:11.5px}' +
96 '.ink{fill:#2b2a27}.dim{fill:#77756f}.rail{stroke:#77756f}' +
97 '@media (prefers-color-scheme: dark){.ink{fill:#ecebe6}.dim{fill:#9c9a92}.rail{stroke:#9c9a92}}' +
98 '</style>'
99
100/** Approximate width of proportional text at the strip's font size. */
101const textWidth = (text: string): number => Math.ceil(text.length * 6.1)
102
103const HEIGHT = 30
104const MID = HEIGHT / 2
105
106/**
107 * The strip as an animated SVG picture: the main loop on the left, a dashed
108 * line flowing out to each running sub-agent, each agent a pill in its
109 * tier's colour with a pulsing dot. Under reduced motion nothing moves, and
110 * under NO_COLOR everything is drawn in the text colour.
111 */
112export const bandSvg = (view: View, width: number): string => {
113 const theme = themeOf(view)
114 const { agents, flash } = view.band
115 const colour = (tone: Tone): string => (theme.hasColor ? `fill="${HEX[tone]}"` : 'class="ink"')
116 const stroke = (tone: Tone): string => (theme.hasColor ? `stroke="${HEX[tone]}"` : 'class="rail"')
117 const moving = (markup: string): string => (theme.hasMotion ? markup : '')
118 const parts: string[] = [STYLE]
119 const isActive = agents.length > 0
120
121 // The main loop.
122 parts.push(
123 `<circle cx="12" cy="${String(MID)}" r="9" ${colour('claude')} opacity="0.18">${moving(
124 isActive
125 ? '<animate attributeName="r" values="6;11;6" dur="1.6s" repeatCount="indefinite"/><animate attributeName="opacity" values="0.3;0.05;0.3" dur="1.6s" repeatCount="indefinite"/>'
126 : '',
127 )}</circle>`,
128 `<circle cx="12" cy="${String(MID)}" r="4.5" ${colour('claude')}/>`,
129 `<text x="24" y="${String(MID + 4)}" class="ink" font-weight="600">tokensaver</text>`,
130 )
131
132 let x = 24 + textWidth('tokensaver') + 14
133
134 if (isActive) {
135 agents.slice(0, MAX_SHOWN).forEach((agent, index) => {
136 const tone: Tone = agent.status === 'retrying' ? 'warning' : agent.tier === undefined ? 'inactive' : TIER_TONES[agent.tier]
137 const label = `${tierName(agent)} · ${fit(agent.label, LABEL_CHARS)}`
138 const pill = textWidth(label) + 30
139 const rail = 26
140 const delay = (index * 0.25).toFixed(2)
141
142 // The line the work flows along.
143 parts.push(
144 `<line x1="${String(x)}" y1="${String(MID)}" x2="${String(x + rail)}" y2="${String(MID)}" ${stroke(tone)} stroke-width="1.6" stroke-dasharray="4 4" stroke-linecap="round" fill="none">${moving(
145 `<animate attributeName="stroke-dashoffset" from="8" to="0" dur="0.6s" begin="${delay}s" repeatCount="indefinite"/>`,
146 )}</line>`,
147 )
148 x += rail + 4
149
150 // The sub-agent.
151 parts.push(
152 `<rect x="${String(x)}" y="5" width="${String(pill)}" height="20" rx="10" ${colour(tone)} opacity="0.16"/>`,
153 `<rect x="${String(x)}" y="5" width="${String(pill)}" height="20" rx="10" fill="none" ${stroke(tone)} stroke-width="1"/>`,
154 `<circle cx="${String(x + 12)}" cy="${String(MID)}" r="3.5" ${colour(tone)}>${moving(
155 `<animate attributeName="opacity" values="1;0.25;1" dur="1.1s" begin="${delay}s" repeatCount="indefinite"/>`,
156 )}</circle>`,
157 `<text x="${String(x + 21)}" y="${String(MID + 4)}" class="ink">${escapeXml(label)}</text>`,
158 )
159 x += pill + 8
160 })
161
162 if (agents.length > MAX_SHOWN) {
163 parts.push(
164 `<text x="${String(x + 2)}" y="${String(MID + 4)}" class="dim">+${String(agents.length - MAX_SHOWN)}</text>`,
165 )
166 x += 30
167 }
168 } else if (flash !== undefined) {
169 const tone = FLASH_TONES[flash.tone]
170 const text = `${FLASH_GLYPHS[flash.tone]} ${fit(flash.text, 70)}`
171
172 parts.push(
173 `<text x="${String(x)}" y="${String(MID + 4)}" ${colour(tone)}>${escapeXml(text)}${moving(
174 '<animate attributeName="opacity" values="0;1" dur="0.35s" fill="freeze"/>',
175 )}</text>`,
176 )
177 x += textWidth(text) + 12
178 }
179
180 // The running total, where there is room for it.
181 const total = `saved ~${formatTokens(view.hasReducedMotion ? view.saved : view.shownSaved)}`
182
183 if (x + textWidth(total) + 8 <= width) {
184 parts.push(
185 `<text x="${String(width - 6)}" y="${String(MID + 4)}" text-anchor="end" class="dim">${escapeXml(total)}</text>`,
186 )
187 }
188
189 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${String(width)} ${String(HEIGHT)}" width="${String(width)}" height="${String(HEIGHT)}">${parts.join('')}</svg>`
190}
191
192export const BAND_HEIGHT = HEIGHT
193
194/** What to add after the spinner's word while sub-agents run, or undefined to leave it alone. */
195export const spinnerSuffix = (view: View): string | undefined => {
196 const { agents } = view.band
197
198 if (view.mode === 'off' || agents.length === 0) {
199 return undefined
200 }
201
202 const tiers = [...new Set(agents.map(tierName))].join(', ')
203
204 return ` · ${String(agents.length)} sub-agent${agents.length === 1 ? '' : 's'} on ${tiers}`
205}
206
207/** A one-line badge for an Agent call tokensaver routed, or undefined when it did not. */
208export const routedBadge = (view: View, toolUseId: string): Line | undefined => {
209 const agent = view.routed.find(entry => entry.key === toolUseId)
210
211 if (agent?.tier === undefined) {
212 return undefined
213 }
214
215 const theme = themeOf(view)
216
217 return [
218 span(theme, '◆ tokensaver ', { isDim: true }),
219 span(theme, agent.escalatedFrom === undefined ? '→ ' : `${agent.escalatedFrom} ↑ `, {
220 tone: agent.escalatedFrom === undefined ? TIER_TONES[agent.tier] : 'warning',
221 }),
222 span(theme, agent.tier, { tone: TIER_TONES[agent.tier], isBold: true }),
223 span(theme, ` (${agent.taskType})`, { isDim: true }),
224 ]
225}
226src/ui/clawd.ts 456 lines1/**
2 * Clawd, drawn. A pixel-art vector with a CSS animation per mood for surfaces
3 * that draw SVG (the desktop app), and block-glyph art for the terminal.
4 * Every picture is a pure function of a ClawdView, so the same state always
5 * draws the same markup and a redraw with nothing new does not restart it.
6 */
7import type { FeedItem, FeedKind, Mood } from '../runtime/assistant.ts'
8import { bar, fit, formatTokens } from './format.ts'
9import type { Line, Tone } from './theme.ts'
10
11export type ClawdView = {
12 mood: Mood
13 speech: string
14 mode: 'on' | 'off' | 'dry-run'
15 hasMotion: boolean
16 hasColor: boolean
17 context: { tokens: number; window: number; percent: number }
18 /** Tokens Clawd cut that would otherwise sit in the context right now. */
19 ghost: number
20 stats: {
21 eaten: number
22 reReads: number
23 compactFreed: number
24 routed: number
25 keptOut: number
26 trims: number
27 compactions: number
28 }
29 feed: readonly FeedItem[]
30 activeAgents: number
31 frame: number
32}
33
34const ORANGE = '#D97757'
35const ORANGE_DARK = '#B85C3E'
36const INK = '#1F1A17'
37
38const escape = (text: string): string =>
39 text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
40
41/** Splits text into lines of at most `width` characters, breaking at spaces. */
42export const wrap = (text: string, width: number, maxLines: number): string[] => {
43 const words = text.split(/\s+/).filter(word => word !== '')
44 const lines: string[] = []
45 let line = ''
46
47 for (const word of words) {
48 const candidate = line === '' ? word : `${line} ${word}`
49
50 if (candidate.length <= width) {
51 line = candidate
52 continue
53 }
54
55 if (line !== '') {
56 lines.push(line)
57 }
58
59 line = word.length > width ? fit(word, width) : word
60 }
61
62 if (line !== '') {
63 lines.push(line)
64 }
65
66 if (lines.length <= maxLines) {
67 return lines
68 }
69
70 const kept = lines.slice(0, maxLines)
71 kept[maxLines - 1] = fit(`${kept[maxLines - 1] ?? ''} …`, width)
72
73 return kept
74}
75
76// --- The vector ------------------------------------------------------------
77
78/**
79 * The stylesheet every Clawd picture shares. Animations are keyed by the mood
80 * class on the root group, so one body serves every mood.
81 */
82const STYLE = (hasMotion: boolean): string => `<style>
83svg{font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
84.t{fill:#3b3530}
85.d{fill:#8a817a}
86.bubble{fill:#ffffff;stroke:#e6ddd6}
87.track{fill:#efe8e2}
88.tile{fill:#faf6f3;stroke:#eee5de}
89@media (prefers-color-scheme:dark){
90.t{fill:#ece6e1}.d{fill:#a59d96}.bubble{fill:#2b2724;stroke:#3d3733}.track{fill:#3a3430}.tile{fill:#262220;stroke:#352f2b}
91}
92.c *{transform-box:fill-box;transform-origin:center}
93${
94 hasMotion
95 ? `
96@keyframes bob{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}
97@keyframes blink{0%,92%,100%{transform:scaleY(1)}95%{transform:scaleY(.1)}}
98@keyframes look{0%,40%,100%{transform:translateX(0)}50%,90%{transform:translateX(5px)}}
99@keyframes walkA{0%,100%{transform:translateY(0)}50%{transform:translateY(-4px)}}
100@keyframes walkB{0%,100%{transform:translateY(-4px)}50%{transform:translateY(0)}}
101@keyframes jump{0%,100%{transform:translateY(0)}30%{transform:translateY(-16px) scaleY(1.04)}55%{transform:translateY(0) scaleY(.92)}70%{transform:translateY(-4px)}}
102@keyframes chomp{0%,100%{transform:scaleY(.15)}50%{transform:scaleY(1)}}
103@keyframes crumb{0%{transform:translate(0,0) scale(1);opacity:0}15%{opacity:1}100%{transform:translate(-78px,6px) scale(.3);opacity:0}}
104@keyframes shake{0%,100%{transform:translateX(0)}20%{transform:translateX(-2px)}40%{transform:translateX(2px)}60%{transform:translateX(-1px)}80%{transform:translateX(1px)}}
105@keyframes drip{0%{transform:translateY(0);opacity:0}20%{opacity:1}100%{transform:translateY(18px);opacity:0}}
106@keyframes zzz{0%{transform:translate(0,0) scale(.6);opacity:0}30%{opacity:1}100%{transform:translate(14px,-26px) scale(1.15);opacity:0}}
107@keyframes spark{0%,100%{transform:scale(0) rotate(0);opacity:0}40%{transform:scale(1) rotate(45deg);opacity:1}70%{opacity:.8}}
108@keyframes pop{0%{transform:scale(.6);opacity:0}60%{transform:scale(1.08);opacity:1}100%{transform:scale(1)}}
109@keyframes breathe{0%,100%{transform:scaleY(1)}50%{transform:scaleY(.96)}}
110@keyframes flow{from{background-position:0 0}to{background-position:12px 0}}
111@keyframes dash{to{stroke-dashoffset:-12}}
112.idle .whole{animation:bob 2.8s ease-in-out infinite}
113.idle .eyes,.busy .eyes,.happy .eyes,.chomp .eyes{animation:blink 4.2s infinite}
114.busy .whole{animation:bob 1.1s ease-in-out infinite}
115.busy .pupils{animation:look 2.4s ease-in-out infinite}
116.busy .legA{animation:walkA .5s steps(2) infinite}
117.busy .legB{animation:walkB .5s steps(2) infinite}
118.happy .whole{animation:jump 1.2s ease-out infinite}
119.happy .spark{animation:spark 1.2s ease-out infinite}
120.chomp .whole{animation:bob .45s ease-in-out infinite}
121.chomp .mouth{animation:chomp .3s ease-in-out infinite}
122.chomp .crumb{animation:crumb 1.1s linear infinite}
123.worried .whole{animation:shake .9s ease-in-out infinite}
124.worried .drop{animation:drip 1.6s ease-in infinite}
125.sleepy .whole{animation:breathe 3.6s ease-in-out infinite}
126.sleepy .z{animation:zzz 2.7s ease-out infinite}
127.alert .whole{animation:shake .4s ease-in-out infinite}
128.alert .bang{animation:pop .5s ease-out both}
129.pop{animation:pop .45s ease-out both}
130.flowing{animation:dash .8s linear infinite}
131`
132 : ''
133}</style>`
134
135const rect = (x: number, y: number, w: number, h: number, p: number, fill: string, cls = ''): string =>
136 `<rect${cls === '' ? '' : ` class="${cls}"`} x="${String(x * p)}" y="${String(y * p)}" width="${String(w * p)}" height="${String(h * p)}" fill="${fill}"/>`
137
138/**
139 * Clawd's body on a 14 x 10 pixel grid, `p` CSS pixels a cell, with the parts
140 * each mood moves: eyes, pupils, mouth, legs, and the mood's own props.
141 */
142export const clawdBody = (mood: Mood, p: number): string => {
143 const body = mood === 'off' ? '#9b948e' : ORANGE
144 const shade = mood === 'off' ? '#86807a' : ORANGE_DARK
145 const isClosed = mood === 'sleepy' || mood === 'off'
146 const eyes = isClosed
147 ? `<g class="eyes">${rect(3.6, 3.2, 1.6, 0.45, p, INK)}${rect(8.8, 3.2, 1.6, 0.45, p, INK)}</g>`
148 : `<g class="eyes"><g class="pupils">${rect(4, 2, 1, 2, p, INK)}${rect(9, 2, 1, 2, p, INK)}</g></g>`
149 const props: string[] = []
150
151 switch (mood) {
152 case 'chomp':
153 props.push(
154 `<g class="mouth">${rect(5.5, 5, 3, 1.2, p, INK)}</g>`,
155 ...[0, 1, 2, 3].map(
156 index =>
157 `<g class="crumb" style="animation-delay:${String(index * 0.27)}s">${rect(17 + (index % 2), 4.3 + (index % 3) * 0.5, 0.9, 0.9, p, index % 2 === 0 ? '#7B83EB' : '#3FA55B')}</g>`,
158 ),
159 )
160 break
161 case 'worried':
162 props.push(
163 `<path class="drop" d="M${String(12.4 * p)} ${String(0.2 * p)} q${String(0.7 * p)} ${String(1.1 * p)} 0 ${String(1.6 * p)} q${String(-0.7 * p)} ${String(-0.5 * p)} 0 ${String(-1.6 * p)}z" fill="#6FB7E9"/>`,
164 )
165 break
166 case 'sleepy':
167 props.push(
168 ...['z', 'z', 'Z'].map(
169 (letter, index) =>
170 `<text class="t z" x="${String(12.5 * p)}" y="${String(0.5 * p)}" font-size="${String(1.4 * p + index * 2)}" font-weight="700" style="animation-delay:${String(index * 0.9)}s">${letter}</text>`,
171 ),
172 )
173 break
174 case 'happy':
175 props.push(
176 ...[
177 [-1.5, 0.5],
178 [14.3, 1],
179 [0, -1.8],
180 [13, -1.5],
181 ].map(
182 ([x = 0, y = 0], index) =>
183 `<path class="spark" style="animation-delay:${String(index * 0.18)}s" transform="translate(${String(x * p)} ${String(y * p)})" d="M0 -${String(p)} L${String(p * 0.28)} -${String(p * 0.28)} L${String(p)} 0 L${String(p * 0.28)} ${String(p * 0.28)} L0 ${String(p)} L-${String(p * 0.28)} ${String(p * 0.28)} L-${String(p)} 0 L-${String(p * 0.28)} -${String(p * 0.28)}Z" fill="#F2B84B"/>`,
184 ),
185 )
186 break
187 case 'alert':
188 props.push(
189 `<text class="t bang" x="${String(6.2 * p)}" y="${String(-0.6 * p)}" font-size="${String(2.6 * p)}" font-weight="800" fill="#E5484D" style="fill:#E5484D">!</text>`,
190 )
191 break
192 case 'idle':
193 case 'busy':
194 case 'off':
195 break
196 }
197
198 return [
199 `<ellipse cx="${String(7 * p)}" cy="${String(10.4 * p)}" rx="${String(5.5 * p)}" ry="${String(0.55 * p)}" fill="#000" opacity=".12"/>`,
200 '<g class="whole">',
201 `<g class="legA">${rect(3, 8, 1, 2, p, shade)}${rect(8, 8, 1, 2, p, shade)}</g>`,
202 `<g class="legB">${rect(5, 8, 1, 2, p, shade)}${rect(10, 8, 1, 2, p, shade)}</g>`,
203 rect(2, 0, 10, 8, p, body),
204 rect(0, 4, 2, 2, p, body),
205 rect(12, 4, 2, 2, p, body),
206 rect(2, 7, 10, 1, p, shade),
207 eyes,
208 ...props,
209 '</g>',
210 ].join('')
211}
212
213const KIND_COLORS: Readonly<Record<FeedKind, string>> = {
214 trim: '#3FA55B',
215 paste: '#3FA55B',
216 compact: '#7B83EB',
217 cold: '#6FB7E9',
218 warn: '#D99A00',
219 route: '#3FA55B',
220 escalate: '#E5484D',
221 info: '#8B8B8B',
222}
223
224const fillColor = (percent: number): string => {
225 if (percent >= 85) {
226 return '#E5484D'
227 }
228
229 return percent >= 70 ? '#D99A00' : ORANGE
230}
231
232/**
233 * The pane's hero: Clawd, a speech bubble, and the context meter, which also
234 * shows as a hatched ghost what the context would hold without the trims.
235 */
236export const heroSvg = (view: ClawdView, width: number): string => {
237 const w = Math.max(300, Math.round(width))
238 const p = 7
239 const clawdX = 18
240 const clawdY = 30
241 const bubbleX = clawdX + 14 * p + 26
242 const bubbleW = w - bubbleX - 10
243 const lines = wrap(view.speech, Math.max(16, Math.floor((bubbleW - 28) / 7.1)), 4)
244 const bubbleH = Math.max(46, lines.length * 18 + 22)
245 const bubbleY = Math.max(10, 58 - bubbleH / 2)
246 const meterY = 132
247 const meterW = w - 36
248 const { percent, tokens, window } = view.context
249 const fillW = window <= 0 ? 0 : Math.min(meterW, (tokens / window) * meterW)
250 const ghostW = window <= 0 ? 0 : Math.min(meterW - fillW, (view.ghost / window) * meterW)
251 const height = meterY + 44
252 const tail = `M${String(bubbleX)} ${String(bubbleY + bubbleH / 2 - 8)} L${String(bubbleX - 12)} ${String(bubbleY + bubbleH / 2 + 2)} L${String(bubbleX)} ${String(bubbleY + bubbleH / 2 + 8)}`
253 const label =
254 window <= 0
255 ? 'Context: waiting for the first reply'
256 : `Context ${String(percent)}% · ${formatTokens(tokens)} of ${formatTokens(window)}`
257
258 return [
259 `<svg xmlns="http://www.w3.org/2000/svg" width="${String(w)}" height="${String(height)}" viewBox="0 0 ${String(w)} ${String(height)}">`,
260 STYLE(view.hasMotion),
261 '<defs>',
262 `<linearGradient id="fill" x1="0" x2="1"><stop offset="0" stop-color="${ORANGE}"/><stop offset="1" stop-color="${fillColor(percent)}"/></linearGradient>`,
263 '<pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="3" height="6" fill="#3FA55B" opacity=".55"/></pattern>',
264 '</defs>',
265 `<g class="c ${view.mood}" transform="translate(${String(clawdX)} ${String(clawdY)})">${clawdBody(view.mood, p)}</g>`,
266 `<g class="pop">`,
267 `<rect class="bubble" x="${String(bubbleX)}" y="${String(bubbleY)}" width="${String(bubbleW)}" height="${String(bubbleH)}" rx="14" stroke-width="1.5"/>`,
268 `<path class="bubble" d="${tail}" stroke-width="1.5"/>`,
269 `<rect class="bubble" x="${String(bubbleX - 1)}" y="${String(bubbleY + bubbleH / 2 - 7)}" width="4" height="14" stroke="none"/>`,
270 ...lines.map(
271 (line, index) =>
272 `<text class="t" x="${String(bubbleX + 14)}" y="${String(bubbleY + 25 + index * 18)}" font-size="13">${escape(line)}</text>`,
273 ),
274 '</g>',
275 `<text class="t" x="18" y="${String(meterY - 8)}" font-size="12" font-weight="600">${escape(label)}</text>`,
276 view.ghost > 0
277 ? `<text class="d" x="${String(w - 18)}" y="${String(meterY - 8)}" font-size="11" text-anchor="end">hatched: ${formatTokens(view.ghost)} Clawd kept out</text>`
278 : '',
279 `<rect class="track" x="18" y="${String(meterY)}" width="${String(meterW)}" height="12" rx="6"/>`,
280 `<rect x="18" y="${String(meterY)}" width="${Math.max(fillW, window > 0 ? 6 : 0).toFixed(1)}" height="12" rx="6" fill="url(#fill)"/>`,
281 ghostW > 1
282 ? `<rect x="${(18 + fillW).toFixed(1)}" y="${String(meterY)}" width="${ghostW.toFixed(1)}" height="12" rx="3" fill="url(#hatch)"/>`
283 : '',
284 ...[50, 70, 85].map(mark => {
285 const x = 18 + (meterW * mark) / 100
286
287 return `<rect x="${x.toFixed(1)}" y="${String(meterY - 2)}" width="1" height="16" fill="#8b8b8b" opacity=".35"/>`
288 }),
289 `<text class="d" x="18" y="${String(meterY + 28)}" font-size="11">${escape(
290 view.context.percent >= 70
291 ? 'Past 70%: every request is heavy. Compact to lighten it.'
292 : 'Marks at 50 · 70 · 85%. Clawd speaks up as you cross them.',
293 )}</text>`,
294 '</svg>',
295 ].join('')
296}
297
298type Tile = { value: string; label: string; color: string; hint: string }
299
300/** The savings, as tiles: what was eaten, what re-sending that avoided, what compaction freed, what routing saved. */
301export const tilesSvg = (view: ClawdView, width: number): string => {
302 const w = Math.max(300, Math.round(width))
303 const tiles: Tile[] = [
304 {
305 value: formatTokens(view.stats.eaten),
306 label: 'noise eaten',
307 color: '#3FA55B',
308 hint: `${String(view.stats.trims)} outputs trimmed`,
309 },
310 {
311 value: formatTokens(view.stats.reReads),
312 label: 're-sends avoided',
313 color: '#7B83EB',
314 hint: 'trimmed tokens × later requests',
315 },
316 {
317 value: formatTokens(view.stats.compactFreed),
318 label: 'freed by compacting',
319 color: ORANGE,
320 hint: `${String(view.stats.compactions)} compaction${view.stats.compactions === 1 ? '' : 's'}`,
321 },
322 {
323 value: formatTokens(view.stats.routed + view.stats.keptOut),
324 label: 'routing & delegation',
325 color: '#D99A00',
326 hint: 'cheaper models for helpers',
327 },
328 ]
329 const columns = w >= 560 ? 4 : 2
330 const gap = 10
331 const tileW = (w - gap * (columns - 1)) / columns
332 const tileH = 70
333 const rows = Math.ceil(tiles.length / columns)
334 const height = rows * tileH + (rows - 1) * gap
335
336 return [
337 `<svg xmlns="http://www.w3.org/2000/svg" width="${String(w)}" height="${String(height)}" viewBox="0 0 ${String(w)} ${String(height)}">`,
338 STYLE(view.hasMotion),
339 ...tiles.map((tile, index) => {
340 const x = (index % columns) * (tileW + gap)
341 const y = Math.floor(index / columns) * (tileH + gap)
342
343 return [
344 `<g class="pop" style="animation-delay:${String(index * 0.06)}s"><title>${escape(tile.hint)}</title>`,
345 `<rect class="tile" x="${x.toFixed(1)}" y="${String(y)}" width="${tileW.toFixed(1)}" height="${String(tileH)}" rx="12"/>`,
346 `<rect x="${(x + 12).toFixed(1)}" y="${String(y + 14)}" width="4" height="${String(tileH - 28)}" rx="2" fill="${tile.color}"/>`,
347 `<text class="t" x="${(x + 26).toFixed(1)}" y="${String(y + 36)}" font-size="22" font-weight="700">${escape(tile.value)}</text>`,
348 `<text class="d" x="${(x + 26).toFixed(1)}" y="${String(y + 55)}" font-size="11.5">${escape(tile.label)}</text>`,
349 '</g>',
350 ].join('')
351 }),
352 '</svg>',
353 ].join('')
354}
355
356/** The strip above the prompt: a small Clawd, what it just did, and the context fill. */
357export const bandSvgOf = (view: ClawdView, width: number): string => {
358 const w = Math.max(240, Math.round(width))
359 const p = 3.4
360 const h = 46
361 const textX = 14 * p + 30
362 const pillW = 86
363 const text = fit(view.speech, Math.max(10, Math.floor((w - textX - pillW - 24) / 6.9)))
364 const { percent } = view.context
365
366 return [
367 `<svg xmlns="http://www.w3.org/2000/svg" width="${String(w)}" height="${String(h)}" viewBox="0 0 ${String(w)} ${String(h)}">`,
368 STYLE(view.hasMotion),
369 `<g class="c ${view.mood}" transform="translate(12 6)">${clawdBody(view.mood, p)}</g>`,
370 `<text class="t pop" x="${String(textX)}" y="${String(h / 2 + 4.5)}" font-size="13">${escape(text)}</text>`,
371 view.context.window > 0
372 ? [
373 `<rect class="track" x="${String(w - pillW - 8)}" y="${String(h / 2 - 9)}" width="${String(pillW)}" height="18" rx="9"/>`,
374 `<rect x="${String(w - pillW - 8)}" y="${String(h / 2 - 9)}" width="${Math.max(18, (pillW * percent) / 100).toFixed(1)}" height="18" rx="9" fill="${fillColor(percent)}" opacity=".85"/>`,
375 `<text class="t" x="${String(w - 8 - pillW / 2)}" y="${String(h / 2 + 4)}" font-size="11" font-weight="700" text-anchor="middle">ctx ${String(percent)}%</text>`,
376 ].join('')
377 : '',
378 '</svg>',
379 ].join('')
380}
381
382export const feedColor = (kind: FeedKind): string => KIND_COLORS[kind]
383
384// --- The terminal ----------------------------------------------------------
385
386const ART: Readonly<Record<Mood, readonly [string, string, string]>> = {
387 idle: [' ▐▛███▜▌ ', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
388 busy: [' ▐▛███▜▌ ', '▝▜█████▛▘', ' ▝▘ ▘▝ '],
389 happy: [' ▐▛███▜▌ ', '▝▜█▄▄▄█▛▘', ' ▘▘ ▝▝ '],
390 chomp: [' ▐▛███▜▌ ', '▝▜██▀██▛▘', ' ▘▘ ▝▝ '],
391 worried: [' ▐▛███▜▌▖', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
392 sleepy: [' ▐▄███▄▌ ', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
393 alert: [' ▐▛███▜▌!', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
394 off: [' ▐▄███▄▌ ', '▝▜█████▛▘', ' ▘▘ ▝▝ '],
395}
396
397const BLINK = ' ▐█████▌ '
398
399/** Clawd in block glyphs, three rows; blinks now and then while motion is on. */
400export const clawdArt = (view: ClawdView): readonly [string, string, string] => {
401 const art = ART[view.mood]
402 const isBlinking = view.hasMotion && view.mood !== 'sleepy' && view.mood !== 'off' && view.frame % 16 === 15
403
404 return isBlinking ? [BLINK, art[1], art[2]] : art
405}
406
407const CHOMP_TRAIL = ['◂ ▪ ▪ ▪', '◂▪ ▪ ▪ ', '◂ ▪ ▪ ', '◂▪ ▪ ']
408
409const toneOf = (view: ClawdView, tone: Tone): { tone?: Tone } => (view.hasColor ? { tone } : {})
410
411const moodTone = (mood: Mood): Tone => {
412 switch (mood) {
413 case 'worried':
414 return 'warning'
415 case 'alert':
416 return 'error'
417 case 'off':
418 case 'sleepy':
419 return 'inactive'
420 case 'happy':
421 case 'chomp':
422 return 'success'
423 case 'idle':
424 case 'busy':
425 return 'claude'
426 }
427}
428
429/** The strip above the prompt, in the terminal: one line. */
430export const bandLineOf = (view: ClawdView, columns: number): Line => {
431 const face = view.mood === 'sleepy' ? '▐▄█▄▌' : view.mood === 'chomp' ? '▐▛▀▜▌' : '▐▛█▜▌'
432 const trail = view.mood === 'chomp' && view.hasMotion ? ` ${CHOMP_TRAIL[view.frame % CHOMP_TRAIL.length] ?? ''}` : ''
433 const meter =
434 view.context.window > 0 ? ` ${bar(view.context.percent / 100, 8)} ${String(view.context.percent)}%` : ''
435 const room = Math.max(10, columns - face.length - trail.length - meter.length - 3)
436
437 return [
438 { text: face, ...toneOf(view, 'claude') },
439 { text: trail, ...toneOf(view, 'success'), isDim: true },
440 { text: ` ${fit(view.speech, room)}`, ...toneOf(view, moodTone(view.mood)) },
441 { text: meter, isDim: true },
442 ]
443}
444
445/** The speech bubble beside the art in a terminal pane, three rows to match it. */
446export const bubbleRows = (view: ClawdView, columns: number): readonly string[] => {
447 const width = Math.max(14, columns - 14)
448 const lines = wrap(view.speech, width - 4, 3)
449
450 while (lines.length < 3) {
451 lines.push('')
452 }
453
454 return lines.map((line, index) => `${index === 1 ? '◀ ' : ' '}${line}`)
455}
456src/ui/format.ts 36 lines1const SPINNER = ['◐', '◓', '◑', '◒'] as const
2
3/** 1234 -> "1.2k", 950 -> "950". A negative count keeps its sign. */
4export const formatTokens = (tokens: number): string => {
5 const size = Math.abs(tokens)
6 const sign = tokens < 0 ? '-' : ''
7
8 if (size >= 1_000_000) {
9 return `${sign}${(size / 1_000_000).toFixed(1)}M`
10 }
11
12 return size >= 1000 ? `${sign}${(size / 1000).toFixed(1)}k` : `${sign}${String(Math.round(size))}`
13}
14
15/** A fixed-width meter: `fraction` of `width` cells filled. */
16export const bar = (fraction: number, width: number): string => {
17 const cells = Math.max(1, Math.round(width))
18 const ratio = Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0
19 const filled = Math.round(ratio * cells)
20
21 return '█'.repeat(filled) + '░'.repeat(cells - filled)
22}
23
24/** The spinner glyph for a frame; one fixed glyph when motion is off. */
25export const spinner = (frame: number, hasMotion: boolean): string =>
26 hasMotion ? (SPINNER[Math.abs(frame) % SPINNER.length] ?? SPINNER[0]) : '◆'
27
28/** Cuts text to a width, marking the cut. */
29export const fit = (text: string, width: number): string => {
30 if (text.length <= width) {
31 return text
32 }
33
34 return width <= 1 ? text.slice(0, Math.max(0, width)) : `${text.slice(0, width - 1)}…`
35}
36src/ui/theme.ts 36 lines1/** Colours are named by meaning, as Claude Code's theme keys are, so they follow the user's theme. */
2export type Tone = 'success' | 'warning' | 'error' | 'claude' | 'suggestion' | 'inactive'
3
4/** One run of text with one style. The renderers build these; a surface paints them. */
5export type Span = {
6 text: string
7 tone?: Tone
8 isBold?: boolean
9 isDim?: boolean
10}
11
12export type Line = readonly Span[]
13
14export type Theme = {
15 /** False under NO_COLOR: no span carries a tone, and meaning rests on glyphs and words. */
16 hasColor: boolean
17 /** False under reduced motion: one static frame, and counters show their final value. */
18 hasMotion: boolean
19}
20
21export type SpanStyle = {
22 tone?: Tone
23 isBold?: boolean
24 isDim?: boolean
25}
26
27/** Builds a span for the theme: under NO_COLOR the tone is left out entirely. */
28export const span = (theme: Theme, text: string, style: SpanStyle = {}): Span => ({
29 text,
30 ...(theme.hasColor && style.tone !== undefined ? { tone: style.tone } : {}),
31 ...(style.isBold === true ? { isBold: true } : {}),
32 ...(style.isDim === true ? { isDim: true } : {}),
33})
34
35export const plain = (line: Line): string => line.map(part => part.text).join('')
36src/ui/view.ts 131 lines1import { summarizeLog } from '../core/log.ts'
2import type { TaskType } from '../core/score.ts'
3import type { Tier } from '../core/tiers.ts'
4import { activeCount, hasFreshFlash } from '../runtime/session.ts'
5import type { AgentNode, AgentStatus, FlashTone, Session, Spend } from '../runtime/session.ts'
6import type { Theme } from './theme.ts'
7
8export type ViewAgent = {
9 key: string
10 label: string
11 tier: Tier | undefined
12 taskType: TaskType
13 status: AgentStatus
14 tokens: number
15 escalatedFrom: Tier | undefined
16 /** One entry per ancestor level: true where a guide line still runs down beside this row. */
17 guides: readonly boolean[]
18 isLast: boolean
19}
20
21/** Everything the status line and the dashboard draw, as plain data. */
22export type View = {
23 mode: 'on' | 'off' | 'dry-run'
24 hasNoColor: boolean
25 hasReducedMotion: boolean
26 hasStatusLine: boolean
27 context: { tokens: number; window: number }
28 spend: Spend
29 total: number
30 saved: number
31 shownSaved: number
32 keptOut: number
33 history: readonly number[]
34 agents: readonly ViewAgent[]
35 activeCount: number
36 learning: { count: number; cleanRate: number; escalations: number }
37 notes: readonly string[]
38 frame: number
39 /** The strip above the prompt: the sub-agents running now and the newest event, while fresh. */
40 band: {
41 agents: readonly ViewAgent[]
42 flash: { text: string; tone: FlashTone } | undefined
43 }
44 /** Every sub-agent whose model tokensaver chose, for marking its row in the transcript. */
45 routed: readonly ViewAgent[]
46}
47
48const MAX_DEPTH = 4
49
50/** Orders agents as a tree walk: each agent, then the agents it spawned. */
51const walk = (
52 nodes: readonly AgentNode[],
53 parentAgentId: string | undefined,
54 guides: readonly boolean[],
55): readonly ViewAgent[] => {
56 const known = new Set(nodes.flatMap(node => (node.agentId === undefined ? [] : [node.agentId])))
57 const children = nodes.filter(node =>
58 parentAgentId === undefined
59 ? node.parentAgentId === undefined || !known.has(node.parentAgentId)
60 : node.parentAgentId === parentAgentId,
61 )
62
63 return children.flatMap((node, index) => [
64 {
65 key: node.key,
66 label: node.label,
67 tier: node.tier,
68 taskType: node.taskType,
69 status: node.status,
70 tokens: node.tokens,
71 escalatedFrom: node.escalatedFrom,
72 guides,
73 isLast: index === children.length - 1,
74 },
75 ...(node.agentId === undefined || guides.length >= MAX_DEPTH
76 ? []
77 : walk(nodes, node.agentId, [...guides, index < children.length - 1])),
78 ])
79}
80
81const modeOf = (session: Session): View['mode'] => {
82 if (!session.config.isEnabled) {
83 return 'off'
84 }
85
86 return session.config.isDryRun ? 'dry-run' : 'on'
87}
88
89export const toView = (session: Session): View => {
90 const summary = summarizeLog(session.outcomes)
91 const agents = walk(session.agents, undefined, [])
92
93 return {
94 mode: modeOf(session),
95 hasNoColor: session.hasNoColor,
96 hasReducedMotion: session.config.hasReducedMotion,
97 hasStatusLine: session.config.hasStatusLine,
98 context: session.context,
99 spend: session.spend,
100 total: session.spend.haiku + session.spend.sonnet + session.spend.opus + session.spend.other,
101 saved: session.saved,
102 shownSaved: session.shownSaved,
103 keptOut: session.keptOut,
104 history: session.savedHistory,
105 agents,
106 activeCount: activeCount(session),
107 learning: {
108 count: summary.count,
109 cleanRate: summary.cleanRate,
110 escalations: summary.escalations,
111 },
112 notes: session.notes,
113 frame: session.frame,
114 band: {
115 agents: agents.filter(agent => agent.status === 'running' || agent.status === 'retrying'),
116 flash:
117 session.flash !== undefined && hasFreshFlash(session)
118 ? { text: session.flash.text, tone: session.flash.tone }
119 : undefined,
120 },
121 routed: agents.filter(agent =>
122 session.agents.some(node => node.key === agent.key && node.isRouted && !node.isDryRun),
123 ),
124 }
125}
126
127export const themeOf = (view: View): Theme => ({
128 hasColor: !view.hasNoColor,
129 hasMotion: !view.hasReducedMotion,
130})
131src/core/escalate.ts 106 lines1import { nextTierUp } from './tiers.ts'
2import type { Tier } from './tiers.ts'
3
4export const CHECK_SIGNALS = [
5 'ok',
6 'error',
7 'failing-tests',
8 'low-confidence',
9 'empty',
10 'refusal',
11 'user-rejection',
12] as const
13
14/** What the checks made of a sub-agent's result. Anything but `ok` is a failure. */
15export type CheckSignal = (typeof CHECK_SIGNALS)[number]
16
17export const isCheckSignal = (value: unknown): value is CheckSignal =>
18 CHECK_SIGNALS.some(signal => signal === value)
19
20const FAILING_TESTS_PATTERN =
21 /\b\d+\s+(?:tests?\s+)?fail(?:ed|ing|ures?)\b|\btests?\s+(?:are\s+)?(?:still\s+)?fail(?:ed|ing)\b|\bAssertionError\b|^\s*FAIL\b/im
22
23/**
24 * Explicit statements of doubt or of not finishing. "Found nothing" is not
25 * here on purpose: an empty search result is a valid answer, not a failure.
26 */
27const LOW_CONFIDENCE_PATTERN =
28 /\b(?:i(?:'m| am) not (?:sure|certain|confident)|not confident|i (?:may|might) be wrong|(?:unable|was not able|wasn't able) to (?:complete|finish|determine)|could(?: not|n't) (?:complete|finish|determine)|ran out of (?:time|context|turns)|gave up|incomplete|best guess)\b/i
29
30const REJECTION_PATTERN =
31 /^\s*(?:no\b|nope\b|wrong\b|incorrect\b|that(?:'s| is| was)? (?:wrong|not right|incorrect|not what)|not what i|this is wrong|undo\b|revert\b|try again\b|redo\b|(?:it|that|this) (?:didn'?t|doesn'?t|did not|does not) work|still (?:broken|failing|wrong|not working))/i
32
33export type ResultCheck = {
34 isError: boolean
35 text: string
36}
37
38/** Runs the deterministic checks over a sub-agent's result. */
39export const checkResult = ({ isError, text }: ResultCheck): CheckSignal => {
40 if (isError) {
41 return 'error'
42 }
43
44 if (text.trim() === '') {
45 return 'empty'
46 }
47
48 if (FAILING_TESTS_PATTERN.test(text)) {
49 return 'failing-tests'
50 }
51
52 return LOW_CONFIDENCE_PATTERN.test(text) ? 'low-confidence' : 'ok'
53}
54
55/** True when the user's next prompt opens by rejecting the previous result. */
56export const isUserRejection = (prompt: string): boolean => REJECTION_PATTERN.test(prompt)
57
58export type EscalationInput = {
59 signal: CheckSignal
60 /** The tier the failed attempt ran on; undefined when tokensaver did not pick it. */
61 tier: Tier | undefined
62 /** Retries already spent on this task. */
63 attempts: number
64 isDenied: boolean
65 isDryRun: boolean
66}
67
68export type EscalationPlan =
69 | { shouldEscalate: true; to: Tier }
70 | { shouldEscalate: false; reason: string }
71
72/** The most retries one task gets: escalation is one step up, once. */
73export const MAX_RETRIES = 1
74
75/**
76 * Decides whether a failed result is retried one tier up. The answer is
77 * either a strictly higher tier or no retry at all: it never moves down.
78 */
79export const planEscalation = (input: EscalationInput): EscalationPlan => {
80 if (input.isDenied) {
81 return { shouldEscalate: false, reason: 'the call was denied, and a denial is final' }
82 }
83
84 if (input.signal === 'ok') {
85 return { shouldEscalate: false, reason: 'the result passed its checks' }
86 }
87
88 if (input.isDryRun) {
89 return { shouldEscalate: false, reason: 'dry run' }
90 }
91
92 if (input.tier === undefined) {
93 return { shouldEscalate: false, reason: 'tokensaver did not pick this model' }
94 }
95
96 if (input.attempts >= MAX_RETRIES) {
97 return { shouldEscalate: false, reason: 'already retried once' }
98 }
99
100 const to = nextTierUp(input.tier)
101
102 return to === undefined
103 ? { shouldEscalate: false, reason: 'already on the top tier' }
104 : { shouldEscalate: true, to }
105}
106src/core/route.ts 148 lines1import type { TaskScore, TaskType } from './score.ts'
2import { TOP_RANK, nextTierUp, rankOf, rankOfModel, tierAt } from './tiers.ts'
3import type { Tier } from './tiers.ts'
4
5/** A complexity below `haikuMax` runs on Haiku, below `sonnetMax` on Sonnet, the rest on Opus. */
6export type Cutoffs = {
7 haikuMax: number
8 sonnetMax: number
9 /** The log sequence number these cutoffs were last tuned at; older outcomes are spent evidence. */
10 tunedAtSeq: number
11}
12
13export type Thresholds = Readonly<Record<TaskType, Cutoffs>>
14
15/**
16 * Starting cutoffs. Mechanical work gets generous ones; reasoning and
17 * unknown work get tight ones, so an unrecognised task defaults upward.
18 */
19export const DEFAULT_THRESHOLDS: Thresholds = {
20 search: { haikuMax: 45, sonnetMax: 75, tunedAtSeq: 0 },
21 'bulk-read': { haikuMax: 40, sonnetMax: 75, tunedAtSeq: 0 },
22 summarize: { haikuMax: 35, sonnetMax: 70, tunedAtSeq: 0 },
23 'repetitive-edit': { haikuMax: 30, sonnetMax: 65, tunedAtSeq: 0 },
24 edit: { haikuMax: 15, sonnetMax: 55, tunedAtSeq: 0 },
25 reasoning: { haikuMax: 5, sonnetMax: 35, tunedAtSeq: 0 },
26 general: { haikuMax: 10, sonnetMax: 50, tunedAtSeq: 0 },
27}
28
29export type RouteDecision = {
30 tier: Tier
31 /** The tier the cutoffs alone picked, before any upward adjustment. */
32 base: Tier
33 reasons: readonly string[]
34}
35
36const bump = (tier: Tier): Tier => nextTierUp(tier) ?? tier
37
38/**
39 * Picks a tier for a scored task. Every adjustment after the cutoffs moves
40 * up: a boundary tie, an unsure score, a boost and a risky task all raise.
41 */
42export const routeTier = (score: TaskScore, thresholds: Thresholds, boost = 0): RouteDecision => {
43 const cutoffs = thresholds[score.taskType]
44 const base: Tier =
45 score.complexity < cutoffs.haikuMax
46 ? 'haiku'
47 : score.complexity < cutoffs.sonnetMax
48 ? 'sonnet'
49 : 'opus'
50 const reasons: string[] = [`${score.taskType} at complexity ${String(score.complexity)}`]
51 let tier = base
52
53 if (score.isUnsure) {
54 tier = bump(tier)
55 reasons.push('unsure, so one tier up')
56 }
57
58 for (let step = 0; step < boost; step += 1) {
59 tier = bump(tier)
60 }
61
62 if (boost > 0) {
63 reasons.push('previous result rejected, so one tier up')
64 }
65
66 if (score.isRisky) {
67 tier = 'opus'
68 reasons.push(`risky (${score.risks.join(', ')}), so never below the top tier`)
69 }
70
71 return { tier, base, reasons }
72}
73
74export type SpawnContext = {
75 /** The parent's effective model id: what the sub-agent inherits when no model is set. */
76 parentModel: string
77 /** A model the caller asked for by name, if any. */
78 explicitModel?: string | undefined
79 /** A tier an escalation retry must run on. */
80 forcedTier?: Tier | undefined
81}
82
83export type SpawnRouting = {
84 /** The model to hand `agent.spawn`, or undefined to leave the spawn exactly as it came. */
85 model: string | undefined
86 /** The tier the sub-agent runs on, for the log and the dashboard; undefined when unknown. */
87 tier: Tier | undefined
88 note: string
89}
90
91/** A family above the top routable tier has no tier name of its own. */
92const tierForRank = (rank: number): Tier | undefined =>
93 rank > TOP_RANK ? undefined : tierAt(rank)
94
95/**
96 * Turns a tier decision into the model a spawn should run on.
97 *
98 * Invariants the safety tests hold this to: a risky task never runs below the
99 * parent's tier or below a model the caller named, and an unknown parent
100 * model is never rerouted.
101 */
102export const resolveSpawnModel = (
103 decision: RouteDecision,
104 score: TaskScore,
105 context: SpawnContext,
106): SpawnRouting => {
107 if (context.forcedTier !== undefined) {
108 return { model: context.forcedTier, tier: context.forcedTier, note: 'escalation retry' }
109 }
110
111 const parentRank = rankOfModel(context.parentModel)
112 const explicitRank = rankOfModel(context.explicitModel)
113
114 if (parentRank === undefined) {
115 return { model: undefined, tier: undefined, note: 'unknown parent model, left as is' }
116 }
117
118 if (context.explicitModel !== undefined && explicitRank === undefined) {
119 return { model: undefined, tier: undefined, note: 'caller named an unknown model, left as is' }
120 }
121
122 const decided = rankOf(decision.tier)
123 // The top decision means "the best available": under a parent above Opus that is the parent.
124 const wanted = explicitRank ?? (decision.tier === 'opus' ? Math.max(decided, parentRank) : decided)
125 const floor = score.isRisky ? Math.max(parentRank, explicitRank ?? 0) : 0
126 const final = Math.max(wanted, floor)
127 const current = explicitRank ?? parentRank
128
129 if (final === current) {
130 return {
131 model: undefined,
132 tier: tierForRank(final),
133 note: context.explicitModel === undefined ? 'inherits the parent model' : 'caller chose the model',
134 }
135 }
136
137 // Reaching the parent's rank from a lower named model: name the parent's own model.
138 if (final === parentRank) {
139 return {
140 model: context.parentModel,
141 tier: tierForRank(final),
142 note: 'risky, raised to the parent model',
143 }
144 }
145
146 return { model: tierAt(final), tier: tierAt(final), note: decision.reasons.join('; ') }
147}
148src/core/score.ts 200 lines1/**
2 * Deterministic task scoring. No model call: every signal is a regular
3 * expression or a count over the task text, so scoring costs zero tokens.
4 */
5
6export const TASK_TYPES = [
7 'search',
8 'bulk-read',
9 'repetitive-edit',
10 'summarize',
11 'edit',
12 'reasoning',
13 'general',
14] as const
15
16export type TaskType = (typeof TASK_TYPES)[number]
17
18export const RISK_KINDS = ['security', 'destructive', 'production'] as const
19
20export type RiskKind = (typeof RISK_KINDS)[number]
21
22/** Each feature is normalised to 0..1. */
23export type Features = {
24 scope: number
25 files: number
26 ambiguity: number
27 depth: number
28 risk: number
29}
30
31export type TaskScore = {
32 taskType: TaskType
33 features: Features
34 /** 0..100: how much reasoning the task needs, which is what picks the tier. */
35 complexity: number
36 isRisky: boolean
37 risks: readonly RiskKind[]
38 /** True when the heuristics cannot place the task with confidence. */
39 isUnsure: boolean
40 /** Files the task names, or the count it states. */
41 namedFiles: number
42}
43
44export type TaskInput = {
45 text: string
46 description?: string | undefined
47 subagentType?: string | undefined
48}
49
50const RISK_PATTERNS: Readonly<Record<RiskKind, RegExp>> = {
51 security:
52 /\b(auth(?:entication|orization|n|z)?|passwords?|passphrases?|secrets?|credentials?|(?:access|auth|api|bearer|refresh|session)[- ]tokens?|api[- ]?keys?|private keys?|encrypt\w*|decrypt\w*|oauth|jwt|csrf|xss|sql injection|vulnerab\w*|security|permissions?|sudo|chmod|chown|ssh|certificates?|iam|rbac|cve-\d+)\b|\.env\b/gi,
53 destructive:
54 /\b(rm -rf?|delete\w*|drop (?:table|database|schema|index)|truncate\w*|wipe\w*|purge\w*|destroy\w*|force[- ]push\w*|reset --hard|git clean|overwrit\w*|erase\w*|remove all|uninstall\w*|migrations?|rollback|format (?:the )?(?:disk|drive))\b|push (?:-f\b|--force)/gi,
55 production:
56 /\b(prod(?:uction)?|deploy\w*|releas\w*|live (?:site|system|server|database|db|traffic)|customer data|billing|payments?|invoic\w*|payroll|terraform|kubectl|kubernetes|infra(?:structure)?|ci\/cd|dns|rollout|hotfix)\b/gi,
57}
58
59/** Task types that can be told from the text. `general` is what is left. */
60type KnownType = Exclude<TaskType, 'general'>
61
62const TYPE_PATTERNS: Readonly<Record<KnownType, RegExp>> = {
63 summarize:
64 /\b(summari[sz]\w*|summary|tl;?dr|recap|digest|condense\w*|overview|gist)\b/gi,
65 search:
66 /\b(find|search\w*|grep|locate|look (?:for|up)|where (?:is|are|does|do)|which files?|list (?:all|every)|usages?|references? to|occurrences?|who calls|callers of)\b/gi,
67 'bulk-read':
68 /\b(read (?:all|every|each|through)|go through|scan\w*|inventory|catalogu?e?|survey|review (?:all|every|each)|collect (?:all|every)|gather\w*|crawl\w*)\b/gi,
69 'repetitive-edit':
70 /\b(renam\w*|replace (?:all|every|each)|(?:find|search) and replace|codemod|bulk|mass|in (?:all|every|each) files?|every (?:file|occurrence|instance)|across all files|update (?:all|every|each)|apply the same|convert (?:all|every|each)|reformat\w*|bump (?:all|the) versions?)\b/gi,
71 reasoning:
72 /\b(design\w*|architect\w*|why|root cause|debug\w*|diagnos\w*|race conditions?|deadlocks?|trade-?offs?|algorithms?|prove|optimi[sz]\w*|plan|strategy|investigat\w*|concurrency|refactor\w*|redesign\w*|evaluat\w*|compar\w*|decide|reason about|analy[sz]\w*|performance|memory leaks?)\b/gi,
73 edit: /\b(fix\w*|implement\w*|add|chang\w*|writ\w*|updat\w*|creat\w*|modif\w*|remov\w*|edit\w*|patch\w*|build|make)\b/gi,
74}
75
76/**
77 * Tie-break order: when two types match equally often, the one that routes
78 * to the higher tier wins, so a tie never sends work to a cheaper model.
79 */
80const TYPE_PRIORITY: readonly KnownType[] = [
81 'reasoning',
82 'edit',
83 'repetitive-edit',
84 'summarize',
85 'bulk-read',
86 'search',
87]
88
89const SCOPE_PATTERN =
90 /\b(all|every|each|entire|whole|across|everywhere|codebase|repo(?:sitory)?|project-wide|global(?:ly)?|monorepo|recursive(?:ly)?)\b|\*\*?\/|\*\.\w+/gi
91
92const PATH_PATTERN =
93 /(?:[\w.-]+\/)+[\w.-]+|\b[\w-]+\.(?:tsx?|jsx?|mjs|cjs|py|go|rs|java|rb|md|json|ya?ml|toml|s?css|html|sql|sh|c|cpp|h|cs|php|kt|swift)\b/gi
94
95const FILE_COUNT_PATTERN = /\b(\d{1,4}) files?\b/i
96
97const VAGUE_PATTERN =
98 /\b(somehow|maybe|perhaps|something|stuff|things?|etc|whatever|figure out|not sure|i guess|kind of|sort of|improve\w*|better|clean ?up|tidy|polish|as needed|if needed|appropriate(?:ly)?)\b/gi
99
100const IDENTIFIER_PATTERN = /`[^`]+`|\b[a-z]+[A-Z]\w*\b|\b\w+_\w+\b/g
101
102const STEP_PATTERN = /\b(then|after that|afterwards|finally|next,)\b|^\s*\d+[.)]\s/gim
103
104const clamp01 = (value: number): number => Math.min(1, Math.max(0, value))
105
106const matchesOf = (text: string, pattern: RegExp): readonly string[] =>
107 Array.from(text.matchAll(pattern), match => match[0].toLowerCase())
108
109const countOf = (text: string, pattern: RegExp): number => matchesOf(text, pattern).length
110
111const wordCountOf = (text: string): number => text.split(/\s+/).filter(word => word !== '').length
112
113const classify = (text: string): TaskType => {
114 const ranked = TYPE_PRIORITY.map((type, priority) => ({
115 type,
116 priority,
117 hits: countOf(text, TYPE_PATTERNS[type]),
118 })).sort((a, b) => b.hits - a.hits || a.priority - b.priority)
119
120 const best = ranked[0]
121
122 return best === undefined || best.hits === 0 ? 'general' : best.type
123}
124
125const risksOf = (text: string): readonly RiskKind[] =>
126 RISK_KINDS.filter(kind => countOf(text, RISK_PATTERNS[kind]) > 0)
127
128const namedFilesOf = (text: string): number => {
129 const paths = new Set(matchesOf(text, PATH_PATTERN)).size
130 const stated = Number(FILE_COUNT_PATTERN.exec(text)?.[1] ?? 0)
131
132 return Math.max(paths, stated)
133}
134
135const filesFeature = (count: number, scope: number): number => {
136
137 // A broad task that names no file touches an unknown number of them.
138 if (count === 0 && scope >= 0.34) {
139 return 0.5
140 }
141
142 return clamp01(count / 8)
143}
144
145const ambiguityFeature = (text: string, words: number): number => {
146 const anchors = countOf(text, IDENTIFIER_PATTERN) + new Set(matchesOf(text, PATH_PATTERN)).size
147 const vague = countOf(text, VAGUE_PATTERN) / 3
148 const isTerse = words < 6 && anchors === 0
149 const isConcrete = anchors >= 2
150
151 return clamp01(vague + (isTerse ? 0.4 : 0) - (isConcrete ? 0.2 : 0))
152}
153
154const depthFeature = (text: string, words: number): number => {
155 const reasoning = countOf(text, TYPE_PATTERNS.reasoning) / 3
156 const steps = Math.min(0.2, countOf(text, STEP_PATTERN) * 0.1)
157
158 return clamp01(reasoning + steps + (words > 150 ? 0.2 : 0))
159}
160
161/** Scores a task from its text alone. Pure and deterministic. */
162export const scoreTask = (input: TaskInput): TaskScore => {
163 const text = [input.description ?? '', input.text].join('\n').trim()
164 const words = wordCountOf(text)
165 const scope = clamp01(countOf(text, SCOPE_PATTERN) / 3)
166 const risks = risksOf(text)
167 const namedFiles = namedFilesOf(text)
168 const riskHits = RISK_KINDS.reduce((sum, kind) => sum + countOf(text, RISK_PATTERNS[kind]), 0)
169 const features: Features = {
170 scope,
171 files: filesFeature(namedFiles, scope),
172 ambiguity: ambiguityFeature(text, words),
173 depth: depthFeature(text, words),
174 risk: clamp01(riskHits / 2),
175 }
176 const taskType = classify(text)
177 const complexity = Math.round(
178 100 *
179 clamp01(
180 0.45 * features.depth +
181 0.25 * features.ambiguity +
182 0.15 * features.scope +
183 0.15 * features.files,
184 ),
185 )
186
187 return {
188 taskType,
189 features,
190 complexity,
191 isRisky: risks.length > 0,
192 risks,
193 isUnsure: features.ambiguity >= 0.6 || taskType === 'general' || words < 3,
194 namedFiles,
195 }
196}
197
198export const isTaskType = (value: unknown): value is TaskType =>
199 TASK_TYPES.some(type => type === value)
200