pantheon-opencode 1.6.0-beta.8 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -346
  4. package/README.md +83 -608
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-audit.md +7 -1
  8. package/commands/pantheon-consolidate.md +1 -1
  9. package/commands/pantheon-deepwork.md +14 -3
  10. package/commands/pantheon-focus.md +17 -0
  11. package/commands/pantheon-vision.md +61 -12
  12. package/package.json +19 -11
  13. package/plugin.json +1 -1
  14. package/pyproject.toml +6 -2
  15. package/scripts/_pantheon_paths.py +24 -0
  16. package/scripts/build-agents-md.mjs +368 -69
  17. package/scripts/changelog-merge.mjs +161 -0
  18. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  19. package/scripts/docs-check-changelog.mjs +204 -0
  20. package/scripts/docs-link-check.mjs +314 -0
  21. package/scripts/docs-media.mjs +157 -0
  22. package/scripts/doctor.mjs +828 -40
  23. package/scripts/install/agents-md.mjs +2 -2
  24. package/scripts/install/backup.mjs +648 -0
  25. package/scripts/install/cli-ui.mjs +303 -72
  26. package/scripts/install/component-selection.mjs +61 -0
  27. package/scripts/install/config-migration.mjs +583 -27
  28. package/scripts/install/exit-codes.mjs +26 -0
  29. package/scripts/install/file-inventory.mjs +555 -0
  30. package/scripts/install/health-check.mjs +31 -25
  31. package/scripts/install/interactive.mjs +78 -383
  32. package/scripts/install/migrate.mjs +49 -25
  33. package/scripts/install/model-picker.mjs +218 -250
  34. package/scripts/install/opencode-version.mjs +83 -21
  35. package/scripts/install/opencode.mjs +1465 -180
  36. package/scripts/install/plan-artifact.mjs +517 -0
  37. package/scripts/install/plan.mjs +475 -0
  38. package/scripts/install/plugin.mjs +251 -30
  39. package/scripts/install/prompt-result.mjs +2 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +60 -4
  43. package/scripts/install/venv.mjs +90 -47
  44. package/scripts/install/verify.mjs +128 -0
  45. package/scripts/install/vision-prompt.mjs +173 -0
  46. package/scripts/install-mcp.mjs +2 -2
  47. package/scripts/manifest-inventory.mjs +49 -3
  48. package/scripts/mcp_persistence.py +1535 -1050
  49. package/scripts/memory_mcp.py +12 -843
  50. package/scripts/node-engine-policy.mjs +85 -0
  51. package/scripts/package-evidence.mjs +10 -2
  52. package/scripts/postinstall.mjs +26 -26
  53. package/scripts/probe-pantheon-cost.mjs +118 -19
  54. package/scripts/prune.mjs +9 -3
  55. package/scripts/reconcile.mjs +325 -0
  56. package/scripts/release-gates.mjs +682 -0
  57. package/scripts/restore.mjs +222 -0
  58. package/scripts/run-node-tests.mjs +24 -8
  59. package/scripts/sync-artifacts.mjs +20 -7
  60. package/scripts/sync-tui.mjs +29 -4
  61. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  62. package/scripts/uninstall.mjs +369 -34
  63. package/scripts/update.mjs +164 -0
  64. package/scripts/validate-node-engine-policy.mjs +13 -0
  65. package/scripts/version-check.mjs +34 -1
  66. package/scripts/versioning.mjs +23 -3
  67. package/scripts/vision-status.mjs +682 -0
  68. package/skills-lock.json +8 -8
  69. package/src/agents/aphrodite.md +13 -10
  70. package/src/agents/apollo.md +4 -5
  71. package/src/agents/athena.md +74 -46
  72. package/src/agents/demeter.md +10 -7
  73. package/src/agents/gaia.md +0 -1
  74. package/src/agents/hephaestus.md +4 -3
  75. package/src/agents/hermes.md +10 -9
  76. package/src/agents/iris.md +6 -1
  77. package/src/agents/mnemosyne.md +14 -15
  78. package/src/agents/nyx.md +4 -4
  79. package/src/agents/prometheus.md +12 -11
  80. package/src/agents/talos.md +6 -0
  81. package/src/agents/zeus.md +84 -56
  82. package/src/instructions/agent-return-format.instructions.md +12 -41
  83. package/src/instructions/memory-protocol.instructions.md +5 -11
  84. package/src/instructions/test-economy.instructions.md +12 -0
  85. package/src/instructions/yagni.instructions.md +6 -15
  86. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  87. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  88. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  89. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  90. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  91. package/src/mcp/_pantheon_paths.py +24 -0
  92. package/src/mcp/mcp_codemap_module.py +86 -18
  93. package/src/mcp/mcp_persistence.py +1535 -1050
  94. package/src/mcp/memory_mcp.py +444 -94
  95. package/src/mcp/pantheon_vision.py +285 -41
  96. package/src/mcp/requirements-mcp.txt +5 -0
  97. package/src/pantheon/context-pruner.ts +541 -0
  98. package/src/pantheon/cost-command.ts +814 -60
  99. package/src/pantheon/goal-loop.ts +11 -8
  100. package/src/pantheon/memory-context.ts +1017 -0
  101. package/src/pantheon/model-agents.ts +19 -0
  102. package/src/pantheon/model-command.ts +218 -56
  103. package/src/pantheon/model-pricing.ts +536 -0
  104. package/src/pantheon/presets.mjs +2 -0
  105. package/src/pantheon/task-result-guard.ts +50 -14
  106. package/src/pantheon/v2-bounded-read.ts +640 -0
  107. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  108. package/src/pantheon/v2-execute-after.ts +135 -24
  109. package/src/pantheon/v2-model-overrides.ts +275 -0
  110. package/src/pantheon/v2-tools.ts +89 -35
  111. package/src/pantheon/v2-unsupported.mjs +2 -3
  112. package/src/pantheon/v2-vision.ts +622 -0
  113. package/src/pantheon/vision-local.ts +531 -0
  114. package/src/pantheon/vision.ts +1160 -115
  115. package/src/plugin-v2.ts +654 -162
  116. package/src/plugin.ts +15 -11
  117. package/src/plugins/tui/dist/tui-v2.d.ts +1036 -0
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -0
  119. package/src/plugins/tui/dist/tui-v2.js +3808 -0
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -0
  121. package/src/plugins/tui/dist/tui.js +4 -4
  122. package/src/plugins/tui/index-v2.ts +6 -0
  123. package/src/plugins/tui/package-lock.json +5416 -1297
  124. package/src/plugins/tui/package.json +14 -10
  125. package/src/plugins/tui/src/index-v2.tsx +4372 -0
  126. package/src/plugins/tui/src/index.tsx +3 -3
  127. package/src/plugins/tui/src/opencode-v2.d.ts +13 -0
  128. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  129. package/src/plugins/tui/tsdown.config.ts +2 -2
  130. package/src/plugins/tui/tui-v2.ts +2 -0
  131. package/src/plugins/tui/tui.ts +3 -0
  132. package/src/routing.yml +50 -5
  133. package/src/skills/agent-coordination/SKILL.md +7 -2
  134. package/src/skills/artifact-management/SKILL.md +5 -1
  135. package/src/skills/auto-continue/SKILL.md +14 -6
  136. package/src/skills/codemap/SKILL.md +1 -1
  137. package/src/skills/memory-bank/SKILL.md +21 -13
  138. package/src/skills/session-goal/SKILL.md +14 -15
  139. package/src/skills/spec-driven-development/SKILL.md +3 -1
  140. package/src/skills/worktrees/SKILL.md +30 -11
  141. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -0,0 +1,4372 @@
