pantheon-opencode 1.7.0 → 2.0.0-beta.2

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