The session's dashboard in one pane, opened by /dash: the model, the effort and presets that set both, ultracode and fast mode, each switched with one click…

One pane, opened by /dash, that gathers what you would otherwise reach through a dozen slash commands: the model, the effort level and presets that set both, ultracode and fast mode, the context and quota gauges, the cost and the duration, /compact, the session's name, your agents, commands, skills, plugins, MCP servers and hooks, and the /config settings. A click changes any of them. The model, the effort and the session's gauges can also sit in the band above the prompt, and compact mode folds each list onto its current row.
At the prompt of a Claude Code session in a terminal:
/plugin install dash --marketplace devohmycode/ccmods
Answer y to add the marketplace, then pick a scope.
<table> <tr> <th>Terminal</th> <th>Claude desktop (Code tab)</th> </tr> <tr> <td valign="top"><img src="assets/dash-terminal.png" alt="dash in the terminal" width="300"></td> <td valign="top"><img src="assets/dash-desktop.png" alt="dash in the Claude desktop app" width="300"></td> </tr> </table>
Each model has its color: purple for Fable, orange for Opus, blue for Sonnet, green for Haiku. The Model frame takes the active model's color, and its row carries the version read from its id (Opus 5.5). Effort runs from green to red, and its frame takes the active level's color. The desktop app draws the effort gauges and the context bar as graphics, the terminal as text.
A switch that goes through is announced by a 5 s toast: ⇄ Model Opus → Sonnet, ⚡ Effort medium → max or ◇ Preset deep: Sonnet → Opus, medium → xhigh. When a switch fails, the toast says why.
| Command | Effect |
|---|---|
/dash | opens the pane |
/dash opus, /dash sonnet, /dash haiku, /dash fable | switches model without the pane |
/dash low … /dash max | switches effort without the pane |
/dash deep, /dash quick, … | applies a preset |
/dash ultracode, /dash ultracode off | turns ultracode on or off (/effort ultracode) |
/dash set … | lists or changes the mod's settings (see Settings) |
/model's list, so the mod keeps its own (MORE_MODELS).low to max, each with its gauge. An effort just picked shows (asked) until a main request carries it.deep (Opus · xhigh), daily (Sonnet · medium) and quick (Haiku) out of the box. + New preset opens a form — name, model, effort or the model's own — and Add saves it to the presets setting. A preset you added can be deleted from the pane; the shipped ones cannot./cost totals it, and how long it has run. The pane redraws once a minute so the durations stay current./compact <instructions>. A stray click summarizes nothing./rename. A /rename you type yourself shows here too.The ↧ next to the Model, Effort and Session titles puts that frame's values in the band above the prompt, and takes them out again; it is dim while they are not there, and a toast says which. The band shows them in one row, wrapped where it is narrow:
What the band shows is kept in the band setting, from one session to the next; nothing put there, the band is left to Claude Code.
Compact mode at the foot of the pane, above the shortcuts (or /dash set compact on), folds the Model, Effort and Presets frames onto their current row, or their first where none is current, and hides Other and + New preset. Pressed again, it unfolds them.
Seven folded sections, each with its count. A click on a title unfolds it in a frame of its color.
| Section | What it lists | A click on an entry | |
|---|---|---|---|
| Subagents | your custom agents (the local /context breakdown) | puts @agent-<name> at the head of the prompt: your next message goes to it | |
| Commands | the .md files under commands/ (a subfolder is a namespace: git/commit.md → /git:commit) | puts /<name> at the head of the prompt | |
| Skills | the folders under skills/ that hold a SKILL.md | puts /<name> at the head of the prompt | |
| Plugins | the plugins enabledPlugins names in your settings | turns it on or off (`claude plugin enable\ | disable`); ↻ /reload-plugins then applies it |
| MCP servers | the connected, configured and disabled servers | turns it on or off (`/mcp enable\ | disable`) |
| Hooks | the hooks in your settings, by event, with how many run on each | nothing: /hooks changes them | |
| Settings | every /config row | changes it at once: a switch, a drop-down or a field |
Subagents, commands and skills are split into two frames: Global (~/.claude/…) then Project (the session folder's .claude/…). The plugins' and the built-in ones are left out. Each frame shows its first 3 entries; ▾ Expand (+N) shows the rest, ▴ Collapse goes back. What is unfolded stays so until the module reloads.
Putting a command or an agent in the prompt replaces one already there and keeps what you typed after it. Nothing is sent until you send it. The filled dot marks the entry the draft opens with. The lists are read again each time /dash opens, so a file added during the session shows on the next open. The global folder is CLAUDE_CONFIG_DIR where set, ~/.claude otherwise.
Hidden by default. Keyboard shortcuts: hidden at the foot of the pane (or /dash set keyboard on) shows them, each next to its row, and binds them while the pane has focus.
The switches take one run of keys: digits for the models then the levels, letters for the presets, then fast mode and ultracode. With the default catalog: 1–4 model, 5–9 effort, b d e preset, f fast mode, i ultracode. The run follows your settings.
The other buttons have a fixed key: o other models, n new preset, v add it, x compact (y to confirm), r rename, a c s p m h the library sections, g Settings, l /reload-plugins, k hide the shortcuts.
/dash set)Installing the mod asks nothing: its settings are not in the manifest's userConfig, every line of which Claude Code would show at install time. They are set by command, and the mod keeps them in its own store, from one session to the next.
| Command | Effect |
|---|---|
/dash set | lists the settings and their values |
/dash set language fr | changes a setting, in effect at once |
/dash set presets | no value: back to the default |
| Setting | Default | Effect |
|---|---|---|
language | en | en, fr, es, de. A line a translation lacks shows in English. |
presets | deep=opus/xhigh, daily=sonnet/medium, quick=haiku | name=model/effort or name=model (the effort stays as it is). |
models | empty | ids to add after the built-in models: id or id=Label (claude-opus-4-1=Opus 4.1). |
hideModels | empty | keys or ids to remove from the pane (fable). |
maxAgents | empty | cap on agents per workflow (3); empty, none. |
keyboard | off | on shows and binds the shortcuts. |
compact | off | on folds the lists onto their current row. |
band | empty | what the band above the prompt shows: model, effort, session, comma-separated. |
models and hideModels let you follow a model the built-in list does not name yet: /dash set hideModels fable then /dash set models claude-fable-5-2=Fable 5.2 replace Fable's id without touching the code. A preset named like a model, a level, set or ultracode (opus, max) could never be reached by /dash, since that name means something else first: it is refused. Any part of a setting that does not read is set aside and named at the foot of the pane and in /dash set's answer, rather than failing the mod.
The description of /dash in the command list takes the new language at the next session; the pane and the answers take it at once.
/model <alias> or /effort <level>, as if you typed it. The session's setting changes and the status line follows; the mod does not stand between the session and its model./effort saves the level picked as the default setting./model if the model differs, then /effort if the level differs and the model takes one. Both land before the next request, so the cache is lost only once./effort (a version that lacks it), the mod keeps the level picked and writes it into each main request at turn.step, and the pane says so. If the engine then sends another level under the same model, the mod lets go of its own.turn.step carries the model and effort the engine resolved, including after a silent downgrade: the pane shows what was sent, not what was asked. Before the first request, the model comes from $.session.model() and the effort from the effortLevel setting.already on …, and the cache stays intact.models), then by its family. A model the pane does not offer shows by its id in the header, with no row checked./dash opus cannot run /model from its own hook: the session is waiting on that hook. The mod answers at once, then runs the command on a 0 ms timer. If the session is not ready yet, it says so rather than announcing a switch that will not happen./dash low answers without running anything./fast. It toggles; no hook reads its state, so the pane shows the one the last /fast reported (yours or its own), and — until one has run./effort. It runs /effort ultracode or /effort ultracode off and leaves the effort level as it is. No hook reads its state: the pane shows the one the mod last asked for (off at session start, since it lasts one session). A /effort ultracode typed by hand escapes it. Its frame also shows the workflow size set in /config, read from .claude.json (read only: a mod does not write there)./dash set maxAgents 3): a hard cap on how many agents a workflow starts. A workflow's agents pass no hook (agent.spawn only sees the Agent tool), so the mod rewrites the script when the Workflow tool is called, a counter right after meta. Past the cap, agent() fails with dash: agent cap (N) reached, which parallel() and pipeline() turn into null. The cap fails closed: a script run by scriptPath is read and sent inline, capped; a workflow run by name, or a script with no meta literal, is refused with the reason; a nested workflow() is refused, its agents escaping the counter. Finding meta skips strings and comments. There is no token budget: a +300k typed in the message gave workflows no cap (budget.total empty, measured), so the mod adds none.Switching model or effort mid-session invalidates the message cache: the next request writes the whole context again at full price. The pane does not show it; the switch's toast says it, when it happens.
· 84 k tokens to cache again when the cache could still hold them./effort auto is not offered: turn.step reports the resolved level, so an auto button could never show as active. A "session only" mode, which would leave the default for new sessions alone, does not exist yet: for the model, it would mean rewriting e.model at turn.step, and the status line would no longer follow.
hooks/register.ts 1150 lines1/**
2 * Switch: a pane that lists the models, the effort levels and the presets
3 * that set both, and switches any of them with one click.
4 *
5 * A click runs the engine's own command, `/model <alias>` or
6 * `/effort <level>`, as if the person typed it: the session's setting
7 * changes, the status line follows, and nothing of the mod stands between
8 * the session and its model. Where the session has no `/effort`, the mod
9 * holds the level and writes it on each main request at `turn.step`.
10 *
11 * The current values come from the requests themselves: every main
12 * `turn.step` carries the model and the effort the engine resolved for it,
13 * after any downgrade, so the pane shows what was sent, not what was asked.
14 * Its result carries the usage the pane prices a switch with.
15 */
16
17import type { ConfigRow, ConfigValue, EngineInterface, FsEntry, PromptBox, PromptFilled, Register, SettingsSource } from 'claude-code'
18
19import { agentsOf, draftWith, mentionOf, mentionedIn } from './agents'
20import type { AgentScope } from './agents'
21import {
22 MORE_MODELS,
23 cappedScriptOf,
24 fastStateOf,
25 choiceOf,
26 effortOf,
27 idleReasonOf,
28 pickOf,
29 planOf,
30 presetText,
31 savedEffortOf,
32 switchedText,
33} from './catalog'
34import type { Effort, Pick } from './catalog'
35import { catalogOf, isOwnPreset, presetPartOf, withoutPreset } from './config'
36import type { Catalog, PresetDraft } from './config'
37import { LONG_TTL_MS, WARM_MS, costSuffixOf, measureOf, switchCostOf } from './cost'
38import type { LastRequest, SwitchCost } from './cost'
39import {
40 EMPTY_LIBRARY,
41 commandNameOf,
42 draftWithCommand,
43 entriesOf,
44 hooksOf,
45 invokedIn,
46 isToggleKind,
47 jsonOf,
48 keysOf,
49 mcpOf,
50 pluginsOf,
51 projectStateOf,
52 serverNameOf,
53 stringsOf,
54 toggleCommandOf,
55} from './library'
56import type { Library, LibraryKind, Sourced } from './library'
57import { COMMAND, NEW_PRESET_KEY, PANE_ID } from './names'
58import { drawBand, drawPane } from './pane'
59import { LANGUAGES, say, setSay } from './say'
60import {
61 BAND_PARTS,
62 DEFAULT_PREFS,
63 PREF_KEYS,
64 bandOf,
65 prefKeyOf,
66 prefsLines,
67 prefsOf,
68 setRequestOf,
69 stateFileOf,
70 withPref,
71} from './settings'
72import type { BandPart, Prefs } from './settings'
73import { USAGE_TICK_MS, usageViewOf } from './usage'
74
75/**
76 * The calls the buttons make after the render that drew them has returned,
77 * captured from `engine.create`.
78 */
79type Host = {
80 invalidate: () => void
81 model: () => Promise<string>
82 run: (command: string, args: string) => Promise<unknown>
83 toast: (text: string, timeoutMs?: number) => void
84 later: (fn: () => void) => void
85 after: (ms: number, fn: () => void) => { cancel: () => void }
86 now: () => Promise<number>
87 read: () => Promise<PromptBox>
88 fill: (text: string) => Promise<PromptFilled>
89 list: (path: string) => Promise<FsEntry[]>
90 exists: (path: string) => Promise<boolean>
91 save: (prefs: Prefs) => Promise<unknown>
92 settings: (source: SettingsSource) => Promise<Record<string, unknown>>
93 file: (path: string) => Promise<string>
94 cwd: () => Promise<string>
95 exec: (argv: readonly string[]) => Promise<{ exitCode: number; stdout: string; stderr: string }>
96 setConfig: (key: string, value: ConfigValue) => Promise<{ value?: unknown; deny?: string }>
97}
98
99/** The settings sources the setup is read from, lowest first, each with its scope. */
100const SETUP_SOURCES: readonly [AgentScope, SettingsSource][] = [
101 ['user', 'user'],
102 ['project', 'project'],
103 ['project', 'local'],
104]
105
106/**
107 * Where the person's own definitions and the engine's state file live;
108 * unreadable variables leave the global folders out, not the pane.
109 *
110 * @param $ the engine
111 * @returns the `.claude` folder and the state file, where known
112 */
113async function pathsOf($: EngineInterface): Promise<{ configDir: string | undefined; stateFile: string | undefined }> {
114 const home =
115 (await $.env.get('USERPROFILE').catch(() => undefined)) ?? (await $.env.get('HOME').catch(() => undefined))
116 const custom = await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)
117
118 return { configDir: custom ?? (home === undefined ? undefined : `${home}/.claude`), stateFile: stateFileOf(home, custom) }
119}
120
121/**
122 * The settings the mod's store keeps, each missing one at its default.
123 *
124 * @param $ the engine
125 * @returns the settings
126 */
127async function storedPrefsOf($: EngineInterface): Promise<Prefs> {
128 return prefsOf(await $.store.get('settings').catch(() => undefined))
129}
130
131/** How deep a commands folder's namespaces are followed. */
132const COMMANDS_DEPTH = 3
133
134/** How long a switch's notification stays, in milliseconds. */
135const TOAST_MS = 5000
136
137/**
138 * Registers `/dash`, its pane, and the `turn.step` hook that keeps the
139 * pane's values current. Each switch that takes is announced by a toast
140 * naming the values before and after; one that fails, by its reason.
141 *
142 * The settings come from the mod's store, read at `session.start` and
143 * rewritten by `/dash set`; the manifest declares none, so installing
144 * the mod asks nothing.
145 *
146 * @param on the module's hook registrar
147 */
148export const register: Register = on => {
149 let prefs: Prefs = DEFAULT_PREFS
150 let catalog: Catalog = catalogOf(prefs)
151
152 /**
153 * Puts the settings in force: the language, then the catalog they name.
154 *
155 * @param next the settings
156 */
157 const settle = (next: Prefs): void => {
158 prefs = next
159 setSay(prefs.language)
160 catalog = catalogOf(prefs)
161 }
162
163 settle(prefs)
164
165 let host: Host | undefined
166 let model: string | undefined
167 let effort: Effort | undefined
168 // The level a click asked for where the session has no /effort: the mod
169 // writes it on each main request instead.
170 let held: Effort | undefined
171 let hasEffortCommand = true
172 // The model and level the engine itself last sent, before the mod's: when
173 // the level moves under the same model, the person ran /effort, and their
174 // level wins over the held one. A new model brings its own default level.
175 let engineSeen: { model: string; effort: string | number | undefined } | undefined
176 let hasFast = false
177 // Fast mode's state, from the last /fast output; unknown until one runs.
178 let isFast: boolean | undefined
179 // Ultracode lasts the session and no hook reads it: the mod keeps what it
180 // last asked, off at the start.
181 let isUltracode = false
182 // Whether the paths and the lists were read: a module reloaded mid-session
183 // gets no session.start, and its first draw reads them instead.
184 let isRead = false
185 // Whether the settings were read from the store: a module reloaded
186 // mid-session reads them on its first draw, the band's or the pane's.
187 let isPrefsRead = false
188 // True from a click on an effort until a main request carries a level:
189 // till then the pane shows what was asked, not what was sent.
190 let isEffortAsked = false
191 // The last main request, measured, and the timers that redraw the pane
192 // when its cache crosses 5 minutes, then 1 hour.
193 let last: LastRequest | undefined
194 let expiry: { cancel: () => void }[] = []
195 // The redraw that ages the Session frame's durations, armed by a draw.
196 let tick: { cancel: () => void } | undefined
197 // The person's agents, commands and skills, read at session.start and
198 // again each time /dash opens the pane.
199 let library: Library = EMPTY_LIBRARY
200 // Where the person's own definitions live (`~/.claude`), read at session.start.
201 let configDir: string | undefined
202 // The engine's state file (`.claude.json`), read at session.start and on each open.
203 let stateFile: string | undefined
204 // True from a plugin's toggle until `/reload-plugins` has run.
205 let isReloadPending = false
206 // The MCP servers with tools in the context, from the last breakdown.
207 let connected: string[] = []
208 // What the prompt box opens with, by kind: read when /dash opens the pane
209 // and set by a pick, never by the render, which must not wait on the box.
210 let current: Partial<Record<LibraryKind, string>> = {}
211 // The sections the person opened and the scope frames they expanded
212 // (`<kind>:<scope>`), for the life of the module.
213 const openKinds = new Set<LibraryKind>()
214 const expandedFrames = new Set<string>()
215 // The session's name, once /rename gave one, and whether its field is
216 // open again to change it: a named session shows the name, not the field.
217 let sessionName: string | undefined
218 let isRenaming = false
219 // Whether /compact waits for its confirmation: a stray click summarizes
220 // the conversation for good.
221 let isCompactAsked = false
222 // The instructions typed for it, passed on as `/compact <instructions>`.
223 let compactNote = ''
224 // The preset the person is composing in the pane.
225 let draftPreset: PresetDraft = { name: '', model: '', effort: '' }
226 // The drop-downs the person opened, by key.
227 const openMenus = new Set<string>()
228
229 /**
230 * The commands or the skills defined under one `.claude` folder.
231 *
232 * @param kind `commands` (Markdown files, a subfolder a namespace) or `skills` (folders with a SKILL.md)
233 * @param base the `.claude` folder
234 * @returns their names; none where the folder is missing
235 */
236 const namesIn = async (kind: 'commands' | 'skills', base: string): Promise<string[]> => {
237 const h = host
238
239 if (h === undefined) {
240 return []
241 }
242
243 if (kind === 'skills') {
244 const dirs = await h.list(`${base}/skills`).catch(() => [])
245 const found = await Promise.all(
246 dirs
247 .filter(one => one.kind === 'dir' || one.isLink)
248 .map(async one => ((await h.exists(`${base}/skills/${one.name}/SKILL.md`).catch(() => false)) ? one.name : '')),
249 )
250
251 return found.filter(name => name !== '')
252 }
253
254 const names: string[] = []
255 const walk = async (path: string, depth: number): Promise<void> => {
256 for (const one of await h.list(`${base}/commands${path}`).catch(() => [])) {
257 if (one.kind === 'dir' && depth < COMMANDS_DEPTH) {
258 await walk(`${path}/${one.name}`, depth + 1)
259 } else if (one.kind === 'file') {
260 const name = commandNameOf(`${path}/${one.name}`)
261
262 if (name !== undefined) {
263 names.push(name)
264 }
265 }
266 }
267 }
268
269 await walk('', 0)
270
271 return names
272 }
273
274 /**
275 * Reads the library again: the agents from the breakdown, the commands
276 * and the skills from the global and the project's folders.
277 *
278 * @param agents the breakdown's agents, or `undefined` to keep the last ones
279 */
280 const readLibrary = async (agents: readonly { agentType: string; source: string }[] | undefined): Promise<void> => {
281 const roots: [AgentScope, string | undefined][] = [
282 ['user', configDir],
283 ['project', '.claude'],
284 ]
285 const read = async (kind: 'commands' | 'skills') =>
286 (
287 await Promise.all(
288 roots.map(async ([scope, base]) => (base === undefined ? [] : entriesOf(await namesIn(kind, base), scope))),
289 )
290 ).flat()
291
292 library = {
293 ...library,
294 agents: agents === undefined ? library.agents : agentsOf(agents).map(one => ({ name: one.type, scope: one.scope })),
295 commands: await read('commands'),
296 skills: await read('skills'),
297 }
298 }
299
300 /**
301 * Reads the setup again: the plugins and the hooks from the settings
302 * sources, the MCP servers from the breakdown, the state file and `.mcp.json`.
303 *
304 * @param mcpTools the breakdown's MCP tools, or `undefined` to keep the last servers
305 */
306 const readSetup = async (mcpTools: readonly { serverName: string }[] | undefined): Promise<void> => {
307 const h = host
308
309 if (h === undefined) {
310 return
311 }
312
313 connected = mcpTools === undefined ? connected : mcpTools.map(one => serverNameOf(one.serverName))
314 const sources = await Promise.all(
315 SETUP_SOURCES.map(async ([scope, source]) => [scope, await h.settings(source).catch((): Record<string, unknown> => ({}))] as const),
316 )
317 const state = jsonOf(stateFile === undefined ? '' : await h.file(stateFile).catch(() => ''))
318 const project = projectStateOf(state, await h.cwd().catch(() => ''))
319 const mcpJson = jsonOf(await h.file('.mcp.json').catch(() => '')) as { mcpServers?: unknown } | undefined
320 const of = (key: string): Sourced[] => sources.map(([scope, settings]) => [scope, settings[key]])
321
322 library = {
323 ...library,
324 plugins: pluginsOf(of('enabledPlugins')),
325 hooks: hooksOf(of('hooks')),
326 mcp: mcpOf({
327 connected,
328 user: keysOf((state as { mcpServers?: unknown } | undefined)?.mcpServers),
329 project: [...keysOf(project['mcpServers']), ...keysOf(mcpJson?.mcpServers)],
330 disabled: [...stringsOf(project['disabledMcpServers']), ...stringsOf(project['disabledMcpjsonServers'])],
331 }),
332 }
333 }
334
335 /**
336 * Turns a plugin or an MCP server the other way through the engine's own
337 * command, `/plugin enable|disable` or `/mcp enable|disable`.
338 *
339 * @param kind `plugins` or `mcp`
340 * @param name the entry clicked
341 * @returns once the command has run and the pane redrawn
342 */
343 const toggleEntry = async (kind: 'plugins' | 'mcp', name: string): Promise<void> => {
344 const entry = library[kind].find(one => one.name === name)
345
346 if (host === undefined || entry === undefined) {
347 return
348 }
349
350 const toggle = toggleCommandOf(kind, entry)
351
352 if ('argv' in toggle) {
353 const { exitCode, stdout, stderr } = await host.exec(toggle.argv)
354
355 if (exitCode !== 0) {
356 throw new Error((stderr || stdout).trim())
357 }
358 } else {
359 await host.run(toggle.command, toggle.args)
360 }
361
362 const isOn = entry.isOn === false
363 isReloadPending ||= kind === 'plugins'
364 library = { ...library, [kind]: library[kind].map(one => (one === entry ? { ...one, isOn } : one)) }
365 host.toast(kind === 'plugins' ? say().pluginToggled(name, isOn) : say().serverToggled(name, isOn), TOAST_MS)
366 host.invalidate()
367 }
368
369 /**
370 * Puts a pick at the head of the prompt box, the draft kept after it: an
371 * agent's mention, which hands it the next message, or `/<name>` for a
372 * command or a skill. Nothing is sent.
373 *
374 * @param kind what was picked
375 * @param name its name
376 * @returns once the box is filled and the person told
377 */
378 const pickEntry = async (kind: LibraryKind, name: string): Promise<void> => {
379 if (isToggleKind(kind)) {
380 return toggleEntry(kind, name)
381 }
382
383 if (host === undefined || kind === 'hooks') {
384 return
385 }
386
387 const box = await host.read()
388 const isAgent = kind === 'agents'
389 const filled = await host.fill(isAgent ? draftWith(box.text, name) : draftWithCommand(box.text, name))
390
391 current = filled.isFilled ? { [kind]: name } : current
392 host.toast(
393 filled.isFilled ? (isAgent ? say().agentPut(mentionOf(name)) : say().commandPut(`/${name}`)) : say().agentNotPut,
394 TOAST_MS,
395 )
396 host.invalidate()
397 }
398
399 /**
400 * Tells the person a switch did not take, the command's reason in it.
401 *
402 * @param error what the command rejected with
403 */
404 const failed = (error: unknown): void => {
405 host?.toast(`${say().failed} ${error instanceof Error ? error.message : String(error)}`, TOAST_MS)
406 }
407
408 /**
409 * What a switch would cost right now.
410 *
411 * @returns the cost, none known before the clock answers
412 */
413 const costNow = async (): Promise<SwitchCost> => {
414 const now = await host?.now().catch(() => undefined)
415
416 return now === undefined ? { state: 'none' } : switchCostOf(last, now)
417 }
418
419 /**
420 * Records the last main request and re-arms the redraws at the cache's
421 * two thresholds, so the pane's cost line ages without a request.
422 *
423 * @param request the request just answered
424 */
425 const recordRequest = (request: LastRequest): void => {
426 last = request
427
428 for (const timer of expiry) {
429 timer.cancel()
430 }
431
432 expiry = host === undefined ? [] : [WARM_MS, LONG_TTL_MS].map(ms => host!.after(ms, host!.invalidate))
433 }
434
435 /**
436 * The name the toasts give the current model.
437 *
438 * @returns its label, or its id for a model the pane does not offer
439 */
440 const modelName = (): string | undefined => choiceOf(model, catalog.models)?.label ?? model
441
442 /**
443 * Applies a pick: `/model` first where the model changes, then `/effort`
444 * (or the held level) where the level does, and one toast for both. A
445 * pick that would change nothing runs nothing and says so.
446 *
447 * @param pick a model, a level or a preset
448 * @returns once the commands have run and the pane redrawn
449 */
450 const apply = async (pick: Pick): Promise<void> => {
451 if (host === undefined) {
452 return
453 }
454
455 const idle = idleReasonOf(pick, model, effort, catalog.models)
456
457 if (idle !== undefined) {
458 host.toast(idle, TOAST_MS)
459
460 return
461 }
462
463 const plan = planOf(pick, model, effort, catalog.models)
464 const cost = await costNow()
465 const moves: [string | undefined, string][] = []
466 let kind: 'model' | 'effort' = 'model'
467
468 if (plan.model !== undefined) {
469 const before = modelName()
470 const target = plan.model
471
472 await host.run('model', target.arg)
473 model = await host.model().catch(() => target.arg)
474 moves.push([before, modelName() ?? target.label])
475 }
476
477 if (plan.effort !== undefined) {
478 if (hasEffortCommand) {
479 await host.run('effort', plan.effort)
480 } else {
481 held = plan.effort
482 }
483
484 moves.push([effort, plan.effort])
485 kind = plan.model === undefined ? 'effort' : kind
486 effort = plan.effort
487 isEffortAsked = true
488 }
489
490 host.invalidate()
491
492 const [before, after] = moves[0] ?? [undefined, '']
493 const text = 'preset' in pick ? presetText(pick.preset, moves) : switchedText(kind, before, after)
494
495 host.toast(text + costSuffixOf(cost), TOAST_MS)
496 }
497
498 /**
499 * Runs `/fast`, the engine's own toggle; the pane cannot read its state.
500 *
501 * @returns once the command has run
502 */
503 const toggleFast = async (): Promise<void> => {
504 const ran = (await host?.run('fast', '')) as { text?: string } | undefined
505 isFast = fastStateOf(ran?.text) ?? isFast
506 host?.invalidate()
507 }
508
509 /**
510 * Turns ultracode on or off through `/effort`, the level kept as it is.
511 *
512 * @param isOn the state asked; the other one of the mod's where omitted
513 * @returns once the command has run and the pane redrawn
514 */
515 const setUltracode = async (isOn = !isUltracode): Promise<void> => {
516 if (host === undefined) {
517 return
518 }
519
520 // Set before the command runs, so a second press while it runs flips back.
521 const was = isUltracode
522 isUltracode = isOn
523
524 try {
525 await host.run('effort', isOn ? 'ultracode' : 'ultracode off')
526 } catch (error) {
527 isUltracode = was
528 throw error
529 } finally {
530 host.invalidate()
531 }
532
533 host.toast(`${say().ultracode} ${isOn ? say().ultracodeOn : say().ultracodeOff}`, TOAST_MS)
534 }
535
536 /**
537 * Renames the session through `/rename`.
538 *
539 * @param name the name typed; an empty one does nothing
540 * @returns once the command has run
541 */
542 const renameSession = async (name: string): Promise<void> => {
543 const trimmed = name.trim()
544
545 if (host === undefined || trimmed === '') {
546 return
547 }
548
549 await host.run('rename', trimmed)
550 sessionName = trimmed
551 isRenaming = false
552 host.toast(say().renamed(trimmed), TOAST_MS)
553 host.invalidate()
554 }
555
556 /**
557 * Changes one `/config` row as the menu would; a refusal is told.
558 *
559 * @param key the row's key
560 * @param value its new value
561 * @returns once written and the pane redrawn
562 */
563 const setConfig = async (key: string, value: ConfigValue): Promise<void> => {
564 if (host === undefined) {
565 return
566 }
567
568 const { deny } = await host.setConfig(key, value)
569
570 if (deny !== undefined) {
571 host.toast(`${say().configRefused} ${deny}`, TOAST_MS)
572 }
573
574 host.invalidate()
575 }
576
577 /**
578 * Adds the preset composed in the pane to the `presets` setting.
579 *
580 * @returns once saved and the pane redrawn, or the refusal told
581 */
582 const addPreset = async (): Promise<void> => {
583 if (host === undefined) {
584 return
585 }
586
587 const draft = { ...draftPreset, model: draftPreset.model || (catalog.models[0]?.key ?? '') }
588 const made = presetPartOf(draft, catalog.models, catalog.presets)
589
590 if ('error' in made) {
591 host.toast(made.error === 'exists' ? say().presetExists : say().presetBadName, TOAST_MS)
592
593 return
594 }
595
596 const set = withPref(prefs, 'presets', prefs.presets.trim() === '' ? made.part : `${prefs.presets}, ${made.part}`)
597
598 if ('error' in set) {
599 return
600 }
601
602 settle(set.prefs)
603 await host.save(set.prefs)
604 draftPreset = { name: '', model: draft.model, effort: draft.effort }
605 openMenus.delete(NEW_PRESET_KEY)
606 host.toast(`${say().presetAdded} ${made.part}`, TOAST_MS)
607 host.invalidate()
608 }
609
610 /**
611 * Deletes a preset of the person's own from the `presets` setting.
612 *
613 * @param key the preset's name
614 * @returns once saved and the pane redrawn
615 */
616 const deletePreset = async (key: string): Promise<void> => {
617 if (host === undefined || !isOwnPreset(key, DEFAULT_PREFS.presets)) {
618 return
619 }
620
621 // An empty setting would read as the default: keep the shipped ones then.
622 const rest = withoutPreset(prefs.presets, key)
623 const set = withPref(prefs, 'presets', rest === '' ? DEFAULT_PREFS.presets : rest)
624
625 if ('error' in set) {
626 return
627 }
628
629 settle(set.prefs)
630 await host.save(set.prefs)
631 host.toast(`${say().presetDeleted} ${key}`, TOAST_MS)
632 host.invalidate()
633 }
634
635 /**
636 * Shows or hides the pane's hotkeys, kept with the settings.
637 *
638 * @returns once saved and the pane redrawn
639 */
640 const toggleKeyboard = async (): Promise<void> => {
641 const set = withPref(prefs, 'keyboard', prefs.keyboard === 'off' ? 'on' : 'off')
642
643 if ('error' in set || host === undefined) {
644 return
645 }
646
647 settle(set.prefs)
648 await host.save(set.prefs)
649 host.invalidate()
650 }
651
652 /**
653 * Folds the pane's lists onto their current row, or unfolds them, kept
654 * with the settings.
655 *
656 * @returns once saved and the pane redrawn
657 */
658 const toggleCompact = async (): Promise<void> => {
659 const set = withPref(prefs, 'compact', prefs.compact === 'off' ? 'on' : 'off')
660
661 if ('error' in set || host === undefined) {
662 return
663 }
664
665 settle(set.prefs)
666 await host.save(set.prefs)
667 host.invalidate()
668 }
669
670 /**
671 * Puts a frame's values in the band above the prompt, or takes them out,
672 * kept with the settings; the toast says which.
673 *
674 * @param part the frame's values
675 * @returns once saved and the pane and the band redrawn
676 */
677 const toggleBand = async (part: BandPart): Promise<void> => {
678 const band = bandOf(prefs.band)
679 const isIn = !band.includes(part)
680 const set = withPref(prefs, 'band', BAND_PARTS.filter(one => (one === part ? isIn : band.includes(one))).join(','))
681
682 if ('error' in set || host === undefined) {
683 return
684 }
685
686 settle(set.prefs)
687 await host.save(set.prefs)
688 const title = { model: say().models, effort: say().efforts, session: say().session }[part]
689 host.toast(`${title} ${isIn ? say().bandPut : say().bandTaken}`, TOAST_MS)
690 host.invalidate()
691 }
692
693 /**
694 * Asks for `/compact`, or drops the question, from the pane or the band.
695 *
696 * @param isAsked whether it is asked
697 */
698 const askCompact = (isAsked: boolean): void => {
699 isCompactAsked = isAsked
700 compactNote = ''
701 host?.invalidate()
702 }
703
704 /** Runs `/compact` with the instructions typed, once confirmed. */
705 const compact = (): void => {
706 const note = compactNote.trim()
707 isCompactAsked = false
708 compactNote = ''
709 host?.invalidate()
710 void host?.run('compact', note).catch(failed)
711 }
712
713 /**
714 * Switches to a model of the drop-down, which the rows may not hold.
715 *
716 * @param id its id
717 * @returns once the switch has run
718 */
719 const pickMoreModel = async (id: string): Promise<void> => {
720 const known = MORE_MODELS.find(one => one.id === id)
721
722 if (known === undefined) {
723 return
724 }
725
726 await apply({
727 model: {
728 key: id,
729 label: known.label,
730 arg: id,
731 hasEffort: !id.includes('haiku'),
732 color: choiceOf(id, catalog.models)?.color ?? '#888888',
733 },
734 })
735 }
736
737 on('engine.create', async (_$, e, next) => {
738 const beneath = await next(e)
739
740 host ??= {
741 invalidate: () => beneath.ui.invalidate('ui.render'),
742 model: () => beneath.session.model(),
743 run: (command, args) => beneath.command.run({ command, args }),
744 toast: (text, timeoutMs) => beneath.ui.toast(text, { timeoutMs }),
745 later: fn => void beneath.clock.after(0, fn),
746 after: (ms, fn) => beneath.clock.after(ms, fn),
747 now: () => beneath.clock.now(),
748 read: () => beneath.prompt.read(),
749 fill: text => beneath.prompt.fill({ text }),
750 list: path => beneath.fs.list(path),
751 exists: path => beneath.fs.exists(path),
752 save: kept => beneath.store.set('settings', kept),
753 // Async, so an engine without the noun rejects instead of throwing.
754 settings: async source => (await beneath.settings.read({ source })) as Record<string, unknown>,
755 file: async path => String(await beneath.fs.read(path)),
756 cwd: async () => beneath.session.cwd(),
757 exec: argv => beneath.process.run(argv),
758 setConfig: async (key, value) => (await beneath.config.set({ key, value })) as { value?: unknown; deny?: string },
759 }
760
761 return beneath
762 })
763
764 on('session.start', async ($, e, next) => {
765 // Before the command is registered: its description is in the language.
766 settle(await storedPrefsOf($))
767 isPrefsRead = true
768
769 await $.command.register({
770 name: COMMAND,
771 description: say().description,
772 argumentHint: say().argumentHint,
773 })
774
775 const started = await next(e)
776
777 model = await $.session.model().catch(() => undefined)
778
779 const commands = await $.command.list().catch(() => [])
780 hasEffortCommand = commands.some(one => one.name === 'effort')
781 hasFast = commands.some(one => one.name === 'fast')
782
783 effort ??= savedEffortOf(await $.settings.read().catch(() => ({})), model, catalog.models)
784
785 ;({ configDir, stateFile } = await pathsOf($))
786
787 // The summary breakdown is local and free; the agents and the MCP tools are in it.
788 const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => undefined)
789 await readLibrary(usage?.context.breakdown?.agents ?? [])
790 await readSetup(usage?.context.breakdown?.mcpTools ?? [])
791
792 return started
793 })
794
795 on('command.run', { command: COMMAND }, async ($, e) => {
796 const request = setRequestOf(e.args)
797
798 if (request !== undefined) {
799 if (request.key === undefined) {
800 return { text: [say().settingsTitle, ...prefsLines(prefs)].join('\n') }
801 }
802
803 const key = prefKeyOf(request.key)
804
805 if (key === undefined) {
806 return { text: `${say().settingUnknown} ${PREF_KEYS.join(', ')}` }
807 }
808
809 const set = withPref(prefs, key, request.value ?? '')
810
811 if ('error' in set) {
812 const refusals = {
813 maxAgents: say().settingBadMaxAgents,
814 keyboard: say().settingBadKeyboard,
815 compact: say().settingBadCompact,
816 band: say().settingBadBand,
817 language: `${say().settingBadLanguage} ${Object.keys(LANGUAGES).join(', ')}`,
818 }
819
820 return { text: refusals[set.error] }
821 }
822
823 await $.store.set('settings', set.prefs)
824 settle(set.prefs)
825 $.ui.invalidate('ui.render')
826
827 const lines = [`${say().settingSaved} ${key}`, ...prefsLines(prefs)]
828
829 return { text: catalog.ignored.length === 0 ? lines.join('\n') : [...lines, `${say().ignored} ${catalog.ignored.join(', ')}`].join('\n') }
830 }
831
832 const ultracode = /^ultracode(?:\s+(on|off))?$/i.exec(e.args.trim())
833
834 if (ultracode !== null && hasEffortCommand) {
835 if (host === undefined) {
836 return { text: say().notReady }
837 }
838
839 const isOn = ultracode[1]?.toLowerCase() !== 'off'
840 host.later(() => void setUltracode(isOn).catch(failed))
841
842 return { text: `${say().ultracodeSet} ${isOn ? say().ultracodeOn : say().ultracodeOff}` }
843 }
844
845 const pick = pickOf(e.args, catalog.models, catalog.presets)
846
847 if (pick === undefined && e.args.trim() !== '') {
848 return { text: `${say().unknownPick} ${e.args.trim()}` }
849 }
850
851 if (pick !== undefined) {
852 const idle = idleReasonOf(pick, model, effort, catalog.models)
853
854 if (idle !== undefined) {
855 return { text: idle }
856 }
857
858 if (host === undefined) {
859 return { text: say().notReady }
860 }
861
862 // `/model` and `/effort` cannot run from inside this hook: the session
863 // waits on it. A timer runs them once `/dash` has answered.
864 host.later(() => void apply(pick).catch(failed))
865
866 if ('model' in pick) {
867 return { text: `${say().modelSet} ${pick.model.label}` }
868 }
869
870 return 'effort' in pick
871 ? { text: `${say().effortSet} ${pick.effort}` }
872 : { text: `${say().presetSet} ${pick.preset.key}` }
873 }
874
875 ;({ configDir, stateFile } = await pathsOf($))
876 isRead = true
877
878 // A file added since the session began shows on the next open.
879 const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => undefined)
880 await readLibrary(usage?.context.breakdown?.agents)
881 await readSetup(usage?.context.breakdown?.mcpTools)
882 const draft = (await $.prompt.read().catch(() => ({ text: '' }))).text
883 current = { agents: mentionedIn(draft), commands: invokedIn(draft), skills: invokedIn(draft) }
884
885 await $.ui.open({ id: PANE_ID, title: say().paneTitle, focus: true })
886
887 return { text: say().opened }
888 })
889
890 // A /rename the person types names the session too.
891 on('command.run', { command: 'rename' }, async ($, e, next) => {
892 const result = await next(e)
893 sessionName = e.args.trim() || sessionName
894 isRenaming = false
895 $.ui.invalidate('ui.render')
896
897 return result
898 })
899
900 // A /fast the person types says the new state too.
901 on('command.run', { command: 'fast' }, async ($, e, next) => {
902 const result = await next(e)
903 isFast = fastStateOf(result.text) ?? isFast
904 $.ui.invalidate('ui.render')
905
906 return result
907 })
908
909 on('turn.step', async function* ($, e, next) {
910 if (e.agentId !== undefined) {
911 return yield* next(e)
912 }
913
914 if (engineSeen?.model === e.model && e.effort !== undefined && e.effort !== engineSeen.effort) {
915 held = undefined
916 }
917
918 engineSeen = { model: e.model, effort: e.effort ?? engineSeen?.effort }
919
920 const sent = held !== undefined && e.effort !== undefined ? { ...e, effort: held } : e
921 const seen = effortOf(sent.effort) ?? effort
922 const isSeen = effortOf(sent.effort) !== undefined
923
924 if (sent.model !== model || seen !== effort || (isEffortAsked && isSeen)) {
925 model = sent.model
926 effort = seen
927 isEffortAsked &&= !isSeen
928 $.ui.invalidate('ui.render')
929 }
930
931 const result = yield* next(sent)
932 const measure = measureOf(result.usage)
933
934 if (measure !== undefined) {
935 recordRequest({ ...measure, at: await $.clock.now() })
936 $.ui.invalidate('ui.render')
937 }
938
939 return result
940 })
941
942 // The agent cap: a workflow's agents pass no hook (agent.spawn sees only
943 // the Agent tool's), so the cap goes into the script itself. A script on
944 // disk is read and sent inline; one run by name cannot be reached and is
945 // refused, as is any the cap cannot be fitted into: the cap fails closed.
946 on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
947 if (prefs.maxAgents === '') {
948 return next(e)
949 }
950
951 const args = e as unknown as Record<string, unknown>
952 const path = args['scriptPath']
953 const script =
954 typeof path === 'string'
955 ? String(await $.fs.read(path).catch(() => ''))
956 : typeof args['script'] === 'string'
957 ? args['script']
958 : undefined
959
960 if (script === undefined) {
961 return { deny: say().capNamed(prefs.maxAgents) }
962 }
963
964 const capped = cappedScriptOf(script, Number(prefs.maxAgents))
965
966 if (capped === undefined) {
967 return { deny: say().capUnfit(prefs.maxAgents) }
968 }
969
970 const { scriptPath: _path, ...rest } = args
971
972 return next({ ...rest, script: capped } as unknown as typeof e)
973 })
974
975 // The durations count in minutes: one redraw a minute ages them while the
976 // pane or the band draws them, and stops with them, since a site not drawn
977 // re-arms none.
978 const armTick = (): void => {
979 tick ??= host?.after(USAGE_TICK_MS, () => {
980 tick = undefined
981 host?.invalidate()
982 })
983 }
984
985 // The band above the prompt: the values the pane's ↧ buttons put there.
986 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
987 // A module reloaded mid-session starts blank: no session.start comes again.
988 if (!isPrefsRead) {
989 isPrefsRead = true
990 settle(await storedPrefsOf($))
991 }
992
993 const band = bandOf(prefs.band)
994
995 if (band.length === 0 || e.props.hasSurvey) {
996 return next(e)
997 }
998
999 model ??= await $.session.model().catch(() => undefined)
1000 effort ??= savedEffortOf(await $.settings.read().catch(() => ({})), model, catalog.models)
1001 const sessionUsage = band.includes('session') ? await $.session.usage().catch(() => undefined) : undefined
1002 const context = sessionUsage?.context
1003 const now = await $.clock.now().catch(() => undefined)
1004
1005 if (band.includes('session')) {
1006 armTick()
1007 }
1008
1009 return drawBand($.ui.resolve(e), {
1010 band,
1011 models: catalog.models,
1012 model,
1013 effort,
1014 context: context === undefined ? undefined : { percent: context.percent, tokens: context.tokens, window: context.window },
1015 usage: sessionUsage === undefined || now === undefined ? undefined : usageViewOf(sessionUsage, now),
1016 isCompactAsked,
1017 askCompact,
1018 compact,
1019 }, e.surface)
1020 })
1021
1022 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
1023 // A module reloaded mid-session starts blank: no session.start comes again.
1024 if (!isPrefsRead) {
1025 isPrefsRead = true
1026 settle(await storedPrefsOf($))
1027 }
1028
1029 model ??= await $.session.model().catch(() => undefined)
1030 effort ??= savedEffortOf(await $.settings.read().catch(() => ({})), model, catalog.models)
1031
1032 // Nor are the lists read: the first draw reads them, as /dash would.
1033 if (!isRead) {
1034 isRead = true
1035 ;({ configDir, stateFile } = await pathsOf($))
1036 const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => undefined)
1037 await readLibrary(usage?.context.breakdown?.agents ?? [])
1038 await readSetup(usage?.context.breakdown?.mcpTools ?? [])
1039 }
1040
1041 // Both cheap, read on each draw: the gauge follows every request, which
1042 // redraws the pane, and a row changed in /config shows on the next draw.
1043 const sessionUsage = await $.session.usage().catch(() => undefined)
1044 const context = sessionUsage?.context
1045 const now = await $.clock.now().catch(() => undefined)
1046 const configRows: ConfigRow[] = await $.config.list().catch(() => [])
1047
1048 armTick()
1049
1050 return drawPane($.ui.resolve(e), {
1051 context: context === undefined ? undefined : { percent: context.percent, tokens: context.tokens, window: context.window },
1052 usage: sessionUsage === undefined || now === undefined ? undefined : usageViewOf(sessionUsage, now),
1053 renameSession: name => void renameSession(name).catch(failed),
1054 sessionName,
1055 isRenaming,
1056 editName: () => {
1057 isRenaming = true
1058 host?.invalidate()
1059 },
1060 isCompactAsked,
1061 askCompact,
1062 compactNote,
1063 setCompactNote: note => {
1064 compactNote = note
1065 },
1066 compact,
1067 configRows,
1068 setConfig: (key, value) => void setConfig(key, value).catch(failed),
1069 models: catalog.models,
1070 presets: catalog.presets,
1071 model,
1072 effort,
1073 hasEffortCommand,
1074 isEffortAsked,
1075 hasFast,
1076 isFast,
1077 isUltracode,
1078 ignored: catalog.ignored,
1079 pickModel: key => {
1080 const choice = catalog.models.find(one => one.key === key)
1081
1082 if (choice !== undefined) {
1083 void apply({ model: choice }).catch(failed)
1084 }
1085 },
1086 pickEffort: level => void apply({ effort: level }).catch(failed),
1087 pickPreset: key => {
1088 const preset = catalog.presets.find(one => one.key === key)
1089
1090 if (preset !== undefined) {
1091 void apply({ preset }).catch(failed)
1092 }
1093 },
1094 toggleFast: () => void toggleFast().catch(failed),
1095 toggleUltracode: () => void setUltracode().catch(failed),
1096 pickMoreModel: id => void pickMoreModel(id).catch(failed),
1097 isKeyboard: prefs.keyboard !== 'off',
1098 toggleKeyboard: () => void toggleKeyboard().catch(failed),
1099 isCompact: prefs.compact === 'on',
1100 toggleCompact: () => void toggleCompact().catch(failed),
1101 band: bandOf(prefs.band),
1102 toggleBand: part => void toggleBand(part).catch(failed),
1103 library,
1104 current,
1105 openKinds: [...openKinds],
1106 toggleKind: kind => {
1107 if (!openKinds.delete(kind)) {
1108 openKinds.add(kind)
1109 }
1110
1111 host?.invalidate()
1112 },
1113 expandedFrames: [...expandedFrames],
1114 toggleFrame: (kind, scope) => {
1115 if (!expandedFrames.delete(`${kind}:${scope}`)) {
1116 expandedFrames.add(`${kind}:${scope}`)
1117 }
1118
1119 host?.invalidate()
1120 },
1121 pickEntry: (kind, name) => void pickEntry(kind, name).catch(failed),
1122 openMenus: [...openMenus],
1123 draftPreset: { ...draftPreset, model: draftPreset.model || (catalog.models[0]?.key ?? '') },
1124 setDraftPreset: patch => {
1125 draftPreset = { ...draftPreset, ...patch }
1126 host?.invalidate()
1127 },
1128 addPreset: () => void addPreset().catch(failed),
1129 ownPresets: catalog.presets.filter(one => isOwnPreset(one.key, DEFAULT_PREFS.presets)).map(one => one.key),
1130 deletePreset: key => void deletePreset(key).catch(failed),
1131 toggleMenu: key => {
1132 if (!openMenus.delete(key)) {
1133 openMenus.add(key)
1134 }
1135
1136 host?.invalidate()
1137 },
1138 isReloadPending,
1139 reloadPlugins: () =>
1140 void host
1141 ?.run('reload-plugins', '')
1142 .then(() => {
1143 isReloadPending = false
1144 host?.invalidate()
1145 })
1146 .catch(failed),
1147 }, e.surface)
1148 })
1149}
1150hooks/agents/index.ts 2 lines1export * from './agents'
2hooks/catalog/index.ts 2 lines1export * from './catalog'
2hooks/config/index.ts 2 lines1export * from './config'
2hooks/cost/index.ts 2 lines1export * from './cost'
2hooks/library/index.ts 2 lines1export * from './library'
2hooks/names.ts 92 lines1/**
2 * The names of the mod, gathered so a test reads the same ones. What the
3 * person reads lives in `say/`, by language.
4 */
5
6/** The slash command, without its slash. */
7export const COMMAND = 'dash'
8
9/** The pane's id. */
10export const PANE_ID = 'dash'
11
12/** The key of a model's button. */
13export const modelKey = (key: string): string => `model:${key}`
14
15/** The key of an effort level's button. */
16export const effortKey = (level: string): string => `effort:${level}`
17
18/** The key of a preset's button. */
19export const presetKey = (key: string): string => `preset:${key}`
20
21/** The keys of the new preset's form: its opener, its fields and its button. */
22export const NEW_PRESET_KEY = 'presets:new'
23export const PRESET_NAME_KEY = 'presets:new:name'
24export const PRESET_MODEL_KEY = 'presets:new:model'
25export const PRESET_EFFORT_KEY = 'presets:new:effort'
26export const PRESET_ADD_KEY = 'presets:new:add'
27
28/** The key of the button that deletes a preset of the person's own. */
29export const presetDeleteKey = (key: string): string => `presets:delete:${key}`
30
31/** The key of the fast mode's button. */
32export const FAST_KEY = 'fast'
33
34/** The key of the ultracode button. */
35export const ULTRACODE_KEY = 'ultracode'
36
37/** The key of the drop-down of the models beside the rows. */
38export const MORE_MODELS_KEY = 'model:more'
39
40/** The key of one option of a drop-down. */
41export const menuOptionKey = (menu: string, value: string): string => `${menu}:${value}`
42
43/** The key of the field that renames the session. */
44export const RENAME_KEY = 'session:rename'
45
46/** The key of the button that brings the rename field back. */
47export const RENAME_EDIT_KEY = 'session:rename:edit'
48
49/** The key of the button that runs `/compact`. */
50export const COMPACT_KEY = 'session:compact'
51
52/** The key of the button that confirms `/compact`. */
53export const COMPACT_CONFIRM_KEY = 'session:compact:confirm'
54
55/** The key of the button that drops the `/compact` asked for. */
56export const COMPACT_CANCEL_KEY = 'session:compact:cancel'
57
58/** The key of the field that takes `/compact`'s instructions. */
59export const COMPACT_NOTE_KEY = 'session:compact:note'
60
61/** The key of the Settings section's header. */
62export const CONFIG_KEY = 'config:open'
63
64/** The key of one `/config` row's control. */
65export const configKey = (key: string): string => `config:${key}`
66
67/** The key of the button that shows or hides the hotkeys. */
68export const KEYBOARD_KEY = 'keyboard'
69
70/** The key of the button that folds the lists onto their current row. */
71export const COMPACT_MODE_KEY = 'compact-mode'
72
73/** The key of the button that puts a frame's values in the band, or takes them out. */
74export const bandKey = (part: string): string => `band:${part}`
75
76/** The keys of the band's `/compact` button, its confirmation and its cancel. */
77export const BAND_COMPACT_KEY = 'band:compact'
78export const BAND_COMPACT_CONFIRM_KEY = 'band:compact:confirm'
79export const BAND_COMPACT_CANCEL_KEY = 'band:compact:cancel'
80
81/** The key of the button that runs `/reload-plugins`. */
82export const RELOAD_KEY = 'plugins:reload'
83
84/** The key of a library section's header, which opens and closes it. */
85export const sectionKey = (kind: string): string => `${kind}:open`
86
87/** The key of an agent's, a command's or a skill's button. */
88export const entryKey = (kind: string, name: string): string => `${kind}:item:${name}`
89
90/** The key of a scope frame's Expand / Collapse button. */
91export const frameToggleKey = (kind: string, scope: string): string => `${kind}:more:${scope}`
92hooks/pane/index.ts 2 lines1export * from './pane'
2hooks/say/index.ts 3 lines1export * from './en'
2export * from './say'
3hooks/settings/index.ts 2 lines1export * from './settings'
2hooks/usage/index.ts 2 lines1export * from './usage'
2hooks/agents/agents.ts 97 lines1/**
2 * The custom subagents the session can hand a message to: the person's own
3 * (`~/.claude/agents`) and the project's (`.claude/agents`). The plugins'
4 * agents are left out: a session can carry dozens of them.
5 *
6 * They come from the context breakdown the engine computes for `/context`,
7 * whose summary is local and free; built-in agents are not in it. Picking
8 * one puts its mention, `@agent-<type>`, at the head of the prompt box: the
9 * person's next message goes to it, and nothing leaves until they send it.
10 */
11
12/** Where an agent was defined. */
13export type AgentScope = 'user' | 'project'
14
15/** One subagent the pane offers. */
16export type AgentEntry = {
17 /** Its type, as the Agent tool and a mention name it. */
18 type: string
19 scope: AgentScope
20}
21
22/** The order the groups are listed in. */
23export const AGENT_SCOPES: readonly AgentScope[] = ['user', 'project']
24
25const SOURCES: Readonly<Record<string, AgentScope>> = {
26 userSettings: 'user',
27 projectSettings: 'project',
28 localSettings: 'project',
29}
30
31/**
32 * The scope of a definition's source, by the engine's word for it.
33 *
34 * @param source `userSettings`, `projectSettings`, `plugin`, ...
35 * @returns its scope, or `undefined` for a source the pane does not list
36 */
37export function scopeOf(source: string): AgentScope | undefined {
38 return SOURCES[source]
39}
40
41/**
42 * The agents to offer: listed sources only, once each, grouped by scope
43 * then sorted by type.
44 *
45 * @param agents the breakdown's agents
46 * @returns the entries
47 */
48export function agentsOf(agents: readonly { agentType: string; source: string }[]): AgentEntry[] {
49 const seen = new Set<string>()
50 const entries: AgentEntry[] = []
51
52 for (const one of agents) {
53 const scope = scopeOf(one.source)
54
55 if (scope !== undefined && one.agentType !== '' && !seen.has(one.agentType)) {
56 seen.add(one.agentType)
57 entries.push({ type: one.agentType, scope })
58 }
59 }
60
61 return entries.sort(
62 (a, b) => AGENT_SCOPES.indexOf(a.scope) - AGENT_SCOPES.indexOf(b.scope) || a.type.localeCompare(b.type),
63 )
64}
65
66/**
67 * The mention that hands a message to an agent.
68 *
69 * @param type the agent's type
70 * @returns `@agent-<type>`
71 */
72export const mentionOf = (type: string): string => `@agent-${type}`
73
74/**
75 * The prompt box once an agent is picked: its mention at the head, in place
76 * of one already there, and the draft kept after it.
77 *
78 * @param draft the prompt box as it stands
79 * @param type the agent picked
80 * @returns the new draft
81 */
82export function draftWith(draft: string, type: string): string {
83 const rest = draft.replace(/^\s*@agent-\S+\s*/, '')
84
85 return `${mentionOf(type)} ${rest}`
86}
87
88/**
89 * The agent a draft is addressed to, if it opens with a mention.
90 *
91 * @param draft the prompt box as it stands
92 * @returns the agent's type, or `undefined`
93 */
94export function mentionedIn(draft: string): string | undefined {
95 return /^\s*@agent-(\S+)/.exec(draft)?.[1]
96}
97