1
+ // biome-ignore-all lint/suspicious/noExplicitAny: OpenCode V2 exposes its TUI API at runtime.
2
+ // biome-ignore-all lint/a11y/noStaticElementInteractions: TUI elements, not DOM
3
+ /** @jsxImportSource @opentui/solid */
4
+
5
+ import { execFile } from 'node:child_process'
6
+ import { readFile } from 'node:fs/promises'
7
+ import { homedir } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import { Plugin } from '@opencode/plugin/tui'
10
+ import type { Context, KeymapLayer, PanelInput } from '@opencode/plugin/tui/context'
11
+ import type { Accessor } from 'solid-js'
12
+ import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show } from 'solid-js'
13
+
14
+ const SINGLETON = Symbol.for('pantheon.tui.v2.loaded')
15
+
16
+ /* ─── Constants ─────────────────────────────────────────── */
17
+
18
+ /** How often the sidebar re-reads .pantheon/active-preset.json (V1 parity) so
19
+ * `set-tier` changes made while opencode is open show up within ~30s. */
20
+ const PRESET_REFRESH_MS = 30_000
21
+ /** Running-row spinner cadence — matches V1's animation tick. */
22
+ const SPINNER_INTERVAL_MS = 80
23
+ /** Bounded warm-up: sync at most this many sessions at plugin load. */
24
+ const WARMUP_SESSION_LIMIT = 24
25
+ /** Sidebar body shown while the host has not published a session yet. */
26
+ export const SIDEBAR_WAITING_LABEL = 'Aguardando sessão…'
27
+ /** Delegate-completion toast title. */
28
+ const TOAST_TITLE = 'Pantheon'
29
+ /** Marker before the preset label (fixed header, home status, prompt footer).
30
+ * `▸` U+25B8 is one cell; the previous bolt (U+26A1) carries
31
+ * Emoji_Presentation and is measured as two cells, which misaligned the line. */
32
+ export const PRESET_MARKER = '\u25B8'
33
+ /** Git ahead / behind arrows (U+2191 / U+2193), one cell each — the glyphs the
34
+ * reference sidebars use for `↑ahead ↓behind`. */
35
+ export const GIT_ARROW_UP = '\u2191'
36
+ export const GIT_ARROW_DOWN = '\u2193'
37
+ /** One event name the host publishes on `data.on` — the OpenCode V2 union. */
38
+ export type SidebarDataEvent = Parameters<Context['data']['on']>[0]
39
+ /** V2 events that refresh the sidebar. V1 also listened to `session.updated`,
40
+ * but that name is absent from the OpenCode V2 event union (verified against
41
+ * `@opencode/client`'s `OpenCodeEvent`), so the valid events that carry the
42
+ * same state changes are used instead: `session.renamed` /
43
+ * `session.metadata.updated` / `session.moved` (the mutations `session.updated`
44
+ * used to stand for) and `session.idle` (a child finishing). `satisfies` keeps
45
+ * the literals while making a name outside the union a type error (surfaced by
46
+ * `tsc -p tsconfig.build.json`), and the sidebar test asserts the same names
47
+ * against the installed union at runtime. */
48
+ export const SIDEBAR_REFRESH_EVENTS = [
49
+ 'session.created',
50
+ 'session.renamed',
51
+ 'session.metadata.updated',
52
+ 'session.moved',
53
+ 'session.idle',
54
+ 'session.status',
55
+ 'session.deleted',
56
+ ] as const satisfies readonly SidebarDataEvent[]
57
+
58
+ /* ─── Active Preset Detection ──────────────────────────────
59
+ * Inline replica of the V1 sidebar resolver (src/plugins/tui/src/index.tsx,
60
+ * which itself mirrors src/pantheon/presets.mjs). The copied plugin ships only
61
+ * dist/ + package.json, so it can reach neither module at runtime — the
62
+ * resolution logic is mirrored here rather than imported.
63
+ *
64
+ * Priority: env PANTHEON_MODEL_PRESET > first existing candidate file > none.
65
+ * Custom/unknown preset names are shown as-is. "none" disables → default. */
66
+
67
+ export type PresetInfo = { name: string | null; source: 'env' | 'file' | null }
68
+
69
+ /** One `overrides.agents[<agent>]` entry from active-preset.json. */
70
+ export type AgentModelOverride = { model?: string; variant?: string }
71
+ /** The override map the CLI wrote into active-preset.json. */
72
+ export type PresetOverrides = { agents: Record<string, AgentModelOverride> }
73
+ /** A preset plus the explicit overrides stored next to it. */
74
+ export type ActivePresetDetail = { info: PresetInfo; overrides: PresetOverrides }
75
+
76
+ function emptyOverrides(): PresetOverrides {
77
+ return { agents: {} }
78
+ }
79
+
80
+ /** Keep only well-formed per-agent overrides: unknown keys are ignored and a
81
+ * non-string model/variant is dropped instead of leaking into the render. */
82
+ export function parsePresetOverrides(value: unknown): PresetOverrides {
83
+ const overrides = emptyOverrides()
84
+ if (!value || typeof value !== 'object') return overrides
85
+ const agents = (value as { agents?: unknown }).agents
86
+ if (!agents || typeof agents !== 'object') return overrides
87
+ for (const [agent, entry] of Object.entries(agents as Record<string, unknown>)) {
88
+ if (agent === '' || !entry || typeof entry !== 'object') continue
89
+ const model = (entry as { model?: unknown }).model
90
+ const variant = (entry as { variant?: unknown }).variant
91
+ const override: AgentModelOverride = {}
92
+ if (typeof model === 'string' && model !== '') override.model = model
93
+ if (typeof variant === 'string' && variant !== '') override.variant = variant
94
+ if (override.model !== undefined || override.variant !== undefined) {
95
+ overrides.agents[agent] = override
96
+ }
97
+ }
98
+ return overrides
99
+ }
100
+
101
+ /** Read .pantheon/active-preset.json — first existing candidate wins; malformed
102
+ * JSON or a `preset` that is missing, empty or "none" → null (no fall-through
103
+ * to lower candidates). The explicit per-agent overrides stored in the same
104
+ * file come along so the sidebar can mark them with `*`. */
105
+ async function readActivePresetDetail(cwd: string): Promise<ActivePresetDetail | null> {
106
+ const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config')
107
+ const candidates = [
108
+ join(cwd, '.pantheon', 'active-preset.json'),
109
+ join(xdgConfig, 'opencode', '.pantheon', 'active-preset.json'),
110
+ join(homedir(), '.opencode', '.pantheon', 'active-preset.json'),
111
+ ]
112
+ for (const candidate of candidates) {
113
+ let raw: string
114
+ try {
115
+ raw = await readFile(candidate, 'utf8')
116
+ } catch {
117
+ continue // candidate does not exist — try the next one
118
+ }
119
+ try {
120
+ const parsed = JSON.parse(raw) as { preset?: unknown; overrides?: unknown }
121
+ const name = parsed && typeof parsed === 'object' ? parsed.preset : undefined
122
+ if (typeof name !== 'string' || name.length === 0 || name === 'none') return null
123
+ return {
124
+ info: { name, source: 'file' },
125
+ overrides: parsePresetOverrides(parsed.overrides),
126
+ }
127
+ } catch {
128
+ return null // malformed file — treat as default (mirrors presets.mjs)
129
+ }
130
+ }
131
+ return null
132
+ }
133
+
134
+ /** Env leg of resolution: PANTHEON_MODEL_PRESET set and !== 'none' wins. */
135
+ export function presetFromEnv(env: Record<string, string | undefined>): PresetInfo {
136
+ const name = env.PANTHEON_MODEL_PRESET
137
+ if (name !== undefined && name !== '' && name !== 'none') {
138
+ return { name, source: 'env' }
139
+ }
140
+ return { name: null, source: null }
141
+ }
142
+
143
+ /** Resolve the active preset plus its per-agent overrides: env > file > default.
144
+ * An env-selected preset has no file overrides by construction. */
145
+ export async function resolveActivePresetForTui(
146
+ env: Record<string, string | undefined>,
147
+ cwd: string,
148
+ ): Promise<ActivePresetDetail> {
149
+ const envPreset = presetFromEnv(env)
150
+ if (envPreset.source === 'env') return { info: envPreset, overrides: emptyOverrides() }
151
+ return (
152
+ (await readActivePresetDetail(cwd)) ?? {
153
+ info: { name: null, source: null },
154
+ overrides: emptyOverrides(),
155
+ }
156
+ )
157
+ }
158
+
159
+ /* ─── Session helpers ────────────────────────────────────── */
160
+
161
+ /** `SessionInfo.id` is always a `ses…` handle. Guarded so a placeholder or a
162
+ * foreign id never reaches the status/navigate APIs. */
163
+ export function isValidSessionID(id: unknown): id is string {
164
+ return typeof id === 'string' && id.startsWith('ses')
165
+ }
166
+
167
+ function numberOrNull(value: unknown): number | null {
168
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
169
+ }
170
+
171
+ /* ─── Sidebar metrics ─────────────────────────────────────
172
+ * The context gauge mirrors the host's own computation: the token total of the
173
+ * last assistant message that carries `tokens`, measured after the most recent
174
+ * compaction and before an active revert boundary, against the model's context
175
+ * limit. Everything is pure so the arithmetic is testable without a renderer. */
176
+
177
+ /** Model reference shapes the host publishes: `ModelRef` objects, bare ids, or
178
+ * `provider/model` strings. Returns the id part, never throws. */
179
+ export function modelRefID(ref: unknown): string | null {
180
+ if (typeof ref === 'string') return ref === '' ? null : ref
181
+ if (ref && typeof ref === 'object') {
182
+ const id = (ref as { id?: unknown }).id
183
+ if (typeof id === 'string' && id !== '') return id
184
+ }
185
+ return null
186
+ }
187
+
188
+ /** Short display id: the segment after the last `/` (`opencode-go/kimi-k3` →
189
+ * `kimi-k3`), truncated so a long id never wraps the sidebar. */
190
+ export function shortModelID(ref: unknown, max = 24): string | null {
191
+ const id = modelRefID(ref)
192
+ if (id === null) return null
193
+ const segment = id.slice(id.lastIndexOf('/') + 1)
194
+ if (segment === '') return null
195
+ return segment.length > max ? `${segment.slice(0, Math.max(1, max - 1))}…` : segment
196
+ }
197
+
198
+ /** `providerID` of a model reference, trimmed; null when absent/blank. Derived
199
+ * only from what the host already published — never a lookup table. */
200
+ export function providerIDFromRef(ref: unknown): string | null {
201
+ if (ref === null || typeof ref !== 'object') return null
202
+ const providerID = (ref as { providerID?: unknown }).providerID
203
+ return typeof providerID === 'string' && providerID.trim() !== '' ? providerID.trim() : null
204
+ }
205
+
206
+ /** Provider for a bare-string model reference: match its id (or bare segment)
207
+ * in the host model list. Null when the list cannot answer. */
208
+ export function providerIDFromModels(models: unknown, ref: unknown): string | null {
209
+ if (!Array.isArray(models)) return null
210
+ const id = modelRefID(ref)
211
+ if (id === null) return null
212
+ const segment = id.slice(id.lastIndexOf('/') + 1)
213
+ for (const model of models) {
214
+ if (!model || typeof model !== 'object') continue
215
+ const modelID = typeof model.modelID === 'string' ? model.modelID : ''
216
+ const rowID = typeof model.id === 'string' ? model.id : ''
217
+ if (modelID !== id && rowID !== id && modelID !== segment && rowID !== segment) continue
218
+ const providerID = providerIDFromRef(model)
219
+ if (providerID !== null) return providerID
220
+ }
221
+ return null
222
+ }
223
+
224
+ /** Resolve `model.limit.context` for a model reference. Match order: the
225
+ * provider-qualified id, then the bare id (the host's `id`/`modelID` fields).
226
+ * Absent/ambiguous models degrade to null so the gauge is simply omitted. */
227
+ export function resolveContextLimit(models: readonly any[], ref: unknown): number | null {
228
+ const id = modelRefID(ref)
229
+ if (id === null) return null
230
+ const providerID =
231
+ ref && typeof ref === 'object' ? (ref as { providerID?: unknown }).providerID : undefined
232
+ const segment = id.slice(id.lastIndexOf('/') + 1)
233
+ const matches = models.filter((model) => {
234
+ if (!model || typeof model !== 'object') return false
235
+ const modelID = typeof model.modelID === 'string' ? model.modelID : ''
236
+ const rowID = typeof model.id === 'string' ? model.id : ''
237
+ const idMatches = modelID === id || rowID === id || modelID === segment || rowID === segment
238
+ if (!idMatches) return false
239
+ if (typeof providerID !== 'string' || providerID === '') return true
240
+ return model.providerID === providerID
241
+ })
242
+ const candidates =
243
+ matches.length > 0
244
+ ? matches
245
+ : models.filter((model) => {
246
+ const modelID = typeof model?.modelID === 'string' ? model.modelID : ''
247
+ const rowID = typeof model?.id === 'string' ? model.id : ''
248
+ return modelID === segment || rowID === segment
249
+ })
250
+ for (const model of candidates) {
251
+ const limit = model?.limit?.context
252
+ if (typeof limit === 'number' && Number.isFinite(limit) && limit > 0) return limit
253
+ }
254
+ return null
255
+ }
256
+
257
+ /** Native token total: input + output + reasoning + cache read + cache write. */
258
+ export function messageTokensTotal(tokens: any): number {
259
+ const cacheRead = numberOrNull(tokens?.cache?.read) ?? 0
260
+ const cacheWrite = numberOrNull(tokens?.cache?.write) ?? 0
261
+ return (
262
+ (numberOrNull(tokens?.input) ?? 0) +
263
+ (numberOrNull(tokens?.output) ?? 0) +
264
+ (numberOrNull(tokens?.reasoning) ?? 0) +
265
+ cacheRead +
266
+ cacheWrite
267
+ )
268
+ }
269
+
270
+ export type ContextUsage = { tokens: number; percent: number; limit: number }
271
+
272
+ /** The part of a transcript that still counts: everything before the revert
273
+ * boundary (when a revert is active), then after the last compaction. Both
274
+ * derived numbers that read "the last assistant with usage" — the context
275
+ * gauge and the cache hit rate — share this window, so a reverted-away or
276
+ * compacted-away message can never feed either one. Pure. */
277
+ export function transcriptWindow(
278
+ messages: readonly any[],
279
+ revertMessageID?: string | null,
280
+ ): { start: number; end: number } {
281
+ let end = messages.length
282
+ if (typeof revertMessageID === 'string' && revertMessageID !== '') {
283
+ const boundary = messages.findIndex((message) => message?.id === revertMessageID)
284
+ if (boundary >= 0) end = boundary
285
+ }
286
+
287
+ let start = 0
288
+ for (let index = end - 1; index >= 0; index--) {
289
+ if (messages[index]?.type === 'compaction') {
290
+ start = index + 1
291
+ break
292
+ }
293
+ }
294
+
295
+ return { start, end }
296
+ }
297
+
298
+ /** Context usage for a message list. Scope: the live window (see
299
+ * `transcriptWindow`). The last assistant message carrying `tokens` in that
300
+ * window wins. Null when there is no limit or no such message — the caller
301
+ * then omits the block. */
302
+ export function computeContextUsage(
303
+ messages: readonly any[],
304
+ contextLimit: number | null | undefined,
305
+ revertMessageID?: string | null,
306
+ ): ContextUsage | null {
307
+ const limit = numberOrNull(contextLimit)
308
+ if (limit === null || limit <= 0) return null
309
+ if (!Array.isArray(messages) || messages.length === 0) return null
310
+
311
+ const { start, end } = transcriptWindow(messages, revertMessageID)
312
+
313
+ for (let index = end - 1; index >= start; index--) {
314
+ const message = messages[index]
315
+ if (message?.type !== 'assistant' || !message.tokens) continue
316
+ const tokens = messageTokensTotal(message.tokens)
317
+ if (!Number.isFinite(tokens) || tokens <= 0) continue
318
+ return { tokens, percent: Math.round((tokens / limit) * 100), limit }
319
+ }
320
+ return null
321
+ }
322
+
323
+ /** Semantic tone for a context percentage, inclusive at the top of each band:
324
+ * info (blue) up to 25%, success (green) up to 50%, warning (yellow) up to
325
+ * 90%, error (red) above it. Four explicit stages, each backed by a feedback
326
+ * token, so the gauge follows the active theme. Pure. */
327
+ export function contextUsageTone(percent: number): ContextProgressTone {
328
+ if (percent > 90) return 'error'
329
+ if (percent > 50) return 'warning'
330
+ if (percent > 25) return 'success'
331
+ return 'info'
332
+ }
333
+
334
+ /** The gauge's four stages, one per theme feedback token. */
335
+ export type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'
336
+
337
+ /** Color for one gauge stage. Filled cells and the percent value both come from
338
+ * this one call, so the bar and its number can never disagree. `theme` is the
339
+ * host's resolved theme (loosely typed at runtime); a missing token falls back
340
+ * to the theme's base text instead of an unstyled cell. Pure. */
341
+ export function contextProgressColor(stage: ContextProgressTone, theme: any): any {
342
+ return theme?.text?.feedback?.[stage]?.base ?? theme?.text?.base
343
+ }
344
+
345
+ /** The muted extra line under the gauge: `cache 92% · 42.3 tok/s`. Either half
346
+ * may be missing (no cache read, no measurable turn); no data at all yields
347
+ * null so no empty line is rendered. The speed keeps the host's own one
348
+ * decimal and `tok/s` label. Pure. */
349
+ export function contextPerformanceLine(
350
+ performance: ContextPerformance | null | undefined,
351
+ ): string | null {
352
+ if (!performance) return null
353
+ const parts: string[] = []
354
+ const cacheHit = numberOrNull(performance.cacheHit)
355
+ if (cacheHit !== null) parts.push(`cache ${Math.round(cacheHit)}%`)
356
+ const tokensPerSecond = numberOrNull(performance.tokensPerSecond)
357
+ if (tokensPerSecond !== null) parts.push(`${tokensPerSecond.toFixed(1)} tok/s`)
358
+ return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR)
359
+ }
360
+
361
+ /** Cache hit rate of one message: `cache.read / (input + cache.read)` as a
362
+ * percentage. The denominator must be > 0, otherwise the ratio is meaningless
363
+ * (a message that only wrote to the cache has no input to hit). Null when the
364
+ * numbers are absent. Pure. */
365
+ export function cacheHitPercent(tokens: any): number | null {
366
+ const read = numberOrNull(tokens?.cache?.read)
367
+ const input = numberOrNull(tokens?.input)
368
+ if (read === null || input === null) return null
369
+ const denominator = input + read
370
+ if (!(denominator > 0)) return null
371
+ return (read / denominator) * 100
372
+ }
373
+
374
+ /** The message the cache hit rate comes from: the last assistant of the live
375
+ * window (see `transcriptWindow`) that actually carries `tokens`. Later
376
+ * messages without usage — a streaming placeholder that the host publishes
377
+ * before any step completes, a step that reports no usage — are skipped
378
+ * instead of blanking a ratio the previous message already measured. Null
379
+ * when nothing in the window has usage. Pure. */
380
+ export function lastAssistantWithTokens(
381
+ messages: readonly any[] | null | undefined,
382
+ revertMessageID?: string | null,
383
+ ): any | null {
384
+ if (!Array.isArray(messages) || messages.length === 0) return null
385
+ const { start, end } = transcriptWindow(messages, revertMessageID)
386
+ for (let index = end - 1; index >= start; index--) {
387
+ const message = messages[index]
388
+ if (message?.type !== 'assistant' || !message.tokens) continue
389
+ return message
390
+ }
391
+ return null
392
+ }
393
+
394
+ /** Tokens per second of the current turn. Mirrors the host's
395
+ * `turnTokensPerSecond` (anomalyco/opencode v2.0.30,
396
+ * `packages/tui/src/routes/session/rows.ts`) so the sidebar and the native
397
+ * session footer can never disagree: the numerator is `output + reasoning`
398
+ * summed over every assistant step of the turn and the denominator is the
399
+ * summed active streaming time `max(0, time.streamed - time.created)`, so the
400
+ * division happens once, after aggregating — each step weighs by its own
401
+ * duration instead of each step voting equally. `completed` is never used; a
402
+ * turn with a step that has no `time.streamed` has no measurable speed. The
403
+ * turn starts after the last `user` message; with no user message only the
404
+ * last assistant step counts (degraded: there is no boundary to group by).
405
+ * Pure and fail-open. */
406
+ export function turnTokensPerSecond(
407
+ messages: readonly any[] | null | undefined,
408
+ position?: number | null,
409
+ ): number | null {
410
+ if (!Array.isArray(messages) || messages.length === 0) return null
411
+ let anchor = -1
412
+ if (
413
+ typeof position === 'number' &&
414
+ Number.isInteger(position) &&
415
+ position >= 0 &&
416
+ position < messages.length
417
+ ) {
418
+ anchor = position
419
+ } else {
420
+ for (let index = messages.length - 1; index >= 0; index--) {
421
+ if (messages[index]?.type === 'assistant') {
422
+ anchor = index
423
+ break
424
+ }
425
+ }
426
+ }
427
+ if (anchor === -1 || messages[anchor]?.type !== 'assistant') return null
428
+
429
+ let start = -1
430
+ for (let index = anchor - 1; index >= 0; index--) {
431
+ if (messages[index]?.type === 'user') {
432
+ start = index
433
+ break
434
+ }
435
+ }
436
+ const steps =
437
+ start === -1
438
+ ? [messages[anchor]]
439
+ : messages.slice(start + 1, anchor + 1).filter((item) => item?.type === 'assistant')
440
+ if (steps.length === 0) return null
441
+
442
+ let output = 0
443
+ let duration = 0
444
+ for (const step of steps) {
445
+ output +=
446
+ (numberOrNull(step?.tokens?.output) ?? 0) + (numberOrNull(step?.tokens?.reasoning) ?? 0)
447
+ const created = numberOrNull(step?.time?.created)
448
+ const streamed = numberOrNull(step?.time?.streamed)
449
+ if (created === null || streamed === null) return null
450
+ duration += Math.max(0, streamed - created)
451
+ }
452
+ if (output <= 0 || duration <= 0) return null
453
+ const rate = output / (duration / 1_000)
454
+ return Number.isFinite(rate) && rate > 0 ? rate : null
455
+ }
456
+
457
+ /** Last-message telemetry the Context block renders in muted text. Both halves
458
+ * are optional; the block renders no line when neither is available. */
459
+ export type ContextPerformance = { cacheHit: number | null; tokensPerSecond: number | null }
460
+
461
+ /** Thousands-separated token total: `55320` → `55,320` (en-US, matching the
462
+ * native block this one replaces). Null for a missing/invalid value. Pure. */
463
+ export function formatTokenCount(tokens: number | null | undefined): string | null {
464
+ const value = numberOrNull(tokens)
465
+ if (value === null || value < 0) return null
466
+ return Math.round(value).toLocaleString('en-US')
467
+ }
468
+
469
+ /** Context-window label: `1_000_000` → `1.0M`, `200_000` → `200K`,
470
+ * `128_000` → `128K`, `32_768` → `32K`. Sub-million limits truncate to whole K
471
+ * so the printed window never overstates the model's capacity. Pure. */
472
+ export function formatContextWindow(limit: number | null | undefined): string | null {
473
+ const value = numberOrNull(limit)
474
+ if (value === null || value <= 0) return null
475
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`
476
+ if (value >= 1_000) return `${Math.floor(value / 1_000)}K`
477
+ return `${Math.floor(value)}`
478
+ }
479
+
480
+ /** Cells in the Context gauge: always rendered in full, so the bar never
481
+ * changes width between refreshes. With the space, the percent and the
482
+ * `of <window>` tail (at most 9 columns) the line stays inside 34 columns. */
483
+ export const CONTEXT_BAR_CELLS = 12
484
+ /** Filled cell (U+25B0) and empty cell (U+25B1), both single-width. */
485
+ export const CONTEXT_BAR_FILLED_CELL = '\u25B0'
486
+ export const CONTEXT_BAR_EMPTY_CELL = '\u25B1'
487
+
488
+ /** Filled cells for a percentage: rounded, clamped to `0..cells`, so 0% is an
489
+ * empty bar and anything at or above 100% is a full one. Pure. */
490
+ export function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {
491
+ const total = Math.max(1, Math.floor(cells))
492
+ const filled = Math.round((percent / 100) * total)
493
+ if (!Number.isFinite(filled)) return 0
494
+ return Math.min(total, Math.max(0, filled))
495
+ }
496
+
497
+ /** The gauge split into its toned half (filled cells) and its muted half (empty
498
+ * cells), so the caller colors each side. Null when the percentage is missing:
499
+ * the Context block then keeps its tokens + cost rows and renders no bar. Pure. */
500
+ export function contextBar(
501
+ percent: number | null | undefined,
502
+ cells = CONTEXT_BAR_CELLS,
503
+ ): { filled: string; empty: string } | null {
504
+ const value = numberOrNull(percent)
505
+ if (value === null) return null
506
+ const total = Math.max(1, Math.floor(cells))
507
+ const filled = contextBarFilled(value, total)
508
+ return {
509
+ filled: CONTEXT_BAR_FILLED_CELL.repeat(filled),
510
+ empty: CONTEXT_BAR_EMPTY_CELL.repeat(total - filled),
511
+ }
512
+ }
513
+
514
+ /** USD spent with two decimals (`$0.18`), the native block's format. Null for
515
+ * a missing/negative value. Pure. */
516
+ export function formatSpent(cost: number | null | undefined): string | null {
517
+ const value = numberOrNull(cost)
518
+ if (value === null || value < 0) return null
519
+ return `$${value.toFixed(2)}`
520
+ }
521
+
522
+ /** One rendered context row. `lead` and `tail` carry the gauge bar when the row
523
+ * has one (`lead` is toned with the value, `tail` is muted), so the 12 cells
524
+ * stay contiguous while the empty half still reads as background. */
525
+ export type ContextRow = {
526
+ lead: string | null
527
+ value: string
528
+ tail: string | null
529
+ suffix: string | null
530
+ tone: ContextProgressTone | null
531
+ }
532
+
533
+ /** The `Context` block's data rows; null rows are not rendered. */
534
+ export type ContextBlockRows = {
535
+ tokens: ContextRow | null
536
+ percent: ContextRow | null
537
+ spent: ContextRow | null
538
+ }
539
+
540
+ /** Rows for the `Context` block:
541
+ * `<tokens> tokens` / `▰▰▰▰▰▱▱▱▱▱▱▱ <percent>% of <window>` /
542
+ * `$<spent> spent`. The percentage row carries the only semantic tone, the
543
+ * gauge bar (12 cells) and is omitted entirely when the percentage is
544
+ * unavailable (never `undefined%`). A block with neither tokens nor cost
545
+ * yields null. Pure. */
546
+ export function contextBlockRows(
547
+ usage: ContextUsage | null,
548
+ cost: number | null | undefined,
549
+ ): ContextBlockRows | null {
550
+ const spentValue = formatSpent(cost)
551
+ const spent: ContextRow | null =
552
+ spentValue === null
553
+ ? null
554
+ : { lead: null, value: spentValue, tail: null, suffix: ' spent', tone: null }
555
+ if (usage === null) return spent === null ? null : { tokens: null, percent: null, spent }
556
+
557
+ const tokensValue = formatTokenCount(usage.tokens)
558
+ const tokens: ContextRow | null =
559
+ tokensValue === null
560
+ ? null
561
+ : { lead: null, value: tokensValue, tail: null, suffix: ' tokens', tone: null }
562
+
563
+ const percentValue = numberOrNull(usage.percent)
564
+ const window = formatContextWindow(usage.limit)
565
+ const bar = contextBar(percentValue)
566
+ const percent: ContextRow | null =
567
+ bar === null || percentValue === null
568
+ ? null
569
+ : {
570
+ lead: bar.filled,
571
+ value: ` ${Math.round(percentValue)}%`,
572
+ tail: bar.empty,
573
+ suffix: window === null ? null : ` of ${window}`,
574
+ tone: contextUsageTone(percentValue),
575
+ }
576
+
577
+ if (tokens === null && percent === null && spent === null) return null
578
+ return { tokens, percent, spent }
579
+ }
580
+
581
+ /* ─── Per-model real usage ────────────────────────────────
582
+ * `SessionMessageAssistant` carries the real `model` (`ModelRef`), an optional
583
+ * `cost` (`MoneyUSD` = number) and optional `tokens`, so the sidebar can show
584
+ * what each model actually cost instead of estimating from pricing tables.
585
+ * Everything below is pure so the aggregation is testable without a renderer;
586
+ * a message without `cost` contributes 0 and is omitted (never a guessed
587
+ * price). */
588
+
589
+ /** Models rendered in the Context block before the aggregate `… +N` line. */
590
+ export const MODEL_USAGE_VISIBLE_CEILING = 3
591
+ /** Newest messages read per session — bounds the O(n) walk on long sessions. */
592
+ export const MODEL_USAGE_MESSAGE_LIMIT = 400
593
+ /** Sessions read per family (root + delegations) for the aggregate. */
594
+ export const MODEL_USAGE_SESSION_LIMIT = 8
595
+ /** Column widths for one model row (labels are muted, numbers right-aligned). */
596
+ export const MODEL_USAGE_MODEL_WIDTH = 12
597
+ export const MODEL_USAGE_TOKEN_WIDTH = 6
598
+ export const MODEL_USAGE_COST_WIDTH = 8
599
+ /** Session events arrive in bursts; model rows are recomputed at most once
600
+ * per window (same cadence as the git-count revalidation). */
601
+ export const MODEL_USAGE_DEBOUNCE_MS = 400
602
+
603
+ /** Real usage for one model, summed across the assistant messages that used it. */
604
+ export type ModelUsage = { model: string; tokens: number; cost: number }
605
+
606
+ /** Totals per model from assistant messages: sums `cost` and `tokens`, drops
607
+ * models whose real cost is 0/absent, and orders by cost (then tokens, then
608
+ * name). `providerID` participates in the key so two providers exposing the
609
+ * same bare id are not merged. Pure. */
610
+ export function collectModelUsage(messages: readonly any[]): ModelUsage[] {
611
+ if (!Array.isArray(messages)) return []
612
+ const totals = new Map<string, ModelUsage>()
613
+ for (const message of messages) {
614
+ if (message?.type !== 'assistant') continue
615
+ const id = modelRefID(message.model)
616
+ const model = shortModelID(message.model, MODEL_USAGE_MODEL_WIDTH)
617
+ if (id === null || model === null) continue
618
+ const providerID = typeof message.model?.providerID === 'string' ? message.model.providerID : ''
619
+ const key = `${providerID}\u0000${id}`
620
+ const tokenCount = message.tokens ? messageTokensTotal(message.tokens) : 0
621
+ const cost = numberOrNull(message.cost) ?? 0
622
+ const current = totals.get(key)
623
+ if (current) {
624
+ current.tokens += Math.max(0, tokenCount)
625
+ current.cost += Math.max(0, cost)
626
+ } else {
627
+ totals.set(key, { model, tokens: Math.max(0, tokenCount), cost: Math.max(0, cost) })
628
+ }
629
+ }
630
+ return [...totals.values()]
631
+ .filter((row) => row.cost > 0)
632
+ .sort((a, b) => b.cost - a.cost || b.tokens - a.tokens || a.model.localeCompare(b.model))
633
+ }
634
+
635
+ /** Visible rows plus the aggregate of the models that did not fit. Pure. */
636
+ export type ModelUsageCeiling = {
637
+ visible: ModelUsage[]
638
+ hidden: number
639
+ hiddenCost: number
640
+ hiddenTokens: number
641
+ }
642
+
643
+ /** Cap the model list at `maxVisible`; the rest is aggregated (still real
644
+ * totals) for the `… +N` line. Pure. */
645
+ export function ceilingModelUsage(
646
+ rows: readonly ModelUsage[],
647
+ maxVisible = MODEL_USAGE_VISIBLE_CEILING,
648
+ ): ModelUsageCeiling {
649
+ const limit = Math.max(0, maxVisible)
650
+ const visible = rows.slice(0, limit)
651
+ const rest = rows.slice(visible.length)
652
+ return {
653
+ visible,
654
+ hidden: rest.length,
655
+ hiddenCost: rest.reduce((sum, row) => sum + row.cost, 0),
656
+ hiddenTokens: rest.reduce((sum, row) => sum + row.tokens, 0),
657
+ }
658
+ }
659
+
660
+ /** Compact tokens for a model row (`80,000` → `80K`); `0` stays explicit. Pure. */
661
+ export function formatUsageTokens(tokens: number | null | undefined): string {
662
+ const value = numberOrNull(tokens)
663
+ if (value === null || value <= 0) return '0'
664
+ return formatContextWindow(value) ?? String(Math.round(value))
665
+ }
666
+
667
+ /** Real per-model cost with adaptive precision: cents for `>= $0.01`, up to
668
+ * four decimals below that (a real `$0.0031` must not render as `$0.00`), and
669
+ * an explicit `< $0.0001` for the remainder. Pure. */
670
+ export function formatUsageCost(cost: number | null | undefined): string | null {
671
+ const value = numberOrNull(cost)
672
+ if (value === null || value < 0) return null
673
+ if (value === 0) return '$0.00'
674
+ if (value >= 0.01) return `$${value.toFixed(2)}`
675
+ if (value >= 0.0001) {
676
+ const fixed = value.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')
677
+ return `$${fixed}`
678
+ }
679
+ return '<$0.0001'
680
+ }
681
+
682
+ /** One formatted model row: truncated label + compact tokens + real cost. */
683
+ export type ModelUsageRow = { model: string; tokens: string; cost: string }
684
+
685
+ /** Format the visible model rows for rendering. Labels are already short ids
686
+ * (12 chars); the second truncation only guards host drift. Pure. */
687
+ export function modelUsageRows(rows: readonly ModelUsage[]): ModelUsageRow[] {
688
+ return rows.map((row) => ({
689
+ model: truncateLabel(row.model, MODEL_USAGE_MODEL_WIDTH),
690
+ tokens: formatUsageTokens(row.tokens),
691
+ cost: formatUsageCost(row.cost) ?? '$0.00',
692
+ }))
693
+ }
694
+
695
+ /** Exact single-line text of a model row, with numbers right-aligned. Pure. */
696
+ export function modelUsageRowText(row: ModelUsageRow): string {
697
+ return `${row.model.padEnd(MODEL_USAGE_MODEL_WIDTH)} ${row.tokens.padStart(MODEL_USAGE_TOKEN_WIDTH)} ${row.cost.padStart(MODEL_USAGE_COST_WIDTH)}`
698
+ }
699
+
700
+ /** Muted aggregate line for the models beyond the cap (`… +2 $0.03`). Null
701
+ * when every model fits. Pure. */
702
+ export function hiddenModelUsageText(hidden: number, hiddenCost: number): string | null {
703
+ if (!Number.isFinite(hidden) || hidden <= 0) return null
704
+ const cost = formatUsageCost(hiddenCost)
705
+ return cost === null ? `… +${hidden}` : `… +${hidden} ${cost}`
706
+ }
707
+
708
+ /* ─── Child agent bucket ──────────────────────────────────
709
+ * `SessionInfo.agent` is the host's per-session agent id, so the `Dispatch`
710
+ * block groups the delegation tree by that field alone — no extra request, no
711
+ * price table, and no per-message refinement: the aggregate is a count plus the
712
+ * summed child cost, which is the only thing the short sidebar can afford. */
713
+
714
+ /** Bucket for a session the host published without an agent id. */
715
+ export const UNKNOWN_AGENT = '?'
716
+
717
+ /** Agent key of a session or message: the trimmed id when it is a non-empty
718
+ * string, else the `?` bucket — never `undefined`. Pure. */
719
+ export function agentKey(value: unknown): string {
720
+ if (typeof value !== 'string') return UNKNOWN_AGENT
721
+ const text = value.trim()
722
+ return text === '' ? UNKNOWN_AGENT : text
723
+ }
724
+
725
+ /* ─── Todo block ──────────────────────────────────────────
726
+ * The host exposes no todo API: the installed client has no
727
+ * `session.todo`/`client.session.todo` and the V2 event union carries no
728
+ * `todo.updated`. The authoritative source is the transcript — the
729
+ * `todowrite` tool part (`SessionMessageAssistantTool`) stores the whole list
730
+ * in `state.input.todos`, and the tool is a full replace (delete + insert), so
731
+ * the newest *completed* write is the current list. Deriving it from the
732
+ * transcript (never from a local write history) also makes a session revert
733
+ * correct for free: the reverted-away write is simply not in `message.list`
734
+ * anymore. Everything below is pure and fail-open. */
735
+
736
+ export type TodoStatus = 'in_progress' | 'pending' | 'completed' | 'cancelled'
737
+
738
+ /** One rendered todo row. `priority` is carried by the tool but not rendered:
739
+ * the reference block uses a single marker column. */
740
+ export type TodoItem = { content: string; status: TodoStatus }
741
+
742
+ /** Rows rendered before the `… +N` line. */
743
+ export const TODO_VISIBLE_CEILING = 6
744
+ /** Content width before the ellipsis — the block has ~30-34 usable columns. */
745
+ export const TODO_TEXT_WIDTH = 28
746
+
747
+ /** Row markers (`•` in progress, `−` cancelled with U+2212, as in the git row). */
748
+ const TODO_MARKERS: Record<TodoStatus, string> = {
749
+ in_progress: '[\u2022]',
750
+ pending: '[ ]',
751
+ completed: '[x]',
752
+ cancelled: '[\u2212]',
753
+ }
754
+
755
+ /** Group order: live work first, then open, then closed. */
756
+ const TODO_STATUS_ORDER: readonly TodoStatus[] = [
757
+ 'in_progress',
758
+ 'pending',
759
+ 'completed',
760
+ 'cancelled',
761
+ ]
762
+
763
+ /** Narrow a loose `status` value to the tool's four states. */
764
+ export function isTodoStatus(value: unknown): value is TodoStatus {
765
+ return (
766
+ value === 'in_progress' || value === 'pending' || value === 'completed' || value === 'cancelled'
767
+ )
768
+ }
769
+
770
+ /** Items from a `todowrite` `input` payload. A missing/malformed `input`,
771
+ * absent `todos`, an unknown `status` or an empty/missing `content` drops the
772
+ * entry instead of throwing; a list with nothing readable yields `[]`. Pure. */
773
+ export function parseTodoItems(input: unknown): TodoItem[] {
774
+ const raw = (input as { todos?: unknown } | null | undefined)?.todos
775
+ if (!Array.isArray(raw)) return []
776
+ const items: TodoItem[] = []
777
+ for (const entry of raw) {
778
+ const content = (entry as { content?: unknown } | null | undefined)?.content
779
+ const status = (entry as { status?: unknown } | null | undefined)?.status
780
+ if (typeof content !== 'string' || content.trim() === '') continue
781
+ if (!isTodoStatus(status)) continue
782
+ items.push({ content: content.trim(), status })
783
+ }
784
+ return items
785
+ }
786
+
787
+ /** Newest completed `todowrite` in a transcript. The tool replaces the list
788
+ * wholesale, so the last write wins; a write with `todos: []` returns null
789
+ * (the block disappears rather than showing the previous list) and a
790
+ * not-yet-completed write is ignored. Null when the transcript carries no
791
+ * such part, so the block never renders a guess. Pure. */
792
+ export function latestTodoItems(messages: readonly any[] | null | undefined): TodoItem[] | null {
793
+ if (!Array.isArray(messages)) return null
794
+ for (let index = messages.length - 1; index >= 0; index--) {
795
+ const message = messages[index]
796
+ if (message?.type !== 'assistant' || !Array.isArray(message.content)) continue
797
+ const parts = message.content
798
+ for (let position = parts.length - 1; position >= 0; position--) {
799
+ const part = parts[position]
800
+ if (part?.type !== 'tool' || part?.name !== 'todowrite') continue
801
+ if (part?.state?.status !== 'completed') continue
802
+ const items = parseTodoItems(part.state.input)
803
+ return items.length === 0 ? null : items
804
+ }
805
+ }
806
+ return null
807
+ }
808
+
809
+ /** Stable group order (in_progress → pending → completed → cancelled); within a
810
+ * group the transcript order is preserved. Pure. */
811
+ export function orderTodoItems(items: readonly TodoItem[]): TodoItem[] {
812
+ return [...items].sort(
813
+ (a, b) => TODO_STATUS_ORDER.indexOf(a.status) - TODO_STATUS_ORDER.indexOf(b.status),
814
+ )
815
+ }
816
+
817
+ /** Row color channel: `accent` for live work, `muted` for closed items, base
818
+ * for pending. Kept separate from the theme so it is testable. Pure. */
819
+ export type TodoTone = 'accent' | 'muted' | 'base'
820
+
821
+ /** Tone for one status — no rainbow, a single accent. Pure. */
822
+ export function todoTone(status: TodoStatus): TodoTone {
823
+ if (status === 'in_progress') return 'accent'
824
+ if (status === 'completed' || status === 'cancelled') return 'muted'
825
+ return 'base'
826
+ }
827
+
828
+ /** Exact rendered text of one row: `[•] <content truncated to 28>`. Pure. */
829
+ export function todoRowText(item: TodoItem): string {
830
+ return `${TODO_MARKERS[item.status]} ${truncateLabel(item.content, TODO_TEXT_WIDTH)}`
831
+ }
832
+
833
+ /** Ordered rows capped for the sidebar, plus how many did not fit. Pure. */
834
+ export type TodoCeiling = { visible: TodoItem[]; hidden: number }
835
+
836
+ /** Order then cap the list at `maxVisible`. Pure. */
837
+ export function ceilingTodoItems(
838
+ items: readonly TodoItem[],
839
+ maxVisible = TODO_VISIBLE_CEILING,
840
+ ): TodoCeiling {
841
+ const ordered = orderTodoItems(items)
842
+ const visible = ordered.slice(0, Math.max(0, maxVisible))
843
+ return { visible, hidden: Math.max(0, ordered.length - visible.length) }
844
+ }
845
+
846
+ /** Overflow line (`… +3`); null when every item fits. Pure. */
847
+ export function hiddenTodoText(hidden: number): string | null {
848
+ if (!Number.isFinite(hidden) || hidden <= 0) return null
849
+ return `… +${Math.round(hidden)}`
850
+ }
851
+
852
+ /* ─── Git change counts ───────────────────────────────────
853
+ * Two sources, in order of authority:
854
+ * 1. the git CLI (`git status --porcelain=v1 -uall` + `git rev-list
855
+ * --count --left-right @{upstream}...HEAD`), which is the only way to see
856
+ * untracked files and ahead/behind — the HTTP protocol exposes neither;
857
+ * 2. `client.vcs.status()` (`GET /api/vcs/status`), one `VcsFileStatus` per
858
+ * changed file: `{ file, additions, deletions, status }` with `status` in
859
+ * `"added" | "modified" | "deleted"`. Used only when the CLI fails, and it
860
+ * counts files per status — never lines.
861
+ * Both are fail-open: no git or no API degrades to the branch-only row. */
862
+
863
+ export type GitChangeCounts = { added: number; modified: number; deleted: number }
864
+
865
+ /** Narrow a `VcsFileStatus["status"]` value read off a loose payload. */
866
+ function isGitChangeStatus(value: unknown): value is keyof GitChangeCounts {
867
+ return value === 'added' || value === 'modified' || value === 'deleted'
868
+ }
869
+
870
+ /** Files per status from a `VcsFileStatus[]` payload. Unknown statuses and
871
+ * malformed entries are ignored. Pure. */
872
+ export function countGitChanges(files: readonly any[] | null | undefined): GitChangeCounts {
873
+ const counts: GitChangeCounts = { added: 0, modified: 0, deleted: 0 }
874
+ if (!Array.isArray(files)) return counts
875
+ for (const entry of files) {
876
+ const status: unknown = entry?.status
877
+ if (isGitChangeStatus(status)) counts[status] += 1
878
+ }
879
+ return counts
880
+ }
881
+
882
+ /** `+1 ±2 −3` for the file counts; each zero term is omitted, and an empty
883
+ * change set returns null so the row is not rendered at all. Pure. */
884
+ export function formatGitChanges(files: readonly any[] | null | undefined): string | null {
885
+ const { added, modified, deleted } = countGitChanges(files)
886
+ const parts: string[] = []
887
+ if (added > 0) parts.push(`+${added}`)
888
+ if (modified > 0) parts.push(`±${modified}`)
889
+ if (deleted > 0) parts.push(`\u2212${deleted}`)
890
+ return parts.length === 0 ? null : parts.join(' ')
891
+ }
892
+
893
+ /* ─── Git CLI (untracked / ahead / behind) ────────────────
894
+ * Run with an async `execFile` — never `execSync`, which would block the TUI's
895
+ * render loop — bounded by a timeout and with `windowsHide` so a Windows host
896
+ * does not flash a console window. One probe is two short git calls; the
897
+ * sidebar revalidates on mount and on the session events it already
898
+ * subscribes to, behind a debounce and a cooldown (see the constants), and
899
+ * skips a revalidation entirely while one is still running — there is no queue
900
+ * and no polling timer. */
901
+
902
+ /** Wall-clock ceiling for one git call. A stuck git (index lock, network
903
+ * filesystem) is killed instead of holding the row forever. */
904
+ export const GIT_CLI_TIMEOUT_MS = 2_000
905
+ /** Session events arrive in bursts; a git probe is scheduled at most once per
906
+ * window instead of once per event. */
907
+ export const GIT_CLI_DEBOUNCE_MS = 1_000
908
+ /** Minimum spacing between two probe starts. Five seconds keeps a chatty event
909
+ * stream from spawning a git process per step while staying fresh enough to
910
+ * show a file appearing mid-turn. */
911
+ export const GIT_CLI_MIN_INTERVAL_MS = 5_000
912
+ /** Stdout ceiling for one git call. `status --porcelain=v1 -uall` lists every
913
+ * untracked file, so a large worktree easily passes the 1 MB `execFile`
914
+ * default — which would reject and silently hand the row back to the
915
+ * `vcs.status` fallback. 4 MB is far above a realistic porcelain listing. */
916
+ export const GIT_CLI_MAX_BUFFER = 4 * 1024 * 1024
917
+
918
+ /** One `execFile` call: `(file, args, options) → { stdout }`. Injectable so the
919
+ * parsing/gating logic is testable without spawning processes. */
920
+ export type GitExec = (
921
+ file: string,
922
+ args: readonly string[],
923
+ options: { cwd: string; timeout: number; windowsHide: boolean; maxBuffer: number },
924
+ ) => Promise<{ stdout: string }>
925
+
926
+ /** Default runner: the promisified `node:child_process.execFile`. A non-zero
927
+ * exit (no repository, no upstream) rejects and the caller decides. */
928
+ export const defaultGitExec: GitExec = (file, args, options) =>
929
+ new Promise((resolve, reject) => {
930
+ execFile(
931
+ file,
932
+ [...args],
933
+ {
934
+ cwd: options.cwd,
935
+ timeout: options.timeout,
936
+ windowsHide: options.windowsHide,
937
+ maxBuffer: options.maxBuffer,
938
+ },
939
+ (error, stdout) => {
940
+ if (error) reject(error)
941
+ else resolve({ stdout: typeof stdout === 'string' ? stdout : String(stdout ?? '') })
942
+ },
943
+ )
944
+ })
945
+
946
+ /** Files per status from `git status --porcelain=v1 -uall`, including the two
947
+ * columns the protocol cannot report. Each line starts with `XY` (index and
948
+ * worktree state); a rename prints `R old -> new`, and `??` / `!!` are
949
+ * untracked / ignored. Precedence per file: deleted > added > modified, so
950
+ * `AM` counts once as added and `AD` once as deleted. Renames, copies and
951
+ * unmerged entries count as modified. Pure. */
952
+ export type GitPorcelainCounts = {
953
+ added: number
954
+ modified: number
955
+ deleted: number
956
+ untracked: number
957
+ }
958
+
959
+ /** Parse porcelain v1 output into file counts. Empty/malformed output yields
960
+ * zero counts (a clean tree), never a throw. Pure. */
961
+ export function parseGitStatusPorcelain(output: string | null | undefined): GitPorcelainCounts {
962
+ const counts: GitPorcelainCounts = { added: 0, modified: 0, deleted: 0, untracked: 0 }
963
+ if (typeof output !== 'string' || output === '') return counts
964
+ for (const line of output.split('\n')) {
965
+ if (line.length < 2) continue
966
+ const index = line[0]
967
+ const worktree = line[1]
968
+ if (index === '!' && worktree === '!') continue // ignored file
969
+ if (index === '?' && worktree === '?') {
970
+ counts.untracked += 1
971
+ continue
972
+ }
973
+ if (index === ' ' && worktree === ' ') continue
974
+ if (index === 'D' || worktree === 'D') counts.deleted += 1
975
+ else if (index === 'A' || worktree === 'A') counts.added += 1
976
+ else counts.modified += 1
977
+ }
978
+ return counts
979
+ }
980
+
981
+ /** `git rev-list --count --left-right @{upstream}...HEAD` prints two numbers:
982
+ * commits only on the upstream (behind) then commits only on HEAD (ahead).
983
+ * Null when the output is not that pair — e.g. the command failed because the
984
+ * branch has no upstream, in which case the arrows are simply omitted. Pure. */
985
+ export function parseGitAheadBehind(
986
+ output: string | null | undefined,
987
+ ): { ahead: number; behind: number } | null {
988
+ if (typeof output !== 'string') return null
989
+ const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(output)
990
+ if (match === null) return null
991
+ const behind = Number(match[1])
992
+ const ahead = Number(match[2])
993
+ if (!Number.isFinite(ahead) || !Number.isFinite(behind)) return null
994
+ return { ahead, behind }
995
+ }
996
+
997
+ /** One git observation: file counts plus the upstream distance (either arrow
998
+ * may be unknown when the branch has no upstream). */
999
+ export type GitCliSnapshot = {
1000
+ changes: GitPorcelainCounts
1001
+ ahead: number | null
1002
+ behind: number | null
1003
+ }
1004
+
1005
+ /** One probe: `git status --porcelain=v1 -uall` for the counts, then
1006
+ * `git rev-list --count --left-right @{upstream}...HEAD` for the arrows (a
1007
+ * failure there only drops the arrows). A status failure rejects — the caller
1008
+ * then falls back to `client.vcs.status`. */
1009
+ export async function readGitSnapshot(
1010
+ directory: string,
1011
+ exec: GitExec = defaultGitExec,
1012
+ ): Promise<GitCliSnapshot> {
1013
+ const options = {
1014
+ cwd: directory,
1015
+ timeout: GIT_CLI_TIMEOUT_MS,
1016
+ windowsHide: true,
1017
+ maxBuffer: GIT_CLI_MAX_BUFFER,
1018
+ }
1019
+ const status = await exec('git', ['status', '--porcelain=v1', '-uall'], options)
1020
+ const changes = parseGitStatusPorcelain(status?.stdout)
1021
+ let ahead: number | null = null
1022
+ let behind: number | null = null
1023
+ try {
1024
+ const counts = await exec(
1025
+ 'git',
1026
+ ['rev-list', '--count', '--left-right', '@{upstream}...HEAD'],
1027
+ options,
1028
+ )
1029
+ const parsed = parseGitAheadBehind(counts?.stdout)
1030
+ if (parsed !== null) {
1031
+ ahead = parsed.ahead
1032
+ behind = parsed.behind
1033
+ }
1034
+ } catch {
1035
+ /* no upstream configured — the arrows are omitted, the counts still show */
1036
+ }
1037
+ return { changes, ahead, behind }
1038
+ }
1039
+
1040
+ /** Rendered git row: `+1 ±2 −1 ?2 ↑3 ↓1`, zero terms omitted. Null when the
1041
+ * tree is clean and in sync, so the block keeps only its branch line. Pure. */
1042
+ export function formatGitSnapshot(snapshot: GitCliSnapshot | null | undefined): string | null {
1043
+ if (!snapshot?.changes) return null
1044
+ const { added, modified, deleted, untracked } = snapshot.changes
1045
+ const parts: string[] = []
1046
+ if (added > 0) parts.push(`+${added}`)
1047
+ if (modified > 0) parts.push(`±${modified}`)
1048
+ if (deleted > 0) parts.push(`\u2212${deleted}`)
1049
+ if (untracked > 0) parts.push(`?${untracked}`)
1050
+ if ((snapshot.ahead ?? 0) > 0) parts.push(`${GIT_ARROW_UP}${snapshot.ahead}`)
1051
+ if ((snapshot.behind ?? 0) > 0) parts.push(`${GIT_ARROW_DOWN}${snapshot.behind}`)
1052
+ return parts.length === 0 ? null : parts.join(' ')
1053
+ }
1054
+
1055
+ /** Whether a new probe may start. An in-flight probe always wins (no queue), and
1056
+ * the previous start must be older than the cooldown. Pure. */
1057
+ export function gitProbeAllowed(
1058
+ state: { now: number; lastRunAt: number | null; inFlight: boolean },
1059
+ cooldownMs = GIT_CLI_MIN_INTERVAL_MS,
1060
+ ): boolean {
1061
+ if (state.inFlight) return false
1062
+ if (state.lastRunAt === null) return true
1063
+ const elapsed = state.now - state.lastRunAt
1064
+ return !Number.isFinite(elapsed) || elapsed >= cooldownMs
1065
+ }
1066
+
1067
+ /* ─── Spend (local server stats) ─────────────────────────
1068
+ * `client.session.stats()` → `GET /api/experimental/session/stats` is the only
1069
+ * source: it is served by the local OpenCode process that is already running,
1070
+ * so the numbers are pure spend — no provider call, no credential read, no
1071
+ * polling, and no plan limit (the protocol exposes no quota/balance field).
1072
+ * The route is experimental: any failure leaves the values unknown and
1073
+ * preserves whatever was last known. */
1074
+
1075
+ /** Spend window labels, in render order. */
1076
+ export const SPEND_TODAY_LABEL = 'hoje'
1077
+ export const SPEND_30D_LABEL = '30d'
1078
+ /** Separator between the two windows on the Context footer line. */
1079
+ export const SPEND_LINE_SEPARATOR = ' \u00B7 '
1080
+ /** `30d` window: 30 × 24 h, measured back from "now". */
1081
+ export const SPEND_30D_MS = 30 * 24 * 60 * 60 * 1000
1082
+ /** Probe window: one hour, narrow enough that a unit mix-up cannot line up. */
1083
+ export const SPEND_PROBE_WINDOW_MS = 60 * 60 * 1000
1084
+ /** The echoed `range` may be rounded server-side; 120 s absorbs that. */
1085
+ export const SPEND_PROBE_TOLERANCE_MS = 120_000
1086
+ /** Session events arrive in bursts — same 400 ms window as the other blocks. */
1087
+ export const SPEND_REFRESH_DEBOUNCE_MS = 400
1088
+
1089
+ /** Spend per window in USD. Either side may be unknown (kept `null`). */
1090
+ export type SpendTotals = { today: number | null; thirtyDays: number | null }
1091
+
1092
+ /** `from`/`to` unit accepted by the route. `SessionStatsInput` declares both as
1093
+ * bare `number` and does not say which unit, so it is measured once per
1094
+ * process (`ms` unless the server echoes seconds) instead of guessed. */
1095
+ type SpendUnit = 'ms' | 's' | 'unavailable'
1096
+
1097
+ /** Resolved unit for this process; `null` until the mount probe answers. */
1098
+ let spendUnit: SpendUnit | null = null
1099
+ /** In-flight probe, so two refreshes cannot each burn the 2-call budget. */
1100
+ let spendProbe: Promise<SpendUnit> | null = null
1101
+
1102
+ /** Test-only: forget the process-wide unit resolution. Never called at runtime. */
1103
+ export function resetSpendUnit(): void {
1104
+ spendUnit = null
1105
+ spendProbe = null
1106
+ }
1107
+
1108
+ /** Resolved unit (`ms` / `s` / `unavailable`) or null while still unknown. */
1109
+ export function resolvedSpendUnit(): SpendUnit | null {
1110
+ return spendUnit
1111
+ }
1112
+
1113
+ /** Local midnight for `now`: `new Date()` with the clock fields zeroed in the
1114
+ * current timezone (DST-safe, unlike subtracting hours). Pure. */
1115
+ export function startOfLocalDay(now: number): number {
1116
+ const date = new Date(now)
1117
+ date.setHours(0, 0, 0, 0)
1118
+ return date.getTime()
1119
+ }
1120
+
1121
+ /** The two windows the block shows: `hoje` (local midnight → now) and `30d`
1122
+ * (now − 30 days → now). Pure. */
1123
+ export function spendWindows(now: number): {
1124
+ today: { from: number; to: number }
1125
+ thirtyDays: { from: number; to: number }
1126
+ } {
1127
+ return {
1128
+ today: { from: startOfLocalDay(now), to: now },
1129
+ thirtyDays: { from: now - SPEND_30D_MS, to: now },
1130
+ }
1131
+ }
1132
+
1133
+ /** USD with two decimals (`$0.42`), four for a positive sub-cent amount
1134
+ * (`$0.0031`), and `<$0.0001` when even four decimals would read `$0.0000`.
1135
+ * `0` prints `$0.00`. Null for a missing/negative/non-finite value. Pure. */
1136
+ export function formatSpendUSD(cost: number | null | undefined): string | null {
1137
+ const value = numberOrNull(cost)
1138
+ if (value === null || value < 0) return null
1139
+ if (value === 0) return '$0.00'
1140
+ if (value >= 0.01) return `$${value.toFixed(2)}`
1141
+ const cents = value.toFixed(2)
1142
+ if (cents !== '0.00') return `$${cents}`
1143
+ const cents4 = value.toFixed(4)
1144
+ return cents4 === '0.0000' ? '<$0.0001' : `$${cents4}`
1145
+ }
1146
+
1147
+ /** `cost` off a `SessionStatsInfo` (`MoneyUSD` = number) or null when the
1148
+ * payload is malformed/negative, so a bad value never reaches a row. Pure. */
1149
+ export function statsCost(result: unknown): number | null {
1150
+ const cost = numberOrNull((result as { cost?: unknown } | null | undefined)?.cost)
1151
+ return cost !== null && cost >= 0 ? cost : null
1152
+ }
1153
+
1154
+ /** True when the server echoed the window we sent, within 120 s. `scale` is how
1155
+ * many milliseconds one unit of the sent window is worth (`1` for `ms`, `1000`
1156
+ * for `s`). The echo is accepted either as the same numbers we sent (the route
1157
+ * keeps the caller's unit) or converted to millisecond epoch (`DateTime.Utc`),
1158
+ * so the probe pins the unit without assuming which of the two it gets. Pure. */
1159
+ export function statsRangeMatches(
1160
+ range: unknown,
1161
+ sent: { from: number; to: number },
1162
+ scale: number,
1163
+ ): boolean {
1164
+ const from = numberOrNull((range as { from?: unknown } | null | undefined)?.from)
1165
+ const to = numberOrNull((range as { to?: unknown } | null | undefined)?.to)
1166
+ if (from === null || to === null) return false
1167
+ const tolerance = SPEND_PROBE_TOLERANCE_MS / scale
1168
+ const sameUnit = Math.abs(from - sent.from) <= tolerance && Math.abs(to - sent.to) <= tolerance
1169
+ const asMilliseconds =
1170
+ Math.abs(from - sent.from * scale) <= SPEND_PROBE_TOLERANCE_MS &&
1171
+ Math.abs(to - sent.to * scale) <= SPEND_PROBE_TOLERANCE_MS
1172
+ return sameUnit || asMilliseconds
1173
+ }
1174
+
1175
+ /** The `Context` block's last line: both spend windows on one muted row
1176
+ * (`hoje $0.42 · 30d $9.80`). A window without a usable amount is omitted, and
1177
+ * no usable window at all yields null so the line (and not the block) is
1178
+ * dropped. Pure. */
1179
+ export function contextSpendLine(totals: SpendTotals | null): string | null {
1180
+ if (totals === null) return null
1181
+ const parts: string[] = []
1182
+ const today = formatSpendUSD(totals.today)
1183
+ if (today !== null) parts.push(`${SPEND_TODAY_LABEL} ${today}`)
1184
+ const thirtyDays = formatSpendUSD(totals.thirtyDays)
1185
+ if (thirtyDays !== null) parts.push(`${SPEND_30D_LABEL} ${thirtyDays}`)
1186
+ return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR)
1187
+ }
1188
+
1189
+ /** Grapheme iterator: a cut never splits a surrogate pair, a combining mark
1190
+ * from its base or a ZWJ emoji sequence, so truncation stays cell-exact. */
1191
+ const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
1192
+
1193
+ /** A grapheme the host draws two cells wide: emoji presentation, an extended
1194
+ * pictograph (a bare `❤` counts too, exactly as the host's `emoji-regex`
1195
+ * does) and a regional-indicator pair (a flag). */
1196
+ const EMOJI_GLYPH = /\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{Regional_Indicator}/u
1197
+ /** VS16 asks for emoji presentation; without it `1` is one cell, with it the
1198
+ * keycap sequence is drawn as one two-cell glyph. */
1199
+ const EMOJI_PRESENTATION_SELECTOR = '\uFE0F'
1200
+ /** Unicode default-ignorable code points carry no width of their own. */
1201
+ const IGNORABLE_GLYPH = /^\p{Default_Ignorable_Code_Point}$/u
1202
+ /** East Asian Wide/Fullwidth ranges — two cells, never the ambiguous width
1203
+ * (the host measures ambiguous as narrow, so `▸`/`✓`/`—` stay one cell).
1204
+ * Generated from the host's own measurement (`string-width` over every code
1205
+ * point, emoji excluded), so this table can be regenerated verbatim when the
1206
+ * host upgrades its Unicode data instead of being hand-edited. */
1207
+ const CELL_WIDE_RANGES: readonly (readonly [number, number])[] = [
1208
+ [0x1100, 0x115e],
1209
+ [0x2329, 0x232a],
1210
+ [0x2630, 0x2637],
1211
+ [0x268a, 0x268f],
1212
+ [0x2e80, 0x2e99],
1213
+ [0x2e9b, 0x2ef3],
1214
+ [0x2f00, 0x2fd5],
1215
+ [0x2ff0, 0x302f],
1216
+ [0x3031, 0x303c],
1217
+ [0x303e, 0x303e],
1218
+ [0x3041, 0x3096],
1219
+ [0x3099, 0x30ff],
1220
+ [0x3105, 0x312f],
1221
+ [0x3131, 0x3163],
1222
+ [0x3165, 0x318e],
1223
+ [0x3190, 0x31e5],
1224
+ [0x31ef, 0x321e],
1225
+ [0x3220, 0x3247],
1226
+ [0x3250, 0x3296],
1227
+ [0x3298, 0x3298],
1228
+ [0x329a, 0xa48c],
1229
+ [0xa490, 0xa4c6],
1230
+ [0xa960, 0xa97c],
1231
+ [0xac00, 0xd7a3],
1232
+ [0xf900, 0xfaff],
1233
+ [0xfe10, 0xfe19],
1234
+ [0xfe30, 0xfe52],
1235
+ [0xfe54, 0xfe66],
1236
+ [0xfe68, 0xfe6b],
1237
+ [0xff01, 0xff60],
1238
+ [0xffe0, 0xffe6],
1239
+ [0x16fe0, 0x16fe4],
1240
+ [0x16ff0, 0x16ff6],
1241
+ [0x17000, 0x18cda],
1242
+ [0x18cff, 0x18d20],
1243
+ [0x18d80, 0x18df2],
1244
+ [0x18e00, 0x19191],
1245
+ [0x191a0, 0x191d2],
1246
+ [0x1aff0, 0x1aff3],
1247
+ [0x1aff5, 0x1affb],
1248
+ [0x1affd, 0x1affe],
1249
+ [0x1b000, 0x1b128],
1250
+ [0x1b132, 0x1b132],
1251
+ [0x1b150, 0x1b152],
1252
+ [0x1b155, 0x1b155],
1253
+ [0x1b164, 0x1b168],
1254
+ [0x1b170, 0x1b2fb],
1255
+ [0x1d300, 0x1d356],
1256
+ [0x1d360, 0x1d376],
1257
+ [0x1f200, 0x1f200],
1258
+ [0x1f210, 0x1f219],
1259
+ [0x1f21b, 0x1f22e],
1260
+ [0x1f230, 0x1f231],
1261
+ [0x1f23b, 0x1f23b],
1262
+ [0x1f240, 0x1f248],
1263
+ [0x1f260, 0x1f265],
1264
+ [0x20000, 0x2fffd],
1265
+ [0x30000, 0x3fffd],
1266
+ ]
1267
+
1268
+ /** One code point the terminal draws no cell for: control characters, the
1269
+ * zero-width joiners/marks, combining marks and variation selectors. */
1270
+ function isZeroWidthCodePoint(code: number, glyph: string): boolean {
1271
+ if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true
1272
+ if (code >= 0x200b && code <= 0x200f) return true
1273
+ if (code === 0xfeff) return true
1274
+ if (code >= 0x300 && code <= 0x36f) return true
1275
+ if (code >= 0x1ab0 && code <= 0x1aff) return true
1276
+ if (code >= 0x1dc0 && code <= 0x1dff) return true
1277
+ if (code >= 0x20d0 && code <= 0x20ff) return true
1278
+ if (code >= 0xfe00 && code <= 0xfe0f) return true
1279
+ if (code >= 0xfe20 && code <= 0xfe2f) return true
1280
+ if (code >= 0xe0100 && code <= 0xe01ef) return true
1281
+ if (code >= 0xd800 && code <= 0xdfff) return true // a lone surrogate
1282
+ return IGNORABLE_GLYPH.test(glyph)
1283
+ }
1284
+
1285
+ function isWideCodePoint(code: number): boolean {
1286
+ for (const [low, high] of CELL_WIDE_RANGES) {
1287
+ if (code < low) return false
1288
+ if (code <= high) return true
1289
+ }
1290
+ return false
1291
+ }
1292
+
1293
+ /** Cells one grapheme occupies. */
1294
+ function graphemeWidth(segment: string): number {
1295
+ if (EMOJI_GLYPH.test(segment)) return 2
1296
+ // A lone VS16 carries no width; after a base it asks for emoji presentation.
1297
+ if (segment.length > 1 && segment.includes(EMOJI_PRESENTATION_SELECTOR)) return 2
1298
+ let width = 0
1299
+ for (const glyph of segment) {
1300
+ const code = glyph.codePointAt(0) ?? 0
1301
+ if (isZeroWidthCodePoint(code, glyph)) continue
1302
+ width += isWideCodePoint(code) ? 2 : 1
1303
+ }
1304
+ return width
1305
+ }
1306
+
1307
+ /** Terminal cells `value` occupies — the unit every column in this plugin is
1308
+ * measured in. Mirrors the host (that is how `@opentui/core` sizes a text
1309
+ * run): emoji count as two cells, East Asian Wide/Fullwidth as two, East
1310
+ * Asian Ambiguous as one, combining marks and variation selectors as none.
1311
+ * Pure. */
1312
+ export function cellWidth(value: string): number {
1313
+ let width = 0
1314
+ for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment)
1315
+ return width
1316
+ }
1317
+
1318
+ /** Clamp a free-form label to `max` terminal cells without wrapping. The width
1319
+ * is measured in display cells, never in UTF-16 code units: a CJK or emoji
1320
+ * label used to overflow the column it was cut for (`計画の移行` is 5 code
1321
+ * units but 10 cells, `🚀` is 2 units and 2 cells). Pure. */
1322
+ export function truncateLabel(value: string, max = 28): string {
1323
+ const text = value.trim()
1324
+ const budget = Math.max(1, Math.floor(numberOrNull(max) ?? 1))
1325
+ if (cellWidth(text) <= budget) return text
1326
+ const ellipsis = '\u2026'
1327
+ const room = budget - cellWidth(ellipsis)
1328
+ let cut = ''
1329
+ let used = 0
1330
+ for (const { segment } of GRAPHEMES.segment(text)) {
1331
+ const width = cellWidth(segment)
1332
+ if (used + width > room) break
1333
+ cut += segment
1334
+ used += width
1335
+ }
1336
+ return `${cut.replace(/\s+$/, '')}${ellipsis}`
1337
+ }
1338
+
1339
+ /** Right-pad `value` with spaces to exactly `cells` display columns (a wider
1340
+ * value is truncated first). `padEnd` counts code units, so it under-pads a
1341
+ * CJK/emoji cell and the next column drifts. Pure. */
1342
+ export function padCell(value: string, cells: number): string {
1343
+ const width = Math.max(0, Math.floor(numberOrNull(cells) ?? 0))
1344
+ if (width === 0) return ''
1345
+ const text = truncateLabel(value, width)
1346
+ return `${text}${' '.repeat(Math.max(0, width - cellWidth(text)))}`
1347
+ }
1348
+
1349
+ /** Columns the fixed header may use before it would wrap the sidebar. */
1350
+ export const HEADER_MAX_WIDTH = 34
1351
+
1352
+ /** Preset row of the fixed header: `▸ <preset> · <provider>`. The provider is
1353
+ * cut first when the row overflows, so the preset name is never the casualty;
1354
+ * a missing provider leaves the preset alone (no `unknown` placeholder). */
1355
+ export function presetHeaderLine(presetName: string, providerID: string | null): string {
1356
+ const name = presetName.trim() === '' ? 'default' : presetName.trim()
1357
+ const base = `${PRESET_MARKER} ${name}`
1358
+ const provider = providerID === null ? '' : providerID.trim()
1359
+ if (provider === '') return truncateLabel(base, HEADER_MAX_WIDTH)
1360
+ const room = HEADER_MAX_WIDTH - `${base} · `.length
1361
+ if (room < 2) return truncateLabel(base, HEADER_MAX_WIDTH)
1362
+ return `${base} · ${truncateLabel(provider, room)}`
1363
+ }
1364
+
1365
+ /* ─── Dispatch kind (why the child exists) ────────────────
1366
+ * The host's own row answers *who* runs and *how much* it cost, never *why* the
1367
+ * child exists. Only two evidence sources are allowed here, and neither is
1368
+ * invented: the `description` the parent typed for the `subagent` call (a
1369
+ * bracketed prefix such as `[review]`), and — when the prefix is absent — the
1370
+ * agent that owns the child (athena plans, themis reviews, talos hotfixes,
1371
+ * apollo scouts). `council` is the single exception: a round of specialists is
1372
+ * a declared intent, not an agent identity, so it is *never* inferred from the
1373
+ * agent. Every classification carries the `origin` of its evidence, and a child
1374
+ * that cannot be correlated to a call degrades to `{ null, 'unavailable' }`
1375
+ * instead of a guess. Pure. */
1376
+
1377
+ export type DispatchKind = 'coun' | 'plan' | 'revw' | 'hot' | 'disc' | 'oth'
1378
+ export type DispatchKindOrigin = 'prefix' | 'agent' | 'unavailable'
1379
+
1380
+ /** One classification plus the evidence that produced it. */
1381
+ export type DispatchKindLabel = { kind: DispatchKind | null; origin: DispatchKindOrigin }
1382
+
1383
+ /** Bracketed description prefix → short label (`[council]` → `coun`). */
1384
+ const DISPATCH_PREFIX_KINDS: ReadonlyArray<readonly [string, DispatchKind]> = [
1385
+ ['council', 'coun'],
1386
+ ['discovery', 'disc'],
1387
+ ['hotfix', 'hot'],
1388
+ ['plan', 'plan'],
1389
+ ['review', 'revw'],
1390
+ ]
1391
+
1392
+ /** Agent → kind, consulted only when the description declares no prefix.
1393
+ * `council` is deliberately absent — see the section comment. */
1394
+ const DISPATCH_AGENT_KINDS: Readonly<Record<string, DispatchKind>> = {
1395
+ apollo: 'disc',
1396
+ athena: 'plan',
1397
+ talos: 'hot',
1398
+ themis: 'revw',
1399
+ }
1400
+
1401
+ /** Kind declared by a leading `[prefix]` on the description: case-insensitive
1402
+ * and tolerant of spaces inside the brackets. Null when none is declared. */
1403
+ export function dispatchKindFromPrefix(description: unknown): DispatchKind | null {
1404
+ if (typeof description !== 'string') return null
1405
+ const match = /^\s*\[\s*([a-z]+)\s*\]/i.exec(description)
1406
+ if (match === null) return null
1407
+ const token = (match[1] ?? '').toLowerCase()
1408
+ for (const [word, kind] of DISPATCH_PREFIX_KINDS) {
1409
+ if (word === token) return kind
1410
+ }
1411
+ return null
1412
+ }
1413
+
1414
+ /** Kind implied by the child's agent, null for an agent that implies none. */
1415
+ export function dispatchKindFromAgent(agent: unknown): DispatchKind | null {
1416
+ if (typeof agent !== 'string') return null
1417
+ return DISPATCH_AGENT_KINDS[agent.trim().toLowerCase()] ?? null
1418
+ }
1419
+
1420
+ /** Classify one dispatch. The description prefix always wins over the agent;
1421
+ * otherwise the agent decides, and anything else is `oth` (a real dispatch we
1422
+ * simply cannot name). A missing call is the only `unavailable` outcome. Pure. */
1423
+ export function classifyDispatchKind(
1424
+ call: { description?: unknown; agent?: unknown } | null | undefined,
1425
+ ): DispatchKindLabel {
1426
+ if (call === null || call === undefined) return { kind: null, origin: 'unavailable' }
1427
+ const fromPrefix = dispatchKindFromPrefix(call.description)
1428
+ if (fromPrefix !== null) return { kind: fromPrefix, origin: 'prefix' }
1429
+ return { kind: dispatchKindFromAgent(call.agent) ?? 'oth', origin: 'agent' }
1430
+ }
1431
+
1432
+ /** A `subagent` tool call the parent made, as its own transcript records it. */
1433
+ export type SubagentCall = {
1434
+ /** Child session id the call created — the correlation key. */
1435
+ sessionID: string
1436
+ agent: string
1437
+ description: string
1438
+ background: boolean
1439
+ }
1440
+
1441
+ /** Host tool that spawns a child (V2 name; it is not `task`). */
1442
+ const SUBAGENT_TOOL = 'subagent'
1443
+ /** The tool result also names its child: `<subagent sessionID="ses_…" …>`. */
1444
+ const SUBAGENT_SESSION_PATTERN = /sessionID="([^"]+)"/
1445
+
1446
+ /** Text of a tool `content` payload, joined; tolerant of the string form. */
1447
+ function toolContentText(content: unknown): string {
1448
+ if (typeof content === 'string') return content
1449
+ if (!Array.isArray(content)) return ''
1450
+ const chunks: string[] = []
1451
+ for (const part of content) {
1452
+ const text = (part as { text?: unknown } | null | undefined)?.text
1453
+ if (typeof text === 'string') chunks.push(text)
1454
+ }
1455
+ return chunks.join('\n')
1456
+ }
1457
+
1458
+ /** Child session id of one `subagent` call: the exact `metadata.sessionID`
1459
+ * first, then an `output`/`result` id, then the `<subagent sessionID="…">` tag
1460
+ * in the result text. Null when the call has not produced a child yet. */
1461
+ function subagentSessionID(state: any): string | null {
1462
+ const direct = [state?.metadata?.sessionID, state?.output?.sessionID, state?.result?.sessionID]
1463
+ for (const candidate of direct) {
1464
+ if (typeof candidate === 'string' && candidate !== '') return candidate
1465
+ }
1466
+ const match = SUBAGENT_SESSION_PATTERN.exec(toolContentText(state?.content))
1467
+ return match?.[1] ?? null
1468
+ }
1469
+
1470
+ /** Correlate the parent transcript's `subagent` calls with the children they
1471
+ * spawned: child session id → `{ agent, description, background }`. One pass
1472
+ * over the list the sidebar already holds — no request, no `message.sync` on
1473
+ * the child. `streaming`/`pending` states carry their input as *partial JSON
1474
+ * text*, so they are skipped rather than parsed. Fail-open: a malformed part
1475
+ * contributes nothing. Pure. */
1476
+ export function collectSubagentCalls(
1477
+ messages: readonly any[] | null | undefined,
1478
+ ): Map<string, SubagentCall> {
1479
+ const calls = new Map<string, SubagentCall>()
1480
+ if (!Array.isArray(messages)) return calls
1481
+ for (const message of messages) {
1482
+ if (message?.type !== 'assistant' || !Array.isArray(message.content)) continue
1483
+ for (const part of message.content) {
1484
+ if (part?.type !== 'tool' || part?.name !== SUBAGENT_TOOL) continue
1485
+ const state = part.state
1486
+ if (state === null || typeof state !== 'object') continue
1487
+ if (state.status === 'streaming' || state.status === 'pending') continue
1488
+ const sessionID = subagentSessionID(state)
1489
+ if (!isValidSessionID(sessionID)) continue
1490
+ const input =
1491
+ state.input !== null && typeof state.input === 'object' ? (state.input as any) : {}
1492
+ const agent = typeof input.agent === 'string' ? input.agent : ''
1493
+ const description = typeof input.description === 'string' ? input.description : ''
1494
+ calls.set(sessionID, {
1495
+ sessionID,
1496
+ agent,
1497
+ description,
1498
+ background: input.background === true,
1499
+ })
1500
+ }
1501
+ }
1502
+ return calls
1503
+ }
1504
+
1505
+ /* ─── Delegation helpers ─────────────────────────────────── */
1506
+
1507
+ export type DelegationState = 'running' | 'completed' | 'failed' | 'interrupted'
1508
+ export type DelegationTone = 'warning' | 'error' | 'success'
1509
+
1510
+ /** Grace window for a child that has not started yet. V2's `session.status()`
1511
+ * returns `idle` both for "created but not started" and for "finished", so an
1512
+ * idle/unknown/absent child whose own last activity (`time.updated`, falling
1513
+ * back to `time.created`) is this recent still reads as running — otherwise a
1514
+ * just-spawned child renders a premature ✓. Trade-off (V1 parity: it had the
1515
+ * same window for its absent statuses): a child that finished within the window
1516
+ * and reports no `outcome` reads as running until the window closes, at which
1517
+ * point it turns terminal and its completion toast fires. A child that reports
1518
+ * a terminal `outcome` is never held back by the window. */
1519
+ export const DELEGATION_CHILD_STATUS_GRACE_MS = 60 * 1000
1520
+
1521
+ /** One delegated child job as the sidebar renders it. */
1522
+ export type DelegationView = {
1523
+ /** Child session id — also the click-through target. */
1524
+ id: string
1525
+ /** Alias shown on the row: the child title, else agent, else short id. */
1526
+ label: string
1527
+ state: DelegationState
1528
+ /** Epoch ms of the child's `time.created`. */
1529
+ startedAt: number | null
1530
+ /** Epoch ms of the child's `time.updated`. */
1531
+ updatedAt: number | null
1532
+ /** Child agent id, when the host published one. */
1533
+ agent: string | null
1534
+ /** Resolved child model, shortened to its bare id. */
1535
+ model: string | null
1536
+ /** Real `SessionInfo.cost` for the child, null when the host published none. */
1537
+ cost: number | null
1538
+ /** Why the child exists — see `classifyDispatchKind`. Null when no `subagent`
1539
+ * call in the parent transcript could be correlated with this child. */
1540
+ kind: DispatchKind | null
1541
+ /** Which evidence produced `kind`. */
1542
+ kindOrigin: DispatchKindOrigin
1543
+ /** The parent asked for this child to run in the background. */
1544
+ background: boolean
1545
+ }
1546
+
1547
+ /** Map the host's live session status to a display state. V2 exposes only
1548
+ * `"idle" | "running"` through the TUI context (the client union adds `retry`
1549
+ * and `busy`); `error`/`failed` are handled defensively for host drift.
1550
+ * `idle`, `retry` and unknown/absent statuses are terminal only once the
1551
+ * child's own activity is older than the grace window — within it the child
1552
+ * reads as running (see `DELEGATION_CHILD_STATUS_GRACE_MS`). An interruption is
1553
+ * not part of this union: it arrives as a terminal `outcome`. Pure. */
1554
+ export function delegationStateFromStatus(
1555
+ status: string | undefined,
1556
+ time?: { created?: number; updated?: number },
1557
+ now = Date.now(),
1558
+ graceMs = DELEGATION_CHILD_STATUS_GRACE_MS,
1559
+ ): DelegationState {
1560
+ switch (status) {
1561
+ case 'running':
1562
+ case 'busy':
1563
+ return 'running'
1564
+ case 'error':
1565
+ case 'failed':
1566
+ return 'failed'
1567
+ default: {
1568
+ const lastActivity = Math.max(time?.updated ?? 0, time?.created ?? 0)
1569
+ if (lastActivity > 0 && now - lastActivity < graceMs) return 'running'
1570
+ return 'completed'
1571
+ }
1572
+ }
1573
+ }
1574
+
1575
+ /** Map a V2 child `outcome` to a display state. `interrupted` (user abort,
1576
+ * shutdown, superseded, inactivity) is distinct from both success and failure,
1577
+ * so an aborted child never renders the ✓ of a completed one. Returns null for
1578
+ * an absent/unrecognised outcome so the live status decides. Pure. */
1579
+ export function delegationStateFromOutcome(outcome: unknown): DelegationState | null {
1580
+ switch (outcome) {
1581
+ case 'succeeded':
1582
+ return 'completed'
1583
+ case 'failed':
1584
+ return 'failed'
1585
+ case 'interrupted':
1586
+ return 'interrupted'
1587
+ default:
1588
+ return null
1589
+ }
1590
+ }
1591
+
1592
+ /** Build a delegation row from a child session + its live status, plus the
1593
+ * `subagent` call that spawned it (when the parent transcript had one). A
1594
+ * terminal `outcome` wins when present (the only V2 primitive that surfaces a
1595
+ * delegation failure/interruption once the status is back to idle); otherwise
1596
+ * the live status decides, with the absent/idle grace window applied. The
1597
+ * `call` only ever *adds* the purpose and the background flag — an absent one
1598
+ * leaves the row fully renderable. Pure. */
1599
+ export function toDelegationView(
1600
+ child: any,
1601
+ status: string | undefined,
1602
+ now = Date.now(),
1603
+ call?: SubagentCall | null,
1604
+ ): DelegationView {
1605
+ const id = typeof child?.id === 'string' ? child.id : ''
1606
+ const title = typeof child?.title === 'string' && child.title !== '' ? child.title : ''
1607
+ const agent = typeof child?.agent === 'string' && child.agent !== '' ? child.agent : ''
1608
+ const label = title !== '' ? title : agent !== '' ? agent : id.slice(0, 8)
1609
+ const state: DelegationState =
1610
+ delegationStateFromOutcome(child?.outcome) ??
1611
+ delegationStateFromStatus(status, child?.time, now)
1612
+ const classification = classifyDispatchKind(call)
1613
+ return {
1614
+ id,
1615
+ label,
1616
+ state,
1617
+ startedAt: numberOrNull(child?.time?.created),
1618
+ updatedAt: numberOrNull(child?.time?.updated),
1619
+ agent: agent !== '' ? agent : null,
1620
+ model: shortModelID(child?.model),
1621
+ cost: numberOrNull(child?.cost),
1622
+ kind: classification.kind,
1623
+ kindOrigin: classification.origin,
1624
+ background: call?.background === true,
1625
+ }
1626
+ }
1627
+
1628
+ const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const
1629
+
1630
+ /** Spinner glyph for a frame counter (incremented every ~80ms while any job is
1631
+ * running). Pure. */
1632
+ export function spinnerFrame(frame: number): string {
1633
+ const index = Math.abs(Math.floor(frame)) % SPINNER_FRAMES.length
1634
+ return SPINNER_FRAMES[index] ?? SPINNER_FRAMES[0]
1635
+ }
1636
+
1637
+ /** Shared order: live work first, then most recent activity. One comparator for
1638
+ * every consumer of the dispatch tree (sidebar block and panel list), so the
1639
+ * two views can never disagree about which child comes first. Pure. */
1640
+ function compareDelegations(a: DelegationView, b: DelegationView): number {
1641
+ const activeA = a.state === 'running' ? 1 : 0
1642
+ const activeB = b.state === 'running' ? 1 : 0
1643
+ if (activeA !== activeB) return activeB - activeA
1644
+ return (b.updatedAt ?? 0) - (a.updatedAt ?? 0)
1645
+ }
1646
+
1647
+ /* ─── Dispatch collector (shared) ─────────────────────────
1648
+ * The single source of the delegation tree: the sidebar block and the
1649
+ * `pantheon.dispatch` panel both render `collectDispatch` output, so a child
1650
+ * can never appear twice under two different semantics — the duplication bug
1651
+ * the two-collector design had. It reads only state the host already cached:
1652
+ * `session.family` for the id set, `session.get` per child, `session.status`
1653
+ * for liveness, and the parent's own `message.list` for the `subagent` calls
1654
+ * that explain each child. Never a child `message.list`, never `message.sync`,
1655
+ * never an HTTP call. */
1656
+
1657
+ /** Token totals published on `SessionInfo.tokens`, one entry per counter. */
1658
+ export type DispatchTokens = {
1659
+ input: number | null
1660
+ output: number | null
1661
+ reasoning: number | null
1662
+ cacheRead: number | null
1663
+ cacheWrite: number | null
1664
+ }
1665
+
1666
+ /** One child of the dispatch tree: the delegation row plus the fields only the
1667
+ * panel's detail view needs (`SessionInfo.title`/`parentID`/`tokens` and the
1668
+ * spawning call's description). */
1669
+ export type DispatchEntry = {
1670
+ view: DelegationView
1671
+ title: string | null
1672
+ description: string | null
1673
+ parentID: string | null
1674
+ tokens: DispatchTokens | null
1675
+ }
1676
+
1677
+ /** Optional inputs of `collectDispatch`: a fixed clock (tests/render ticks) and
1678
+ * an already-computed `agent` map, so a caller that walked the parent
1679
+ * transcript anyway never pays for a second walk. */
1680
+ export type CollectDispatchOptions = {
1681
+ now?: number
1682
+ calls?: Map<string, SubagentCall>
1683
+ }
1684
+
1685
+ /** `message.list` of one session, degrades to an empty list. The host's list is
1686
+ * a cached directory read, not a request. */
1687
+ function readSessionMessages(context: any, sessionID: string): any[] {
1688
+ try {
1689
+ const result = context?.data?.session?.message?.list?.(sessionID)
1690
+ return Array.isArray(result) ? result : []
1691
+ } catch {
1692
+ return []
1693
+ }
1694
+ }
1695
+
1696
+ /** Token counters of a child, null when the host published none of them. Pure. */
1697
+ export function dispatchTokens(tokens: unknown): DispatchTokens | null {
1698
+ if (tokens === null || typeof tokens !== 'object') return null
1699
+ const source = tokens as Record<string, unknown>
1700
+ const cache =
1701
+ source.cache !== null && typeof source.cache === 'object'
1702
+ ? (source.cache as Record<string, unknown>)
1703
+ : {}
1704
+ const totals: DispatchTokens = {
1705
+ input: numberOrNull(source.input),
1706
+ output: numberOrNull(source.output),
1707
+ reasoning: numberOrNull(source.reasoning),
1708
+ cacheRead: numberOrNull(cache.read),
1709
+ cacheWrite: numberOrNull(cache.write),
1710
+ }
1711
+ const values = [
1712
+ totals.input,
1713
+ totals.output,
1714
+ totals.reasoning,
1715
+ totals.cacheRead,
1716
+ totals.cacheWrite,
1717
+ ]
1718
+ return values.every((value) => value === null) ? null : totals
1719
+ }
1720
+
1721
+ /** One child `SessionInfo` + its live status → `DispatchEntry`. The call only
1722
+ * ever adds the kind and the description; an absent one leaves the entry fully
1723
+ * renderable. Pure. */
1724
+ export function toDispatchEntry(
1725
+ child: any,
1726
+ status: string | undefined,
1727
+ now = Date.now(),
1728
+ call?: SubagentCall | null,
1729
+ ): DispatchEntry {
1730
+ const title = typeof child?.title === 'string' && child.title !== '' ? child.title : null
1731
+ const parentID =
1732
+ typeof child?.parentID === 'string' && child.parentID !== '' ? child.parentID : null
1733
+ const description =
1734
+ typeof call?.description === 'string' && call.description !== '' ? call.description : null
1735
+ return {
1736
+ view: toDelegationView(child, status, now, call),
1737
+ title,
1738
+ description,
1739
+ parentID,
1740
+ tokens: dispatchTokens(child?.tokens),
1741
+ }
1742
+ }
1743
+
1744
+ /** The delegation tree of `sessionID` — every child `session.family` returns,
1745
+ * root excluded, each enriched from `session.get`/`session.status` and the
1746
+ * parent's `subagent` calls. Empty when the family API is unavailable or the
1747
+ * session id is not a real handle (never falls back to the root). Ordered by
1748
+ * the shared `compareDelegations`, so callers render the same list in the same
1749
+ * order. A family that repeats an id yields one row per child: the id is
1750
+ * deduplicated before the walk, so a duplicate can never double a row or its
1751
+ * cost. */
1752
+ export function collectDispatch(
1753
+ context: any,
1754
+ sessionID: string | undefined,
1755
+ options: CollectDispatchOptions = {},
1756
+ ): DispatchEntry[] {
1757
+ if (!isValidSessionID(sessionID)) return []
1758
+ let family: string[] = []
1759
+ try {
1760
+ const result = context?.data?.session?.family?.(sessionID)
1761
+ if (Array.isArray(result)) family = result
1762
+ } catch {
1763
+ return []
1764
+ }
1765
+ const now = numberOrNull(options.now) ?? Date.now()
1766
+ const calls = options.calls ?? collectSubagentCalls(readSessionMessages(context, sessionID))
1767
+ const entries: DispatchEntry[] = []
1768
+ // A host may publish the same child more than once (`family()` is not
1769
+ // guaranteed unique). Deduplicate by id, preserving the host's order, so a
1770
+ // repeated id never renders two rows nor counts its cost twice.
1771
+ const seen = new Set<string>()
1772
+ for (const childID of family) {
1773
+ if (childID === sessionID || !isValidSessionID(childID)) continue
1774
+ if (seen.has(childID)) continue
1775
+ seen.add(childID)
1776
+ let child: any
1777
+ try {
1778
+ child = context.data.session.get(childID)
1779
+ } catch {
1780
+ continue
1781
+ }
1782
+ if (!child) continue
1783
+ entries.push(
1784
+ toDispatchEntry(child, sessionStatusOf(context, childID), now, calls.get(childID) ?? null),
1785
+ )
1786
+ }
1787
+ return entries.sort((a, b) => compareDelegations(a.view, b.view))
1788
+ }
1789
+
1790
+ /* ─── Block layout ───────────────────────────────────────── */
1791
+
1792
+ /** Sidebar blocks in render order. Spacing is derived from this list instead of
1793
+ * from the view, so a hidden block can never leave an empty gap behind. */
1794
+ export type SidebarBlockKey = 'context' | 'git' | 'todo' | 'dispatch'
1795
+
1796
+ /** One rendered block: its key, and whether a blank line precedes it. */
1797
+ export type SidebarBlock = { key: SidebarBlockKey; spacer: boolean }
1798
+
1799
+ /** Header glyph per block — one codepoint each, rendered muted before the bold
1800
+ * label. The fixed header (version/preset/session) takes none.
1801
+ * Measured as one terminal cell by the host (`@opentui/core` counts
1802
+ * `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), ▾ U+25BE (N),
1803
+ * ◈ U+25C8 (A). `☑` U+2611 was rejected for the Todo header because it matches
1804
+ * `emoji-regex` and would occupy two cells; `⌁` U+2301 (the old Dispatch glyph)
1805
+ * was replaced by the host's own Notice glyph. */
1806
+ export const BLOCK_ICONS: Record<SidebarBlockKey, string> = {
1807
+ context: '\u25A4',
1808
+ git: '\u25C6',
1809
+ todo: '\u25BE',
1810
+ dispatch: '\u25C8',
1811
+ }
1812
+
1813
+ /** Tag every block that has content with its spacer: never before the first
1814
+ * (the view puts a single blank line after the fixed header instead), one
1815
+ * blank line before every later block. A repeated key collapses instead of
1816
+ * stacking spacers, so an absent optional block can never leave a double gap.
1817
+ * Pure. */
1818
+ export function withBlockSpacers(keys: readonly SidebarBlockKey[]): SidebarBlock[] {
1819
+ const seen = new Set<SidebarBlockKey>()
1820
+ const blocks: SidebarBlock[] = []
1821
+ for (const key of keys) {
1822
+ if (seen.has(key)) continue
1823
+ seen.add(key)
1824
+ blocks.push({ key, spacer: blocks.length > 0 })
1825
+ }
1826
+ return blocks
1827
+ }
1828
+
1829
+ /* ─── Dispatch block ──────────────────────────────────────
1830
+ * One block for the whole child set, in two sections: the live jobs one row
1831
+ * each, then the finished ones aggregated per agent. A per-session list cannot
1832
+ * survive a wide fan-out (71 children would either scroll the sidebar or hide
1833
+ * most of them behind `… +66`), while a per-agent rollup keeps the count, the
1834
+ * spend and the failures readable in a handful of rows. */
1835
+
1836
+ /** Live children rendered one row each; the rest collapse into `… +N rodando`. */
1837
+ export const DISPATCH_RUNNING_CEILING = 3
1838
+ /** Agent rollup rows rendered before the `… +K $<soma>` line. */
1839
+ export const DISPATCH_AGENT_CEILING = 3
1840
+ /** Hard cap on the block's rendered rows, header included. The sidebar is
1841
+ * short; live work is served first, then the finished rollup. */
1842
+ export const DISPATCH_MAX_LINES = 8
1843
+ /** Marker of the aggregated "finished" section. */
1844
+ export const DISPATCH_DONE_MARKER = '\u2713'
1845
+ /** Column width of the agent (or of its title/id fallback). */
1846
+ export const DISPATCH_AGENT_WIDTH = 12
1847
+ /** Narrowest agent column a row may fall back to before the cost is kept whole
1848
+ * and the label truncates further. */
1849
+ export const DISPATCH_MIN_AGENT_WIDTH = 8
1850
+ /** Column width of the short model id — the model is dropped before the agent
1851
+ * or the cost so a row always fits. */
1852
+ export const DISPATCH_MODEL_WIDTH = 7
1853
+ /** Column width of the per-dispatch cost (`$0.04`; a sub-cent cost widens it). */
1854
+ export const DISPATCH_COST_WIDTH = 5
1855
+ /** Column width of the duration (`12.7s` / `1m04s` / `820ms`). */
1856
+ export const DISPATCH_DURATION_WIDTH = 5
1857
+ /** Column width of the `×<count>` cell of an agent rollup row. */
1858
+ export const DISPATCH_COUNT_WIDTH = 3
1859
+ /** Column width of an agent rollup cost (`$0.0051` still fits). */
1860
+ export const DISPATCH_GROUP_COST_WIDTH = 7
1861
+ /** Hard column budget for one row — a Dispatch line never wraps:
1862
+ * marker(2) + agent(12) + model(7) + cost(5) + duration(5) + 3 spaces = 34.
1863
+ * The kind suffix (`·disc`, `·disc~`) is wider evidence than the model, so a
1864
+ * classified row spends the model's columns first: marker(2) + agent(≤12) +
1865
+ * suffix(≤6) + cost(5) + duration(5) + 2 spaces ≤ 32, still inside 34. */
1866
+ export const DISPATCH_MAX_WIDTH = 34
1867
+
1868
+ /** Middle dot used between a label and its kind (`apollo·disc`). */
1869
+ const DISPATCH_KIND_SEPARATOR = '\u00B7'
1870
+ /** Background marker: the parent asked the child to run in the background. */
1871
+ const DISPATCH_BACKGROUND_MARKER = '~'
1872
+
1873
+ /** Kind suffix glued to a row's label: `·disc`, `·disc~` for a background run,
1874
+ * and empty when the child could not be classified (the row then reads exactly
1875
+ * as before). Pure. */
1876
+ export function dispatchKindSuffix(
1877
+ kind: DispatchKind | null | undefined,
1878
+ background?: boolean,
1879
+ ): string {
1880
+ if (kind === null || kind === undefined) return ''
1881
+ const text = `${DISPATCH_KIND_SEPARATOR}${kind}`
1882
+ return background === true ? `${text}${DISPATCH_BACKGROUND_MARKER}` : text
1883
+ }
1884
+
1885
+ /** Header summary: `2 rodando · $3.49`. The live count is omitted when nothing
1886
+ * runs, and the total spend is always printed (the header only renders while
1887
+ * the tree has children, so `$0.00` is a real answer). Pure. */
1888
+ export function dispatchHeaderSummary(
1889
+ running: number | null | undefined,
1890
+ cost: number | null | undefined,
1891
+ ): string | null {
1892
+ const parts: string[] = []
1893
+ const live = numberOrNull(running) ?? 0
1894
+ if (live > 0) parts.push(`${Math.round(live)} rodando`)
1895
+ const formatted = formatSpendUSD(numberOrNull(cost) ?? 0)
1896
+ if (formatted !== null) parts.push(formatted)
1897
+ return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR)
1898
+ }
1899
+
1900
+ /** Compact duration without an internal space: `820` → `820ms`, `12_400` →
1901
+ * `12.4s`, `64_000` → `1m04s`, `3_780_000` → `1h03m`, `172_800_000` → `2d`.
1902
+ * An absent or negative value renders an em dash, never `NaN`s. Pure. */
1903
+ export function formatDispatchDuration(ms: number | null | undefined): string {
1904
+ const value = numberOrNull(ms)
1905
+ if (value === null || value < 0) return '\u2014'
1906
+ if (value < 1_000) return `${Math.round(value)}ms`
1907
+ const seconds = value / 1000
1908
+ if (seconds < 59.95) return `${seconds.toFixed(1)}s`
1909
+ const total = Math.round(seconds)
1910
+ const hours = Math.floor(total / 3_600)
1911
+ const minutes = Math.floor((total % 3_600) / 60)
1912
+ if (hours >= 24) return `${Math.floor(hours / 24)}d`
1913
+ if (hours > 0) return `${hours}h${String(minutes).padStart(2, '0')}m`
1914
+ return `${minutes}m${String(total % 60).padStart(2, '0')}s`
1915
+ }
1916
+
1917
+ /** Elapsed label for one row: a live child measures `now - created`, a finished
1918
+ * one freezes at `updated - created` (em dash when a timestamp is missing).
1919
+ * Pure. */
1920
+ export function dispatchElapsed(view: DelegationView, now = Date.now()): string {
1921
+ if (view.startedAt === null) return '\u2014'
1922
+ if (view.state === 'running') return formatDispatchDuration(now - view.startedAt)
1923
+ if (view.updatedAt === null) return '\u2014'
1924
+ return formatDispatchDuration(view.updatedAt - view.startedAt)
1925
+ }
1926
+
1927
+ /** Name column: the agent when the host published one, else the child title,
1928
+ * else the short id — never `undefined`. Truncated to the column width. Pure. */
1929
+ export function dispatchAgentText(
1930
+ view: Pick<DelegationView, 'agent' | 'label' | 'id'>,
1931
+ max = DISPATCH_AGENT_WIDTH,
1932
+ ): string {
1933
+ const agent = typeof view.agent === 'string' ? view.agent.trim() : ''
1934
+ const label = typeof view.label === 'string' ? view.label.trim() : ''
1935
+ const id = typeof view.id === 'string' ? view.id.trim() : ''
1936
+ const name = agent !== '' ? agent : label !== '' ? label : id
1937
+ return name === '' ? '\u2014' : truncateLabel(name, max)
1938
+ }
1939
+
1940
+ /** Model column, empty when the host published none. Pure. */
1941
+ export function dispatchModelText(view: Pick<DelegationView, 'model'>): string {
1942
+ const model = typeof view.model === 'string' ? view.model.trim() : ''
1943
+ return model === '' ? '' : truncateLabel(model, DISPATCH_MODEL_WIDTH)
1944
+ }
1945
+
1946
+ /** Cost column: the child's real `SessionInfo.cost` with two decimals (up to
1947
+ * four below a cent, so `$0.0031` never collapses to `$0.00`), `$0.00` for a
1948
+ * zero cost, and an em dash when the host published no numeric cost. Pure. */
1949
+ export function formatDispatchCost(cost: number | null | undefined): string {
1950
+ return formatUsageCost(cost) ?? '\u2014'
1951
+ }
1952
+
1953
+ /** Total spend of every child (live + finished), `0` when none published a
1954
+ * numeric cost. Pure. */
1955
+ export function dispatchTotalCost(views: readonly DelegationView[]): number {
1956
+ let total = 0
1957
+ for (const view of views ?? []) {
1958
+ const cost = numberOrNull(view?.cost)
1959
+ if (cost !== null && cost >= 0) total += cost
1960
+ }
1961
+ return total
1962
+ }
1963
+
1964
+ /** One live child: `⠸ <agent 12>·<kind> <custo> <duração>`, with the model as a
1965
+ * fourth column only when the row still fits and the child is unclassified —
1966
+ * the kind is the stronger evidence at this width, so it takes the model's
1967
+ * columns. The kind rides glued to the label (never a column of its own) and
1968
+ * disappears with the label's truncation; then the agent column shrinks (never
1969
+ * below `DISPATCH_MIN_AGENT_WIDTH`); the cost is always present — `$0.00` for a
1970
+ * zero cost, an em dash for a missing one. Pure. */
1971
+ export function runningChildRowText(
1972
+ view: DelegationView,
1973
+ now = Date.now(),
1974
+ frame = 0,
1975
+ max = DISPATCH_MAX_WIDTH,
1976
+ ): string {
1977
+ const marker = `${spinnerFrame(frame)} `
1978
+ const duration = dispatchElapsed(view, now).padStart(DISPATCH_DURATION_WIDTH)
1979
+ const cost = formatDispatchCost(view.cost).padStart(DISPATCH_COST_WIDTH)
1980
+ const model = dispatchModelText(view)
1981
+ const suffix = dispatchKindSuffix(view.kind, view.background)
1982
+ const limit = Math.max(1, max)
1983
+ const row = (agentWidth: number, withModel: boolean, withSuffix = true): string => {
1984
+ const kind = withSuffix ? suffix : ''
1985
+ const name = dispatchAgentText(view, agentWidth)
1986
+ // The kind rides glued to the label and never becomes a column of its own:
1987
+ // an unclassified row keeps the fixed 12-column label cell byte-for-byte.
1988
+ const cell = kind === '' ? name.padEnd(agentWidth) : `${name}${kind}`
1989
+ const tail = withModel
1990
+ ? `${model.padEnd(DISPATCH_MODEL_WIDTH)} ${cost} ${duration}`
1991
+ : `${cost} ${duration}`
1992
+ return `${marker}${cell} ${tail}`
1993
+ }
1994
+ if (model !== '' && suffix === '') {
1995
+ const withModel = row(DISPATCH_AGENT_WIDTH, true)
1996
+ if (withModel.length <= limit) return withModel
1997
+ }
1998
+ const full = row(DISPATCH_AGENT_WIDTH, false)
1999
+ if (full.length <= limit) return full
2000
+ for (let width = DISPATCH_AGENT_WIDTH - 1; width >= DISPATCH_MIN_AGENT_WIDTH; width -= 1) {
2001
+ const narrowed = row(width, false)
2002
+ if (narrowed.length <= limit) return narrowed
2003
+ }
2004
+ // The kind is evidence, the cost is the point: on a budget too narrow even for
2005
+ // the minimum agent column, the suffix yields before the row overflows.
2006
+ if (suffix !== '') return row(DISPATCH_MIN_AGENT_WIDTH, false, false)
2007
+ return row(DISPATCH_MIN_AGENT_WIDTH, false)
2008
+ }
2009
+
2010
+ /** Sessions and spend attributed to one agent in the finished section. `kind`
2011
+ * is only set when every finished session of the group agrees on it — a mixed
2012
+ * group carries no single purpose, so the row omits it rather than picking one.
2013
+ * `background` follows the same rule (all of them background). */
2014
+ export type ChildAgentUsage = {
2015
+ agent: string
2016
+ count: number
2017
+ cost: number
2018
+ kind: DispatchKind | null
2019
+ background: boolean
2020
+ }
2021
+
2022
+ /** Rollup of the finished children by agent: `×count` sessions and the summed
2023
+ * `SessionInfo.cost`. Failed and interrupted children are included (they are
2024
+ * finished); running ones are not. The group's kind survives only when the
2025
+ * whole group agrees, so an aggregate row never claims a purpose it cannot
2026
+ * prove. Ordered by cost, then count, then name. Pure. */
2027
+ export function collectChildAgentUsage(views: readonly DelegationView[]): ChildAgentUsage[] {
2028
+ type Accumulated = {
2029
+ agent: string
2030
+ count: number
2031
+ cost: number
2032
+ kinds: Set<DispatchKind | null>
2033
+ background: boolean
2034
+ }
2035
+ const totals = new Map<string, Accumulated>()
2036
+ for (const view of views ?? []) {
2037
+ if (!view || view.state === 'running') continue
2038
+ const agent = agentKey(view.agent)
2039
+ const current = totals.get(agent) ?? {
2040
+ agent,
2041
+ count: 0,
2042
+ cost: 0,
2043
+ kinds: new Set<DispatchKind | null>(),
2044
+ background: true,
2045
+ }
2046
+ current.count += 1
2047
+ current.kinds.add(view.kind ?? null)
2048
+ if (view.background !== true) current.background = false
2049
+ const cost = numberOrNull(view.cost)
2050
+ if (cost !== null && cost >= 0) current.cost += cost
2051
+ totals.set(agent, current)
2052
+ }
2053
+ return [...totals.values()]
2054
+ .map((entry) => {
2055
+ const shared = entry.kinds.size === 1 ? ([...entry.kinds][0] ?? null) : null
2056
+ return {
2057
+ agent: entry.agent,
2058
+ count: entry.count,
2059
+ cost: entry.cost,
2060
+ kind: shared,
2061
+ background: entry.background,
2062
+ }
2063
+ })
2064
+ .sort((a, b) => b.cost - a.cost || b.count - a.count || a.agent.localeCompare(b.agent))
2065
+ }
2066
+
2067
+ /** One agent rollup row: `<agent 12> ×<count 3>·<kind> <custo 7>`. The kind is
2068
+ * glued to the count (the row's only label) and omitted for a mixed group; the
2069
+ * agent column shrinks (never below the minimum) before the cost, which is
2070
+ * what the row is for. Pure. */
2071
+ export function childAgentRowText(row: ChildAgentUsage, max = DISPATCH_MAX_WIDTH): string {
2072
+ const suffix = dispatchKindSuffix(row?.kind, row?.background)
2073
+ const count = `\u00D7${String(Math.max(0, Math.round(numberOrNull(row?.count) ?? 0))).padStart(
2074
+ DISPATCH_COUNT_WIDTH,
2075
+ )}`
2076
+ const cost = formatDispatchCost(row?.cost).padStart(DISPATCH_GROUP_COST_WIDTH)
2077
+ const limit = Math.max(1, max)
2078
+ const text = (agentWidth: number, withSuffix = true): string => {
2079
+ const kind = withSuffix ? suffix : ''
2080
+ return `${truncateLabel(agentKey(row?.agent), agentWidth).padEnd(agentWidth)} ${count}${kind} ${cost}`
2081
+ }
2082
+ const full = text(DISPATCH_AGENT_WIDTH)
2083
+ if (full.length <= limit) return full
2084
+ for (let width = DISPATCH_AGENT_WIDTH - 1; width >= DISPATCH_MIN_AGENT_WIDTH; width -= 1) {
2085
+ const narrowed = text(width)
2086
+ if (narrowed.length <= limit) return narrowed
2087
+ }
2088
+ // Same rule as a live row: the kind yields before the row overflows.
2089
+ if (suffix !== '') return text(DISPATCH_MIN_AGENT_WIDTH, false)
2090
+ return text(DISPATCH_MIN_AGENT_WIDTH)
2091
+ }
2092
+
2093
+ /** The `… +K $<soma>` line for agents beyond the rollup cap. Null when every
2094
+ * agent fits. Pure. */
2095
+ export function hiddenChildAgentsText(hidden: number, hiddenCost: number): string | null {
2096
+ const count = numberOrNull(hidden) ?? 0
2097
+ if (count <= 0) return null
2098
+ const cost = formatSpendUSD(numberOrNull(hiddenCost) ?? 0)
2099
+ return cost === null ? `\u2026 +${Math.round(count)}` : `\u2026 +${Math.round(count)} ${cost}`
2100
+ }
2101
+
2102
+ /** Summary of the finished section: `✓ 70 · $3.40 · 9 agentes`. `· $<soma>` is
2103
+ * omitted when nothing was spent and `· 1 agente` when a single agent owns
2104
+ * every finished child; `✓ <total>` always prints. Null when nothing finished.
2105
+ * Pure. */
2106
+ export function completedSummaryText(
2107
+ completed: number | null | undefined,
2108
+ cost: number | null | undefined,
2109
+ agents: number | null | undefined,
2110
+ ): string | null {
2111
+ const total = numberOrNull(completed) ?? 0
2112
+ if (total <= 0) return null
2113
+ const parts = [`${DISPATCH_DONE_MARKER} ${Math.round(total)}`]
2114
+ const spend = numberOrNull(cost) ?? 0
2115
+ if (spend > 0) {
2116
+ const formatted = formatSpendUSD(spend)
2117
+ if (formatted !== null) parts.push(formatted)
2118
+ }
2119
+ const groups = Math.round(numberOrNull(agents) ?? 0)
2120
+ if (groups > 1) parts.push(`${groups} agentes`)
2121
+ return parts.join(SPEND_LINE_SEPARATOR)
2122
+ }
2123
+
2124
+ /** The `· <F> falhas` suffix of the finished summary, null when nothing failed.
2125
+ * Pure. */
2126
+ export function failedSuffixText(failures: number | null | undefined): string | null {
2127
+ const count = numberOrNull(failures) ?? 0
2128
+ if (count <= 0) return null
2129
+ const rounded = Math.round(count)
2130
+ return `${rounded} ${rounded === 1 ? 'falha' : 'falhas'}`
2131
+ }
2132
+
2133
+ /** One rendered live row: its text plus the session it navigates to. */
2134
+ export type DispatchRunningLine = { id: string; text: string }
2135
+
2136
+ /** Everything the `Dispatch` block renders, already joined and capped. */
2137
+ export type DispatchBlockView = {
2138
+ runningCount: number
2139
+ completedCount: number
2140
+ agentCount: number
2141
+ failures: number
2142
+ totalCost: number
2143
+ running: DispatchRunningLine[]
2144
+ runningHidden: number
2145
+ summary: string | null
2146
+ agents: ChildAgentUsage[]
2147
+ agentsHidden: number
2148
+ agentsHiddenCost: number
2149
+ }
2150
+
2151
+ /** Newest activity first, so the live rows that just moved lead the section.
2152
+ * Pure. */
2153
+ function lastActivity(view: DelegationView): number {
2154
+ return Math.max(numberOrNull(view?.updatedAt) ?? 0, numberOrNull(view?.startedAt) ?? 0)
2155
+ }
2156
+
2157
+ /** Build the whole block from the child set. Null when there is no child, so
2158
+ * the block (and its spacer) never renders empty. Live work is capped at
2159
+ * `DISPATCH_RUNNING_CEILING` and the finished rollup at
2160
+ * `DISPATCH_AGENT_CEILING`, with the rollup giving up rows first to keep the
2161
+ * block inside `DISPATCH_MAX_LINES`. Pure. */
2162
+ export function buildDispatchBlock(
2163
+ views: readonly DelegationView[],
2164
+ now = Date.now(),
2165
+ frame = 0,
2166
+ max = DISPATCH_MAX_WIDTH,
2167
+ ): DispatchBlockView | null {
2168
+ const list = Array.isArray(views)
2169
+ ? views.filter((view) => view && typeof view.id === 'string')
2170
+ : []
2171
+ if (list.length === 0) return null
2172
+
2173
+ const running = list
2174
+ .filter((view) => view.state === 'running')
2175
+ .sort((a, b) => lastActivity(b) - lastActivity(a))
2176
+ const finished = list.filter((view) => view.state !== 'running')
2177
+ const groups = collectChildAgentUsage(finished)
2178
+ const finishedCost = groups.reduce((sum, group) => sum + group.cost, 0)
2179
+ const failures = finished.filter((view) => view.state === 'failed').length
2180
+ const totalCost = dispatchTotalCost(list)
2181
+
2182
+ const runningSlots = Math.min(DISPATCH_RUNNING_CEILING, running.length)
2183
+ const runningHidden = running.length - runningSlots
2184
+ const runningLines = running.map((view) => ({
2185
+ id: view.id,
2186
+ text: runningChildRowText(view, now, frame, max),
2187
+ }))
2188
+ const summary = completedSummaryText(finished.length, finishedCost, groups.length)
2189
+
2190
+ // Budget: header + live section + summary + rollup. The rollup yields first,
2191
+ // and its own `… +K` line is reserved before any agent row is granted, so the
2192
+ // block can never exceed `DISPATCH_MAX_LINES`.
2193
+ const runningRows = runningSlots + (runningHidden > 0 ? 1 : 0)
2194
+ const room = Math.max(0, DISPATCH_MAX_LINES - 1 - runningRows - (summary === null ? 0 : 1))
2195
+ const wanted = Math.min(DISPATCH_AGENT_CEILING, groups.length)
2196
+ const agentSlots =
2197
+ groups.length > wanted ? Math.min(wanted, Math.max(0, room - 1)) : Math.min(wanted, room)
2198
+ const visibleAgents = groups.slice(0, agentSlots)
2199
+ const hiddenAgents = groups.slice(agentSlots)
2200
+
2201
+ return {
2202
+ runningCount: running.length,
2203
+ completedCount: finished.length,
2204
+ agentCount: groups.length,
2205
+ failures,
2206
+ totalCost,
2207
+ running: runningLines.slice(0, runningSlots),
2208
+ runningHidden,
2209
+ summary,
2210
+ agents: visibleAgents,
2211
+ agentsHidden: hiddenAgents.length,
2212
+ agentsHiddenCost: hiddenAgents.reduce((sum, group) => sum + group.cost, 0),
2213
+ }
2214
+ }
2215
+
2216
+ /* ─── Dispatch panel ──────────────────────────────────────
2217
+ * The `pantheon.dispatch` panel is the full-width counterpart of the sidebar
2218
+ * block: one row per child session (not per agent), the header counters of the
2219
+ * whole tree and a detail column for the selected child. It renders
2220
+ * `collectDispatch` output — the same collector the sidebar block consumes — so
2221
+ * a child can never be listed twice or described two different ways.
2222
+ *
2223
+ * Everything below is pure until `createDispatchPanelModel`: row/header/detail
2224
+ * text is computed without a renderer, and the model owns only the signals the
2225
+ * view needs (selection by id, viewport, expansion, spinner frame). */
2226
+
2227
+ /** Panel content name, registered by the `session.panel` claim and passed to
2228
+ * `ui.panel.open`. */
2229
+ export const DISPATCH_PANEL_NAME = 'pantheon.dispatch'
2230
+ /** Toast shown when `ui.panel.open` refuses (no session route is active). The
2231
+ * panel only exists inside a session, so there is no alternative route. */
2232
+ export const DISPATCH_PANEL_TOAST = 'Abra uma sessão para ver o Dispatch'
2233
+ /** Panel title marker — the same glyph the sidebar block header uses. */
2234
+ export const DISPATCH_PANEL_HEADER_MARKER = '\u25C8'
2235
+ /** Selected-row gutter marker (`▸`, one cell). */
2236
+ export const DISPATCH_PANEL_SELECTION_MARKER = '\u25B8'
2237
+ /** Cells the selection gutter occupies before a row's own text. */
2238
+ export const DISPATCH_PANEL_SELECTION_GUTTER = 2
2239
+ /** Column of the horizontal rule under the header. */
2240
+ export const DISPATCH_PANEL_RULE_CHAR = '\u2500'
2241
+ /** Em dash for any datum the host did not publish. */
2242
+ export const DISPATCH_PANEL_DASH = '\u2014'
2243
+ /** Body of an empty panel (the claim still renders, the list is just empty). */
2244
+ export const DISPATCH_PANEL_EMPTY_TEXT = 'Nenhuma sessão delegada'
2245
+ /** Width at or above which the list and the detail sit side by side. */
2246
+ export const DISPATCH_PANEL_WIDE_MIN_WIDTH = 72
2247
+ /** Rows the viewport holds; pageup/pagedown move by exactly this many rows. */
2248
+ export const DISPATCH_PANEL_PAGE_SIZE = 10
2249
+ /** Panel row columns: marker(2) + agent(12) + kind(4) + cost(≥7) + duration(8).
2250
+ * The cost column is at least this wide; a sub-cent cost widens it per row. */
2251
+ export const DISPATCH_PANEL_AGENT_WIDTH = 12
2252
+ export const DISPATCH_PANEL_MIN_AGENT_WIDTH = 6
2253
+ export const DISPATCH_PANEL_KIND_WIDTH = 4
2254
+ export const DISPATCH_PANEL_COST_WIDTH = 7
2255
+ export const DISPATCH_PANEL_DURATION_WIDTH = 8
2256
+ /** Title column budget (`◈ Dispatch — <sessão>`). */
2257
+ export const DISPATCH_PANEL_TITLE_WIDTH = 44
2258
+ /** Badge appended to the title while the host presents the panel full screen. */
2259
+ export const DISPATCH_PANEL_FULLSCREEN_BADGE = '[fullscreen]'
2260
+ /** Columns a row spends before the agent cell, cost column excluded
2261
+ * (2 marker + 1 + 4 kind + 1 + 8 duration). The cost is measured per row
2262
+ * because `<$0.0001` is one cell wider than `DISPATCH_PANEL_COST_WIDTH`. */
2263
+ const DISPATCH_PANEL_ROW_FIXED_WIDTH = 16
2264
+
2265
+ /** Human labels of a kind's evidence, as the detail line prints them. */
2266
+ export const DISPATCH_KIND_ORIGIN_LABELS: Readonly<Record<DispatchKindOrigin, string>> = {
2267
+ prefix: 'prefixo',
2268
+ agent: 'agente',
2269
+ unavailable: 'indisponível',
2270
+ }
2271
+
2272
+ /** Entries in row order: live work first, then most recent activity — the same
2273
+ * comparator the sidebar block uses. Pure. */
2274
+ export function orderDispatchEntries(entries: readonly DispatchEntry[]): DispatchEntry[] {
2275
+ return [...entries].sort((a, b) => compareDelegations(a.view, b.view))
2276
+ }
2277
+
2278
+ /** `◈ Dispatch — <sessão>`, with the session title truncated (never wrapped),
2279
+ * plus the `[fullscreen]` badge while the host presents the panel full screen.
2280
+ * An absent title leaves the marker and the name alone. Pure. */
2281
+ export function dispatchPanelTitle(
2282
+ sessionTitle: string | null | undefined,
2283
+ max = DISPATCH_PANEL_TITLE_WIDTH,
2284
+ presentation?: string,
2285
+ ): string {
2286
+ const base = `${DISPATCH_PANEL_HEADER_MARKER} Dispatch`
2287
+ const badge = presentation === 'fullscreen' ? ` ${DISPATCH_PANEL_FULLSCREEN_BADGE}` : ''
2288
+ const title = typeof sessionTitle === 'string' ? sessionTitle.trim() : ''
2289
+ if (title === '') return `${base}${badge}`
2290
+ return `${base} ${DISPATCH_PANEL_DASH} ${truncateLabel(title, Math.max(4, max))}${badge}`
2291
+ }
2292
+
2293
+ /** Header counters: `2 rodando · 70 concluídos · 1 falha · $3.59`. A zero
2294
+ * counter is omitted (never `0 rodando`); the total spend is printed whenever
2295
+ * the tree has a child, because `$0.00` is then a real answer. Null for an
2296
+ * empty tree, so the header renders no counter line at all. Pure. */
2297
+ export function dispatchPanelHeader(
2298
+ entries: readonly DispatchEntry[] | null | undefined,
2299
+ ): string | null {
2300
+ const list = Array.isArray(entries) ? entries.filter((entry) => entry?.view) : []
2301
+ if (list.length === 0) return null
2302
+ let running = 0
2303
+ let completed = 0
2304
+ let failed = 0
2305
+ for (const entry of list) {
2306
+ switch (entry.view.state) {
2307
+ case 'running':
2308
+ running += 1
2309
+ break
2310
+ case 'completed':
2311
+ completed += 1
2312
+ break
2313
+ case 'failed':
2314
+ failed += 1
2315
+ break
2316
+ default:
2317
+ break
2318
+ }
2319
+ }
2320
+ const parts: string[] = []
2321
+ if (running > 0) parts.push(`${running} rodando`)
2322
+ if (completed > 0) parts.push(`${completed} ${completed === 1 ? 'concluído' : 'concluídos'}`)
2323
+ if (failed > 0) parts.push(`${failed} ${failed === 1 ? 'falha' : 'falhas'}`)
2324
+ const cost = formatSpendUSD(dispatchTotalCost(list.map((entry) => entry.view)))
2325
+ if (cost !== null) parts.push(cost)
2326
+ return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR)
2327
+ }
2328
+
2329
+ /** Horizontal rule under the header, clamped to the panel's own width. Pure. */
2330
+ export function dispatchPanelRule(width: number, max = 200): string {
2331
+ const columns = Math.max(0, Math.min(max, Math.floor(numberOrNull(width) ?? 0)))
2332
+ return DISPATCH_PANEL_RULE_CHAR.repeat(columns)
2333
+ }
2334
+
2335
+ /** Row marker: animated spinner while running, `✓` done, `✗` failed, `○`
2336
+ * cancelled/interrupted, `?` for a state the host never publishes. Every glyph
2337
+ * is one cell wide and `?` is the only fallback, so an unknown state is visible
2338
+ * instead of silently rendering as success. Pure. */
2339
+ export function dispatchPanelMarker(state: DelegationState | string, frame = 0): string {
2340
+ switch (state) {
2341
+ case 'running':
2342
+ return `${spinnerFrame(frame)} `
2343
+ case 'completed':
2344
+ return '\u2713 '
2345
+ case 'failed':
2346
+ return '\u2717 '
2347
+ case 'interrupted':
2348
+ return '\u25CB '
2349
+ default:
2350
+ return '? '
2351
+ }
2352
+ }
2353
+
2354
+ /** One padded, truncated cell: an absent/blank value becomes the em dash, and
2355
+ * the value is cut to the cell's own width (never to the line's length, so one
2356
+ * long cell cannot squeeze its neighbours out of alignment). Pure. */
2357
+ export function dispatchPanelCell(value: unknown, width: number): string {
2358
+ const cells = Math.max(1, Math.floor(numberOrNull(width) ?? 1))
2359
+ const text = typeof value === 'string' ? value.trim() : ''
2360
+ return padCell(text === '' ? DISPATCH_PANEL_DASH : text, cells)
2361
+ }
2362
+
2363
+ /** One list row: `⠋ prometheus plan $0.09 14m34s`. The agent cell absorbs
2364
+ * the width difference (down to `DISPATCH_PANEL_MIN_AGENT_WIDTH`), so a narrow
2365
+ * panel truncates the label rather than the numbers; the cost column grows by
2366
+ * itself for a sub-cent value so the row never spends more than its budget.
2367
+ * Pure. */
2368
+ export function dispatchPanelRowText(
2369
+ entry: DispatchEntry,
2370
+ options: { now?: number; frame?: number; max?: number } = {},
2371
+ ): string {
2372
+ const view = entry?.view
2373
+ if (!view) return ''
2374
+ const now = numberOrNull(options.now) ?? Date.now()
2375
+ const frame = numberOrNull(options.frame) ?? 0
2376
+ const width = Math.floor(numberOrNull(options.max) ?? 35)
2377
+ const costText = formatDispatchCost(view.cost)
2378
+ const costWidth = Math.max(DISPATCH_PANEL_COST_WIDTH, cellWidth(costText))
2379
+ const agentWidth = Math.max(
2380
+ DISPATCH_PANEL_MIN_AGENT_WIDTH,
2381
+ Math.min(DISPATCH_PANEL_AGENT_WIDTH, width - (DISPATCH_PANEL_ROW_FIXED_WIDTH + costWidth)),
2382
+ )
2383
+ const marker = dispatchPanelMarker(view.state, frame)
2384
+ const agent = dispatchPanelCell(dispatchAgentText(view, DISPATCH_PANEL_AGENT_WIDTH), agentWidth)
2385
+ const kind = dispatchPanelCell(view.kind, DISPATCH_PANEL_KIND_WIDTH)
2386
+ const cost = costText.padStart(costWidth)
2387
+ const duration = truncateLabel(
2388
+ dispatchElapsed(view, now),
2389
+ DISPATCH_PANEL_DURATION_WIDTH,
2390
+ ).padStart(DISPATCH_PANEL_DURATION_WIDTH)
2391
+ return `${marker}${agent} ${kind} ${cost}${duration}`
2392
+ }
2393
+
2394
+ /** `ses_ab12cd`, short enough for a detail line. Full id when it already fits. */
2395
+ export function shortSessionID(id: string | null | undefined, max = 10): string {
2396
+ const text = typeof id === 'string' ? id.trim() : ''
2397
+ if (text === '') return DISPATCH_PANEL_DASH
2398
+ return text.length <= max ? text : `${text.slice(0, Math.max(1, max - 1))}\u2026`
2399
+ }
2400
+
2401
+ /** Token counters of one child on a single line (`in 1.2K · out 430 · r 120 ·
2402
+ * cache 8K/1K`), or `tokens —` when the host published none. Pure. */
2403
+ export function dispatchTokenLine(tokens: DispatchTokens | null | undefined): string {
2404
+ if (!tokens) return `tokens ${DISPATCH_PANEL_DASH}`
2405
+ const value = (token: number | null) =>
2406
+ token === null ? DISPATCH_PANEL_DASH : (formatContextWindow(token) ?? String(token))
2407
+ return [
2408
+ `in ${value(tokens.input)}`,
2409
+ `out ${value(tokens.output)}`,
2410
+ `r ${value(tokens.reasoning)}`,
2411
+ `cache ${value(tokens.cacheRead)}/${value(tokens.cacheWrite)}`,
2412
+ ].join(SPEND_LINE_SEPARATOR)
2413
+ }
2414
+
2415
+ /** Detail lines of the selected child: heading (title, else the spawning
2416
+ * description, else the row label), short id + model, token counters, and the
2417
+ * kind plus its evidence and the parent id. Two to four lines; `expanded:
2418
+ * false` keeps only the heading. Every missing datum prints `—`. Pure. */
2419
+ export function dispatchPanelDetail(
2420
+ entry: DispatchEntry | null | undefined,
2421
+ options: { expanded?: boolean; max?: number } = {},
2422
+ ): string[] {
2423
+ if (!entry?.view) return [DISPATCH_PANEL_DASH]
2424
+ const max = Math.max(8, Math.floor(numberOrNull(options.max) ?? 60))
2425
+ const view = entry.view
2426
+ const heading =
2427
+ entry.title ??
2428
+ entry.description ??
2429
+ (typeof view.label === 'string' && view.label !== '' ? view.label : null) ??
2430
+ view.id
2431
+ const lines = [truncateLabel(heading, max)]
2432
+ if (options.expanded === false) return lines
2433
+ lines.push(
2434
+ truncateLabel(
2435
+ `${shortSessionID(view.id)}${SPEND_LINE_SEPARATOR}${view.model ?? DISPATCH_PANEL_DASH}`,
2436
+ max,
2437
+ ),
2438
+ )
2439
+ lines.push(truncateLabel(dispatchTokenLine(entry.tokens), max))
2440
+ const origin =
2441
+ DISPATCH_KIND_ORIGIN_LABELS[view.kindOrigin] ?? DISPATCH_KIND_ORIGIN_LABELS.unavailable
2442
+ lines.push(
2443
+ truncateLabel(
2444
+ `kind ${view.kind ?? DISPATCH_PANEL_DASH} (${origin})${SPEND_LINE_SEPARATOR}parent ${entry.parentID ?? DISPATCH_PANEL_DASH}`,
2445
+ max,
2446
+ ),
2447
+ )
2448
+ return lines
2449
+ }
2450
+
2451
+ /** Panel geometry for its input width: wide (≥72) puts the detail in a second
2452
+ * column, narrow stacks it under the list. `rowWidth` is what a list row may
2453
+ * spend after the selection gutter. Pure. */
2454
+ export type DispatchPanelLayout = {
2455
+ mode: 'wide' | 'narrow'
2456
+ listWidth: number
2457
+ detailWidth: number
2458
+ rowWidth: number
2459
+ }
2460
+
2461
+ export function dispatchPanelLayout(width: number): DispatchPanelLayout {
2462
+ const columns = Math.max(20, Math.floor(numberOrNull(width) ?? 0))
2463
+ if (columns >= DISPATCH_PANEL_WIDE_MIN_WIDTH) {
2464
+ const listWidth = Math.max(40, Math.min(64, columns - 26))
2465
+ return {
2466
+ mode: 'wide',
2467
+ listWidth,
2468
+ detailWidth: Math.max(24, columns - listWidth - 2),
2469
+ rowWidth: listWidth - DISPATCH_PANEL_SELECTION_GUTTER,
2470
+ }
2471
+ }
2472
+ return {
2473
+ mode: 'narrow',
2474
+ listWidth: columns,
2475
+ detailWidth: columns,
2476
+ rowWidth: columns - DISPATCH_PANEL_SELECTION_GUTTER,
2477
+ }
2478
+ }
2479
+
2480
+ /** Viewport of the list: the page holding the selection, scrolled so the
2481
+ * selected row stays visible with its predecessors. Bounded, so a 71-child
2482
+ * tree renders ten rows, never all of them. Pure. */
2483
+ export function dispatchPanelWindow(
2484
+ total: number,
2485
+ selectedIndex: number,
2486
+ pageSize = DISPATCH_PANEL_PAGE_SIZE,
2487
+ ): { start: number; end: number; size: number } {
2488
+ const count = Math.max(0, Math.floor(numberOrNull(total) ?? 0))
2489
+ const size = Math.max(1, Math.floor(numberOrNull(pageSize) ?? DISPATCH_PANEL_PAGE_SIZE))
2490
+ if (count === 0) return { start: 0, end: 0, size }
2491
+ const index = Math.min(count - 1, Math.max(0, Math.floor(numberOrNull(selectedIndex) ?? 0)))
2492
+ const start = Math.min(Math.max(0, index - size + 1), Math.max(0, count - size))
2493
+ return { start, end: Math.min(count, start + size), size }
2494
+ }
2495
+
2496
+ /** `1-10 de 71` while the list is longer than one page; null when everything
2497
+ * fits (and for an empty list), so the footer never pads itself. Pure. */
2498
+ export function dispatchPanelRangeText(start: number, end: number, total: number): string | null {
2499
+ const count = Math.max(0, Math.floor(numberOrNull(total) ?? 0))
2500
+ const first = Math.max(0, Math.floor(numberOrNull(start) ?? 0))
2501
+ const last = Math.min(count, Math.floor(numberOrNull(end) ?? 0))
2502
+ if (count === 0 || (first === 0 && last >= count)) return null
2503
+ return `${first + 1}-${last} de ${count}`
2504
+ }
2505
+
2506
+ /** One rendered list row, selection resolved by the view against the model's
2507
+ * selected id. */
2508
+ export type DispatchPanelRow = { id: string; state: DelegationState; text: string }
2509
+
2510
+ /** Every entry as a row, ordered by the shared comparator. Pure. */
2511
+ export function dispatchPanelRows(
2512
+ entries: readonly DispatchEntry[] | null | undefined,
2513
+ options: { now?: number; frame?: number; max?: number } = {},
2514
+ ): DispatchPanelRow[] {
2515
+ const list = Array.isArray(entries)
2516
+ ? entries.filter((entry) => entry?.view && typeof entry.view.id === 'string')
2517
+ : []
2518
+ return orderDispatchEntries(list).map((entry) => ({
2519
+ id: entry.view.id,
2520
+ state: entry.view.state,
2521
+ text: dispatchPanelRowText(entry, options),
2522
+ }))
2523
+ }
2524
+
2525
+ /** Panel action, one per command. */
2526
+ export type DispatchPanelAction =
2527
+ | 'up'
2528
+ | 'down'
2529
+ | 'home'
2530
+ | 'end'
2531
+ | 'pageup'
2532
+ | 'pagedown'
2533
+ | 'toggle'
2534
+ | 'fullscreen'
2535
+ | 'close'
2536
+
2537
+ /** One namespaced command: stable id, explicit binding, and the action it runs. */
2538
+ export type DispatchPanelCommandSpec = {
2539
+ action: DispatchPanelAction
2540
+ id: string
2541
+ title: string
2542
+ bind: string
2543
+ }
2544
+
2545
+ /** The panel's whole keymap, in table order. `bind` is explicit for every
2546
+ * command (no auto-binding), and every id is namespaced, so a `k`/`q`/`f`
2547
+ * binding can never collide with the host's own keys. */
2548
+ export const DISPATCH_PANEL_COMMANDS: readonly DispatchPanelCommandSpec[] = [
2549
+ {
2550
+ action: 'up',
2551
+ id: 'pantheon.dispatch.up',
2552
+ title: 'Dispatch: selecionar anterior',
2553
+ bind: 'k,up',
2554
+ },
2555
+ {
2556
+ action: 'down',
2557
+ id: 'pantheon.dispatch.down',
2558
+ title: 'Dispatch: selecionar próxima',
2559
+ bind: 'j,down',
2560
+ },
2561
+ { action: 'home', id: 'pantheon.dispatch.home', title: 'Dispatch: primeira', bind: 'home' },
2562
+ { action: 'end', id: 'pantheon.dispatch.end', title: 'Dispatch: última', bind: 'end' },
2563
+ {
2564
+ action: 'pageup',
2565
+ id: 'pantheon.dispatch.pageup',
2566
+ title: 'Dispatch: página acima',
2567
+ bind: 'pageup',
2568
+ },
2569
+ {
2570
+ action: 'pagedown',
2571
+ id: 'pantheon.dispatch.pagedown',
2572
+ title: 'Dispatch: página abaixo',
2573
+ bind: 'pagedown',
2574
+ },
2575
+ {
2576
+ action: 'toggle',
2577
+ id: 'pantheon.dispatch.toggle',
2578
+ title: 'Dispatch: expandir detalhe',
2579
+ bind: 'enter',
2580
+ },
2581
+ {
2582
+ action: 'fullscreen',
2583
+ id: 'pantheon.dispatch.fullscreen',
2584
+ title: 'Dispatch: tela cheia',
2585
+ bind: 'f',
2586
+ },
2587
+ { action: 'close', id: 'pantheon.dispatch.close', title: 'Dispatch: fechar', bind: 'escape,q' },
2588
+ ]
2589
+
2590
+ /** Run one action against the model and the host-owned panel input. Kept apart
2591
+ * from the keymap so the whole command surface is testable without a renderer.
2592
+ */
2593
+ export function performDispatchPanelAction(
2594
+ action: DispatchPanelAction,
2595
+ model: Pick<DispatchPanelModel, 'move' | 'first' | 'last' | 'pageUp' | 'pageDown' | 'toggle'>,
2596
+ panel: Pick<PanelInput, 'close' | 'toggleFullscreen'>,
2597
+ ): void {
2598
+ switch (action) {
2599
+ case 'up':
2600
+ model.move(-1)
2601
+ return
2602
+ case 'down':
2603
+ model.move(1)
2604
+ return
2605
+ case 'home':
2606
+ model.first()
2607
+ return
2608
+ case 'end':
2609
+ model.last()
2610
+ return
2611
+ case 'pageup':
2612
+ model.pageUp()
2613
+ return
2614
+ case 'pagedown':
2615
+ model.pageDown()
2616
+ return
2617
+ case 'toggle':
2618
+ model.toggle()
2619
+ return
2620
+ case 'fullscreen':
2621
+ panel.toggleFullscreen()
2622
+ return
2623
+ case 'close':
2624
+ panel.close()
2625
+ return
2626
+ default:
2627
+ return
2628
+ }
2629
+ }
2630
+
2631
+ /** Footer: the keys the host reports for each command (`keymap.shortcuts`) with
2632
+ * an em dash whenever a command has no binding, so the hint can never advertise
2633
+ * a key that does nothing. Pure. */
2634
+ export function dispatchPanelFooter(shortcutsOf: (id: string) => readonly string[]): string {
2635
+ const keys = (id: string): string => {
2636
+ let list: readonly string[] = []
2637
+ try {
2638
+ const result = shortcutsOf(id)
2639
+ list = Array.isArray(result) ? result : []
2640
+ } catch {
2641
+ list = []
2642
+ }
2643
+ const text = list
2644
+ .map((key) => String(key ?? '').trim())
2645
+ .filter((key) => key !== '')
2646
+ .join('/')
2647
+ return text === '' ? DISPATCH_PANEL_DASH : text
2648
+ }
2649
+ return [
2650
+ `${keys('pantheon.dispatch.up')} ${keys('pantheon.dispatch.down')} mover`,
2651
+ `${keys('pantheon.dispatch.toggle')} detalhe`,
2652
+ `${keys('pantheon.dispatch.fullscreen')} fullscreen`,
2653
+ `${keys('pantheon.dispatch.close')} fechar`,
2654
+ ].join(SPEND_LINE_SEPARATOR)
2655
+ }
2656
+
2657
+ /** The subset of `PanelInput` the model reads, so tests can drive it with a
2658
+ * plain object. */
2659
+ export type DispatchPanelInput = {
2660
+ readonly name: string
2661
+ readonly sessionID: string
2662
+ readonly width: number
2663
+ readonly presentation?: string
2664
+ }
2665
+
2666
+ /** `keymap.shortcuts` of one command; empty when the keymap is unavailable. */
2667
+ function keymapShortcuts(context: any, id: string): readonly string[] {
2668
+ try {
2669
+ const list = context?.keymap?.shortcuts?.(id)
2670
+ return Array.isArray(list) ? list : []
2671
+ } catch {
2672
+ return []
2673
+ }
2674
+ }
2675
+
2676
+ /** Open the panel from the command palette / slash command. `ui.panel.open`
2677
+ * only accepts a `session` route, so a refusal (no session open) is answered
2678
+ * with a toast — never a fallback route, never a silent no-op. Returns whether
2679
+ * the panel opened. */
2680
+ export function openDispatchPanel(context: any): boolean {
2681
+ let opened = false
2682
+ try {
2683
+ opened = context?.ui?.panel?.open?.(DISPATCH_PANEL_NAME) === true
2684
+ } catch {
2685
+ opened = false
2686
+ }
2687
+ if (opened) return true
2688
+ try {
2689
+ context?.ui?.toast?.show?.({ message: DISPATCH_PANEL_TOAST, variant: 'warning' })
2690
+ } catch {
2691
+ /* toast unavailable — the command still degrades to a no-op */
2692
+ }
2693
+ return false
2694
+ }
2695
+
2696
+ /** Reactive state the panel view renders. Selection is held by session id, so
2697
+ * it survives list updates; the index is derived (and falls back to the first
2698
+ * row when the selected child disappears). */
2699
+ export type DispatchPanelModel = {
2700
+ entries: Accessor<DispatchEntry[]>
2701
+ rows: Accessor<DispatchPanelRow[]>
2702
+ title: Accessor<string>
2703
+ header: Accessor<string | null>
2704
+ detail: Accessor<string[]>
2705
+ layout: Accessor<DispatchPanelLayout>
2706
+ visible: Accessor<{ start: number; rows: DispatchPanelRow[] }>
2707
+ selectedID: Accessor<string | null>
2708
+ selectedIndex: Accessor<number>
2709
+ expanded: Accessor<boolean>
2710
+ hasRunning: Accessor<boolean>
2711
+ frame: Accessor<number>
2712
+ footer: Accessor<string>
2713
+ move: (delta: number) => void
2714
+ first: () => void
2715
+ last: () => void
2716
+ pageUp: () => void
2717
+ pageDown: () => void
2718
+ toggle: () => void
2719
+ }
2720
+
2721
+ /** Model behind the panel. Mounted only while the panel claim renders (the
2722
+ * `Show` in `session.panel`), so the 80 ms tick it arms exists exactly while
2723
+ * the panel is open; it also stops on `isOpen()` going false and on dispose.
2724
+ * It performs no `message.sync`, writes no `session.metadata` and makes no
2725
+ * request: `collectDispatch` reads only host-cached state. */
2726
+ export function createDispatchPanelModel(
2727
+ context: any,
2728
+ panel: () => DispatchPanelInput,
2729
+ ): DispatchPanelModel {
2730
+ const [revision, setRevision] = createSignal(0)
2731
+ const [frame, setFrame] = createSignal(0)
2732
+ const [expanded, setExpanded] = createSignal(true)
2733
+ const [selectedID, setSelectedID] = createSignal<string | null>(null)
2734
+
2735
+ const isOpen = () => panel().name === DISPATCH_PANEL_NAME
2736
+ const activeSessionID = () => {
2737
+ const id = panel().sessionID
2738
+ return isValidSessionID(id) ? id : ''
2739
+ }
2740
+
2741
+ const entries = createMemo(() => {
2742
+ revision()
2743
+ if (!isOpen()) return []
2744
+ return collectDispatch(context, activeSessionID())
2745
+ })
2746
+
2747
+ const layout = createMemo(() => dispatchPanelLayout(panel().width))
2748
+
2749
+ const rows = createMemo(() => {
2750
+ const mode = layout()
2751
+ return dispatchPanelRows(entries(), {
2752
+ now: Date.now(),
2753
+ frame: frame(),
2754
+ max: mode.rowWidth,
2755
+ })
2756
+ })
2757
+
2758
+ const selectedIndex = createMemo(() => {
2759
+ const list = rows()
2760
+ if (list.length === 0) return 0
2761
+ const id = selectedID()
2762
+ if (id === null) return 0
2763
+ const index = list.findIndex((row) => row.id === id)
2764
+ return index === -1 ? 0 : index
2765
+ })
2766
+
2767
+ const selectedIDAccessor = createMemo(() => rows()[selectedIndex()]?.id ?? null)
2768
+ const selectedEntry = createMemo(() => entries()[selectedIndex()] ?? null)
2769
+
2770
+ const session = createMemo(() => {
2771
+ revision()
2772
+ const id = activeSessionID()
2773
+ if (id === '') return undefined
2774
+ try {
2775
+ return context.data.session.get(id)
2776
+ } catch {
2777
+ return undefined
2778
+ }
2779
+ })
2780
+
2781
+ const title = createMemo(() =>
2782
+ dispatchPanelTitle(session()?.title, DISPATCH_PANEL_TITLE_WIDTH, panel().presentation),
2783
+ )
2784
+ const header = createMemo(() => dispatchPanelHeader(entries()))
2785
+ const detail = createMemo(() =>
2786
+ dispatchPanelDetail(selectedEntry(), {
2787
+ expanded: expanded(),
2788
+ max: layout().detailWidth,
2789
+ }),
2790
+ )
2791
+
2792
+ const visible = createMemo(() => {
2793
+ const list = rows()
2794
+ const window = dispatchPanelWindow(list.length, selectedIndex())
2795
+ return { start: window.start, rows: list.slice(window.start, window.end) }
2796
+ })
2797
+
2798
+ const hasRunning = createMemo(() => rows().some((row) => row.state === 'running'))
2799
+
2800
+ const footer = createMemo(() => {
2801
+ const list = rows()
2802
+ const window = dispatchPanelWindow(list.length, selectedIndex())
2803
+ const range = dispatchPanelRangeText(window.start, window.end, list.length)
2804
+ const hints = dispatchPanelFooter((id) => keymapShortcuts(context, id))
2805
+ return range === null ? hints : `${range}${SPEND_LINE_SEPARATOR}${hints}`
2806
+ })
2807
+
2808
+ const select = (index: number) => {
2809
+ const list = rows()
2810
+ if (list.length === 0) return
2811
+ const clamped = Math.min(list.length - 1, Math.max(0, Math.round(index)))
2812
+ setSelectedID(list[clamped]?.id ?? null)
2813
+ }
2814
+
2815
+ onMount(() => {
2816
+ onCleanup(subscribeSidebarRefresh(context, () => setRevision((value) => value + 1)))
2817
+ })
2818
+
2819
+ // Spinner ticks only while the panel is open *and* a child runs; closing the
2820
+ // panel, the last child finishing or the component unmounting all clear it.
2821
+ createEffect(() => {
2822
+ if (!isOpen() || !hasRunning()) return
2823
+ const spinner = setInterval(() => setFrame((value) => value + 1), SPINNER_INTERVAL_MS)
2824
+ onCleanup(() => clearInterval(spinner))
2825
+ })
2826
+
2827
+ return {
2828
+ entries,
2829
+ rows,
2830
+ title,
2831
+ header,
2832
+ detail,
2833
+ layout,
2834
+ visible,
2835
+ selectedID: selectedIDAccessor,
2836
+ selectedIndex,
2837
+ expanded,
2838
+ hasRunning,
2839
+ frame,
2840
+ footer,
2841
+ move: (delta: number) => select(selectedIndex() + (numberOrNull(delta) ?? 0)),
2842
+ first: () => select(0),
2843
+ last: () => select(rows().length - 1),
2844
+ pageUp: () => select(selectedIndex() - DISPATCH_PANEL_PAGE_SIZE),
2845
+ pageDown: () => select(selectedIndex() + DISPATCH_PANEL_PAGE_SIZE),
2846
+ toggle: () => setExpanded((value) => !value),
2847
+ }
2848
+ }
2849
+
2850
+ /** Session ids to eagerly sync at load (deduped, bounded). Pure. */
2851
+ export function collectWarmupTargets(
2852
+ sessions: readonly any[],
2853
+ limit = WARMUP_SESSION_LIMIT,
2854
+ ): string[] {
2855
+ const ids: string[] = []
2856
+ for (const session of sessions) {
2857
+ if (!isValidSessionID(session?.id) || ids.includes(session.id)) continue
2858
+ ids.push(session.id)
2859
+ if (ids.length >= limit) break
2860
+ }
2861
+ return ids
2862
+ }
2863
+
2864
+ /* ─── Known Issue guard ──────────────────────────────────── */
2865
+
2866
+ /** Body a sidebar instance renders when the host has not published a real
2867
+ * session id yet. OpenCode V2 scopes the `sidebar.content` slot to a session
2868
+ * (`SlotMap["sidebar.content"] = { sessionID: string }`), so before the first
2869
+ * prompt the slot may not mount at all — see the `home.footer.status`
2870
+ * contribution for the pre-prompt degradation. Pure. */
2871
+ export function sidebarPlaceholder(sessionID: string | undefined): string | null {
2872
+ return isValidSessionID(sessionID) ? null : SIDEBAR_WAITING_LABEL
2873
+ }
2874
+
2875
+ /* ─── Click-through ──────────────────────────────────────── */
2876
+
2877
+ /** Navigate to a session through the V2 router. Fail-open: an absent router or
2878
+ * a removed session must never break the sidebar. Returns whether a valid
2879
+ * navigation was dispatched. Pure. */
2880
+ export function navigateToSession(
2881
+ router: { navigate?: (destination: any) => void } | undefined,
2882
+ sessionID: string | undefined,
2883
+ ): boolean {
2884
+ if (typeof router?.navigate !== 'function' || !isValidSessionID(sessionID)) return false
2885
+ try {
2886
+ router.navigate({ type: 'session', sessionID })
2887
+ return true
2888
+ } catch {
2889
+ return false
2890
+ }
2891
+ }
2892
+
2893
+ /* ─── Delegate-completion detection (toasts) ─────────────── */
2894
+
2895
+ export type DelegationCompletion = { id: string; label: string; state: DelegationState }
2896
+
2897
+ /** Diff two delegation observations: entries that were `running` and are no
2898
+ * longer running count as completions, fired once per transition. Returns the
2899
+ * next snapshot so callers can keep a single tracker. First observation never
2900
+ * reports a completion (no toast spam on mount). Pure. */
2901
+ export function detectDelegationCompletions(
2902
+ previous: ReadonlyMap<string, DelegationState>,
2903
+ current: ReadonlyArray<DelegationCompletion>,
2904
+ ): { completed: DelegationCompletion[]; snapshot: Map<string, DelegationState> } {
2905
+ const snapshot = new Map<string, DelegationState>()
2906
+ const completed: DelegationCompletion[] = []
2907
+ for (const entry of current) {
2908
+ snapshot.set(entry.id, entry.state)
2909
+ if (previous.get(entry.id) === 'running' && entry.state !== 'running') completed.push(entry)
2910
+ }
2911
+ return { completed, snapshot }
2912
+ }
2913
+
2914
+ /* ─── Runtime helpers ────────────────────────────────────── */
2915
+
2916
+ function resolveLocation(context: any): any {
2917
+ try {
2918
+ return context?.location ?? context?.data?.location?.default()
2919
+ } catch {
2920
+ return undefined
2921
+ }
2922
+ }
2923
+
2924
+ function resolveSidebarCwd(context: any): string {
2925
+ const location = resolveLocation(context)
2926
+ if (location && typeof location.directory === 'string' && location.directory !== '') {
2927
+ return location.directory
2928
+ }
2929
+ return process.cwd()
2930
+ }
2931
+
2932
+ function sessionStatusOf(context: any, sessionID: string): string | undefined {
2933
+ try {
2934
+ const status = context?.data?.session?.status?.(sessionID)
2935
+ return typeof status === 'string' ? status : undefined
2936
+ } catch {
2937
+ return undefined
2938
+ }
2939
+ }
2940
+
2941
+ /** Subscribe `refresh` to every V2 event that can change sidebar state. Returns
2942
+ * a disposer that releases exactly the subscriptions the host handed out. The
2943
+ * event names come from the V2 union; the cast turns an unknown name into a
2944
+ * compile error instead of a silent no-op subscription. */
2945
+ function subscribeSidebarRefresh(context: any, refresh: () => void): () => void {
2946
+ const stop: Array<() => void> = []
2947
+ const data = context?.data as Context['data'] | undefined
2948
+ if (typeof data?.on === 'function') {
2949
+ for (const type of SIDEBAR_REFRESH_EVENTS) {
2950
+ try {
2951
+ const unsubscribe = data.on(type, refresh)
2952
+ if (typeof unsubscribe === 'function') stop.push(unsubscribe)
2953
+ } catch {
2954
+ // Sidebar stays useful with the initial cached state if an event is unavailable.
2955
+ }
2956
+ }
2957
+ }
2958
+ return () => {
2959
+ for (const unsubscribe of stop) {
2960
+ if (typeof unsubscribe === 'function') unsubscribe()
2961
+ }
2962
+ }
2963
+ }
2964
+
2965
+ /** Populate the cached data at load so the sidebar has content before the first
2966
+ * prompt (Known Issue guard). Fire-and-forget: a missing API or a failed sync
2967
+ * degrades silently and the sidebar still renders its static header. */
2968
+ function warmUpSidebarData(context: any, location: any): void {
2969
+ try {
2970
+ void Promise.resolve(context?.data?.location?.vcs?.sync?.(location)).catch(() => {})
2971
+ } catch {
2972
+ /* vcs API unavailable */
2973
+ }
2974
+ let listed: any[] = []
2975
+ try {
2976
+ const result = context?.data?.session?.list?.()
2977
+ if (Array.isArray(result)) listed = result
2978
+ } catch {
2979
+ /* session API unavailable */
2980
+ }
2981
+ for (const id of collectWarmupTargets(listed)) {
2982
+ try {
2983
+ void Promise.resolve(context?.data?.session?.sync?.(id)).catch(() => {})
2984
+ } catch {
2985
+ /* per-session sync unavailable */
2986
+ }
2987
+ }
2988
+ }
2989
+
2990
+ function showDelegationToast(context: any, done: DelegationCompletion): void {
2991
+ const variant =
2992
+ done.state === 'failed' ? 'error' : done.state === 'interrupted' ? 'warning' : 'success'
2993
+ const verb =
2994
+ done.state === 'failed' ? 'falhou' : done.state === 'interrupted' ? 'interrompida' : 'concluída'
2995
+ try {
2996
+ context?.ui?.toast?.show?.({
2997
+ title: TOAST_TITLE,
2998
+ message: `${done.label} ${verb}`,
2999
+ variant,
3000
+ sessionID: done.id,
3001
+ })
3002
+ } catch {
3003
+ /* toast API unavailable — the row already carries the state tone */
3004
+ }
3005
+ }
3006
+
3007
+ /** Active preset signal with mount + 30s refresh. Shared by the sidebar and the
3008
+ * home-screen status contribution. */
3009
+ function useActivePreset(context: any): {
3010
+ preset: Accessor<PresetInfo>
3011
+ overrides: Accessor<PresetOverrides>
3012
+ } {
3013
+ const [preset, setPreset] = createSignal<PresetInfo>(presetFromEnv(process.env))
3014
+ const [overrides, setOverrides] = createSignal<PresetOverrides>(emptyOverrides())
3015
+ onMount(() => {
3016
+ const cwd = resolveSidebarCwd(context)
3017
+ let cancelled = false
3018
+ const refresh = async () => {
3019
+ try {
3020
+ const detail = await resolveActivePresetForTui(process.env, cwd)
3021
+ if (!cancelled) {
3022
+ setPreset(detail.info)
3023
+ setOverrides(detail.overrides)
3024
+ }
3025
+ } catch {
3026
+ /* transient read error — keep the last known value */
3027
+ }
3028
+ }
3029
+ void refresh()
3030
+ const timer = setInterval(() => void refresh(), PRESET_REFRESH_MS)
3031
+ onCleanup(() => {
3032
+ cancelled = true
3033
+ clearInterval(timer)
3034
+ })
3035
+ })
3036
+ return { preset, overrides }
3037
+ }
3038
+
3039
+ /** Debounce for the git file-count revalidation. `vcs.status` is an HTTP call;
3040
+ * session events arrive in bursts, so the row is refreshed at most once per
3041
+ * window instead of on every event. */
3042
+ export const GIT_CHANGES_DEBOUNCE_MS = 400
3043
+
3044
+ /** `context.client.vcs.status(input?, requestOptions?)` →
3045
+ * `Promise<{ data: VcsFileStatus[] }>` (`GET /api/vcs/status`). Returns the
3046
+ * callable or null when the host does not expose it, so callers degrade to
3047
+ * the branch-only row instead of throwing. */
3048
+ function vcsStatusCall(context: any): ((input?: any) => Promise<any>) | null {
3049
+ const status = context?.client?.vcs?.status
3050
+ return typeof status === 'function' ? status.bind(context.client.vcs) : null
3051
+ }
3052
+
3053
+ /** `context.client.session.stats(input?, requestOptions?)` →
3054
+ * `Promise<SessionStatsInfo>` (`GET /api/experimental/session/stats`), served
3055
+ * by the local process. Returns the callable or null when the host does not
3056
+ * expose it, so the Context spend line simply does not render. */
3057
+ function statsCall(context: any): ((input?: any) => Promise<any>) | null {
3058
+ const stats = context?.client?.session?.stats
3059
+ return typeof stats === 'function' ? stats.bind(context.client.session) : null
3060
+ }
3061
+
3062
+ /** Local IANA zone for the stats call (`America/Sao_Paulo`); omitted when the
3063
+ * runtime cannot resolve one. */
3064
+ function localTimezone(): string | undefined {
3065
+ try {
3066
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
3067
+ return typeof zone === 'string' && zone !== '' ? zone : undefined
3068
+ } catch {
3069
+ return undefined
3070
+ }
3071
+ }
3072
+
3073
+ /** Fields every stats call sends. `tools: 'none'` skips the tool aggregation
3074
+ * the block never renders; `project` is omitted (no cheap id in hand) rather
3075
+ * than guessed. */
3076
+ function statsInput(): Record<string, unknown> {
3077
+ const timezone = localTimezone()
3078
+ return timezone === undefined ? { tools: 'none' } : { tools: 'none', timezone }
3079
+ }
3080
+
3081
+ /** Convert a millisecond instant to the unit the route accepted. */
3082
+ function spendInstant(ms: number, unit: SpendUnit): number {
3083
+ return unit === 's' ? Math.floor(ms / 1000) : ms
3084
+ }
3085
+
3086
+ /** Measure the `from`/`to` unit once: millisecond epoch first, then a single
3087
+ * seconds attempt. Bounded to two calls and never throws; anything the route
3088
+ * rejects (mismatch, throw, malformed echo) ends as `unavailable`, which hides
3089
+ * the block for the rest of the process instead of retrying forever. */
3090
+ async function probeSpendUnit(call: (input?: any) => Promise<any>): Promise<SpendUnit> {
3091
+ const now = Date.now()
3092
+ const fromMs = now - SPEND_PROBE_WINDOW_MS
3093
+ const attempts: Array<{ sent: { from: number; to: number }; scale: number; unit: SpendUnit }> = [
3094
+ { sent: { from: fromMs, to: now }, scale: 1, unit: 'ms' },
3095
+ {
3096
+ sent: { from: Math.floor(fromMs / 1000), to: Math.floor(now / 1000) },
3097
+ scale: 1000,
3098
+ unit: 's',
3099
+ },
3100
+ ]
3101
+ for (const attempt of attempts) {
3102
+ try {
3103
+ const result = await call({ ...statsInput(), ...attempt.sent })
3104
+ if (statsRangeMatches(result?.range, attempt.sent, attempt.scale)) return attempt.unit
3105
+ } catch {
3106
+ /* route rejected the call in this unit — try the next one, then give up */
3107
+ }
3108
+ }
3109
+ return 'unavailable'
3110
+ }
3111
+
3112
+ /** Resolve (and cache) the unit for this process. Concurrent callers share one
3113
+ * probe, so a burst of refreshes cannot spend more than two calls on it. */
3114
+ function ensureSpendUnit(call: (input?: any) => Promise<any>): Promise<SpendUnit> {
3115
+ if (spendUnit !== null) return Promise.resolve(spendUnit)
3116
+ if (spendProbe === null) {
3117
+ spendProbe = probeSpendUnit(call).then(
3118
+ (unit) => {
3119
+ spendUnit = unit
3120
+ spendProbe = null
3121
+ return unit
3122
+ },
3123
+ (): SpendUnit => {
3124
+ spendUnit = 'unavailable'
3125
+ spendProbe = null
3126
+ return 'unavailable'
3127
+ },
3128
+ )
3129
+ }
3130
+ return spendProbe
3131
+ }
3132
+
3133
+ /* ─── Reactive model ─────────────────────────────────────── */
3134
+
3135
+ /** Reactive state the sidebar view renders. Accessors keep the view reactive
3136
+ * while the model itself stays free of JSX, so its effects are exercisable
3137
+ * without a TUI renderer. */
3138
+ export type SidebarModel = {
3139
+ activeSessionID: Accessor<string>
3140
+ session: Accessor<any>
3141
+ branch: Accessor<string | null>
3142
+ /** `+N ±N −N` file counts from `vcs.status` (fallback only), null when
3143
+ * clean/unavailable. */
3144
+ gitChanges: Accessor<string | null>
3145
+ /** The rendered git row: CLI counts with `?untracked ↑ahead ↓behind` when git
3146
+ * answered, else the `vcs.status` counts, else null. */
3147
+ gitLine: Accessor<string | null>
3148
+ /** Last successful git CLI observation (counts + upstream distance), null
3149
+ * while git has never answered. */
3150
+ gitCli: Accessor<GitCliSnapshot | null>
3151
+ /** Cache hit rate + output speed of the active session's newest messages. */
3152
+ performance: Accessor<ContextPerformance | null>
3153
+ /** The rendered `Dispatch` block: live rows, the finished rollup and the
3154
+ * spend totals. Null when the session has no child (block hidden). */
3155
+ dispatch: Accessor<DispatchBlockView | null>
3156
+ /** Blocks that have content, in render order, each tagged with its spacer. */
3157
+ blocks: Accessor<SidebarBlock[]>
3158
+ hasRunning: Accessor<boolean>
3159
+ frame: Accessor<number>
3160
+ preset: Accessor<PresetInfo>
3161
+ /** Provider of the model in use, derived from the session, its transcript or
3162
+ * the host location; null when nothing resolves (the header omits it). */
3163
+ provider: Accessor<string | null>
3164
+ /** Resolved preset override map (explicit per-agent models). */
3165
+ presetOverrides: Accessor<PresetOverrides>
3166
+ /** Family cost in USD (root + delegations), null when the host cannot answer. */
3167
+ cost: Accessor<number | null>
3168
+ /** Real per-model totals from assistant messages, capped for the sidebar. */
3169
+ modelUsage: Accessor<ModelUsageCeiling>
3170
+ /** Todo rows derived from the newest completed `todowrite`, ordered + capped. */
3171
+ todo: Accessor<TodoCeiling>
3172
+ /** Local spend for `hoje` / `30d`, null when stats is unavailable/unknown.
3173
+ * Rendered as the Context block's last line, not as its own block. */
3174
+ spend: Accessor<SpendTotals | null>
3175
+ /** Context gauge; null when there is no limit or no token-carrying message. */
3176
+ contextUsage: Accessor<ContextUsage | null>
3177
+ /** Current agent and its resolved short model id (`*` = explicit override). */
3178
+ agentModel: Accessor<{ agent: string; model: string; overridden: boolean } | null>
3179
+ }
3180
+
3181
+ /** Reactive wiring behind the sidebar: refresh subscription, warm syncs, the
3182
+ * running-only spinner and the completion-toast effect. `context` stays loosely
3183
+ * typed (the host API only exists at runtime) but the refresh event names are
3184
+ * narrowed to the V2 union at the subscription site. */
3185
+ export function createSidebarModel(
3186
+ context: any,
3187
+ sessionID: () => string | undefined,
3188
+ gitExec: GitExec = defaultGitExec,
3189
+ ): SidebarModel {
3190
+ const [revision, setRevision] = createSignal(0)
3191
+ const [metricsRevision, setMetricsRevision] = createSignal(0)
3192
+ const [frame, setFrame] = createSignal(0)
3193
+ const location = resolveLocation(context)
3194
+ const activePreset = useActivePreset(context)
3195
+ const preset = activePreset.preset
3196
+ const presetOverrides = activePreset.overrides
3197
+ let observedStates = new Map<string, DelegationState>()
3198
+ let metricsDebounce: ReturnType<typeof setTimeout> | undefined
3199
+
3200
+ // Model rows walk the family's message lists, so they are coalesced instead
3201
+ // of recomputed on every event in a burst (the host publishes many per step).
3202
+ const scheduleMetrics = () => {
3203
+ if (metricsDebounce !== undefined) clearTimeout(metricsDebounce)
3204
+ metricsDebounce = setTimeout(() => {
3205
+ metricsDebounce = undefined
3206
+ setMetricsRevision((value) => value + 1)
3207
+ }, MODEL_USAGE_DEBOUNCE_MS)
3208
+ }
3209
+ const refresh = () => {
3210
+ setRevision((value) => value + 1)
3211
+ scheduleMetrics()
3212
+ }
3213
+ const activeSessionID = () => {
3214
+ const id = sessionID()
3215
+ return isValidSessionID(id) ? id : ''
3216
+ }
3217
+
3218
+ const session = createMemo(() => {
3219
+ revision()
3220
+ const id = activeSessionID()
3221
+ if (id === '') return undefined
3222
+ try {
3223
+ return context.data.session.get(id)
3224
+ } catch {
3225
+ /* session API unavailable */
3226
+ return undefined
3227
+ }
3228
+ })
3229
+
3230
+ const branch = createMemo(() => {
3231
+ revision()
3232
+ try {
3233
+ return context.data.location.vcs.info(location)?.branch?.current ?? null
3234
+ } catch {
3235
+ /* vcs API unavailable */
3236
+ return null
3237
+ }
3238
+ })
3239
+
3240
+ // Git file counts: the git CLI first (it is the only source for untracked and
3241
+ // ahead/behind), with `client.vcs.status` as the fallback when git is missing
3242
+ // or fails. The CLI probe runs at mount and on session events, behind a
3243
+ // debounce, a 5 s cooldown and a single-flight guard — no polling timer, no
3244
+ // queue. `vcs.status` is only queried while the CLI has never answered.
3245
+ // Both git signals are keyed by the session they were read for: the host
3246
+ // reuses one sidebar instance across routes, so a value observed for one
3247
+ // session must never be read as if it belonged to the next one.
3248
+ type GitChangesRead = { session: string; text: string | null }
3249
+ type GitCliRead = { session: string; snapshot: GitCliSnapshot | null }
3250
+ const [gitChangesRead, setGitChangesRead] = createSignal<GitChangesRead>({
3251
+ session: activeSessionID(),
3252
+ text: null,
3253
+ })
3254
+ const [gitCliRead, setGitCliRead] = createSignal<GitCliRead>({
3255
+ session: activeSessionID(),
3256
+ snapshot: null,
3257
+ })
3258
+ const gitChanges = createMemo(() => {
3259
+ const read = gitChangesRead()
3260
+ return read.session === activeSessionID() ? read.text : null
3261
+ })
3262
+ const gitCli = createMemo(() => {
3263
+ const read = gitCliRead()
3264
+ return read.session === activeSessionID() ? read.snapshot : null
3265
+ })
3266
+ let gitRequest = 0
3267
+ let gitDebounce: ReturnType<typeof setTimeout> | undefined
3268
+ let gitProbeDebounce: ReturnType<typeof setTimeout> | undefined
3269
+ let gitProbeSessionID = activeSessionID()
3270
+ let gitProbeStartedAt: number | null = null
3271
+ let gitProbeInFlight = false
3272
+ let disposed = false
3273
+ const loadGitChanges = async () => {
3274
+ const status = vcsStatusCall(context)
3275
+ if (status === null) return
3276
+ const session = activeSessionID()
3277
+ const request = ++gitRequest
3278
+ try {
3279
+ const result = await status({ location: { directory: resolveSidebarCwd(context) } })
3280
+ // Superseded by a newer request, or by a session switch.
3281
+ if (request !== gitRequest || session !== activeSessionID()) return
3282
+ const files = Array.isArray(result?.data) ? result.data : Array.isArray(result) ? result : []
3283
+ setGitChangesRead({ session, text: formatGitChanges(files) })
3284
+ } catch {
3285
+ /* vcs.status unavailable or failed — keep the previous counts */
3286
+ }
3287
+ }
3288
+ const runGitProbe = async () => {
3289
+ const session = activeSessionID()
3290
+ // A different session invalidates the previous 5 s cooldown and any flight
3291
+ // started for the old one: the new directory is probed right away instead
3292
+ // of waiting out a window observed elsewhere.
3293
+ if (session !== gitProbeSessionID) {
3294
+ gitProbeSessionID = session
3295
+ gitProbeStartedAt = null
3296
+ gitProbeInFlight = false
3297
+ }
3298
+ if (
3299
+ !gitProbeAllowed({
3300
+ now: Date.now(),
3301
+ lastRunAt: gitProbeStartedAt,
3302
+ inFlight: gitProbeInFlight,
3303
+ })
3304
+ ) {
3305
+ return // cooldown or a probe still running — no queue, skip this one
3306
+ }
3307
+ gitProbeInFlight = true
3308
+ gitProbeStartedAt = Date.now()
3309
+ try {
3310
+ const snapshot = await readGitSnapshot(resolveSidebarCwd(context), gitExec)
3311
+ // A result read for another session must not land on this one.
3312
+ if (!disposed && session === activeSessionID()) setGitCliRead({ session, snapshot })
3313
+ } catch {
3314
+ /* git CLI unavailable — the vcs.status fallback stays in charge */
3315
+ } finally {
3316
+ if (session === gitProbeSessionID) gitProbeInFlight = false
3317
+ }
3318
+ }
3319
+ const scheduleGitChanges = () => {
3320
+ if (vcsStatusCall(context) === null) return
3321
+ if (gitCli() !== null) return // the CLI is authoritative once it answered
3322
+ if (gitDebounce !== undefined) clearTimeout(gitDebounce)
3323
+ gitDebounce = setTimeout(() => {
3324
+ gitDebounce = undefined
3325
+ void loadGitChanges()
3326
+ }, GIT_CHANGES_DEBOUNCE_MS)
3327
+ }
3328
+ const scheduleGitProbe = () => {
3329
+ if (gitProbeDebounce !== undefined) clearTimeout(gitProbeDebounce)
3330
+ gitProbeDebounce = setTimeout(() => {
3331
+ gitProbeDebounce = undefined
3332
+ void runGitProbe()
3333
+ }, GIT_CLI_DEBOUNCE_MS)
3334
+ }
3335
+ // One rendered git line. A CLI snapshot wins even when it is clean (the
3336
+ // protocol fallback is not consulted then); `vcs.status` is used only while
3337
+ // the CLI has never answered.
3338
+ const gitLine = createMemo(() => {
3339
+ const snapshot = gitCli()
3340
+ if (snapshot !== null) return formatGitSnapshot(snapshot)
3341
+ return gitChanges()
3342
+ })
3343
+
3344
+ // A session switch discards the previous observations (both git accessors are
3345
+ // session-keyed, so a late answer is unreadable rather than merely ignored) and
3346
+ // asks both sources again immediately: the new directory never waits out the
3347
+ // cooldown observed for the old one. Observations kept by the completion toast
3348
+ // are dropped by that effect's own session guard.
3349
+ createEffect(
3350
+ on(
3351
+ activeSessionID,
3352
+ (id) => {
3353
+ if (disposed || id === '') return
3354
+ void runGitProbe()
3355
+ void loadGitChanges()
3356
+ },
3357
+ { defer: true },
3358
+ ),
3359
+ )
3360
+
3361
+ // Spend reads the local server's own aggregate (`session.stats`): two calls
3362
+ // per refresh, one per window, in parallel. Never a provider request, never a
3363
+ // credential read, never an interval. The `from`/`to` unit is measured by a
3364
+ // single probe at mount (see `probeSpendUnit`); while it is unresolved or
3365
+ // unavailable the Context footer line stays hidden. A failed window keeps its
3366
+ // last good value, so a partial failure still renders the other window.
3367
+ const [spend, setSpend] = createSignal<SpendTotals | null>(null)
3368
+ let spendTotals: SpendTotals = { today: null, thirtyDays: null }
3369
+ let spendRequest = 0
3370
+ let spendDebounce: ReturnType<typeof setTimeout> | undefined
3371
+ const loadSpend = async () => {
3372
+ const stats = statsCall(context)
3373
+ if (stats === null) return
3374
+ try {
3375
+ const unit = await ensureSpendUnit(stats)
3376
+ if (unit === 'unavailable') return
3377
+ const request = ++spendRequest
3378
+ const windows = spendWindows(Date.now())
3379
+ const settled = await Promise.allSettled([
3380
+ stats({
3381
+ ...statsInput(),
3382
+ from: spendInstant(windows.today.from, unit),
3383
+ to: spendInstant(windows.today.to, unit),
3384
+ }),
3385
+ stats({
3386
+ ...statsInput(),
3387
+ from: spendInstant(windows.thirtyDays.from, unit),
3388
+ to: spendInstant(windows.thirtyDays.to, unit),
3389
+ }),
3390
+ ])
3391
+ if (request !== spendRequest) return // superseded by a newer refresh
3392
+ const next: SpendTotals = { ...spendTotals }
3393
+ for (const [index, key] of (['today', 'thirtyDays'] as const).entries()) {
3394
+ const result = settled[index]
3395
+ if (result === undefined || result.status !== 'fulfilled') continue
3396
+ const cost = statsCost(result.value)
3397
+ if (cost === null) continue // malformed/negative — keep the last good value
3398
+ next[key] = cost
3399
+ }
3400
+ spendTotals = next
3401
+ setSpend(next)
3402
+ } catch {
3403
+ /* experimental route gone — keep the last good values (block hidden if none) */
3404
+ }
3405
+ }
3406
+ const scheduleSpend = () => {
3407
+ if (statsCall(context) === null) return
3408
+ if (spendDebounce !== undefined) clearTimeout(spendDebounce)
3409
+ spendDebounce = setTimeout(() => {
3410
+ spendDebounce = undefined
3411
+ void loadSpend()
3412
+ }, SPEND_REFRESH_DEBOUNCE_MS)
3413
+ }
3414
+
3415
+ // Messages feed the context gauge. `message.list` is synchronous and returns
3416
+ // the host's cached list; a missing API degrades to an empty window.
3417
+ const messages = createMemo(() => {
3418
+ revision()
3419
+ const id = activeSessionID()
3420
+ if (id === '') return []
3421
+ try {
3422
+ const result = context.data.session.message?.list?.(id)
3423
+ return Array.isArray(result) ? result : []
3424
+ } catch {
3425
+ return []
3426
+ }
3427
+ })
3428
+
3429
+ // Root + delegation sessions, deduped and bounded. `family()` returns ids
3430
+ // (not SessionInfo), so each child is resolved through `session.get`.
3431
+ const familySessionIDs = createMemo(() => {
3432
+ revision()
3433
+ const id = activeSessionID()
3434
+ if (id === '') return []
3435
+ const ids = [id]
3436
+ try {
3437
+ const result = context.data.session.family?.(id)
3438
+ if (Array.isArray(result)) {
3439
+ for (const childID of result) {
3440
+ if (!isValidSessionID(childID) || ids.includes(childID)) continue
3441
+ ids.push(childID)
3442
+ if (ids.length >= MODEL_USAGE_SESSION_LIMIT) break
3443
+ }
3444
+ }
3445
+ } catch {
3446
+ /* family API unavailable — the root session still contributes */
3447
+ }
3448
+ return ids
3449
+ })
3450
+
3451
+ // One `message.list` call per family session feeds the real per-model
3452
+ // aggregate and the Todo block: the newest completed `todowrite` of the
3453
+ // *active* session is captured inside the same walk (a child's list is not
3454
+ // this sidebar's todo). `message.list` is the host's cached list, so this is a
3455
+ // single fetch/scan per refresh, never one per block. Each session contributes
3456
+ // at most MODEL_USAGE_MESSAGE_LIMIT entries, which keeps the walk O(limit) per
3457
+ // update.
3458
+ const transcript = createMemo(() => {
3459
+ metricsRevision()
3460
+ const rootID = activeSessionID()
3461
+ const collected: any[] = []
3462
+ let todo: TodoItem[] = []
3463
+ for (const id of familySessionIDs()) {
3464
+ let list: any[] = []
3465
+ try {
3466
+ const result = context.data.session.message?.list?.(id)
3467
+ if (Array.isArray(result)) list = result
3468
+ } catch {
3469
+ /* one unreadable session must not hide the others */
3470
+ }
3471
+ collected.push(...list.slice(-MODEL_USAGE_MESSAGE_LIMIT))
3472
+ if (id === rootID) todo = latestTodoItems(list) ?? []
3473
+ }
3474
+ return { messages: collected, todo }
3475
+ })
3476
+ const usageMessages = createMemo(() => transcript().messages)
3477
+ // Ordered + capped todo rows; empty when the transcript has no `todowrite`,
3478
+ // so the block stays hidden.
3479
+ const todo = createMemo(() => ceilingTodoItems(transcript().todo, TODO_VISIBLE_CEILING))
3480
+
3481
+ // Session cost is the host's authoritative number for the session; while a
3482
+ // session is live it already includes every assistant message. Summing the
3483
+ // family gives the true spend of the delegation tree. When no cost API is
3484
+ // reachable, the real message costs (never a price-table estimate) are the
3485
+ // fallback.
3486
+ const messageCostTotal = createMemo(() => {
3487
+ let total = 0
3488
+ for (const message of usageMessages()) {
3489
+ if (message?.type !== 'assistant') continue
3490
+ const cost = numberOrNull(message.cost)
3491
+ if (cost !== null && cost > 0) total += cost
3492
+ }
3493
+ return total
3494
+ })
3495
+
3496
+ const cost = createMemo(() => {
3497
+ revision()
3498
+ const ids = familySessionIDs()
3499
+ if (ids.length === 0) return null
3500
+ let total = 0
3501
+ let found = false
3502
+ for (const id of ids) {
3503
+ let value: unknown
3504
+ try {
3505
+ value = context.data.session.cost?.(id)
3506
+ } catch {
3507
+ value = undefined
3508
+ }
3509
+ let resolved = numberOrNull(value)
3510
+ if (resolved === null) {
3511
+ try {
3512
+ resolved = numberOrNull(context.data.session.get(id)?.cost)
3513
+ } catch {
3514
+ resolved = null
3515
+ }
3516
+ }
3517
+ if (resolved !== null && resolved >= 0) {
3518
+ total += resolved
3519
+ found = true
3520
+ }
3521
+ }
3522
+ if (found) {
3523
+ // The session cost is authoritative, but a host that has not recorded it
3524
+ // yet can still expose real message costs. Never show $0.00 next to
3525
+ // positive model rows; take the larger real number, never a price table.
3526
+ return Math.max(total, messageCostTotal())
3527
+ }
3528
+ const fallback = messageCostTotal()
3529
+ return fallback > 0 ? fallback : null
3530
+ })
3531
+
3532
+ const modelUsage = createMemo(() => {
3533
+ metricsRevision()
3534
+ return ceilingModelUsage(collectModelUsage(usageMessages()), MODEL_USAGE_VISIBLE_CEILING)
3535
+ })
3536
+
3537
+ // Resolved model reference: the session's own model first, then the agent's
3538
+ // configured model from the host, with the preset override as the last word.
3539
+ const modelRefs = createMemo(() => {
3540
+ revision()
3541
+ const current = session()
3542
+ const agent = typeof current?.agent === 'string' && current.agent !== '' ? current.agent : ''
3543
+ let agentRef: unknown
3544
+ if (agent !== '') {
3545
+ try {
3546
+ const agents = context.data.location?.agent?.list?.(location)
3547
+ if (Array.isArray(agents)) agentRef = agents.find((entry) => entry?.id === agent)?.model
3548
+ } catch {
3549
+ /* agent list unavailable */
3550
+ }
3551
+ }
3552
+ const override = agent === '' ? undefined : presetOverrides().agents[agent]?.model
3553
+ return {
3554
+ agent,
3555
+ sessionRef: current?.model,
3556
+ agentRef,
3557
+ override: typeof override === 'string' && override !== '' ? override : null,
3558
+ }
3559
+ })
3560
+
3561
+ const agentModel = createMemo(() => {
3562
+ const { agent, sessionRef, agentRef, override } = modelRefs()
3563
+ // An explicit preset override is the user's last word, so it is displayed
3564
+ // (and starred) ahead of the session/agent reference.
3565
+ const model = shortModelID(override) ?? shortModelID(sessionRef) ?? shortModelID(agentRef)
3566
+ if (model === null) return null
3567
+ return { agent, model, overridden: override !== null }
3568
+ })
3569
+
3570
+ // Provider of the model actually in use — derived, never typed: the session's
3571
+ // own model, then the newest assistant message from the transcript walk, then
3572
+ // the current agent's model in the host location (agent list first, its model
3573
+ // list for a bare id). Null when none of them answers, so the header can omit
3574
+ // it instead of inventing a name.
3575
+ const provider = createMemo(() => {
3576
+ revision()
3577
+ const fromSession = providerIDFromRef(session()?.model)
3578
+ if (fromSession !== null) return fromSession
3579
+ const list = messages()
3580
+ for (let index = list.length - 1; index >= 0; index -= 1) {
3581
+ const message = list[index]
3582
+ if (message?.type !== 'assistant') continue
3583
+ const fromMessage = providerIDFromRef(message.model)
3584
+ if (fromMessage !== null) return fromMessage
3585
+ }
3586
+ const { agentRef } = modelRefs()
3587
+ const fromAgent = providerIDFromRef(agentRef)
3588
+ if (fromAgent !== null) return fromAgent
3589
+ try {
3590
+ return providerIDFromModels(context.data.location?.model?.list?.(location), agentRef)
3591
+ } catch {
3592
+ /* model list unavailable */
3593
+ return null
3594
+ }
3595
+ })
3596
+
3597
+ const contextUsage = createMemo(() => {
3598
+ const list = messages()
3599
+ if (list.length === 0) return null
3600
+ const refs = modelRefs()
3601
+ const lastAssistant = [...list]
3602
+ .reverse()
3603
+ .find((message) => message?.type === 'assistant' && message?.model)
3604
+ const ref = lastAssistant?.model ?? refs.sessionRef ?? refs.agentRef ?? refs.override
3605
+ let limit: number | null = null
3606
+ try {
3607
+ const models = context.data.location?.model?.list?.(location)
3608
+ limit = resolveContextLimit(Array.isArray(models) ? models : [], ref)
3609
+ } catch {
3610
+ limit = null
3611
+ }
3612
+ return computeContextUsage(list, limit, session()?.revert?.messageID)
3613
+ })
3614
+
3615
+ // Telemetry that rides on the messages already in hand — no extra request.
3616
+ // The halves are deliberately separate memos: the cache hit rate comes from
3617
+ // the last assistant that carries `tokens` and never looks at the clock,
3618
+ // while the speed needs the turn (and `time.streamed`) to be measurable. One
3619
+ // half being unavailable must never blank the other.
3620
+ const cachePerformance = createMemo<number | null>(() => {
3621
+ const message = lastAssistantWithTokens(messages(), session()?.revert?.messageID)
3622
+ return message === null ? null : cacheHitPercent(message.tokens)
3623
+ })
3624
+
3625
+ // The turn the newest assistant step closes gets the host's aggregated
3626
+ // `turnTokensPerSecond` (see the helper).
3627
+ const turnPerformance = createMemo<number | null>(() => {
3628
+ const list = messages()
3629
+ let anchor = -1
3630
+ for (let index = list.length - 1; index >= 0; index--) {
3631
+ if (list[index]?.type === 'assistant') {
3632
+ anchor = index
3633
+ break
3634
+ }
3635
+ }
3636
+ return anchor === -1 ? null : turnTokensPerSecond(list, anchor)
3637
+ })
3638
+
3639
+ const performance = createMemo<ContextPerformance | null>(() => {
3640
+ const cacheHit = cachePerformance()
3641
+ const tokensPerSecond = turnPerformance()
3642
+ if (cacheHit === null && tokensPerSecond === null) return null
3643
+ return { cacheHit, tokensPerSecond }
3644
+ })
3645
+
3646
+ // Child session id → the `subagent` call that spawned it (description, agent,
3647
+ // background). This rides the transcript the sidebar already holds: one pass,
3648
+ // no request, and no `message.sync` on the children. The call is evidence for
3649
+ // *why* a child exists; when it is missing the row simply stays unclassified.
3650
+ const subagentCalls = createMemo(() => collectSubagentCalls(messages()))
3651
+
3652
+ // Delegations = every child of the active session (native task() children and
3653
+ // a dispatch's own children alike), enriched with each child's live status and
3654
+ // terminal outcome. `collectDispatch` is the same collector the
3655
+ // `pantheon.dispatch` panel renders, so the sidebar and the panel can never
3656
+ // list a child twice or disagree about its evidence; the calls map already
3657
+ // computed above is handed over so this costs no second transcript walk.
3658
+ const dispatchEntries = createMemo(() => {
3659
+ revision()
3660
+ const id = activeSessionID()
3661
+ if (id === '') return []
3662
+ return collectDispatch(context, id, { now: Date.now(), calls: subagentCalls() })
3663
+ })
3664
+
3665
+ /** What the sidebar block renders: the collector's rows, nothing else. */
3666
+ const allDelegations = createMemo(() => dispatchEntries().map((entry) => entry.view))
3667
+
3668
+ const hasRunning = createMemo(() => allDelegations().some((view) => view.state === 'running'))
3669
+
3670
+ // The whole `Dispatch` block in one memo: the live rows (newest first, capped),
3671
+ // the finished rollup per agent and the spend totals. Reading `frame()` is what
3672
+ // re-evaluates it while something runs — the spinner already ticks every 80 ms,
3673
+ // so a live row's duration advances without a second timer and an idle sidebar
3674
+ // stays static. Null when the session has no child, so the block (and its
3675
+ // spacer) never renders empty.
3676
+ const dispatch = createMemo(() => {
3677
+ frame()
3678
+ return buildDispatchBlock(allDelegations(), Date.now(), frame())
3679
+ })
3680
+
3681
+ // Which blocks render, and where a blank line goes. The conditions mirror the
3682
+ // ones in the view's own `<Show>`s — both read these same memos, so a spacer
3683
+ // can never outlive the block it separates.
3684
+ const blocks = createMemo(() => {
3685
+ const present: SidebarBlockKey[] = []
3686
+ // Context also owns the spend line, so the stats totals alone keep it up.
3687
+ if (contextBlockRows(contextUsage(), cost()) !== null || contextSpendLine(spend()) !== null) {
3688
+ present.push('context')
3689
+ }
3690
+ if (branch() !== null || gitLine() !== null) present.push('git')
3691
+ if (todo().visible.length > 0) present.push('todo')
3692
+ if (dispatch() !== null) present.push('dispatch')
3693
+ return withBlockSpacers(present)
3694
+ })
3695
+
3696
+ onMount(() => {
3697
+ const unsubscribeAll = subscribeSidebarRefresh(context, () => {
3698
+ refresh()
3699
+ scheduleGitChanges()
3700
+ scheduleGitProbe()
3701
+ scheduleSpend()
3702
+ })
3703
+ const id = activeSessionID()
3704
+ if (id !== '') {
3705
+ try {
3706
+ void Promise.resolve(context.data.session.sync(id)).then(refresh)
3707
+ } catch {
3708
+ /* sync unavailable */
3709
+ }
3710
+ try {
3711
+ void Promise.resolve(context.data.session.message?.sync?.(id)).then(refresh)
3712
+ } catch {
3713
+ /* message sync unavailable — the gauge degrades to cost-only */
3714
+ }
3715
+ }
3716
+ try {
3717
+ void Promise.resolve(context.data.location.vcs.sync(location)).then(refresh)
3718
+ } catch {
3719
+ /* vcs sync unavailable */
3720
+ }
3721
+
3722
+ void loadGitChanges()
3723
+ void runGitProbe()
3724
+ void loadSpend()
3725
+
3726
+ // Spinner ticks only while a job is running; terminal rows stay static. The
3727
+ // interval is armed on the running edge and cleared on the terminal one, so
3728
+ // an idle sidebar schedules no work at all.
3729
+ createEffect(() => {
3730
+ if (!hasRunning()) return
3731
+ const spinner = setInterval(() => setFrame((value) => value + 1), SPINNER_INTERVAL_MS)
3732
+ onCleanup(() => clearInterval(spinner))
3733
+ })
3734
+
3735
+ onCleanup(() => {
3736
+ disposed = true
3737
+ if (gitDebounce !== undefined) clearTimeout(gitDebounce)
3738
+ if (gitProbeDebounce !== undefined) clearTimeout(gitProbeDebounce)
3739
+ if (spendDebounce !== undefined) clearTimeout(spendDebounce)
3740
+ if (metricsDebounce !== undefined) clearTimeout(metricsDebounce)
3741
+ })
3742
+ onCleanup(unsubscribeAll)
3743
+ })
3744
+
3745
+ // Discrete completion toast: exactly one per running→terminal transition, and
3746
+ // never across a session switch — a state observed in one session says nothing
3747
+ // about the next one, so the snapshot is dropped with the session id.
3748
+ let observedSessionID = activeSessionID()
3749
+ createEffect(() => {
3750
+ const id = activeSessionID()
3751
+ const views = allDelegations()
3752
+ if (id !== observedSessionID) {
3753
+ observedSessionID = id
3754
+ observedStates = new Map()
3755
+ }
3756
+ if (id === '') {
3757
+ observedStates = new Map()
3758
+ return
3759
+ }
3760
+ const { completed, snapshot } = detectDelegationCompletions(
3761
+ observedStates,
3762
+ views.map((view) => ({ id: view.id, label: view.label, state: view.state })),
3763
+ )
3764
+ observedStates = snapshot
3765
+ for (const done of completed) showDelegationToast(context, done)
3766
+ })
3767
+
3768
+ return {
3769
+ activeSessionID,
3770
+ session,
3771
+ branch,
3772
+ gitChanges,
3773
+ gitLine,
3774
+ gitCli,
3775
+ performance,
3776
+ dispatch,
3777
+ blocks,
3778
+ hasRunning,
3779
+ frame,
3780
+ preset,
3781
+ provider,
3782
+ presetOverrides,
3783
+ cost,
3784
+ modelUsage,
3785
+ todo,
3786
+ spend,
3787
+ contextUsage,
3788
+ agentModel,
3789
+ }
3790
+ }
3791
+
3792
+ /* ─── Components ─────────────────────────────────────────── */
3793
+
3794
+ /** One `Context` row: an optional toned lead segment (the gauge's filled
3795
+ * cells), the value, the muted gauge tail (empty cells) and the muted unit
3796
+ * suffix (`tokens` / `of 200K` / `spent`). */
3797
+ function ContextRowView(props: { row: ContextRow; fg: string; muted: string }) {
3798
+ return (
3799
+ <box flexDirection="row">
3800
+ <Show when={props.row.lead}>{(lead) => <text fg={props.fg}>{lead()}</text>}</Show>
3801
+ <Show when={props.row.tail}>{(tail) => <text fg={props.muted}>{tail()}</text>}</Show>
3802
+ <text fg={props.fg}>{props.row.value}</text>
3803
+ <Show when={props.row.suffix}>{(suffix) => <text fg={props.muted}>{suffix()}</text>}</Show>
3804
+ </box>
3805
+ )
3806
+ }
3807
+
3808
+ /** Block title: a muted single-width glyph, then the bold label. The fixed
3809
+ * header at the top of the sidebar deliberately renders no icon. `summary` is
3810
+ * the muted tail some blocks carry (`· 2 rodando · $0.47`), so the header
3811
+ * stays one line. */
3812
+ function BlockHeader(props: {
3813
+ icon: string
3814
+ label: string
3815
+ fg: string
3816
+ muted: string
3817
+ summary?: string | null
3818
+ }) {
3819
+ return (
3820
+ <box flexDirection="row">
3821
+ <text fg={props.muted}>{`${props.icon} `}</text>
3822
+ <text fg={props.fg} attributes={1}>
3823
+ {props.label}
3824
+ </text>
3825
+ <Show when={props.summary}>
3826
+ {(summary) => <text fg={props.muted}>{`${SPEND_LINE_SEPARATOR}${summary()}`}</text>}
3827
+ </Show>
3828
+ </box>
3829
+ )
3830
+ }
3831
+
3832
+ function Sidebar(props: { context: any; sessionID?: string }) {
3833
+ const { context } = props
3834
+ const model = createSidebarModel(context, () => props.sessionID)
3835
+ const text = () => context.theme.text?.base
3836
+ const muted = () => context.theme.text?.muted ?? text()
3837
+ const tone = (value: DelegationTone) => context.theme?.text?.feedback?.[value]?.base ?? text()
3838
+ /* Single accent: in-progress uses `theme.text.feedback.warning.base` when the
3839
+ * theme ships it, so live work is the only colored row. */
3840
+ const todoFg = (status: TodoStatus) => {
3841
+ const rowTone = todoTone(status)
3842
+ if (rowTone === 'accent') return tone('warning')
3843
+ return rowTone === 'muted' ? muted() : text()
3844
+ }
3845
+ const open = (sessionID: string) => () => navigateToSession(context.ui?.router, sessionID)
3846
+ /* Spacing comes from the block list, never from the view: a block with no
3847
+ * content is simply absent there, so it leaves no orphan gap behind. */
3848
+ const block = (key: SidebarBlockKey) => model.blocks().find((entry) => entry.key === key)
3849
+ /* Read the flag live (not through a captured entry) so a block that becomes
3850
+ * the first one loses its spacer instead of keeping a stale blank line. */
3851
+ const spacer = (key: SidebarBlockKey) => block(key)?.spacer === true
3852
+ const usageRows = () => modelUsageRows(model.modelUsage().visible)
3853
+ const usageHidden = () =>
3854
+ hiddenModelUsageText(model.modelUsage().hidden, model.modelUsage().hiddenCost)
3855
+ const contextRows = () => contextBlockRows(model.contextUsage(), model.cost())
3856
+ const spendLine = () => contextSpendLine(model.spend())
3857
+ const performanceLine = () => contextPerformanceLine(model.performance())
3858
+ /* Filled cells and the percent value resolve through the same stage, so the
3859
+ * bar and its number can never disagree. */
3860
+ const gaugeFg = (row: ContextRow) => contextProgressColor(row.tone ?? 'warning', context.theme)
3861
+ const dispatchView = () => model.dispatch()
3862
+ const dispatchSummary = () => {
3863
+ const view = dispatchView()
3864
+ return view === null ? null : dispatchHeaderSummary(view.runningCount, view.totalCost)
3865
+ }
3866
+ const failedSuffix = () => failedSuffixText(dispatchView()?.failures)
3867
+
3868
+ return (
3869
+ <box flexDirection="column" width="100%" padding={1}>
3870
+ <text fg={text()} attributes={1}>{`Pantheon v${__PANTHEON_VERSION__}`}</text>
3871
+ {/* Preset plus the provider of the model in use — both derived from host
3872
+ state. The provider is dropped when nothing resolves, so the row is
3873
+ never a placeholder. */}
3874
+ <text fg={muted()}>{presetHeaderLine(model.preset().name ?? '', model.provider())}</text>
3875
+ <Show
3876
+ when={model.activeSessionID() !== '' && model.session()}
3877
+ fallback={<text fg={muted()}>{sidebarPlaceholder(props.sessionID)}</text>}
3878
+ >
3879
+ {(current: any) => (
3880
+ <text fg={text()}>{`Sessão: ${truncateLabel(current().title || current().id)}`}</text>
3881
+ )}
3882
+ </Show>
3883
+
3884
+ {/* Exactly one blank line between the fixed header and the first block, so
3885
+ the session line never touches the first gauge. Blocks carry their own
3886
+ spacer (see `withBlockSpacers`), so this never doubles. */}
3887
+ <Show when={model.blocks().length > 0}>
3888
+ <box height={1} />
3889
+ </Show>
3890
+
3891
+ {/* Context — a 12-cell gauge of the model's window, one row per model
3892
+ with real message cost > 0 (`<model> <tokens> $<cost>`), and one muted
3893
+ footer line with the local `hoje` / `30d` totals. The native block is
3894
+ disabled in cli.json, so this is the only source of the data. Only the
3895
+ gauge carries a semantic tone; labels and units stay muted. */}
3896
+ <Show when={block('context')}>
3897
+ <box flexDirection="column">
3898
+ <Show when={spacer('context')}>
3899
+ <box height={1} />
3900
+ </Show>
3901
+ <BlockHeader icon={BLOCK_ICONS.context} label="Context" fg={text()} muted={muted()} />
3902
+ <Show when={contextRows()}>
3903
+ {(rows) => (
3904
+ <box flexDirection="column">
3905
+ <Show when={rows().tokens}>
3906
+ {(row) => <ContextRowView row={row()} fg={text()} muted={muted()} />}
3907
+ </Show>
3908
+ <Show when={rows().percent}>
3909
+ {(row) => <ContextRowView row={row()} fg={gaugeFg(row())} muted={muted()} />}
3910
+ </Show>
3911
+ <Show when={rows().spent}>
3912
+ {(row) => <ContextRowView row={row()} fg={text()} muted={muted()} />}
3913
+ </Show>
3914
+ {/* Real per-model spend, only for models with cost > 0. Label muted,
3915
+ numbers right-aligned; the gauge above remains the block's
3916
+ single accent. When no message carries cost this loop is empty
3917
+ and the block keeps its original token/spend rows. */}
3918
+ <For each={usageRows()}>
3919
+ {(row: ModelUsageRow) => (
3920
+ <box flexDirection="row">
3921
+ <text fg={muted()}>{row.model.padEnd(MODEL_USAGE_MODEL_WIDTH)}</text>
3922
+ <text fg={text()}>{` ${row.tokens.padStart(MODEL_USAGE_TOKEN_WIDTH)}`}</text>
3923
+ <text fg={text()}>{` ${row.cost.padStart(MODEL_USAGE_COST_WIDTH)}`}</text>
3924
+ </box>
3925
+ )}
3926
+ </For>
3927
+ <Show when={usageHidden()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
3928
+ </box>
3929
+ )}
3930
+ </Show>
3931
+ {/* Cache hit + output speed of the newest messages: already in the
3932
+ transcript walk, so these cost no request. Muted, one line, and
3933
+ absent entirely when neither number exists. */}
3934
+ <Show when={performanceLine()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
3935
+ {/* Spend, not budget: two local windows on one muted line. Absent
3936
+ whenever stats is missing or the from/to unit probe failed. */}
3937
+ <Show when={spendLine()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
3938
+ </box>
3939
+ </Show>
3940
+
3941
+ {/* Git status — branch from the location cache; file counts from the git
3942
+ CLI (`+1 ±2 −1 ?2 ↑3 ↓1`, async, debounced, 5 s cooldown) and only
3943
+ `client.vcs.status` when git is unavailable. Untracked and
3944
+ ahead/behind exist only on the CLI path: the HTTP protocol has no
3945
+ field for either. The header renders even without a branch when the
3946
+ CLI answered, so a repo with a detached HEAD still shows its counts. */}
3947
+ <Show when={block('git')}>
3948
+ <box flexDirection="column">
3949
+ <Show when={spacer('git')}>
3950
+ <box height={1} />
3951
+ </Show>
3952
+ <BlockHeader icon={BLOCK_ICONS.git} label="Git status" fg={text()} muted={muted()} />
3953
+ <Show when={model.branch()}>
3954
+ {(value) => (
3955
+ <box flexDirection="row">
3956
+ <text fg={muted()}>{'⎇ '}</text>
3957
+ <text fg={text()}>{truncateLabel(value(), 32)}</text>
3958
+ </box>
3959
+ )}
3960
+ </Show>
3961
+ <Show when={model.gitLine()}>{(line) => <text fg={text()}>{line()}</text>}</Show>
3962
+ </box>
3963
+ </Show>
3964
+
3965
+ {/* Todo — derived from the newest completed `todowrite` in the active
3966
+ session's transcript (no todo API exists in the installed client).
3967
+ Rows are grouped in_progress → pending → completed → cancelled, capped
3968
+ at six, and every row keeps a single accent: live work only. The
3969
+ header takes `warning` so the block reads apart from the neutral
3970
+ reference blocks above it. */}
3971
+ <Show when={block('todo')}>
3972
+ <box flexDirection="column">
3973
+ <Show when={spacer('todo')}>
3974
+ <box height={1} />
3975
+ </Show>
3976
+ <Show when={model.todo().visible.length > 0}>
3977
+ <box flexDirection="column">
3978
+ <BlockHeader
3979
+ icon={BLOCK_ICONS.todo}
3980
+ label="Todo"
3981
+ fg={tone('warning')}
3982
+ muted={muted()}
3983
+ />
3984
+ <For each={model.todo().visible}>
3985
+ {(item: TodoItem) => <text fg={todoFg(item.status)}>{todoRowText(item)}</text>}
3986
+ </For>
3987
+ <Show when={hiddenTodoText(model.todo().hidden)}>
3988
+ {(line) => <text fg={muted()}>{line()}</text>}
3989
+ </Show>
3990
+ </box>
3991
+ </Show>
3992
+ </box>
3993
+ </Show>
3994
+
3995
+ {/* Dispatch — one block for the whole child set. The header carries the
3996
+ live count and the subtree's real spend; then one row per live child
3997
+ (newest first, capped at three, `… +N rodando` beyond), the aggregated
3998
+ `✓ <total> · $<soma> · <M> agentes` line of the finished ones, up to
3999
+ three per-agent rollup rows (`<agente> ×<n> $<soma>`), `… +K $<soma>`
4000
+ beyond, and `· <F> falhas` on the summary when any child failed. Every
4001
+ row is one preformatted line, so no column can be squeezed away by the
4002
+ layout; live rows navigate to the child session on click. */}
4003
+ <Show when={block('dispatch')}>
4004
+ <box flexDirection="column">
4005
+ <Show when={spacer('dispatch')}>
4006
+ <box height={1} />
4007
+ </Show>
4008
+ <Show when={dispatchView()}>
4009
+ {(view) => (
4010
+ <box flexDirection="column">
4011
+ <BlockHeader
4012
+ icon={BLOCK_ICONS.dispatch}
4013
+ label="Dispatch"
4014
+ fg={view().runningCount > 0 ? tone('success') : muted()}
4015
+ muted={muted()}
4016
+ summary={dispatchSummary()}
4017
+ />
4018
+ <For each={view().running}>
4019
+ {(row: DispatchRunningLine) => (
4020
+ <box onMouseDown={open(row.id)} flexShrink={0}>
4021
+ <text fg={tone('success')}>{row.text}</text>
4022
+ </box>
4023
+ )}
4024
+ </For>
4025
+ <Show when={view().runningHidden > 0}>
4026
+ <text fg={muted()}>{`\u2026 +${view().runningHidden} rodando`}</text>
4027
+ </Show>
4028
+ <Show when={view().summary}>
4029
+ {(line) => (
4030
+ <box flexDirection="row" flexShrink={0}>
4031
+ <text fg={muted()}>{line()}</text>
4032
+ <Show when={failedSuffix()}>
4033
+ {(suffix) => (
4034
+ <text fg={tone('error')}>{`${SPEND_LINE_SEPARATOR}${suffix()}`}</text>
4035
+ )}
4036
+ </Show>
4037
+ </box>
4038
+ )}
4039
+ </Show>
4040
+ <For each={view().agents}>
4041
+ {(row: ChildAgentUsage) => <text fg={muted()}>{childAgentRowText(row)}</text>}
4042
+ </For>
4043
+ <Show when={hiddenChildAgentsText(view().agentsHidden, view().agentsHiddenCost)}>
4044
+ {(line) => <text fg={muted()}>{line()}</text>}
4045
+ </Show>
4046
+ </box>
4047
+ )}
4048
+ </Show>
4049
+ </box>
4050
+ </Show>
4051
+ </box>
4052
+ )
4053
+ }
4054
+
4055
+ /** Panel actions that only make sense with a row selected. A panel over an
4056
+ * empty tree still owns `f`/`escape`, but the navigation keys fall through
4057
+ * instead of being swallowed by a no-op. */
4058
+ const DISPATCH_PANEL_ROW_ACTIONS: ReadonlySet<DispatchPanelAction> = new Set<DispatchPanelAction>([
4059
+ 'up',
4060
+ 'down',
4061
+ 'home',
4062
+ 'end',
4063
+ 'pageup',
4064
+ 'pagedown',
4065
+ 'toggle',
4066
+ ])
4067
+
4068
+ /** One command: runs only while the panel owns the keyboard, and reports
4069
+ * `false` (the host keeps the key) when it cannot act. `undefined` means the
4070
+ * key was consumed. */
4071
+ export function runDispatchPanelCommand(
4072
+ action: DispatchPanelAction,
4073
+ panel: Pick<PanelInput, 'focused' | 'close' | 'toggleFullscreen'>,
4074
+ model: Pick<
4075
+ DispatchPanelModel,
4076
+ 'rows' | 'move' | 'first' | 'last' | 'pageUp' | 'pageDown' | 'toggle'
4077
+ >,
4078
+ ): false | undefined {
4079
+ if (panel.focused !== true) return false
4080
+ if (DISPATCH_PANEL_ROW_ACTIONS.has(action) && model.rows().length === 0) return false
4081
+ performDispatchPanelAction(action, model, panel)
4082
+ return undefined
4083
+ }
4084
+
4085
+ /** Keymap layer of the panel, as data. It is registered inside the
4086
+ * `session.panel` claim, but the host mounts the effects of *every* panel
4087
+ * contribution, so the layer itself is not proof of focus: without `enabled`
4088
+ * the `j/k/f/q/enter/escape` bindings were consumed while the panel was not
4089
+ * focused and the composer lost its keys. `enabled` (the documented gate) makes
4090
+ * the whole layer inert until `panel.focused` is true. Pure. */
4091
+ export function dispatchPanelKeymapLayer(
4092
+ panel: Pick<PanelInput, 'focused' | 'close' | 'toggleFullscreen'>,
4093
+ model: DispatchPanelModel,
4094
+ ): KeymapLayer {
4095
+ const focused = () => panel.focused === true
4096
+ return {
4097
+ mode: 'global',
4098
+ enabled: focused,
4099
+ commands: DISPATCH_PANEL_COMMANDS.map((spec) => ({
4100
+ id: spec.id,
4101
+ title: spec.title,
4102
+ bind: spec.bind,
4103
+ run: () => (focused() ? runDispatchPanelCommand(spec.action, panel, model) : false),
4104
+ })),
4105
+ }
4106
+ }
4107
+
4108
+ /** Keymap layer of the panel. Created inside the `session.panel` claim, so the
4109
+ * host removes it with the panel; it renders nothing. */
4110
+ function DispatchPanelKeymap(props: {
4111
+ context: any
4112
+ panel: PanelInput
4113
+ model: DispatchPanelModel
4114
+ }) {
4115
+ props.context.keymap.layer(() => dispatchPanelKeymapLayer(props.panel, props.model))
4116
+ return null
4117
+ }
4118
+
4119
+ // TODO(dispatch panel): jumping to the selected child session. `ui.router` only
4120
+ // has the destination shape verified for the sidebar's click-through
4121
+ // (`navigateToSession`), and no verified destination exists for a *child* id
4122
+ // from inside a session route — so panel rows stay non-interactive and the
4123
+ // detail prints the short id instead. Revisit once the router API for `session`
4124
+ // destinations is verified against the installed host.
4125
+ /** The full-width dispatch panel: header counters, one row per child session,
4126
+ * the detail of the selected child and the key hints. Wide panels put the
4127
+ * detail beside the list; narrow ones stack it under the list and every cell is
4128
+ * truncated to its own column instead of wrapping. */
4129
+ function DispatchPanel(props: { context: any; panel: PanelInput }) {
4130
+ const model = createDispatchPanelModel(props.context, () => props.panel)
4131
+ const text = () => props.context.theme.text?.base
4132
+ const muted = () => props.context.theme.text?.muted ?? text()
4133
+ const tone = (value: DelegationTone) =>
4134
+ props.context.theme?.text?.feedback?.[value]?.base ?? text()
4135
+ const rowFg = (state: DelegationState) => {
4136
+ if (state === 'failed') return tone('error')
4137
+ if (state === 'running') return tone('success')
4138
+ if (state === 'interrupted') return tone('warning')
4139
+ return text()
4140
+ }
4141
+ const selected = (id: string) => id === model.selectedID()
4142
+ const rows = () => (
4143
+ <For each={model.visible().rows}>
4144
+ {(row: DispatchPanelRow) => (
4145
+ <box flexDirection="row" flexShrink={0}>
4146
+ <text fg={selected(row.id) ? text() : muted()}>
4147
+ {selected(row.id) ? `${DISPATCH_PANEL_SELECTION_MARKER} ` : ' '}
4148
+ </text>
4149
+ <text fg={rowFg(row.state)} attributes={selected(row.id) ? 1 : 0}>
4150
+ {row.text}
4151
+ </text>
4152
+ </box>
4153
+ )}
4154
+ </For>
4155
+ )
4156
+ const detail = () => (
4157
+ <For each={model.detail()}>
4158
+ {(line: string, index: () => number) => (
4159
+ <text fg={index() === 0 ? text() : muted()}>{line}</text>
4160
+ )}
4161
+ </For>
4162
+ )
4163
+ const empty = () => <text fg={muted()}>{DISPATCH_PANEL_EMPTY_TEXT}</text>
4164
+
4165
+ return (
4166
+ <box flexDirection="column" width="100%" padding={1}>
4167
+ <DispatchPanelKeymap context={props.context} panel={props.panel} model={model} />
4168
+ {/* `◈ Dispatch — <sessão>` then the counters of the whole tree; a counter
4169
+ that is zero is absent, and an empty tree renders no counter line. */}
4170
+ <text fg={text()} attributes={1}>
4171
+ {model.title()}
4172
+ </text>
4173
+ <Show when={model.header()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
4174
+ <text fg={muted()}>{dispatchPanelRule(props.panel.width - 2)}</text>
4175
+ <Show
4176
+ when={model.layout().mode === 'wide'}
4177
+ fallback={
4178
+ <box flexDirection="column">
4179
+ <Show when={model.rows().length > 0} fallback={empty()}>
4180
+ <box flexDirection="column">{rows()}</box>
4181
+ </Show>
4182
+ <Show when={model.selectedID()}>
4183
+ <box flexDirection="column">
4184
+ <box height={1} />
4185
+ {detail()}
4186
+ </box>
4187
+ </Show>
4188
+ </box>
4189
+ }
4190
+ >
4191
+ <box flexDirection="row">
4192
+ <box flexDirection="column" width={model.layout().listWidth}>
4193
+ <Show when={model.rows().length > 0} fallback={empty()}>
4194
+ {rows()}
4195
+ </Show>
4196
+ </box>
4197
+ {/* No selected child (an empty tree) → no detail column at all, so an
4198
+ empty panel never renders a dangling em dash beside the list. */}
4199
+ <Show when={model.selectedID()}>
4200
+ <box flexDirection="column" width={model.layout().detailWidth}>
4201
+ {detail()}
4202
+ </box>
4203
+ </Show>
4204
+ </box>
4205
+ </Show>
4206
+ <box height={1} />
4207
+ <text fg={muted()}>{model.footer()}</text>
4208
+ </box>
4209
+ )
4210
+ }
4211
+
4212
+ /** App-level command claim: the only way into the panel. It registers the
4213
+ * `pantheon.dispatch.open` command (palette + `/dispatch`) and renders nothing;
4214
+ * the panel itself lives behind its own `session.panel` claim. */
4215
+ function DispatchCommandLayer(props: { context: any }) {
4216
+ props.context.keymap.layer(() => ({
4217
+ mode: 'global',
4218
+ commands: [
4219
+ {
4220
+ id: 'pantheon.dispatch.open',
4221
+ title: 'Pantheon: Dispatch',
4222
+ group: 'Pantheon',
4223
+ palette: true,
4224
+ slash: { name: 'dispatch', aliases: ['pantheon-dispatch'] },
4225
+ run: () => {
4226
+ openDispatchPanel(props.context)
4227
+ },
4228
+ },
4229
+ ],
4230
+ }))
4231
+ return null
4232
+ }
4233
+
4234
+ /** Home-screen status contribution. The sidebar slot is session-scoped, so
4235
+ * before the first prompt the sidebar may not mount at all (Known Issue) —
4236
+ * this keeps a compact Pantheon line visible on the home footer meanwhile. */
4237
+ function HomeStatus(props: { context: any }) {
4238
+ const preset = useActivePreset(props.context).preset
4239
+ const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base
4240
+ return (
4241
+ <text
4242
+ fg={muted()}
4243
+ >{`Pantheon v${__PANTHEON_VERSION__}${preset().name ? ` ${PRESET_MARKER} ${preset().name}` : ''}`}</text>
4244
+ )
4245
+ }
4246
+
4247
+ /** Lean footer model: only the preset label and the live delegation count. It
4248
+ * deliberately does not reuse `createSidebarModel` — that model owns the
4249
+ * completion toasts and the spinner, and a second instance would double-toast.
4250
+ * No session id in the slot input is a graceful no-op (count 0). */
4251
+ export type FooterModel = {
4252
+ preset: Accessor<PresetInfo>
4253
+ running: Accessor<number>
4254
+ }
4255
+
4256
+ export function createFooterModel(context: any, sessionID: () => string | undefined): FooterModel {
4257
+ const [revision, setRevision] = createSignal(0)
4258
+ const preset = useActivePreset(context).preset
4259
+ const activeSessionID = () => {
4260
+ const id = sessionID()
4261
+ return isValidSessionID(id) ? id : ''
4262
+ }
4263
+
4264
+ const running = createMemo(() => {
4265
+ revision()
4266
+ const id = activeSessionID()
4267
+ if (id === '') return 0
4268
+ let family: string[] = []
4269
+ try {
4270
+ const result = context.data.session.family?.(id)
4271
+ if (Array.isArray(result)) family = result
4272
+ } catch {
4273
+ return 0
4274
+ }
4275
+ const now = Date.now()
4276
+ let count = 0
4277
+ for (const childID of family) {
4278
+ if (childID === id || !isValidSessionID(childID)) continue
4279
+ try {
4280
+ const child = context.data.session.get(childID)
4281
+ if (child?.parentID !== id) continue
4282
+ const view = toDelegationView(child, sessionStatusOf(context, childID), now)
4283
+ if (view.state === 'running') count += 1
4284
+ } catch {
4285
+ /* one unreadable child must not hide the rest */
4286
+ }
4287
+ }
4288
+ return count
4289
+ })
4290
+
4291
+ onMount(() => {
4292
+ onCleanup(subscribeSidebarRefresh(context, () => setRevision((value) => value + 1)))
4293
+ })
4294
+
4295
+ return { preset, running }
4296
+ }
4297
+
4298
+ /** Prompt-footer contribution: `▸<preset> · ✦<n> ativos`, appended next to the
4299
+ * native line (never replacing it) and only while a delegation is running. */
4300
+ function PromptFooter(props: { context: any; sessionID?: string | undefined }) {
4301
+ const model = createFooterModel(props.context, () => props.sessionID)
4302
+ const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base
4303
+ return (
4304
+ <Show when={model.running() > 0}>
4305
+ <text fg={muted()}>
4306
+ {`${PRESET_MARKER}${model.preset().name ?? 'default'} · ✦${model.running()} ativos`}
4307
+ </text>
4308
+ </Show>
4309
+ )
4310
+ }
4311
+
4312
+ /* ─── Plugin registration ────────────────────────────────── */
4313
+
4314
+ const plugin = Plugin.define({
4315
+ id: 'pantheon.tui',
4316
+ setup(context: Context) {
4317
+ const globalState = globalThis as unknown as Record<PropertyKey, unknown>
4318
+ if (globalState[SINGLETON]) return
4319
+ globalState[SINGLETON] = true
4320
+
4321
+ const location = resolveLocation(context)
4322
+ // Eager load/sync at setup so the cache is warm before the slot's first
4323
+ // render (Known Issue: empty sidebar before the first prompt).
4324
+ warmUpSidebarData(context, location)
4325
+
4326
+ const unregisterSidebar = context.ui.slot({
4327
+ append: 'sidebar.content',
4328
+ render: ({ sessionID }: { sessionID: string }) => (
4329
+ <Sidebar context={context} sessionID={sessionID} />
4330
+ ),
4331
+ })
4332
+ const unregisterHome = context.ui.slot({
4333
+ append: 'home.footer.status',
4334
+ render: () => <HomeStatus context={context} />,
4335
+ })
4336
+ // Additive claim: the native prompt footer keeps its own tokens/cost line.
4337
+ const unregisterPromptFooter = context.ui.slot({
4338
+ append: 'prompt.footer',
4339
+ render: ({ sessionID }: { sessionID?: string }) => (
4340
+ <PromptFooter context={context} sessionID={sessionID} />
4341
+ ),
4342
+ })
4343
+ // The dispatch panel is a session-scoped slot: the claim renders only when
4344
+ // the host's selected panel is ours, and the host keeps `focused`, `close`
4345
+ // and `toggleFullscreen` (the panel never steals focus or routing).
4346
+ const unregisterPanel = context.ui.slot({
4347
+ append: 'session.panel',
4348
+ render: (panel) => (
4349
+ <Show when={panel.name === DISPATCH_PANEL_NAME}>
4350
+ <DispatchPanel context={context} panel={panel} />
4351
+ </Show>
4352
+ ),
4353
+ })
4354
+ // Command layer: an additive claim at `app` that renders nothing and only
4355
+ // registers the keymap layer, so `/dispatch` and the palette entry exist
4356
+ // even while no panel is open.
4357
+ const unregisterCommands = context.ui.slot({
4358
+ append: 'app',
4359
+ render: () => <DispatchCommandLayer context={context} />,
4360
+ })
4361
+ return () => {
4362
+ if (typeof unregisterSidebar === 'function') unregisterSidebar()
4363
+ if (typeof unregisterHome === 'function') unregisterHome()
4364
+ if (typeof unregisterPromptFooter === 'function') unregisterPromptFooter()
4365
+ if (typeof unregisterPanel === 'function') unregisterPanel()
4366
+ if (typeof unregisterCommands === 'function') unregisterCommands()
4367
+ delete globalState[SINGLETON]
4368
+ }
4369
+ },
4370
+ })
4371
+
4372
+ export default plugin