pantheon-opencode 1.5.0-beta.9 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/AGENTS.md +14 -63
  2. package/CHANGELOG.md +304 -0
  3. package/README.md +14 -27
  4. package/README.pt-BR.md +5 -6
  5. package/commands/pantheon.md +1 -35
  6. package/package.json +1 -2
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +2 -5
  9. package/scripts/doctor.mjs +32 -3
  10. package/scripts/install/plugin.mjs +9 -12
  11. package/scripts/mcp_persistence_server.py +1 -1
  12. package/scripts/sync-tui.mjs +8 -11
  13. package/src/agents/apollo.md +1 -0
  14. package/src/agents/gaia.md +1 -0
  15. package/src/agents/zeus.md +9 -52
  16. package/src/instructions/memory-protocol.instructions.md +6 -3
  17. package/src/instructions/zeus-anti-stall.instructions.md +2 -4
  18. package/src/instructions/zeus-council-synthesis.instructions.md +3 -28
  19. package/src/instructions/zeus-timeout-retry.instructions.md +3 -28
  20. package/src/mcp/mcp_persistence_server.py +1 -1
  21. package/src/mcp/toon_codec.py +2 -4
  22. package/src/pantheon/background-job-board.ts +4 -4
  23. package/src/pantheon/{delegation-compaction.ts → compaction-context.ts} +10 -100
  24. package/src/pantheon/cost-command.ts +1 -2
  25. package/src/pantheon/delegation-enforce.ts +59 -14
  26. package/src/pantheon/goal-loop.ts +1 -1
  27. package/src/pantheon/goal-store.ts +1 -1
  28. package/src/pantheon/idle-continuation.ts +4 -6
  29. package/src/pantheon/model-command.ts +1 -2
  30. package/src/pantheon/native-task-status.ts +2 -2
  31. package/src/pantheon/presets.d.mts +0 -20
  32. package/src/pantheon/presets.mjs +0 -64
  33. package/src/pantheon/session-guard.ts +2 -2
  34. package/src/pantheon/session-id.ts +30 -0
  35. package/src/pantheon/task-result-guard.ts +2 -3
  36. package/src/pantheon/todo-enforcer.ts +3 -3
  37. package/src/pantheon/tool-context.ts +23 -0
  38. package/src/pantheon/v2-bridge.ts +1 -4
  39. package/src/plugin-v2.ts +8 -21
  40. package/src/plugin.ts +61 -245
  41. package/src/plugins/pantheon-hooks.ts +1 -1
  42. package/src/plugins/tui/dist/tui.d.ts +212 -81
  43. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  44. package/src/plugins/tui/dist/tui.js +475 -254
  45. package/src/plugins/tui/package-lock.json +2 -2
  46. package/src/plugins/tui/package.json +2 -2
  47. package/src/plugins/tui/src/index.tsx +667 -269
  48. package/src/routing.yml +0 -16
  49. package/src/skills/context-compression/SKILL.md +1 -1
  50. package/scripts/generate-preset-docs.mjs +0 -300
  51. package/scripts/generate-prompts.sh +0 -222
  52. package/scripts/hash_verify.py +0 -192
  53. package/scripts/install/component.mjs +0 -24
  54. package/scripts/install/migrate-config.mjs +0 -302
  55. package/scripts/test-context-compression.sh +0 -169
  56. package/src/pantheon/auto-wake.ts +0 -85
  57. package/src/pantheon/chat-reminders.ts +0 -9
  58. package/src/pantheon/comment-checker.ts +0 -48
  59. package/src/pantheon/compaction-assert.ts +0 -160
  60. package/src/pantheon/compaction-handoff.ts +0 -304
  61. package/src/pantheon/cost-tracker.ts +0 -108
  62. package/src/pantheon/delegate-manager.ts +0 -766
  63. package/src/pantheon/delegation-classifier.ts +0 -307
  64. package/src/pantheon/delegation-finalize.ts +0 -406
  65. package/src/pantheon/delegation-notify.ts +0 -212
  66. package/src/pantheon/delegation-toast.ts +0 -73
  67. package/src/pantheon/delegation.ts +0 -1337
  68. package/src/pantheon/dispatch-guard.ts +0 -109
  69. package/src/pantheon/native-probe.ts +0 -234
  70. package/src/pantheon/permission-eval.ts +0 -284
  71. package/src/pantheon/preemptive-compact.ts +0 -76
  72. package/src/pantheon/provider-capabilities.ts +0 -221
  73. package/src/pantheon/provider-stream-tracker.ts +0 -182
  74. package/src/pantheon/retry-policy.ts +0 -212
  75. package/src/pantheon/step-cap.ts +0 -110
  76. package/src/pantheon/token-opt.ts +0 -689
  77. package/src/pantheon/toon-codec.ts +0 -481
  78. package/src/pantheon/v2-events.ts +0 -148
  79. package/src/pantheon/v2-hooks.ts +0 -287
  80. package/src/pantheon/v2-tool-definitions.ts +0 -331
  81. package/src/pantheon/zeus-delegate-with-retry.ts +0 -406
  82. package/src/plugins/tui/dist/tui.tsx +0 -2853
@@ -1,2853 +0,0 @@
1
- // biome-ignore-all lint/suspicious/noExplicitAny: necessary for TuiPluginApi dynamic state access
2
- // biome-ignore-all lint/a11y/noStaticElementInteractions: TUI elements, not DOM
3
- /** @jsxImportSource @opentui/solid */
4
-
5
- /**
6
- * pantheon-tui — Pantheon TUI plugin for opencode.
7
- *
8
- * Single self-contained entry file: `tsdown && cp src/index.tsx dist/tui.tsx`
9
- * keeps the no-build load path working (dist/tui.tsx is raw source, transpiled
10
- * on the fly by opencode). All feature code lives in this one file.
11
- *
12
- * Slots:
13
- * - sidebar_content (order 900) — Pantheon sidebar (header/version/
14
- * branch, Sessions, real-time Delegations panel).
15
- * - app_bottom (order 60) — AI subscription usage gauges
16
- * (Anthropic/OpenAI quotas, OpenCode Go/Zen dollar limits + provider
17
- * status incidents).
18
- *
19
- * ─────────────────────────────────────────────────────────────────────────────
20
- * VENDORED FEATURES (MIT) — incorporated with their license headers preserved:
21
- *
22
- * • satas20/opencode-usage-bar (MIT)
23
- * https://github.com/satas20/opencode-usage-bar
24
- *
25
- * v1.2.0 added an OpenCode Go/Zen usage provider (`opencodego`) on top of
26
- * the vendored base — dollar-denominated rolling limits ($12/5h, $30/7d,
27
- * $60/month) via the same key used for inference. Still MIT-credited to
28
- * satas20 for the original bar/config/poll code.
29
- *
30
- * satas20/opencode-todo-progress was vendored in v1.1.0 alongside the
31
- * usage-bar but has since been REMOVED as redundant — the native session
32
- * footer already surfaces todo/context state, so its todo bar slot was
33
- * dropped entirely. Only usage-bar code remains.
34
- * ─────────────────────────────────────────────────────────────────────────────
35
- *
36
- * LIMITATION — native context/tokens statusline:
37
- * The opencode session footer natively shows a context/tokens statusline
38
- * next to the prompt. There is NO config option to hide it: the tui.json
39
- * schema (opencode.ai/tui.json) only exposes `theme`, `keybinds`,
40
- * `scroll_speed`, `scroll_acceleration`, `diff_style`, `mouse` and
41
- * `attention`, and the SDK `Config` type has no statusline/tokens display
42
- * flag (checked against @opencode-ai/sdk `Config` and the published
43
- * schema). The Pantheon sidebar therefore no longer duplicates that footer
44
- * (the old ContextBar was removed) and we deliberately do NOT hack the
45
- * native footer. Track upstream: opencode statusline config.
46
- */
47
-
48
- import { Buffer } from 'node:buffer'
49
- import type { Dirent } from 'node:fs'
50
- import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
51
- import { homedir } from 'node:os'
52
- import { dirname, join } from 'node:path'
53
- import { fileURLToPath } from 'node:url'
54
- import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from '@opencode-ai/plugin/tui'
55
- import {
56
- createEffect,
57
- createMemo,
58
- createResource,
59
- createSignal,
60
- For,
61
- onCleanup,
62
- onMount,
63
- Show,
64
- } from 'solid-js'
65
-
66
- // ─── Double-load guard (mirrors src/pantheon/plugin-once.ts) ───────────────
67
- // Opencode merges global + project plugin paths, so this module can load twice
68
- // in one process. The second factory invocation becomes a no-op.
69
- const __tuiPluginOnceKey = '__pantheonPluginsLoaded'
70
- function pantheonPluginOnce(key: string): boolean {
71
- try {
72
- const g = globalThis as unknown as Record<string, unknown>
73
- if (g[__tuiPluginOnceKey] === undefined) g[__tuiPluginOnceKey] = new Set<string>()
74
- const set = g[__tuiPluginOnceKey]
75
- if (!(set instanceof Set)) return false
76
- if ((set as Set<string>).has(key)) return true
77
- ;(set as Set<string>).add(key)
78
- return false
79
- } catch {
80
- return false
81
- }
82
- }
83
-
84
- /* ─── Constants ─────────────────────────────────────────── */
85
-
86
- /** How often the sidebar re-reads .pantheon/active-preset.json so `set-tier`
87
- * changes made while opencode is open show up within ~30s. */
88
- const PRESET_REFRESH_MS = 30_000
89
-
90
- /* ─── Helpers ───────────────────────────────────────────── */
91
-
92
- /* ─── Active Preset Detection ──────────────────────────────
93
- * Inline replica of src/pantheon/presets.mjs resolveActivePreset() — the TUI
94
- * plugin is self-contained (dist/tui.tsx is a raw copy of this file with no
95
- * relative imports), so the resolution logic is mirrored here rather than
96
- * importing presets.mjs.
97
- *
98
- * Priority: env PANTHEON_MODEL_PRESET > first existing candidate file > none.
99
- * Custom/unknown preset names are shown as-is (a preset may be defined that
100
- * is not in the built-in list). "none" disables → default. */
101
-
102
- type PresetInfo = { name: string | null; source: 'env' | 'file' | null }
103
-
104
- /** Read .pantheon/active-preset.json — mirrors the presets.mjs file leg:
105
- * first existing candidate wins; malformed JSON or a `preset` that is
106
- * missing, empty or "none" → null (no fall-through to lower candidates). */
107
- async function readActivePresetFile(cwd: string): Promise<{ name: string; source: 'file' } | null> {
108
- const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config')
109
- const candidates = [
110
- join(cwd, '.pantheon', 'active-preset.json'),
111
- join(xdgConfig, 'opencode', '.pantheon', 'active-preset.json'),
112
- join(homedir(), '.opencode', '.pantheon', 'active-preset.json'),
113
- ]
114
- for (const candidate of candidates) {
115
- let raw: string
116
- try {
117
- raw = await readFile(candidate, 'utf8')
118
- } catch {
119
- continue // candidate does not exist — try the next one
120
- }
121
- try {
122
- const parsed = JSON.parse(raw) as { preset?: unknown }
123
- const name = parsed && typeof parsed === 'object' ? parsed.preset : undefined
124
- if (typeof name !== 'string' || name.length === 0 || name === 'none') return null
125
- return { name, source: 'file' }
126
- } catch {
127
- return null // malformed file — treat as default (mirrors presets.mjs)
128
- }
129
- }
130
- return null
131
- }
132
-
133
- /** Env leg of resolution: PANTHEON_MODEL_PRESET set and !== 'none' wins. */
134
- function presetFromEnv(env: Record<string, string | undefined>): PresetInfo {
135
- const name = env.PANTHEON_MODEL_PRESET
136
- if (name !== undefined && name !== '' && name !== 'none') {
137
- return { name, source: 'env' }
138
- }
139
- return { name: null, source: null }
140
- }
141
-
142
- /** Resolve the active preset for the sidebar: env > file > default. */
143
- async function resolvePresetForTui(
144
- env: Record<string, string | undefined>,
145
- cwd: string,
146
- ): Promise<PresetInfo> {
147
- const envPreset = presetFromEnv(env)
148
- if (envPreset.source === 'env') return envPreset
149
- return (await readActivePresetFile(cwd)) ?? { name: null, source: null }
150
- }
151
-
152
- /* ─── Version Detection ────────────────────────────────────
153
- * 100% dinâmico — fallback embutido em build (__PANTHEON_VERSION__).
154
- * Se falhar, retorna null e a View omite a versão.
155
- *
156
- * Try order:
157
- * 0a. pantheon-tui/package.json (installed: dist/tui.js → 2 níveis)
158
- * 0b. pantheon/package.json (dev: src/plugins/tui/dist/tui.tsx → 4 níveis)
159
- * 1. api.client.file.read package.json
160
- * 2. git describe --tags
161
- * 3. opencode --version
162
- * 4. __PANTHEON_VERSION__ (tsdown define — build-time embed)
163
- * 5. null */
164
-
165
- // Build-time embedded version (tsdown `define` in tsdown.config.ts). Injected
166
- // only into the bundled dist/tui.js; the raw dist/tui.tsx copy falls through.
167
- declare const __PANTHEON_VERSION__: string | undefined
168
-
169
- async function detectVersion(api: TuiPluginApi): Promise<string | null> {
170
- // Try 0a: installed location (2 levels: dist/tui.js → pantheon-tui/package.json)
171
- try {
172
- const pkgUrl = new URL('../../package.json', import.meta.url)
173
- const pkgContent = await readFile(fileURLToPath(pkgUrl), 'utf8')
174
- const pkg = JSON.parse(pkgContent)
175
- if (pkg.version) return pkg.version
176
- } catch {}
177
-
178
- // Try 0b: dev location (4 levels: src/plugins/tui/dist/tui.tsx → package.json)
179
- try {
180
- const pkgUrl = new URL('../../../../package.json', import.meta.url)
181
- const pkgContent = await readFile(fileURLToPath(pkgUrl), 'utf8')
182
- const pkg = JSON.parse(pkgContent)
183
- if (pkg.version) return pkg.version
184
- } catch {}
185
-
186
- // Try 1: package.json do projeto (via worktree path)
187
- try {
188
- const wt = ((api.state as any).path?.worktree ?? '') as string
189
- const fp = wt ? `${wt}/package.json` : 'package.json'
190
- const result = await api.client.file.read({ path: fp })
191
- const content = String(result?.data?.content ?? '')
192
- const match = content.match(/"version":\s*"([^"]+)"/)
193
- if (match?.[1]) return match[1]
194
- } catch {
195
- /* fall through */
196
- }
197
-
198
- // Try 2: git describe --tags
199
- try {
200
- const proc = (api as any).client?.process
201
- if (typeof proc?.exec === 'function') {
202
- const r = await proc.exec({
203
- command: 'git',
204
- args: ['describe', '--tags', '--always'],
205
- timeoutMs: 3000,
206
- })
207
- const stdout = (r.stdout ?? r.output ?? '') as string
208
- const tag = stdout
209
- .trim()
210
- .replace(/^v/, '')
211
- .replace(/-\d+-g[0-9a-f]+$/, '')
212
- if (tag) return tag
213
- }
214
- } catch {
215
- /* fall through */
216
- }
217
-
218
- // Try 3: opencode --version
219
- try {
220
- const proc = (api as any).client?.process
221
- if (typeof proc?.exec === 'function') {
222
- const r = await proc.exec({ command: 'opencode', args: ['--version'], timeoutMs: 3000 })
223
- const stdout = (r.stdout ?? r.output ?? '') as string
224
- const ver = stdout.trim().replace(/^v/, '')
225
- if (ver) return ver
226
- }
227
- } catch {
228
- /* fall through */
229
- }
230
-
231
- // Try 4: build-time embedded version (tsdown define) — last-resort fallback
232
- // so the sidebar ALWAYS shows a version even when every probe above fails.
233
- if (typeof __PANTHEON_VERSION__ !== 'undefined' && __PANTHEON_VERSION__) {
234
- return __PANTHEON_VERSION__
235
- }
236
-
237
- return null // sem fallback — versão não aparece
238
- }
239
-
240
- /* ──────────────────────────────────────────────────────────
241
- * VENDORED: opencode-usage-bar (MIT) — satas20
242
- * https://github.com/satas20/opencode-usage-bar
243
- * ────────────────────────────────────────────────────────── */
244
-
245
- /**
246
- * usage-bar — AI subscription usage gauge for the opencode TUI.
247
- *
248
- * Renders a compact usage strip in the `app_bottom` slot — a full-width row
249
- * just below the session footer:
250
- *
251
- * ▓▓▓▓░░ 65% · 0h 11m (one window)
252
- * cld ▓▓▓▓░ 65% · 0h 11m 7d ▓░░░░ 19% · 1d 11h oai ▓░░░░ 12% · 3h 4m
253
- * ! cld ▓▓▓▓░ 65% · 0h 11m (anthropic incident)
254
- *
255
- * Providers:
256
- * anthropic — Claude Pro/Max via the OAuth token in ~/.claude/.credentials.json
257
- * openai — ChatGPT Plus/Pro via the Codex CLI login in ~/.codex/auth.json
258
- * opencodego— OpenCode Go/Zen dollar limits ($12/5h, $30/7d, $60/mo) via
259
- * PANTHEON_OPENCODE_API_KEY (fallback OPENCODE_API_KEY). No
260
- * status page — the provider hides silently when unconfigured
261
- * or when the (not yet public) usage endpoint is unavailable.
262
- *
263
- * When a provider's public status page reports an incident, a colored `!`
264
- * marker appears next to its prefix (red = major/critical, amber = minor,
265
- * cyan = maintenance). The usage bar itself is unaffected. Disable with
266
- * `show_status = false` under `[ui]`.
267
- *
268
- * Configured via ~/.config/opencode/usage-bar.toml (auto-created with
269
- * commented defaults on first run; read once at startup). Tokens/keys are
270
- * only ever sent to their own provider's API host.
271
- *
272
- * Loaded via tui.json, e.g.:
273
- * { "plugin": ["@satas/opencode-usage-bar"] } // published npm package
274
- * { "plugin": ["/abs/path/to/src/index.tsx"] } // local file (no build)
275
- */
276
-
277
- const POLL_MS = 120_000
278
- const FETCH_TIMEOUT_MS = 10_000
279
- const CONFIG_FILE = 'usage-bar.toml'
280
-
281
- // ---------------------------------------------------------------------------
282
- // Types
283
- // ---------------------------------------------------------------------------
284
-
285
- /** Which quota window a value belongs to; toggled per provider in config. */
286
- type WindowCategory = '5h' | '7d' | '1m' | 'model'
287
-
288
- /** Provider health from the vendor's public status page (Statuspage schema). */
289
- type StatusIndicator = 'none' | 'minor' | 'major' | 'critical' | 'maintenance'
290
-
291
- type UsageWindow = {
292
- category: WindowCategory
293
- /** short display label, e.g. "5h", "7d", "Fable" */
294
- label: string
295
- /** 0–100 percent of the window used */
296
- percent: number
297
- /** epoch ms when the window resets */
298
- resetsAt: number
299
- }
300
-
301
- type ProviderId = 'anthropic' | 'openai' | 'opencodego'
302
-
303
- type ProviderConfig = {
304
- enabled: boolean
305
- show: Record<WindowCategory, boolean>
306
- /** anthropic: path to .credentials.json */
307
- credentialsPath?: string
308
- /** openai: path to Codex auth.json */
309
- codexAuthPath?: string
310
- }
311
-
312
- type UsageBarConfig = {
313
- showBars: boolean
314
- showStatus: boolean
315
- barWidth?: number
316
- providers: Record<ProviderId, ProviderConfig>
317
- }
318
-
319
- type Provider = {
320
- id: ProviderId
321
- /** short prefix shown when multiple providers are visible */
322
- short: string
323
- /** vendor status page JSON endpoint (Statuspage `status.json`); optional */
324
- statusUrl?: string
325
- fetchUsage(cfg: ProviderConfig): Promise<UsageWindow[] | null>
326
- }
327
-
328
- // ---------------------------------------------------------------------------
329
- // Helpers
330
- // ---------------------------------------------------------------------------
331
-
332
- function expandTilde(p: string) {
333
- return p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p
334
- }
335
-
336
- function fmtDuration(ms: number) {
337
- const totalMinutes = Math.max(0, Math.ceil(ms / 60_000))
338
- const days = Math.floor(totalMinutes / 1440)
339
- const hours = Math.floor((totalMinutes % 1440) / 60)
340
- const minutes = totalMinutes % 60
341
- if (days > 0) return `${days}d ${hours}h`
342
- return `${hours}h ${minutes}m`
343
- }
344
-
345
- /** Decode a JWT's `exp` claim (unix seconds) without verifying. 0 on failure. */
346
- function jwtExp(token: string): number {
347
- try {
348
- const payload = token.split('.')[1]
349
- if (!payload) return 0
350
- const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as {
351
- exp?: number
352
- }
353
- return typeof claims.exp === 'number' ? claims.exp : 0
354
- } catch {
355
- return 0
356
- }
357
- }
358
-
359
- async function fetchJson(url: string, headers: Record<string, string>): Promise<unknown | null> {
360
- try {
361
- const res = await fetch(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
362
- if (!res.ok) return null
363
- return await res.json()
364
- } catch {
365
- return null
366
- }
367
- }
368
-
369
- /** Fetch a vendor's overall status from its public Statuspage JSON endpoint.
370
- * Returns the `indicator` ("none" when healthy), or `null` when the fetch
371
- * itself failed — so a network blip never clears a known incident. */
372
- async function fetchStatus(url: string): Promise<StatusIndicator | null> {
373
- const data = (await fetchJson(url, {})) as {
374
- status?: { indicator?: string }
375
- } | null
376
- if (!data?.status) return null
377
- const indicator = data.status.indicator
378
- return indicator === 'minor' ||
379
- indicator === 'major' ||
380
- indicator === 'critical' ||
381
- indicator === 'maintenance'
382
- ? indicator
383
- : 'none'
384
- }
385
-
386
- // ---------------------------------------------------------------------------
387
- // opencode auth store (fallback credential source)
388
- // ---------------------------------------------------------------------------
389
-
390
- type OpencodeAuthEntry = {
391
- type?: string
392
- access?: string
393
- expires?: number // epoch ms; 0 = no expiry
394
- accountId?: string
395
- }
396
-
397
- /** Set from `api.state.path.state` at startup; default matches opencode's
398
- * XDG data dir. */
399
- let opencodeAuthFile = join(homedir(), '.local', 'share', 'opencode', 'auth.json')
400
-
401
- /** Read a provider's entry from opencode's own auth store
402
- * (`opencode auth login`). Returns null when missing/unreadable. */
403
- async function opencodeAuth(...ids: string[]): Promise<OpencodeAuthEntry | null> {
404
- try {
405
- const auth = JSON.parse(await readFile(opencodeAuthFile, 'utf8')) as Record<
406
- string,
407
- OpencodeAuthEntry
408
- >
409
- for (const id of ids) {
410
- const entry = auth[id]
411
- if (entry) return entry
412
- }
413
- return null
414
- } catch {
415
- return null
416
- }
417
- }
418
-
419
- // ---------------------------------------------------------------------------
420
- // Providers
421
- // ---------------------------------------------------------------------------
422
-
423
- /** Claude Pro/Max — Anthropic's OAuth usage endpoint (same one Claude Code's
424
- * `/usage` uses). Token from ~/.claude/.credentials.json, falling back to
425
- * opencode's own auth store; sent only to api.anthropic.com. */
426
- const anthropicProvider: Provider = {
427
- id: 'anthropic',
428
- short: 'cld',
429
- statusUrl: 'https://status.anthropic.com/api/v2/status.json',
430
- async fetchUsage(cfg) {
431
- let token: string | undefined
432
- try {
433
- const path = expandTilde(
434
- cfg.credentialsPath ?? join(homedir(), '.claude', '.credentials.json'),
435
- )
436
- const creds = JSON.parse(await readFile(path, 'utf8')) as {
437
- claudeAiOauth?: { accessToken?: string; expiresAt?: number }
438
- }
439
- const oauth = creds.claudeAiOauth
440
- if (oauth?.accessToken && !(oauth.expiresAt && Date.now() >= oauth.expiresAt))
441
- token = oauth.accessToken
442
- } catch {
443
- // fall through to opencode auth
444
- }
445
- if (!token) {
446
- const entry = await opencodeAuth('anthropic')
447
- if (entry?.access && !(entry.expires && Date.now() >= entry.expires)) token = entry.access
448
- }
449
- if (!token) return null
450
-
451
- const data = (await fetchJson('https://api.anthropic.com/api/oauth/usage', {
452
- authorization: `Bearer ${token}`,
453
- 'anthropic-beta': 'oauth-2025-04-20',
454
- })) as {
455
- limits?: Array<{
456
- kind?: string
457
- percent?: number
458
- resets_at?: string
459
- scope?: { model?: { display_name?: string | null } | null } | null
460
- }>
461
- } | null
462
- if (!data || !Array.isArray(data.limits)) return null
463
-
464
- const windows: UsageWindow[] = []
465
- for (const limit of data.limits) {
466
- if (!limit || typeof limit.percent !== 'number' || !Number.isFinite(limit.percent)) continue
467
- if (!limit.kind || !limit.resets_at) continue
468
- const resetsAt = Date.parse(limit.resets_at)
469
- if (Number.isNaN(resetsAt)) continue
470
- const category: WindowCategory =
471
- limit.kind === 'session' ? '5h' : limit.kind === 'weekly_all' ? '7d' : 'model'
472
- const label = category === 'model' ? (limit.scope?.model?.display_name ?? 'model') : category
473
- windows.push({ category, label, percent: limit.percent, resetsAt })
474
- }
475
- // Session window first, then the rest in API order.
476
- windows.sort((a, b) => Number(b.category === '5h') - Number(a.category === '5h'))
477
- return windows.length > 0 ? windows : null
478
- },
479
- }
480
-
481
- /** ChatGPT Plus/Pro (Codex) — reads the Codex CLI login and asks the wham
482
- * usage endpoint. Read-only: never refreshes/rewrites auth.json; when the
483
- * token is expired we simply hide (Codex CLI refreshes the file itself). */
484
- const openaiProvider: Provider = {
485
- id: 'openai',
486
- short: 'oai',
487
- statusUrl: 'https://status.openai.com/api/v2/status.json',
488
- async fetchUsage(cfg) {
489
- let accessToken: string | undefined
490
- let accountId: string | undefined
491
- try {
492
- const path = expandTilde(cfg.codexAuthPath ?? join(homedir(), '.codex', 'auth.json'))
493
- const auth = JSON.parse(await readFile(path, 'utf8')) as {
494
- tokens?: { access_token?: string; id_token?: string; account_id?: string }
495
- }
496
- const tokens = auth.tokens
497
- // Check the expiry of the token we actually send (the access token);
498
- // the id_token expires much earlier and would cause false negatives.
499
- const exp = tokens?.access_token ? jwtExp(tokens.access_token) : 0
500
- if (tokens?.access_token && !(exp > 0 && exp * 1000 <= Date.now() + 60_000)) {
501
- accessToken = tokens.access_token
502
- accountId = tokens.account_id
503
- }
504
- } catch {
505
- // fall through to opencode auth
506
- }
507
- if (!accessToken) {
508
- const entry = await opencodeAuth('openai')
509
- if (entry?.access && !(entry.expires && Date.now() >= entry.expires)) {
510
- accessToken = entry.access
511
- accountId = entry.accountId
512
- }
513
- }
514
- if (!accessToken) return null
515
-
516
- const headers: Record<string, string> = {
517
- authorization: `Bearer ${accessToken}`,
518
- 'user-agent': 'codex-cli',
519
- }
520
- if (accountId) headers['chatgpt-account-id'] = accountId
521
-
522
- const data = (await fetchJson('https://chatgpt.com/backend-api/wham/usage', headers)) as {
523
- rate_limit?: {
524
- primary_window?: WhamWindow | null
525
- secondary_window?: WhamWindow | null
526
- }
527
- } | null
528
- if (!data?.rate_limit) return null
529
-
530
- // Classify by window duration when present (some accounts return the
531
- // weekly window as primary_window), falling back to position.
532
- const windows: UsageWindow[] = []
533
- const primary = parseWhamWindow(data.rate_limit.primary_window, '5h')
534
- if (primary) windows.push(primary)
535
- const secondary = parseWhamWindow(data.rate_limit.secondary_window, '7d')
536
- if (secondary) windows.push(secondary)
537
- windows.sort((a, b) => Number(b.category === '5h') - Number(a.category === '5h'))
538
- return windows.length > 0 ? windows : null
539
- },
540
- }
541
-
542
- type WhamWindow = {
543
- used_percent?: number
544
- limit_window_seconds?: number
545
- reset_at?: number
546
- reset_after_seconds?: number
547
- }
548
-
549
- function parseWhamWindow(
550
- w: WhamWindow | null | undefined,
551
- fallback: WindowCategory,
552
- ): UsageWindow | null {
553
- if (!w || typeof w.used_percent !== 'number' || !Number.isFinite(w.used_percent)) return null
554
- let resetsAt: number | undefined
555
- if (typeof w.reset_at === 'number') resetsAt = w.reset_at * 1000
556
- else if (typeof w.reset_after_seconds === 'number')
557
- resetsAt = Date.now() + w.reset_after_seconds * 1000
558
- if (!resetsAt || !Number.isFinite(resetsAt)) return null
559
- const category: WindowCategory =
560
- typeof w.limit_window_seconds === 'number' && w.limit_window_seconds > 0
561
- ? w.limit_window_seconds <= 21_600 // ≤ 6h → session window
562
- ? '5h'
563
- : '7d'
564
- : fallback
565
- return { category, label: category, percent: w.used_percent, resetsAt }
566
- }
567
-
568
- /** OpenCode Go/Zen — dollar-denominated rolling usage limits ($12 / 5h,
569
- * $30 / 7d, $60 / subscription month). Token is the same key used for
570
- * inference: PANTHEON_OPENCODE_API_KEY, falling back to OPENCODE_API_KEY.
571
- * It is only ever sent in the Authorization header to opencode.ai — never
572
- * logged or written to disk. The usage endpoint (opencode.ai/zen/go/v1/
573
- * usage) is not yet part of the public docs, so any non-ok response
574
- * (404/401/403/500) hides the provider silently instead of erroring out. */
575
- const opencodeGoProvider: Provider = {
576
- id: 'opencodego',
577
- short: 'go',
578
- // No statusUrl — opencode.ai has no verified public status page to poll.
579
- async fetchUsage(_cfg) {
580
- const token = process.env.PANTHEON_OPENCODE_API_KEY ?? process.env.OPENCODE_API_KEY
581
- if (!token) return null
582
-
583
- const data = (await fetchJson('https://opencode.ai/zen/go/v1/usage', {
584
- authorization: `Bearer ${token}`,
585
- })) as {
586
- rolling5h?: GoUsageWindow
587
- weekly?: GoUsageWindow
588
- monthly?: GoUsageWindow
589
- } | null
590
- if (!data) return null
591
-
592
- const windows: UsageWindow[] = []
593
- // Mirror the defensive parsing used by the other providers: a window
594
- // missing its percent or reset time is skipped rather than rendered.
595
- const push = (w: GoUsageWindow | undefined, category: '5h' | '7d' | '1m') => {
596
- if (!w) return
597
- if (typeof w.usagePercent !== 'number' || !Number.isFinite(w.usagePercent)) return
598
- if (typeof w.resetInSec !== 'number' || !Number.isFinite(w.resetInSec)) return
599
- windows.push({
600
- category,
601
- label: category,
602
- percent: Math.round(w.usagePercent),
603
- resetsAt: Date.now() + w.resetInSec * 1000,
604
- })
605
- }
606
- push(data.rolling5h, '5h')
607
- push(data.weekly, '7d')
608
- push(data.monthly, '1m')
609
- return windows.length > 0 ? windows : null
610
- },
611
- }
612
-
613
- type GoUsageWindow = {
614
- usageDollars?: number
615
- limitDollars?: number
616
- usagePercent?: number
617
- resetInSec?: number
618
- }
619
-
620
- const providers: Provider[] = [anthropicProvider, openaiProvider, opencodeGoProvider]
621
-
622
- // ---------------------------------------------------------------------------
623
- // Config
624
- // ---------------------------------------------------------------------------
625
-
626
- const DEFAULT_TOML = `# opencode-usage-bar configuration
627
- # Read once at startup — restart opencode after editing.
628
-
629
- [ui]
630
- show_bars = true # render ▓▓░░ mini-bars (false = text only)
631
- show_status = true # show a ! marker next to a provider during incidents
632
- # bar_width = 6 # override bar width (default: 6 for a single window, 5 otherwise)
633
-
634
- [anthropic]
635
- enabled = true # Claude Pro/Max via ~/.claude/.credentials.json
636
- show_5h = true # rolling 5-hour session window
637
- show_7d = false # weekly cap across all models
638
- show_model = false # per-model weekly windows (e.g. Fable)
639
- # credentials_path = "~/.claude/.credentials.json"
640
-
641
- [openai]
642
- enabled = false # ChatGPT Plus/Pro via the Codex CLI login
643
- show_5h = true
644
- show_7d = false
645
- # codex_auth_path = "~/.codex/auth.json"
646
-
647
- [opencodego]
648
- enabled = true # OpenCode Go/Zen dollar usage via PANTHEON_OPENCODE_API_KEY
649
- show_5h = true # rolling 5-hour window ($12)
650
- show_7d = true # rolling 7-day window ($30)
651
- show_1m = false # subscription-month window ($60) — opt-in
652
- # Falls back to OPENCODE_API_KEY when PANTHEON_OPENCODE_API_KEY is unset.
653
- `
654
-
655
- function defaultConfig(): UsageBarConfig {
656
- const show = (over: Partial<Record<WindowCategory, boolean>> = {}) => ({
657
- '5h': true,
658
- '7d': false,
659
- '1m': false,
660
- model: false,
661
- ...over,
662
- })
663
- return {
664
- showBars: true,
665
- showStatus: true,
666
- providers: {
667
- anthropic: { enabled: true, show: show() },
668
- openai: { enabled: false, show: show() },
669
- // 5h+7d on by default; monthly window opt-in; model never for Go.
670
- opencodego: { enabled: true, show: show({ '7d': true }) },
671
- },
672
- }
673
- }
674
-
675
- type TomlTable = Record<string, unknown>
676
-
677
- function asTable(v: unknown): TomlTable {
678
- return v && typeof v === 'object' && !Array.isArray(v) ? (v as TomlTable) : {}
679
- }
680
-
681
- function bool(v: unknown, fallback: boolean) {
682
- return typeof v === 'boolean' ? v : fallback
683
- }
684
-
685
- function str(v: unknown): string | undefined {
686
- return typeof v === 'string' && v.length > 0 ? v : undefined
687
- }
688
-
689
- function parseConfig(raw: string): UsageBarConfig {
690
- const toml = (globalThis as Record<string, any>).Bun?.TOML
691
- if (!toml?.parse) return defaultConfig()
692
- const root = asTable(toml.parse(raw))
693
- const cfg = defaultConfig()
694
-
695
- const ui = asTable(root.ui)
696
- cfg.showBars = bool(ui.show_bars, cfg.showBars)
697
- cfg.showStatus = bool(ui.show_status, cfg.showStatus)
698
- const rawWidth = ui.bar_width
699
- if (typeof rawWidth === 'number' && Number.isFinite(rawWidth) && rawWidth >= 1)
700
- cfg.barWidth = Math.min(40, Math.floor(rawWidth))
701
-
702
- for (const id of ['anthropic', 'openai', 'opencodego'] as ProviderId[]) {
703
- const t = asTable(root[id])
704
- const p = cfg.providers[id]
705
- p.enabled = bool(t.enabled, p.enabled)
706
- p.show['5h'] = bool(t.show_5h, p.show['5h'])
707
- p.show['7d'] = bool(t.show_7d, p.show['7d'])
708
- p.show['1m'] = bool(t.show_1m, p.show['1m'])
709
- p.show.model = bool(t.show_model, p.show.model)
710
- // Assign only when present — keeps `exactOptionalPropertyTypes` happy.
711
- const credentialsPath = str(t.credentials_path)
712
- if (credentialsPath !== undefined) p.credentialsPath = credentialsPath
713
- const codexAuthPath = str(t.codex_auth_path)
714
- if (codexAuthPath !== undefined) p.codexAuthPath = codexAuthPath
715
- }
716
- return cfg
717
- }
718
-
719
- /** Load `<config dir>/usage-bar.toml`, creating it with commented defaults on
720
- * first run. Any failure falls back to defaults without touching an existing
721
- * file. */
722
- async function loadConfig(configPath: string | undefined): Promise<UsageBarConfig> {
723
- const dir =
724
- configPath && !configPath.endsWith('.json')
725
- ? configPath
726
- : configPath
727
- ? dirname(configPath)
728
- : join(homedir(), '.config', 'opencode')
729
- const file = join(dir, CONFIG_FILE)
730
-
731
- try {
732
- const raw = await readFile(file, 'utf8')
733
- try {
734
- return parseConfig(raw)
735
- } catch {
736
- return defaultConfig() // malformed TOML — keep the file, use defaults
737
- }
738
- } catch (err) {
739
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') {
740
- try {
741
- await mkdir(dir, { recursive: true })
742
- await writeFile(file, DEFAULT_TOML, { flag: 'wx' })
743
- } catch {
744
- // ignore — config stays default in memory
745
- }
746
- }
747
- return defaultConfig()
748
- }
749
- }
750
-
751
- /** Vendored usage-bar plugin init: reads config, seeds the kv cache, starts
752
- * the poll loop and registers the `app_bottom` slot. Skips everything (and
753
- * registers nothing) when no provider is enabled — mirrors the standalone
754
- * plugin's early return. */
755
- async function setupUsageBar(api: TuiPluginApi) {
756
- const config = await loadConfig(api.state.path?.config)
757
- if (api.state.path?.state) opencodeAuthFile = join(api.state.path.state, 'auth.json')
758
-
759
- const enabled = providers.filter((p) => config.providers[p.id].enabled)
760
- if (enabled.length === 0) return // nothing to poll or render
761
-
762
- const seed: Record<string, UsageWindow[]> = {}
763
- for (const p of enabled) {
764
- const cached = api.kv.get<UsageWindow[] | undefined>(`usage-bar.${p.id}.windows`, undefined)
765
- if (cached) seed[p.id] = cached
766
- }
767
- const [byProvider, setByProvider] = createSignal<Record<string, UsageWindow[]>>(seed)
768
- // Status is deliberately not cached across restarts: incidents are
769
- // short-lived, and the first poll lands seconds after startup anyway.
770
- const [byStatus, setByStatus] = createSignal<Record<string, StatusIndicator>>({})
771
- const [now, setNow] = createSignal(Date.now())
772
-
773
- setInterval(() => setNow(Date.now()), 1_000)
774
-
775
- for (const p of enabled) {
776
- const cfg = config.providers[p.id]
777
- const poll = async () => {
778
- // Fetch usage and status concurrently; status pages are CDN-backed and
779
- // never throttle, so we poll them on the same cadence as usage.
780
- const statusP = config.showStatus && p.statusUrl ? fetchStatus(p.statusUrl) : null
781
- const [all, status] = await Promise.all([p.fetchUsage(cfg), statusP])
782
- if (all) {
783
- const windows = all.filter((w) => cfg.show[w.category] && w.resetsAt > Date.now())
784
- setByProvider((prev) => ({ ...prev, [p.id]: windows }))
785
- api.kv.set(`usage-bar.${p.id}.windows`, windows)
786
- }
787
- // `null` means the status fetch failed — keep the last known indicator.
788
- if (status !== null) setByStatus((prev) => ({ ...prev, [p.id]: status }))
789
- // Back off when the usage fetch failed (e.g. 429 — these endpoints throttle).
790
- setTimeout(poll, all ? POLL_MS : POLL_MS * 3)
791
- }
792
- void poll()
793
- }
794
-
795
- api.slots.register({
796
- order: 60,
797
- slots: {
798
- // `app_bottom` renders as a full-width row below the session footer.
799
- app_bottom() {
800
- const theme = () => api.theme.current
801
-
802
- type Group = { short: string; status: StatusIndicator; windows: UsageWindow[] }
803
- const groups = createMemo<Group[]>(() => {
804
- const map = byProvider()
805
- const statusMap = byStatus()
806
- const out: Group[] = []
807
- for (const p of enabled) {
808
- // Drop windows that have reset since the last poll.
809
- const windows = (map[p.id] ?? []).filter((w) => w.resetsAt > now())
810
- if (windows.length > 0)
811
- out.push({ short: p.short, status: statusMap[p.id] ?? 'none', windows })
812
- }
813
- return out
814
- })
815
- const totalWindows = createMemo(() =>
816
- groups().reduce((sum, g) => sum + g.windows.length, 0),
817
- )
818
- const barWidth = createMemo(() => config.barWidth ?? (totalWindows() === 1 ? 6 : 5))
819
- const multiProvider = createMemo(() => groups().length >= 2)
820
-
821
- const pctOf = (w: UsageWindow) => Math.min(100, Math.max(0, Math.round(w.percent)))
822
- const filledOf = (w: UsageWindow) =>
823
- Math.min(barWidth(), Math.max(0, Math.round((pctOf(w) / 100) * barWidth())))
824
- const colorOf = (w: UsageWindow) => {
825
- const t = theme()
826
- const pct = pctOf(w)
827
- if (pct > 85) return t.error
828
- if (pct >= 50) return t.warning
829
- return t.success
830
- }
831
- // Status marker color: red for severe incidents, amber for minor,
832
- // cyan for scheduled maintenance.
833
- const statusColor = (s: StatusIndicator) => {
834
- const t = theme()
835
- if (s === 'critical' || s === 'major') return t.error
836
- if (s === 'minor') return t.warning
837
- return t.info
838
- }
839
-
840
- return (
841
- <Show when={groups().length > 0}>
842
- <box flexDirection="row" gap={3} alignItems="center" width="100%" paddingLeft={1}>
843
- <For each={groups()}>
844
- {(g) => (
845
- <box flexDirection="row" gap={2} alignItems="center" flexShrink={0}>
846
- <Show when={config.showStatus && g.status !== 'none'}>
847
- <text fg={statusColor(g.status)}>!</text>
848
- </Show>
849
- <Show when={multiProvider()}>
850
- <text fg={theme().textMuted}>{g.short}</text>
851
- </Show>
852
- <For each={g.windows}>
853
- {(w) => (
854
- <box flexDirection="row" gap={1} alignItems="center" flexShrink={0}>
855
- <Show when={g.windows.length >= 2}>
856
- <text fg={theme().textMuted}>{w.label}</text>
857
- </Show>
858
- <Show when={config.showBars}>
859
- <box flexDirection="row">
860
- <text fg={colorOf(w)}>{'▓'.repeat(filledOf(w))}</text>
861
- <text fg={theme().textMuted}>
862
- {'░'.repeat(barWidth() - filledOf(w))}
863
- </text>
864
- </box>
865
- </Show>
866
- <text fg={theme().text}>{pctOf(w)}%</text>
867
- <text
868
- fg={theme().textMuted}
869
- >{`· ${fmtDuration(w.resetsAt - now())}`}</text>
870
- </box>
871
- )}
872
- </For>
873
- </box>
874
- )}
875
- </For>
876
- </box>
877
- </Show>
878
- )
879
- },
880
- },
881
- })
882
- }
883
-
884
- /* ─── Delegations (real-time panel) ────────────────────────
885
- * CHILDREN + MD (delegations-sidebar pattern, feat/compaction-134):
886
- *
887
- * 1. PRIMARY — SDK child sessions via `api.client.session.children`:
888
- * every pantheon_delegate creates a child session with
889
- * parentID = caller (src/pantheon/delegation.ts session.create), so
890
- * the children of the current session ARE the delegation list — the
891
- * same mechanism the opencode-delegations-sidebar reference uses
892
- * (`client.session.children` + `session.parentID === current`).
893
- * Live status comes from `api.state.session.status(childID)`
894
- * (busy/retry → running; idle → terminal). This does NOT depend on
895
- * tool-part events, which runtime 1.18.13 may not deliver for
896
- * pantheon_delegate (the "(0) even while delegating" symptom).
897
- *
898
- * 1b. NATIVE task() CHILDREN — `session.children` returns ALL children,
899
- * and the native `task()` tool ALSO spawns a child session with
900
- * parentID = caller. A child WITHOUT a board report is a native
901
- * task() child: childrenToDelegationEntries tags it source
902
- * 'children-only' with the `[native]` row tag (distinct info color),
903
- * so native task() work is visible in the panel alongside board
904
- * delegates ([pantheon:apo-1]) — never filtered out, never duplicated
905
- * with a board row for the same child (a child WITH a report keeps the
906
- * md entry, source 'md').
907
- *
908
- * 2. ENRICHMENT + HISTORY — markdown reports the job board persists under
909
- * `.pantheon/delegations/<sessionID>/<alias>.md` (written by
910
- * src/pantheon/delegation-finalize.ts at terminal state). Each child
911
- * is matched to its report by the `Task ID` header (== child session
912
- * id == board task id), which supplies the alias (apo-N), agent,
913
- * description and terminal duration/timedOut. No report → the child
914
- * itself still renders (title as description, derived state). The md
915
- * channel is ALSO read from EVERY session (readAllDelegationEntries) —
916
- * the panel shows the full delegation history even without a focused
917
- * session.
918
- *
919
- * 3. REFRESH — session.created/updated/deleted/status events and
920
- * message.part.updated/removed (via liveStore.version bumps) re-fetch
921
- * children; a 1s safety poll (oh-my-opencode-slim pattern) re-fetches
922
- * children + re-reads the md so the panel updates EVEN without events.
923
- *
924
- * 4. DIAGNOSTICS — every re-fetch logs
925
- * "panel: children=N(pantheon=M native=K) md=N events=N"
926
- * to `.pantheon/logs/hooks.log` (silence-by-default, createPantheonLogger
927
- * policy) so the (0) symptom is diagnosable from disk: children>0 means
928
- * the source works, pantheon/native splits board vs task() children.
929
- * A children fetch
930
- * failure logs "panel: error <msg>" (previously silenced), and a missing
931
- * current session (null/placeholder sessionID) logs "panel: children=0
932
- * md=N ... (no sessionID — history shown)" — the md HISTORY renders
933
- * instead of erroring.
934
- *
935
- * 5. SESSIONID GUARD (placeholder regression) — the runtime may hand the
936
- * sidebar the UNSUBSTITUTED template literal "{sessionID}" as its
937
- * session_id (no focused session). Forwarding it to session.children
938
- * made opencode's server reject every poll (~1 err/s: "Expected a string
939
- * starting with \"ses\", got \"%7BsessionID%7D\"") and fail-open the
940
- * panel into "(0)". resolveCurrentSessionID (slot prop → api.state →
941
- * route.current) never yields a placeholder (isValidSessionId rejects
942
- * "{sessionID}" and "%7BsessionID%7D" via the startsWith("ses")
943
- * contract); a null resolution SKIPS the children fetch entirely and
944
- * renders the md history — zero errors.
945
- *
946
- * The live tool-part lifecycle helpers below remain (tested, exported) but
947
- * are no longer the source of truth: they feed a version signal that merely
948
- * re-triggers the children fetch. Everything is fail-open: a missing
949
- * children API or directory yields [], and any unreadable input is skipped —
950
- * never crash. */
951
-
952
- export type DelegationEntry = {
953
- /** Job alias, e.g. "apo-1" (from the H1 title, falling back to filename). */
954
- alias: string
955
- /** Parent session the job was launched from (dir name under .pantheon/delegations). */
956
- sessionID: string
957
- /** Child session id (= board task id, from the `Task ID` header). The
958
- * children channel always sets it from the child session itself; the md
959
- * channel parses it so child↔md matching works by taskID. */
960
- taskID?: string
961
- /** Agent name, e.g. "apollo". */
962
- agent: string
963
- state:
964
- | 'running'
965
- | 'retry'
966
- | 'completed'
967
- | 'error'
968
- | 'startup_failed'
969
- | 'startup_unknown'
970
- | 'cancelled'
971
- | 'stale-running'
972
- /** Epoch ms of the `Started` header. */
973
- startedAt: number
974
- /** Epoch ms of the `Finalized` header — null while still running. */
975
- updatedAt: number | null
976
- timedOut: boolean
977
- description: string
978
- /** True while the panel is waiting for pantheon_delegation_read. */
979
- read?: boolean
980
- /** Internal provenance used to keep a finalized md report authoritative.
981
- * 'children-only' = a native task() child session with NO board report
982
- * (rendered with the distinct `[native]` tag); 'md' = board report wins. */
983
- source?: 'child' | 'live' | 'md' | 'children-only'
984
- }
985
-
986
- /** True for `\s` characters (space, tab, newline, CR) — plain char checks so
987
- * the parser stays regex-free (CodeQL flagged the old `\s*`/`\s+` + `(.+)`
988
- * patterns as polynomial ReDoS: 12x HIGH). */
989
- function isWs(ch: string | undefined): boolean {
990
- return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r'
991
- }
992
-
993
- /** Em/en dash + hyphen — the separators accepted after the H1 title. */
994
- const TITLE_SEPARATORS = '—–-'
995
-
996
- /** Parse one delegation report md header into a structured entry.
997
- * Returns null (skip) when the file is not a recognizable report:
998
- * missing agent/state/startedAt, an unknown state, or an unparsable
999
- * Started timestamp. The alias falls back to the file name when the H1
1000
- * title is missing. Pure — no I/O.
1001
- *
1002
- * Linear, single-pass over `raw.split('\n')` with plain string operations
1003
- * (startsWith/indexOf/slice) — zero regex, so worst case is O(bytes) even
1004
- * on adversarial whitespace-heavy input (ReDoS regression, CodeQL 12x HIGH). */
1005
- export function parseDelegationMarkdown(
1006
- raw: string,
1007
- fileAlias?: string,
1008
- sessionID = '',
1009
- ): DelegationEntry | null {
1010
- let title: string | undefined
1011
- let agent: string | undefined
1012
- let description = ''
1013
- let state: string | undefined
1014
- let timedOut = false
1015
- let started: string | undefined
1016
- let finalized: string | undefined
1017
- let taskID: string | undefined
1018
-
1019
- for (const rawLine of raw.split('\n')) {
1020
- // H1 title: `# Delegation Report — <alias>` (empty alias → fallback later).
1021
- if (rawLine[0] === '#' && isWs(rawLine[1])) {
1022
- let i = 2
1023
- while (i < rawLine.length && isWs(rawLine[i])) i++
1024
- if (rawLine.startsWith('Delegation Report', i)) {
1025
- i += 'Delegation Report'.length
1026
- while (i < rawLine.length && isWs(rawLine[i])) i++
1027
- if (i < rawLine.length && TITLE_SEPARATORS.includes(rawLine[i])) {
1028
- const rest = rawLine.slice(i + 1).trim()
1029
- if (rest !== '' && title === undefined) title = rest
1030
- }
1031
- }
1032
- continue
1033
- }
1034
- // Field bullets: `- **Name**: value` — unknown names are ignored.
1035
- if (rawLine[0] !== '-') continue
1036
- let i = 1
1037
- while (i < rawLine.length && isWs(rawLine[i])) i++
1038
- if (!rawLine.startsWith('**', i)) continue
1039
- const nameStart = i + 2
1040
- const valueEnd = rawLine.indexOf('**:', nameStart)
1041
- if (valueEnd < 0) continue
1042
- const name = rawLine.slice(nameStart, valueEnd)
1043
- const value = rawLine.slice(valueEnd + 3).trim()
1044
- switch (name) {
1045
- case 'Task ID':
1046
- // `- **Task ID**: \`ses_x\`` — strip the surrounding backticks.
1047
- if (value !== '' && taskID === undefined) taskID = stripTaskIdTicks(value)
1048
- break
1049
- case 'Agent':
1050
- // Empty value counts as missing (old regex `(.+)` required 1+ chars).
1051
- if (value !== '' && agent === undefined) agent = value
1052
- break
1053
- case 'Description':
1054
- description = value
1055
- break
1056
- case 'State':
1057
- if (value !== '' && state === undefined) state = value
1058
- break
1059
- case 'Timed out':
1060
- // Old `(true|false)` prefix match, case-sensitive — kept verbatim.
1061
- timedOut = value.startsWith('true')
1062
- break
1063
- case 'Started':
1064
- if (value !== '' && started === undefined) started = value
1065
- break
1066
- case 'Finalized':
1067
- finalized = value
1068
- break
1069
- default:
1070
- break // unknown field (e.g. Task ID) → ignore the line
1071
- }
1072
- }
1073
-
1074
- const startedAt = started !== undefined ? Date.parse(started) : NaN
1075
- if (agent === undefined || state === undefined || Number.isNaN(startedAt)) return null
1076
- const normalized = state.toLowerCase()
1077
- // Running state should only come from live channels, never from persisted
1078
- // reports. A stale "running" MD artifact contaminates the panel — skip it.
1079
- if (normalized === 'running') return null
1080
- if (
1081
- normalized !== 'completed' &&
1082
- normalized !== 'error' &&
1083
- normalized !== 'startup_failed' &&
1084
- normalized !== 'startup_unknown' &&
1085
- normalized !== 'cancelled'
1086
- ) {
1087
- return null
1088
- }
1089
- const finalizedAt = finalized !== undefined ? Date.parse(finalized) : NaN
1090
-
1091
- return {
1092
- alias: title ?? (fileAlias !== undefined ? stripMdSuffix(fileAlias) : 'unknown'),
1093
- sessionID,
1094
- ...(taskID !== undefined ? { taskID } : {}),
1095
- agent,
1096
- state: normalized,
1097
- startedAt,
1098
- updatedAt: Number.isNaN(finalizedAt) ? null : finalizedAt,
1099
- timedOut,
1100
- description,
1101
- source: 'md',
1102
- }
1103
- }
1104
-
1105
- /** Strip a trailing `.md` (any case) — linear replacement for /\.md$/i. */
1106
- function stripMdSuffix(name: string): string {
1107
- return name.toLowerCase().endsWith('.md') ? name.slice(0, name.length - 3) : name
1108
- }
1109
-
1110
- /** Strip surrounding backticks from a `Task ID` value: "`ses_x`" → "ses_x". */
1111
- function stripTaskIdTicks(value: string): string {
1112
- const start = value[0] === '`' ? 1 : 0
1113
- const end =
1114
- value.length > start && value[value.length - 1] === '`' ? value.length - 1 : value.length
1115
- return value.slice(start, end)
1116
- }
1117
-
1118
- /** Read every delegation report under `<dir>/<sessionID>/<alias>.md`.
1119
- * Fail-open: a missing/unreadable directory yields [], and each unreadable
1120
- * or malformed file is skipped individually. Entries are sorted running
1121
- * first, then terminal by `updatedAt` (most recent first) so the panel can
1122
- * render them in order directly. */
1123
- export async function readDelegationEntries(dir: string): Promise<DelegationEntry[]> {
1124
- let sessionDirs: Dirent[]
1125
- try {
1126
- sessionDirs = await readdir(dir, { withFileTypes: true })
1127
- } catch {
1128
- return [] // directory absent/unreadable — nothing to show
1129
- }
1130
-
1131
- const entries: DelegationEntry[] = []
1132
- for (const session of sessionDirs) {
1133
- if (!session.isDirectory()) continue
1134
- let files: Dirent[]
1135
- try {
1136
- files = await readdir(join(dir, session.name), { withFileTypes: true })
1137
- } catch {
1138
- continue // unreadable session dir — skip
1139
- }
1140
- for (const file of files) {
1141
- if (!file.isFile() || !file.name.endsWith('.md')) continue
1142
- try {
1143
- const raw = await readFile(join(dir, session.name, file.name), 'utf8')
1144
- const entry = parseDelegationMarkdown(raw, file.name, session.name)
1145
- if (entry !== null) entries.push(entry)
1146
- } catch {
1147
- // unreadable/malformed file — skip, never crash
1148
- }
1149
- }
1150
- }
1151
-
1152
- entries.sort(compareDelegationEntries)
1153
- return entries
1154
- }
1155
-
1156
- /** Read delegation reports from EVERY session under
1157
- * `<root>/.pantheon/delegations/<sessionID>/<alias>.md` — the panel's
1158
- * HISTORY channel. Unlike the children/live channels it does NOT depend on a
1159
- * resolved sessionID: with no focused session (null/placeholder), the panel
1160
- * still shows the reports from all past sessions (running first, Finalized
1161
- * desc — the sort applied by readDelegationEntries). Fail-open: a
1162
- * missing/unreadable directory yields []. */
1163
- export async function readAllDelegationEntries(root: string): Promise<DelegationEntry[]> {
1164
- return readDelegationEntries(join(root, '.pantheon', 'delegations'))
1165
- }
1166
-
1167
- /** Resolve the directory where the job board writes delegation md reports.
1168
- * The board writes `.pantheon/delegations` RELATIVE to the server cwd,
1169
- * which the TUI exposes as `TuiState.path.directory`. `project` does NOT
1170
- * exist on `TuiState.path` (the old `state?.project ?? state?.worktree`
1171
- * resolution was always undefined for the first term) and `worktree` is
1172
- * `/` when there is no git (e.g. the sandbox test project) — a root of
1173
- * `''` or `'/'` must fall back to `process.cwd()`. */
1174
- export function resolveDelegationsDir(
1175
- state: { directory?: string; worktree?: string } | undefined,
1176
- cwd = process.cwd(),
1177
- ): string {
1178
- const root = state?.directory ?? state?.worktree ?? ''
1179
- if (root === '' || root === '/') return join(cwd, '.pantheon', 'delegations')
1180
- return join(root, '.pantheon', 'delegations')
1181
- }
1182
-
1183
- /** Project root derived from the delegations dir: `<root>/.pantheon/delegations`
1184
- * → `<root>`. Used to point the panel logger at the REAL hooks.log — passing
1185
- * the delegations dir (or its dirname) directly made createTuiLogger append
1186
- * to `<root>/.pantheon/.pantheon/logs/hooks.log`, a nested empty dir the real
1187
- * log never saw. Pure — no I/O. */
1188
- export function panelLogDir(delegationsDir: string): string {
1189
- return dirname(dirname(delegationsDir))
1190
- }
1191
-
1192
- /** Where the panel logger appends lines: `<projectRoot>/.pantheon/logs/hooks.log`.
1193
- * Pure — testable without the runtime. */
1194
- export function tuiLogPath(projectRoot: string): string {
1195
- return join(projectRoot, '.pantheon', 'logs', 'hooks.log')
1196
- }
1197
-
1198
- /** Sort delegations: running first, then terminal by recency (updatedAt,
1199
- * falling back to startedAt, descending). Shared by the md reader and
1200
- * mergeDelegationSources. */
1201
- export function compareDelegationEntries(a: DelegationEntry, b: DelegationEntry): number {
1202
- const isActive = (st: DelegationEntry['state']) =>
1203
- st === 'running' || st === 'retry' || st === 'stale-running' ? 1 : 0
1204
- const aRun = isActive(a.state)
1205
- const bRun = isActive(b.state)
1206
- if (aRun !== bRun) return bRun - aRun
1207
- return (b.updatedAt ?? b.startedAt) - (a.updatedAt ?? a.startedAt)
1208
- }
1209
-
1210
- /** Split the panel list: active jobs (running/retry, stale-marked) first,
1211
- * then the most recent terminal reports, then the archived tail (paginated
1212
- * in the View). Pure — so the history-only panel (no sessionID) is testable
1213
- * without the TUI runtime. */
1214
- export function splitDelegationList(
1215
- all: readonly DelegationEntry[],
1216
- maxRecent = 8,
1217
- now = Date.now(),
1218
- staleThresholdMs = 30 * 60 * 1000, // 30 minutes
1219
- ): { active: DelegationEntry[]; recent: DelegationEntry[]; archived: DelegationEntry[] } {
1220
- const active = all
1221
- .filter((d) => d.state === 'running' || d.state === 'retry')
1222
- .map((d) => markStaleIfRunning(d, now, staleThresholdMs))
1223
- const terminal = all.filter((d) => d.state !== 'running' && d.state !== 'retry')
1224
- return {
1225
- active,
1226
- recent: terminal.slice(0, maxRecent),
1227
- archived: terminal.slice(maxRecent),
1228
- }
1229
- }
1230
-
1231
- /** The list the panel actually renders (kept for the header count and
1232
- * existing tests): active jobs first, then the most recent terminal
1233
- * reports (capped) — the archived tail is rendered separately. Pure. */
1234
- export function visibleDelegationList(
1235
- all: readonly DelegationEntry[],
1236
- maxTerminal = 8,
1237
- now = Date.now(),
1238
- staleThresholdMs = 30 * 60 * 1000, // 30 minutes
1239
- ): DelegationEntry[] {
1240
- const { active, recent } = splitDelegationList(all, maxTerminal, now, staleThresholdMs)
1241
- return [...active, ...recent]
1242
- }
1243
-
1244
- /** Default stale-running threshold: 30 minutes. */
1245
- export const STALE_RUNNING_THRESHOLD_MS = 30 * 60 * 1000
1246
-
1247
- /** Idle silence window: if no updatedAt change in this window, the entry is
1248
- * considered stale. Combined with the stale-running threshold to produce the
1249
- * display-only `stale-running` state. */
1250
- export const IDLE_SILENCE_MS = 60 * 1000
1251
-
1252
- /**
1253
- * Mark a running entry as `stale-running` if it has been running longer than
1254
- * the threshold AND has no recent activity (no `updatedAt` change in the last
1255
- * `IDLE_SILENCE_MS`). This is DISPLAY-ONLY — the board state is unchanged.
1256
- *
1257
- * A `stale-running` entry renders with a warning indicator but the underlying
1258
- * delegation is still treated as running by the backend.
1259
- */
1260
- export function markStaleIfRunning(
1261
- entry: DelegationEntry,
1262
- now: number,
1263
- thresholdMs = STALE_RUNNING_THRESHOLD_MS,
1264
- ): DelegationEntry {
1265
- if (entry.state !== 'running') return entry
1266
- const elapsed = now - entry.startedAt
1267
- if (elapsed < thresholdMs) return entry
1268
- // If updatedAt exists and is recent, entry is still active — not stale.
1269
- if (entry.updatedAt !== null && now - entry.updatedAt < IDLE_SILENCE_MS) return entry
1270
- return { ...entry, state: 'stale-running' as const }
1271
- }
1272
-
1273
- /** Compact elapsed-time label: "5m 12s", "1h 30m", "2d 4h" — ticks every
1274
- * second for running jobs. */
1275
- export function fmtElapsed(ms: number): string {
1276
- const total = Math.max(0, Math.floor(ms / 1000))
1277
- const days = Math.floor(total / 86_400)
1278
- const hours = Math.floor((total % 86_400) / 3_600)
1279
- const minutes = Math.floor((total % 3_600) / 60)
1280
- const seconds = total % 60
1281
- if (days > 0) return `${days}d ${hours}h`
1282
- if (hours > 0) return `${hours}h ${minutes}m`
1283
- if (minutes > 0) return `${minutes}m ${seconds}s`
1284
- return `${seconds}s`
1285
- }
1286
-
1287
- /** Elapsed label for one entry: running → ticks `now - startedAt`, terminal
1288
- * → fixed `updatedAt - startedAt` (em dash when no finalized timestamp). */
1289
- export function delegationElapsed(entry: DelegationEntry, now: number): string {
1290
- if (entry.state === 'running' || entry.state === 'stale-running')
1291
- return fmtElapsed(now - entry.startedAt)
1292
- return entry.updatedAt !== null ? fmtElapsed(entry.updatedAt - entry.startedAt) : '\u2014'
1293
- }
1294
-
1295
- /** The activity labels shown by the animated row. Keeping this pure makes the
1296
- * state machine testable without booting OpenCode's renderer. */
1297
- export type DelegationActivity =
1298
- | 'delegating'
1299
- | 'working'
1300
- | 'reading'
1301
- | 'completed'
1302
- | 'error'
1303
- | 'cancelled'
1304
-
1305
- export function delegationActivity(entry: DelegationEntry): DelegationActivity {
1306
- if (entry.state === 'completed') return 'completed'
1307
- if (
1308
- entry.state === 'error' ||
1309
- entry.state === 'startup_failed' ||
1310
- entry.state === 'startup_unknown'
1311
- )
1312
- return 'error'
1313
- if (entry.state === 'cancelled') return 'cancelled'
1314
- if (entry.read) return 'reading'
1315
- if (entry.alias.startsWith('live-') && entry.taskID === undefined) return 'delegating'
1316
- return 'working'
1317
- }
1318
-
1319
- export function delegationActivityLabel(entry: DelegationEntry): string {
1320
- if (entry.state === 'retry') return 'RETRYING'
1321
- switch (delegationActivity(entry)) {
1322
- case 'delegating':
1323
- return 'DELEGATING'
1324
- case 'working':
1325
- return 'WORKING'
1326
- case 'reading':
1327
- return 'READING RESULT'
1328
- case 'completed':
1329
- return entry.timedOut ? 'DONE (TIMED OUT)' : 'DONE'
1330
- case 'error':
1331
- return 'ERROR'
1332
- default:
1333
- return 'CANCELLED'
1334
- }
1335
- }
1336
-
1337
- const DELEGATION_SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
1338
-
1339
- /** Return a deterministic spinner frame. The View ticks this every 140ms. */
1340
- export function delegationSpinnerFrame(now: number): string {
1341
- const index = Math.floor(Math.max(0, now) / 140) % DELEGATION_SPINNER_FRAMES.length
1342
- return DELEGATION_SPINNER_FRAMES[index] ?? DELEGATION_SPINNER_FRAMES[0]
1343
- }
1344
-
1345
- /* ─── Live tool activity per child session (beta.6) ────────────────────────
1346
- * The delegation panel's activity line ("↳ bash npm test") — what the agent
1347
- * is doing RIGHT NOW. Sourced from message.part.updated tool parts: every
1348
- * pending/running tool part updates a per-child-session record (latest wins).
1349
- * Module-level by design: the sidebar remounts on route changes and the
1350
- * "what is each agent doing" state should survive that (OMO pattern). */
1351
-
1352
- export type ToolActivity = {
1353
- tool: string
1354
- summary: string
1355
- at: number
1356
- }
1357
-
1358
- /** Bounded tracker: child session id → latest running tool call. */
1359
- const latestToolActivity = new Map<string, ToolActivity>()
1360
- const MAX_TOOL_ACTIVITY_ENTRIES = 200
1361
- const TOOL_ACTIVITY_TTL_MS = 5 * 60 * 1000
1362
-
1363
- /** Archived-section pagination state — module-level so it survives sidebar
1364
- * remounts (route changes) without leaking into the component tree. */
1365
- const archivedUiState = { page: 0 }
1366
-
1367
- /** First usable summary string from common tool input fields. */
1368
- function summarizeToolInput(input: Record<string, unknown> | undefined): string {
1369
- if (!input) return ''
1370
- const candidates = ['command', 'description', 'prompt', 'filePath', 'pattern', 'url', 'query']
1371
- for (const key of candidates) {
1372
- const value = input[key]
1373
- if (typeof value === 'string' && value.trim() !== '') return value
1374
- }
1375
- return ''
1376
- }
1377
-
1378
- /** Reduce one message.part.updated tool part to displayable activity.
1379
- * Returns null for non-tool parts, completed/error parts (no live activity)
1380
- * or parts without a session id. Pure. */
1381
- export function extractToolActivity(
1382
- part: {
1383
- type?: string
1384
- tool?: string
1385
- sessionID?: string
1386
- state?: { status?: string; input?: Record<string, unknown> }
1387
- },
1388
- now = Date.now(),
1389
- ): { sessionID: string; activity: ToolActivity } | null {
1390
- if (part?.type !== 'tool') return null
1391
- const status = part.state?.status
1392
- if (status !== 'pending' && status !== 'running') return null
1393
- const sessionID = typeof part.sessionID === 'string' ? part.sessionID : ''
1394
- if (sessionID === '') return null
1395
- const tool = typeof part.tool === 'string' && part.tool !== '' ? part.tool : 'tool'
1396
- const summary = summarizeToolInput(part.state?.input).replace(/\s+/g, ' ').trim().slice(0, 48)
1397
- return { sessionID, activity: { tool, summary, at: now } }
1398
- }
1399
-
1400
- /** Record an activity sample (bounded map, oldest dropped). */
1401
- export function trackToolActivity(
1402
- map: Map<string, ToolActivity>,
1403
- sessionID: string,
1404
- activity: ToolActivity,
1405
- ): void {
1406
- if (sessionID === '') return
1407
- if (map.size >= MAX_TOOL_ACTIVITY_ENTRIES) {
1408
- const oldest = map.keys().next().value
1409
- if (oldest !== undefined) map.delete(oldest)
1410
- }
1411
- map.set(sessionID, activity)
1412
- }
1413
-
1414
- /** Latest live activity for a child session, or null when absent/stale. */
1415
- export function latestToolActivityFor(
1416
- map: Map<string, ToolActivity>,
1417
- sessionID: string | undefined,
1418
- now = Date.now(),
1419
- ttlMs = TOOL_ACTIVITY_TTL_MS,
1420
- ): ToolActivity | null {
1421
- if (!sessionID) return null
1422
- const hit = map.get(sessionID)
1423
- if (hit === undefined) return null
1424
- if (now - hit.at > ttlMs) return null
1425
- return hit
1426
- }
1427
-
1428
- /** Merge the immediate tool-event channel into the child-session channel.
1429
- *
1430
- * Children remain the durable source, while live entries make a delegation
1431
- * visible before the child API/report catches up. A finalized md entry wins
1432
- * over a stale live entry; a child-only row is upgraded with live agent,
1433
- * alias, phase and timestamps. */
1434
- export function mergeChildDelegationSources(
1435
- children: readonly DelegationEntry[],
1436
- live: readonly LiveDelegationEntry[],
1437
- ): DelegationEntry[] {
1438
- const result = [...children]
1439
- const byTask = new Map<string, number>()
1440
- const bySessionAlias = new Map<string, number>()
1441
- const key = (sessionID: string, alias: string): string => `${sessionID}\u0000${alias}`
1442
-
1443
- result.forEach((entry, index) => {
1444
- if (entry.taskID !== undefined) byTask.set(entry.taskID, index)
1445
- bySessionAlias.set(key(entry.sessionID, entry.alias), index)
1446
- })
1447
-
1448
- for (const liveEntry of live) {
1449
- if (
1450
- liveEntry.alias === null &&
1451
- liveEntry.taskID === null &&
1452
- Date.now() - liveEntry.startedAt > 30_000
1453
- )
1454
- continue
1455
- const incoming = toDelegationEntry(liveEntry)
1456
- const index =
1457
- (incoming.taskID !== undefined ? byTask.get(incoming.taskID) : undefined) ??
1458
- (incoming.alias !== ''
1459
- ? bySessionAlias.get(key(incoming.sessionID, incoming.alias))
1460
- : undefined)
1461
-
1462
- if (index === undefined) {
1463
- result.push(incoming)
1464
- const newIndex = result.length - 1
1465
- if (incoming.taskID !== undefined) byTask.set(incoming.taskID, newIndex)
1466
- bySessionAlias.set(key(incoming.sessionID, incoming.alias), newIndex)
1467
- continue
1468
- }
1469
-
1470
- const existing = result[index]
1471
- if (existing === undefined) continue
1472
- // Any terminal state is authoritative — a child session that went idle
1473
- // correctly derives 'completed' via childStatusToState before the MD
1474
- // report is written. The live tool-part channel stays 'running' until
1475
- // pantheon_delegation_read fires, so allowing it to overwrite a
1476
- // terminal state would flip completed → running (the bug this fixes).
1477
- //
1478
- // When the existing entry IS terminal, we still absorb live metadata
1479
- // (alias, agent, read) but preserve the terminal state.
1480
- if (existing.state !== 'running') {
1481
- if (liveEntry.alias !== null && existing.alias !== incoming.alias) {
1482
- existing.alias = incoming.alias
1483
- }
1484
- if (incoming.agent !== 'agent' && existing.agent !== incoming.agent) {
1485
- existing.agent = incoming.agent
1486
- }
1487
- if (incoming.read && !existing.read) {
1488
- existing.read = true
1489
- }
1490
- continue
1491
- }
1492
- result[index] = {
1493
- ...existing,
1494
- alias: liveEntry.alias !== null ? incoming.alias : existing.alias,
1495
- sessionID: existing.sessionID || incoming.sessionID,
1496
- taskID: existing.taskID ?? incoming.taskID,
1497
- agent: incoming.agent !== 'agent' ? incoming.agent : existing.agent,
1498
- description: incoming.description !== '' ? incoming.description : existing.description,
1499
- state: incoming.state,
1500
- startedAt: Math.min(existing.startedAt, incoming.startedAt),
1501
- updatedAt: incoming.updatedAt,
1502
- read: incoming.read,
1503
- source: 'live',
1504
- }
1505
- }
1506
-
1507
- result.sort(compareDelegationEntries)
1508
- return result
1509
- }
1510
-
1511
- /* ─── Live tool-call lifecycle (agent-sidebar pattern) ─────
1512
- * Source of truth for jobs born while opencode is open. The TUI event bus
1513
- * (api.event.on) delivers `message.part.updated` for every part change;
1514
- * we only care about tool parts whose `tool` is pantheon_delegate (job
1515
- * launch), the native `task` subagent tool (same parentID === caller
1516
- * mechanism — its rows render `[native]`), or pantheon_delegation_read
1517
- * (blocking until terminal → closes the entry). Shape-adapted from the
1518
- * SDK v2 ToolPart but duck-typed so the pure helpers are testable without
1519
- * the SDK. */
1520
-
1521
- /** Duck-typed subset of a tool part (SDK v2 `ToolPart` / `ToolState`). */
1522
- export type DelegationToolPart = {
1523
- id?: string
1524
- callID?: string
1525
- sessionID?: string
1526
- type?: string
1527
- tool?: string
1528
- state?: {
1529
- status?: string
1530
- input?: Record<string, unknown>
1531
- output?: string
1532
- error?: string
1533
- time?: { start?: number; end?: number }
1534
- }
1535
- }
1536
-
1537
- /** One live delegation tracked in-memory, keyed by the delegate callID. */
1538
- export type LiveDelegationEntry = {
1539
- /** Tool call id of the pantheon_delegate part (stable across events). */
1540
- callID: string
1541
- /** Part id (for message.part.removed cleanup). */
1542
- partID: string
1543
- /** Parent session the delegation was launched from. */
1544
- sessionID: string
1545
- tool: 'pantheon_delegate' | 'pantheon_delegation_read' | 'task'
1546
- /** Agent name (from the delegate input args). */
1547
- agent: string
1548
- description: string
1549
- /** Known after the delegate tool completes (parsed from its output). */
1550
- alias: string | null
1551
- /** Child session id (parsed from the delegate output). */
1552
- taskID: string | null
1553
- state: 'running' | 'completed' | 'error' | 'cancelled'
1554
- startedAt: number
1555
- updatedAt: number | null
1556
- /** True once a pantheon_delegation_read for this job has been observed. */
1557
- read: boolean
1558
- }
1559
-
1560
- /** Result of parsing one tool part into lifecycle-relevant fields. */
1561
- export type ParsedDelegationToolPart = {
1562
- callID: string
1563
- partID: string
1564
- sessionID: string
1565
- tool: 'pantheon_delegate' | 'pantheon_delegation_read' | 'task'
1566
- /** null for read parts (no agent arg — the id targets an existing job). */
1567
- agent: string | null
1568
- description: string
1569
- status: 'pending' | 'running' | 'completed' | 'error'
1570
- alias: string | null
1571
- taskID: string | null
1572
- startedAt: number
1573
- endAt: number | null
1574
- }
1575
-
1576
- /** Alias in the delegate output: "Delegated to apollo: [apo-1] (task …)". */
1577
- const DELEGATE_ALIAS_PATTERN = /\[([a-z]{2,8}-\d+)\]/i
1578
- /** Child task id in the delegate output: "(task ses_child_9)". */
1579
- const DELEGATE_TASKID_PATTERN = /\(task\s+([a-z0-9_]+)\)/i
1580
- /** Plain alias, as passed to pantheon_delegation_read input.id: "apo-1". */
1581
- const READ_ALIAS_PATTERN = /^[a-z]{2,8}-\d+$/i
1582
-
1583
- /** Extract the tool name + args from a `message.part.updated` part and
1584
- * reduce it to what the panel needs. Returns null for anything that is
1585
- * not a pantheon delegation tool part, the native `task` subagent tool
1586
- * (same parentID === caller mechanism — its children render `[native]`),
1587
- * or is missing its callID. */
1588
- export function parseDelegationToolPart(
1589
- part: DelegationToolPart,
1590
- now = Date.now(),
1591
- ): ParsedDelegationToolPart | null {
1592
- if (part.type !== 'tool') return null
1593
- if (
1594
- part.tool !== 'pantheon_delegate' &&
1595
- part.tool !== 'pantheon_delegation_read' &&
1596
- part.tool !== 'task'
1597
- )
1598
- return null
1599
- const callID = part.callID
1600
- if (callID === undefined || callID === '') return null
1601
- const sessionID = part.sessionID ?? ''
1602
- const state = part.state ?? {}
1603
- const status = state.status ?? 'pending'
1604
- if (status !== 'pending' && status !== 'running' && status !== 'completed' && status !== 'error')
1605
- return null
1606
- const input = state.input ?? {}
1607
- const startedAt = state.time?.start ?? now
1608
- const endAt = state.time?.end ?? null
1609
-
1610
- if (part.tool === 'pantheon_delegation_read') {
1611
- const target = typeof input.id === 'string' ? input.id : null
1612
- let alias: string | null = null
1613
- let taskID: string | null = null
1614
- if (target !== null) {
1615
- if (READ_ALIAS_PATTERN.test(target)) alias = target
1616
- else if (target.startsWith('ses_')) taskID = target // raw child session id
1617
- }
1618
- return {
1619
- callID,
1620
- partID: part.id ?? '',
1621
- sessionID,
1622
- tool: 'pantheon_delegation_read',
1623
- agent: null,
1624
- description: '',
1625
- status,
1626
- alias,
1627
- taskID,
1628
- startedAt,
1629
- endAt,
1630
- }
1631
- }
1632
-
1633
- const agent =
1634
- typeof input.agent === 'string'
1635
- ? input.agent
1636
- : typeof input.subagent_type === 'string'
1637
- ? (input.subagent_type as string)
1638
- : 'agent'
1639
- const description =
1640
- typeof input.description === 'string'
1641
- ? input.description
1642
- : typeof input.prompt === 'string'
1643
- ? (input.prompt as string).slice(0, 120)
1644
- : ''
1645
- // The alias/taskID only exist once the delegate tool COMPLETES (they are
1646
- // returned in its output); a running/pending part has neither. Native
1647
- // `task` parts never carry a board alias — the children channel supplies
1648
- // the child session id, so the row renders `[native]`.
1649
- let alias: string | null = null
1650
- let taskID: string | null = null
1651
- if (status === 'completed') {
1652
- const output = state.output ?? ''
1653
- alias = DELEGATE_ALIAS_PATTERN.exec(output)?.[1] ?? null
1654
- taskID = DELEGATE_TASKID_PATTERN.exec(output)?.[1] ?? null
1655
- }
1656
- return {
1657
- callID,
1658
- partID: part.id ?? '',
1659
- sessionID,
1660
- tool: part.tool === 'task' ? 'task' : 'pantheon_delegate',
1661
- agent,
1662
- description,
1663
- status,
1664
- alias,
1665
- taskID,
1666
- startedAt,
1667
- endAt,
1668
- }
1669
- }
1670
-
1671
- /** Find a live entry by alias or taskID (read parts resolve by id). */
1672
- function findLiveByTarget(
1673
- map: Map<string, LiveDelegationEntry>,
1674
- alias: string | null,
1675
- taskID: string | null,
1676
- ): LiveDelegationEntry | undefined {
1677
- if (alias === null && taskID === null) return undefined
1678
- for (const entry of map.values()) {
1679
- if (alias !== null && entry.alias === alias) return entry
1680
- if (taskID !== null && entry.taskID === taskID) return entry
1681
- }
1682
- return undefined
1683
- }
1684
-
1685
- /** Apply one tool part to the live map. Returns true when the map changed.
1686
- * Pure w.r.t. I/O — only mutates `map`. */
1687
- export function reduceDelegationToolPart(
1688
- map: Map<string, LiveDelegationEntry>,
1689
- part: DelegationToolPart,
1690
- now = Date.now(),
1691
- ): boolean {
1692
- const parsed = parseDelegationToolPart(part, now)
1693
- if (parsed === null) return false
1694
-
1695
- // Read tool: never creates a row — it resolves a delegation by id. It
1696
- // marks the target `read` and (because it blocks until terminal) closes
1697
- // the entry on completed/error with its end timestamp.
1698
- if (parsed.tool === 'pantheon_delegation_read') {
1699
- const target = findLiveByTarget(map, parsed.alias, parsed.taskID)
1700
- if (target === undefined) return false
1701
- let changed = false
1702
- if (!target.read) {
1703
- target.read = true
1704
- changed = true
1705
- }
1706
- if (parsed.status === 'completed' && target.state === 'running') {
1707
- target.state = 'completed'
1708
- target.updatedAt = parsed.endAt ?? now
1709
- changed = true
1710
- } else if (parsed.status === 'error' && target.state === 'running') {
1711
- target.state = 'error'
1712
- target.updatedAt = parsed.endAt ?? now
1713
- changed = true
1714
- }
1715
- return changed
1716
- }
1717
-
1718
- // Delegate tool (pantheon_delegate AND native task): pending/running →
1719
- // job launched (running). A COMPLETED delegate tool only means the job was
1720
- // registered — it stays running and we pick up alias + taskID from the
1721
- // output. Native `task` parts never yield a board alias, so their rows
1722
- // stay `[native]` until the children channel resolves them.
1723
- const existing = map.get(parsed.callID)
1724
- if (parsed.status === 'error') {
1725
- if (existing !== undefined && existing.state === 'error' && existing.updatedAt === parsed.endAt)
1726
- return false
1727
- map.set(parsed.callID, {
1728
- callID: parsed.callID,
1729
- partID: parsed.partID,
1730
- sessionID: parsed.sessionID,
1731
- tool: parsed.tool,
1732
- agent: parsed.agent ?? 'agent',
1733
- description: parsed.description,
1734
- alias: existing?.alias ?? null,
1735
- taskID: existing?.taskID ?? null,
1736
- state: 'error',
1737
- startedAt: existing?.startedAt ?? parsed.startedAt,
1738
- updatedAt: parsed.endAt ?? now,
1739
- read: existing?.read ?? false,
1740
- })
1741
- return true
1742
- }
1743
- if (existing === undefined) {
1744
- map.set(parsed.callID, {
1745
- callID: parsed.callID,
1746
- partID: parsed.partID,
1747
- sessionID: parsed.sessionID,
1748
- tool: parsed.tool,
1749
- agent: parsed.agent ?? 'agent',
1750
- description: parsed.description,
1751
- alias: parsed.alias,
1752
- taskID: parsed.taskID,
1753
- state: 'running',
1754
- startedAt: parsed.startedAt,
1755
- updatedAt: null,
1756
- read: false,
1757
- })
1758
- return true
1759
- }
1760
- // Existing entry: absorb newly-discovered alias/taskID/agent/description.
1761
- let changed = false
1762
- if (parsed.alias !== null && existing.alias !== parsed.alias) {
1763
- existing.alias = parsed.alias
1764
- changed = true
1765
- }
1766
- if (parsed.taskID !== null && existing.taskID !== parsed.taskID) {
1767
- existing.taskID = parsed.taskID
1768
- changed = true
1769
- }
1770
- if (parsed.agent !== null && existing.agent !== parsed.agent) {
1771
- existing.agent = parsed.agent
1772
- changed = true
1773
- }
1774
- if (parsed.description !== '' && existing.description !== parsed.description) {
1775
- existing.description = parsed.description
1776
- changed = true
1777
- }
1778
- if (existing.partID === '' && parsed.partID !== '') {
1779
- existing.partID = parsed.partID
1780
- changed = true
1781
- }
1782
- return changed
1783
- }
1784
-
1785
- /** Remove a live entry by part id (message.part.removed) or call id.
1786
- * Returns true when something was removed. */
1787
- export function removeDelegationEntry(
1788
- map: Map<string, LiveDelegationEntry>,
1789
- partIDOrCallID: string,
1790
- ): boolean {
1791
- if (map.delete(partIDOrCallID)) return true
1792
- for (const [key, entry] of map) {
1793
- if (entry.partID === partIDOrCallID) {
1794
- map.delete(key)
1795
- return true
1796
- }
1797
- }
1798
- return false
1799
- }
1800
-
1801
- /** Collect pantheon delegation + native task tool parts from a session's messages.
1802
- * Messages may carry their parts inline (duck-typed `msg.parts`); when
1803
- * they don't, the optional `getParts(messageID)` callback is used (the TUI
1804
- * SDK exposes `api.state.part(messageID)`). The native `task` tool spawns a
1805
- * child session with parentID = caller — the same mechanism as
1806
- * pantheon_delegate — so its parts feed the live-map as the native signal
1807
- * (rows render `[native]` via the children channel). Pure w.r.t. I/O — used
1808
- * by the mount re-scan to re-seed the live map after compaction/attach. */
1809
- export function collectDelegationToolParts(
1810
- messages: readonly { id?: string; parts?: unknown[] }[] | undefined,
1811
- getParts?: (messageID: string) => readonly unknown[] | undefined,
1812
- ): DelegationToolPart[] {
1813
- const out: DelegationToolPart[] = []
1814
- for (const msg of messages ?? []) {
1815
- let parts: readonly unknown[] | undefined
1816
- if (Array.isArray(msg?.parts)) {
1817
- parts = msg.parts
1818
- } else if (msg?.id !== undefined && typeof getParts === 'function') {
1819
- parts = getParts(msg.id)
1820
- }
1821
- if (!parts) continue
1822
- for (const raw of parts) {
1823
- const part = raw as DelegationToolPart
1824
- if (
1825
- part?.type === 'tool' &&
1826
- (part.tool === 'pantheon_delegate' ||
1827
- part.tool === 'pantheon_delegation_read' ||
1828
- part.tool === 'task')
1829
- ) {
1830
- out.push(part)
1831
- }
1832
- }
1833
- }
1834
- return out
1835
- }
1836
-
1837
- /** Apply a batch of tool parts (in message order) to the live map. Used on
1838
- * mount to re-seed entries that `message.part.removed` (compaction) wiped,
1839
- * from the session's existing tool parts. Returns how many parts changed
1840
- * the map (0 on the second identical seed — idempotent, no extra bumps). */
1841
- export function seedLiveDelegationMap(
1842
- map: Map<string, LiveDelegationEntry>,
1843
- parts: readonly DelegationToolPart[],
1844
- now = Date.now(),
1845
- ): number {
1846
- let changed = 0
1847
- for (const part of parts) {
1848
- if (reduceDelegationToolPart(map, part, now)) changed++
1849
- }
1850
- return changed
1851
- }
1852
-
1853
- /** Convert a live entry into the shared display shape. Alias falls back to
1854
- * a `live-<callID>` prefix while the delegate tool has not completed yet. */
1855
- export function toDelegationEntry(live: LiveDelegationEntry): DelegationEntry {
1856
- return {
1857
- alias: live.alias ?? `live-${live.callID.slice(0, 8)}`,
1858
- sessionID: live.sessionID,
1859
- ...(live.taskID !== null ? { taskID: live.taskID } : {}),
1860
- agent: live.agent,
1861
- state: live.state,
1862
- startedAt: live.startedAt,
1863
- updatedAt: live.updatedAt,
1864
- timedOut: false,
1865
- description: live.description,
1866
- read: live.read,
1867
- source: 'live',
1868
- }
1869
- }
1870
-
1871
- /** Combine the live channel with the md (historical) channel into one
1872
- * display list. Dedupes by (sessionID, alias) — aliases are per-parent-
1873
- * session, so the same alias in different sessions stays separate. A
1874
- * terminal md entry is authoritative over a live running entry for the
1875
- * same job (it carries Finalized/timedOut/cancelled from finalize). */
1876
- export function mergeDelegationSources(
1877
- live: readonly LiveDelegationEntry[],
1878
- md: readonly DelegationEntry[],
1879
- ): DelegationEntry[] {
1880
- const keyOf = (sessionID: string, alias: string): string => `${sessionID}\u0000${alias}`
1881
- const byKey = new Map<string, DelegationEntry>()
1882
- for (const m of md) {
1883
- const key = keyOf(m.sessionID, m.alias)
1884
- const existing = byKey.get(key)
1885
- if (existing === undefined || (existing.state === 'running' && m.state !== 'running'))
1886
- byKey.set(key, m)
1887
- }
1888
- const aliasless: DelegationEntry[] = []
1889
- for (const l of live) {
1890
- const e = toDelegationEntry(l)
1891
- if (l.alias === null) {
1892
- aliasless.push(e)
1893
- continue
1894
- }
1895
- const key = keyOf(l.sessionID, l.alias)
1896
- const mdEntry = byKey.get(key)
1897
- if (mdEntry !== undefined && mdEntry.state !== 'running') continue // md terminal wins
1898
- byKey.set(key, e)
1899
- }
1900
- const all = [...aliasless, ...byKey.values()]
1901
- all.sort(compareDelegationEntries)
1902
- return all
1903
- }
1904
-
1905
- /* ─── Children channel (primary source, delegations-sidebar pattern) ────
1906
- * `api.client.session.children` returns the child sessions of the current
1907
- * session — every pantheon_delegate spawns one (parentID = caller). The
1908
- * pure helpers here turn those children + the md reports into the display
1909
- * list, and navigate to a child session on click. */
1910
-
1911
- /* ─── Current-session resolution + path guard (placeholder regression) ──
1912
- * The sidebar forwarded `props.session_id` verbatim into
1913
- * `session.children({ path: { id } })`. When the TUI runtime renders the
1914
- * sidebar without a focused session it leaves the route template
1915
- * UNSUBSTITUTED — the literal "{sessionID}" string — which opencode's server
1916
- * rejected every poll (SchemaError: Expected a string starting with "ses",
1917
- * got "%7BsessionID%7D"), ~1 error/s from the 1s safety poll, and the failed
1918
- * call fail-opened into "Delegations (0)".
1919
- *
1920
- * Contract: resolution NEVER yields a placeholder — an invalid/absent id is
1921
- * null, and a null resolution means the children fetch is SKIPPED (empty
1922
- * panel, ZERO errors). Sources, in order:
1923
- * 1. the sidebar_content slot prop (`session_id`);
1924
- * 2. `api.state.sessionID` (duck-typed: the typed TuiState has no such
1925
- * field, but the runtime state is a superset — the delegations-sidebar
1926
- * reference reads the current session from api.state);
1927
- * 3. `api.route.current.params.sessionID` (typed: TuiRouteCurrent's
1928
- * `{ name: 'session', params: { sessionID } }` variant).
1929
- * Each source passes the same server-aligned validity check (non-empty
1930
- * string starting with "ses"), so a placeholder or garbage at any position
1931
- * falls through to the next source instead of hitting the wire. */
1932
-
1933
- /** Server-aligned session id validity: opencode rejects anything not starting
1934
- * with "ses" (SchemaError). This deliberately mirrors that exact contract —
1935
- * nothing stricter, nothing looser — so a template placeholder ("{sessionID}"),
1936
- * its URL-encoded form ("%7BsessionID%7D", what the server reported in the
1937
- * schema error), an empty/undefined value, or a foreign id (e.g. "wrk_") can
1938
- * never reach a path and error-spam the log. Confirmed: "{sessionID}" starts
1939
- * with "{" and "%7BsessionID%7D" with "%" — both fail startsWith("ses"), so
1940
- * the placeholder is rejected WITHOUT an explicit denylist (covered by tests). */
1941
- export function isValidSessionId(id: unknown): id is string {
1942
- return typeof id === 'string' && id.startsWith('ses')
1943
- }
1944
-
1945
- /** Sources the sidebar can resolve the CURRENT session id from. Duck-typed
1946
- * subsets of TuiPluginApi / TuiState / TuiRouteCurrent so the helper stays
1947
- * pure and testable without the TUI runtime. */
1948
- export type TuiSessionSources = {
1949
- /** sidebar_content slot prop (`session_id`). */
1950
- sessionID?: string | null
1951
- api?: {
1952
- /** Runtime state superset — may expose the current session id. */
1953
- state?: { sessionID?: unknown }
1954
- /** Typed route: { name: 'session', params: { sessionID } } when in one. */
1955
- route?: { current?: { name?: string; params?: Record<string, unknown> } }
1956
- } | null
1957
- }
1958
-
1959
- /** Resolve the current session id for the sidebar. Order: slot prop →
1960
- * api.state.sessionID (runtime superset) → api.route.current.params.sessionID
1961
- * (typed route). Every source is validated; invalid/absent → next source.
1962
- * NEVER returns a placeholder or non-ses id. Null → callers MUST skip the
1963
- * fetch (empty panel, zero errors). Pure — no I/O, no runtime required. */
1964
- export function resolveCurrentSessionID(sources: TuiSessionSources): string | null {
1965
- const candidates: unknown[] = [
1966
- sources?.sessionID,
1967
- sources?.api?.state?.sessionID,
1968
- sources?.api?.route?.current?.params?.sessionID,
1969
- ]
1970
- for (const candidate of candidates) {
1971
- if (isValidSessionId(candidate)) return candidate
1972
- }
1973
- return null
1974
- }
1975
-
1976
- /** THE single choke point for every `session.children` / session-API path.
1977
- * Returns `{ path: { id } }` ONLY for a server-valid session id; returns
1978
- * null for anything else (placeholder, empty, foreign id) so the caller
1979
- * skips the call entirely instead of sending an unsubstituted placeholder
1980
- * (the "%7BsessionID%7D" regression). Every session-API call site MUST go
1981
- * through this function (enforced by the source-scan test in
1982
- * tests/pantheon/tui-delegations.test.ts). */
1983
- export function safeSessionPath(id: unknown): { path: { id: string } } | null {
1984
- if (!isValidSessionId(id)) return null
1985
- return { path: { id } }
1986
- }
1987
-
1988
- /** Build the `session.children` path ONLY from a validated session id.
1989
- * Delegates to {@link safeSessionPath} — the single choke point. Returns
1990
- * null for null/invalid ids so the caller skips the fetch instead of
1991
- * sending an unsubstituted placeholder (the "%7BsessionID%7D" regression). */
1992
- export function buildChildrenPath(id: string | null | undefined): { path: { id: string } } | null {
1993
- return safeSessionPath(id)
1994
- }
1995
-
1996
- /** Duck-typed subset of a child Session (+ its live status type). */
1997
- export type ChildDelegationLike = {
1998
- /** Child session id (= board task id). */
1999
- id: string
2000
- /** Session title — the delegate's description or prompt prefix. */
2001
- title?: string
2002
- /** Agent name when the child session carries one (duck-typed; native
2003
- * task() children may expose it, board reports always do). */
2004
- agent?: string
2005
- /** Status type from api.state.session.status: 'busy' | 'retry' | 'idle',
2006
- * or undefined when the status API is unavailable. */
2007
- status?: string
2008
- time?: {
2009
- created?: number
2010
- updated?: number
2011
- }
2012
- }
2013
-
2014
- /** Map a child status type to a display state. busy/retry → running
2015
- * (the child is actively working), idle → completed, unknown → running
2016
- * (fail-open: a freshly-seen child is assumed active; the 1s poll + md
2017
- * correct it as soon as terminal data exists). */
2018
- export function childStatusToState(status: string | undefined): 'running' | 'completed' | 'retry' {
2019
- if (status === 'idle') return 'completed'
2020
- if (status === 'retry') return 'retry'
2021
- return 'running' // busy or unknown
2022
- }
2023
-
2024
- /** Row tag for a delegation entry: `[native]` for native task() children
2025
- * (source 'children-only' — no board report), `[pantheon:<alias>]` for board
2026
- * rows ([pantheon:apo-1]) — the same tags the manager prints in
2027
- * pantheon_delegation_list, so panel rows and CLI list lines match. The
2028
- * panel renders the tag with a distinct style so native task() children are
2029
- * visually separable from pantheon_delegate jobs. */
2030
- export function delegationTag(entry: DelegationEntry): string {
2031
- return entry.source === 'children-only' ? '[native]' : `[pantheon:${entry.alias}]`
2032
- }
2033
-
2034
- /** Split a display list into native task() rows vs pantheon_delegate rows.
2035
- * Native = source 'children-only' (no board report); everything else counts
2036
- * as pantheon. Pure — powers the header breakdown + the hooks.log line. */
2037
- export function countDelegationSources(entries: readonly DelegationEntry[]): {
2038
- native: number
2039
- pantheon: number
2040
- total: number
2041
- } {
2042
- let native = 0
2043
- for (const e of entries) if (e.source === 'children-only') native++
2044
- return { native, pantheon: entries.length - native, total: entries.length }
2045
- }
2046
-
2047
- /** Diagnostic hooks.log line for a panel re-fetch, with the children
2048
- * breakdown (pantheon = children WITH a board report, native = children
2049
- * WITHOUT one). Pure — the View logs the returned string verbatim. */
2050
- export function formatPanelLogLine(
2051
- children: number,
2052
- pantheon: number,
2053
- native: number,
2054
- md: number,
2055
- events: number,
2056
- ): string {
2057
- return `panel: children=${children}(pantheon=${pantheon} native=${native}) md=${md} events=${events}`
2058
- }
2059
-
2060
- /** Turn child sessions (PRIMARY) enriched with md reports into the display
2061
- * list. One entry per child id (duplicates across re-fetches collapse).
2062
- * The md report is matched by `Task ID` (== child.id) and supplies alias,
2063
- * agent, description, terminal state and duration. A child without a
2064
- * report still renders: description from its title, agent from the child
2065
- * itself (fallback 'agent'), state derived from its status, startedAt from
2066
- * time.created. A report-less child is a NATIVE task() child (every
2067
- * child of the current session — pantheon_delegate OR the native `task()`
2068
- * tool — carries parentID = caller), so it gets source 'children-only',
2069
- * the internal alias 'native-task' and the `[native]` tag instead of a
2070
- * board alias. The 'task nativa' description fallback keeps the row
2071
- * non-empty when the child carries no title.
2072
- * Terminal md state wins over the derived state; a running md defers to
2073
- * the child's live status. A running child is NEVER archived — it always
2074
- * lands in the active split (splitDelegationList active = running/retry).
2075
- * Sorted running-first (compareDelegationEntries).
2076
- * Pure — no I/O. */
2077
- export function childrenToDelegationEntries(
2078
- children: readonly ChildDelegationLike[] | undefined,
2079
- md: readonly DelegationEntry[],
2080
- now = Date.now(),
2081
- ): DelegationEntry[] {
2082
- const byTaskID = new Map<string, DelegationEntry>()
2083
- for (const m of md) {
2084
- if (m.taskID !== undefined && !byTaskID.has(m.taskID)) byTaskID.set(m.taskID, m)
2085
- }
2086
- const out: DelegationEntry[] = []
2087
- const seen = new Set<string>()
2088
- for (const child of children ?? []) {
2089
- if (child.id === '' || seen.has(child.id)) continue
2090
- seen.add(child.id)
2091
- const mdEntry = byTaskID.get(child.id)
2092
- const state =
2093
- mdEntry !== undefined && mdEntry.state !== 'running'
2094
- ? mdEntry.state
2095
- : childStatusToState(child.status)
2096
- out.push({
2097
- alias: mdEntry?.alias ?? 'native-task',
2098
- sessionID: mdEntry?.sessionID ?? '',
2099
- taskID: child.id,
2100
- agent: mdEntry?.agent ?? child.agent ?? 'agent',
2101
- state,
2102
- startedAt: mdEntry?.startedAt ?? child.time?.created ?? now,
2103
- updatedAt:
2104
- mdEntry?.updatedAt ??
2105
- (state === 'running' || state === 'stale-running' ? null : (child.time?.updated ?? null)),
2106
- timedOut: mdEntry?.timedOut ?? false,
2107
- description:
2108
- mdEntry !== undefined && mdEntry.description !== ''
2109
- ? mdEntry.description
2110
- : child.title !== undefined && child.title !== ''
2111
- ? child.title
2112
- : 'task nativa',
2113
- source: mdEntry !== undefined ? 'md' : 'children-only',
2114
- })
2115
- }
2116
- out.sort(compareDelegationEntries)
2117
- return out
2118
- }
2119
-
2120
- /** Navigate the TUI to a child session (click/Enter on a delegation row).
2121
- * Returns false when the route API is unavailable or the target id is
2122
- * missing/placeholder — the row stays inert instead of crashing. Only a
2123
- * server-valid session id ("ses...") ever reaches the router, so an
2124
- * unsubstituted "{sessionID}" placeholder can never be routed. */
2125
- export function navigateToDelegationSession(
2126
- route: { navigate?: (name: string, params?: Record<string, unknown>) => void } | undefined,
2127
- taskID: string | undefined,
2128
- ): boolean {
2129
- if (typeof route?.navigate !== 'function' || !isValidSessionId(taskID)) return false
2130
- route.navigate('session', { sessionID: taskID })
2131
- return true
2132
- }
2133
-
2134
- /* ─── Silence-by-default panel logger ──────────────────────
2135
- * Mirrors src/pantheon/logger.ts createPantheonLogger (the TUI plugin is
2136
- * self-contained — dist/tui.tsx is a raw copy with no relative imports):
2137
- * every line is ALWAYS appended to `<logDir>/.pantheon/logs/hooks.log` and
2138
- * echoed to the console ONLY when PANTHEON_HOOKS_LOG is truthy (opencode
2139
- * renders plugin console output directly into the TUI — the pollution bug).
2140
- * Best-effort and fire-and-forget: a logging failure must never break the
2141
- * panel. */
2142
- type TuiLogger = { info: (message: string, ...args: unknown[]) => void }
2143
-
2144
- /** Silence-by-default panel logger.
2145
- * @param projectRoot the PROJECT ROOT — the logger appends to
2146
- * `<projectRoot>/.pantheon/logs/hooks.log` (tuiLogPath). Passing anything
2147
- * deeper (e.g. the delegations dir) used to double-nest the path into
2148
- * `<root>/.pantheon/.pantheon/logs/hooks.log` and never reach the real log;
2149
- * derive the root with {@link panelLogDir}. */
2150
- function createTuiLogger(projectRoot: string | undefined, module = 'pantheon-tui'): TuiLogger {
2151
- const echo = (process.env.PANTHEON_HOOKS_LOG ?? '').trim() !== ''
2152
- const logPath = tuiLogPath(projectRoot ?? process.cwd())
2153
- const formatArg = (arg: unknown): string => {
2154
- if (arg instanceof Error) return arg.stack ?? arg.message
2155
- if (typeof arg === 'string') return arg
2156
- try {
2157
- return JSON.stringify(arg)
2158
- } catch {
2159
- return String(arg)
2160
- }
2161
- }
2162
- const write = (message: string, args: unknown[]) => {
2163
- const lines = [message, ...args.map(formatArg)]
2164
- .join(' ')
2165
- .split('\n')
2166
- .map((p) => p.trim())
2167
- .filter((p) => p !== '')
2168
- if (lines.length === 0) return
2169
- void (async () => {
2170
- try {
2171
- await mkdir(dirname(logPath), { recursive: true })
2172
- const stamp = new Date().toISOString()
2173
- await appendFile(
2174
- logPath,
2175
- `${lines.map((l) => `[${stamp}] [${module}] ${l}`).join('\n')}\n`,
2176
- 'utf8',
2177
- )
2178
- } catch {
2179
- /* best-effort file log — never break the panel over logging */
2180
- }
2181
- })()
2182
- if (echo) {
2183
- for (const line of lines) console.log(`[${module}] ${line}`)
2184
- }
2185
- }
2186
- return { info: (message, ...args) => write(message, args) }
2187
- }
2188
-
2189
- /* ─── Session Row (single session with live status indicator) ─ */
2190
-
2191
- function SessionRow(props: { api: TuiPluginApi; session: any }) {
2192
- const theme = () => props.api.theme.current
2193
-
2194
- const status = createMemo(() => {
2195
- // isValidSessionId guard: a placeholder / foreign session id must never
2196
- // reach the status API (same "%7BsessionID%7D" regression class as the
2197
- // children path). Invalid id → no status call, no icon.
2198
- if (!isValidSessionId(props.session?.id)) return null
2199
- try {
2200
- const s = (props.api.state as any).session?.status?.(props.session.id)
2201
- if (s?.type) return s.type as string
2202
- } catch {
2203
- /* ignore */
2204
- }
2205
- return null
2206
- })
2207
-
2208
- const statusIcon = createMemo(() => {
2209
- switch (status()) {
2210
- case 'busy':
2211
- return '\u25cf ' // ● — running
2212
- case 'retry':
2213
- return '\u26a0 ' // ⚠ — needs attention
2214
- default:
2215
- return '' // idle/unknown — no icon
2216
- }
2217
- })
2218
-
2219
- return (
2220
- <text fg={theme().textMuted}>
2221
- {`${statusIcon()}${props.session?.id?.slice(0, 8) ?? '????'}... ${props.session?.title?.slice(0, 26) ?? '(untitled)'}`}
2222
- </text>
2223
- )
2224
- }
2225
-
2226
- /* ─── Delegation Row (single job from the children/md channels) ─ */
2227
-
2228
- function DelegationRow(props: {
2229
- api: TuiPluginApi
2230
- job: DelegationEntry
2231
- now: number
2232
- animationNow: number
2233
- }) {
2234
- const theme = () => props.api.theme.current
2235
-
2236
- const color = createMemo(() => {
2237
- const t = theme()
2238
- switch (props.job.state) {
2239
- case 'running':
2240
- return t.warning
2241
- case 'retry':
2242
- return t.warning
2243
- case 'stale-running':
2244
- return t.error // warning color for stale delegations
2245
- case 'completed':
2246
- return t.success
2247
- case 'error':
2248
- return t.error
2249
- default:
2250
- return t.textMuted // cancelled
2251
- }
2252
- })
2253
-
2254
- const marker = createMemo(() => {
2255
- if (props.job.state === 'running') return `${delegationSpinnerFrame(props.animationNow)} `
2256
- if (props.job.state === 'retry') return '\u27f3 ' // ⟳ retrying
2257
- if (props.job.state === 'stale-running') return '\u26a0 ' // warning triangle
2258
- switch (props.job.state) {
2259
- case 'completed':
2260
- return '\u2713 '
2261
- case 'error':
2262
- return '\u2715 '
2263
- default:
2264
- return '\u25cb '
2265
- }
2266
- })
2267
-
2268
- // The row tag: `[native]` for native task() children (no board report),
2269
- // `[pantheon:apo-1]`-style alias for pantheon_delegate board rows. Rendered with
2270
- // the info color so task() children are visually distinct from delegates.
2271
- const tagColor = createMemo(() => (props.job.source === 'children-only' ? theme().info : color()))
2272
-
2273
- const detail = createMemo(() => {
2274
- const elapsed = delegationElapsed(props.job, props.now)
2275
- const description = props.job.description !== '' ? ` \u2014 ${props.job.description}` : ''
2276
- const line = `${elapsed}${description}`
2277
- return line.length > 180 ? `${line.slice(0, 177)}\u2026` : line
2278
- })
2279
-
2280
- // beta.6: live tool call the child is running RIGHT NOW ("↳ bash npm test"),
2281
- // fed by message.part.updated activity tracking. Null while idle/done.
2282
- const activity = createMemo(() =>
2283
- latestToolActivityFor(latestToolActivity, props.job.taskID, props.now),
2284
- )
2285
-
2286
- // Click a row → navigate to the child session (route API guarded in the
2287
- // helper). Enter-key binding is left out (per-row keymap wiring is not
2288
- // worth the complexity in this sidebar); mouse is enabled in tui.json.
2289
- const open = () => {
2290
- navigateToDelegationSession(props.api.route, props.job.taskID)
2291
- }
2292
-
2293
- return (
2294
- <box onMouseDown={open}>
2295
- <box flexDirection="row">
2296
- <text fg={color()}>{marker()}</text>
2297
- <text fg={tagColor()}>{delegationTag(props.job)}</text>
2298
- <text
2299
- fg={color()}
2300
- >{` ${props.job.agent} \u2014 ${delegationActivityLabel(props.job)}`}</text>
2301
- </box>
2302
- <text fg={theme().textMuted}>{detail()}</text>
2303
- <Show when={activity()}>
2304
- {(a) => (
2305
- <text
2306
- fg={theme().textMuted}
2307
- >{` \u21b3 ${a().tool}${a().summary !== '' ? ` ${a().summary}` : ''}`}</text>
2308
- )}
2309
- </Show>
2310
- </box>
2311
- )
2312
- }
2313
-
2314
- /* ─── Main Sidebar View ──────────────────────────────────── */
2315
-
2316
- /** Plugin-level live delegation store shared with the event subscriptions
2317
- * in `tui()`: the map of live entries + a version signal bumped on every
2318
- * mutation. The View subscribes to the version (in an effect) to refresh the
2319
- * durable child list and also reads the map as an optimistic live source. */
2320
- export type LiveDelegationStore = {
2321
- map: Map<string, LiveDelegationEntry>
2322
- /** Reactive version getter — View reads it inside an effect to re-fetch. */
2323
- version: () => number
2324
- /** Bump the version after a live mutation. */
2325
- bump: () => void
2326
- }
2327
-
2328
- function View(props: {
2329
- api: TuiPluginApi
2330
- sessionID: string | undefined
2331
- version: string | null
2332
- liveStore: LiveDelegationStore
2333
- }) {
2334
- const [showSessions, setShowSessions] = createSignal(false)
2335
- // Show live work immediately; the header remains clickable to collapse it.
2336
- const [showDelegations, setShowDelegations] = createSignal(true)
2337
-
2338
- const theme = () => props.api.theme.current
2339
-
2340
- const branch = createMemo(() =>
2341
- props.api.state.vcs?.branch ? `\u2387 ${props.api.state.vcs.branch}` : null,
2342
- )
2343
-
2344
- // ── Active preset indicator ──
2345
- // Seeded synchronously from env (never blocks first paint), then re-checked
2346
- // against .pantheon/active-preset.json on mount and every 30s so `set-tier`
2347
- // changes made while opencode is open become visible.
2348
- const [preset, setPreset] = createSignal<PresetInfo>(presetFromEnv(process.env))
2349
-
2350
- onMount(() => {
2351
- const cwd = ((props.api.state as any).path?.worktree ?? '') || process.cwd()
2352
- let cancelled = false
2353
- const refresh = async () => {
2354
- try {
2355
- const info = await resolvePresetForTui(process.env, cwd)
2356
- if (!cancelled) setPreset(info)
2357
- } catch {
2358
- // transient read error — keep the last known value
2359
- }
2360
- }
2361
- void refresh()
2362
- const timer = setInterval(() => void refresh(), PRESET_REFRESH_MS)
2363
- onCleanup(() => {
2364
- cancelled = true
2365
- clearInterval(timer)
2366
- })
2367
- })
2368
-
2369
- // ── Sessions: fetch via api.client.session.list (not proc.exec) ──
2370
- const [sessionList, { refetch: refetchSessions }] = createResource(async () => {
2371
- try {
2372
- const result = await (props.api.client as any)?.session?.list?.({ limit: 100 })
2373
- return result ?? { data: [] }
2374
- } catch {
2375
- return { data: [] }
2376
- }
2377
- })
2378
-
2379
- // Total top-level sessions (excludes subagent sessions)
2380
- const totalSessions = createMemo(() => {
2381
- const result = sessionList()
2382
- if (!result) return 0
2383
- const data: any[] = (result as any).data ?? result
2384
- if (!Array.isArray(data)) return 0
2385
- return data.filter((s: any) => !s.parentID).length
2386
- })
2387
-
2388
- // Recent top-level sessions, sorted by time.updated descending
2389
- const recentSessions = createMemo(() => {
2390
- const result = sessionList()
2391
- if (!result) return []
2392
- const data: any[] = (result as any).data ?? result
2393
- if (!Array.isArray(data)) return []
2394
- return data
2395
- .filter(
2396
- (s: any) =>
2397
- !s.parentID &&
2398
- s.id !== resolveCurrentSessionID({ sessionID: props.sessionID, api: props.api }),
2399
- )
2400
- .sort((a: any, b: any) => {
2401
- const ta = a.time?.updated ?? a.updated ?? 0
2402
- const tb = b.time?.updated ?? b.updated ?? 0
2403
- return tb - ta
2404
- })
2405
- .slice(0, 8)
2406
- })
2407
-
2408
- // ── Delegations: session.children (PRIMARY) + md reports (enrichment) ──
2409
- // The panel's source of truth is the SDK child-session API
2410
- // (`api.client.session.children`) — every pantheon_delegate spawns a child
2411
- // session with parentID = this session, so children ARE the delegation
2412
- // list (delegations-sidebar pattern). The md channel
2413
- // (.pantheon/delegations) enriches each child with alias/agent/description
2414
- // and terminal duration via the `Task ID` match. Live tool-call events are
2415
- // merged optimistically so the row appears before those channels catch up.
2416
- const delegationsDir = createMemo(() => resolveDelegationsDir((props.api.state as any).path))
2417
- // Silence-by-default panel logger → the REAL <root>/.pantheon/logs/hooks.log.
2418
- // panelLogDir(<root>/.pantheon/delegations) = <root>: the old code passed
2419
- // dirname(delegationsDir()) (= <root>/.pantheon), which createTuiLogger
2420
- // re-joined with `.pantheon/logs/hooks.log` → a nested
2421
- // <root>/.pantheon/.pantheon/logs/hooks.log that never reached the real
2422
- // hooks.log (the empty nested dirs observed in production).
2423
- const panelLog = createTuiLogger(panelLogDir(delegationsDir()))
2424
- // The rendered list is childDelegations (children enriched with md);
2425
- // there is no separate md-only signal — the md channel only feeds
2426
- // childrenToDelegationEntries below.
2427
- const [childDelegations, setChildDelegations] = createSignal<DelegationEntry[]>([])
2428
- // 1s ticker drives the running-jobs elapsed counter AND the safety poll
2429
- // (oh-my-opencode-slim pattern): re-fetch children + re-read the md every
2430
- // second so the panel updates even when NO event ever fires.
2431
- const [now, setNow] = createSignal(Date.now())
2432
- // Separate fast ticker for the spinner. The elapsed label intentionally
2433
- // remains on the 1s ticker to avoid unnecessary work.
2434
- const [animationNow, setAnimationNow] = createSignal(Date.now())
2435
- // Cumulative count of event-triggered refreshes — logged with every fetch
2436
- // ("panel: children=N(pantheon=M native=K) md=N events=N") so the (0)
2437
- // symptom is diagnosable: children>0 means the source works; events=0
2438
- // means the event bus isn't delivering, and the 1s poll is what keeps
2439
- // the panel honest.
2440
- let eventRefreshCount = 0
2441
- // In-flight guard: overlap between the poll, events and the version effect
2442
- // collapses into one fetch — no duplicate work, no duplicate entries.
2443
- let delegationsInflight: Promise<void> | null = null
2444
- const refreshDelegations = () => {
2445
- if (delegationsInflight !== null) return delegationsInflight
2446
- delegationsInflight = (async () => {
2447
- try {
2448
- const state = props.api.state as any
2449
- // 0. md reports from EVERY session under .pantheon/delegations — the
2450
- // HISTORY channel. Read BEFORE the sessionID guard so the panel shows
2451
- // past reports (running first, Finalized desc) even when no session
2452
- // is focused (null/placeholder sessionID): the "(0)" symptom becomes
2453
- // the full historical list. Fail-open: a missing dir yields [].
2454
- let md: DelegationEntry[] = []
2455
- try {
2456
- md = await readAllDelegationEntries(panelLogDir(delegationsDir()))
2457
- } catch {
2458
- md = [] // fail-open: never crash the sidebar on a read error
2459
- }
2460
- // 1. current session — resolve + GUARD (placeholder regression). The
2461
- // runtime may render the sidebar with an unsubstituted "{sessionID}"
2462
- // slot prop; forwarding it to session.children made the server reject
2463
- // every poll (~1 err/s: "Expected a string starting with \"ses\", got
2464
- // \"%7BsessionID%7D\"") and fail-open the panel into "(0)". A null
2465
- // resolution SKIPS the fetch entirely: the md history is shown alone
2466
- // (zero children, zero errors).
2467
- const sessionID = resolveCurrentSessionID({ sessionID: props.sessionID, api: props.api })
2468
- if (sessionID === null) {
2469
- setChildDelegations(md)
2470
- panelLog.info(
2471
- `${formatPanelLogLine(0, 0, 0, md.length, eventRefreshCount)} (no sessionID — history shown)`,
2472
- )
2473
- return
2474
- }
2475
- // 2. children — PRIMARY source (SDK: api.client.session.children).
2476
- let children: ChildDelegationLike[] = []
2477
- try {
2478
- // buildChildrenPath re-validates: with sessionID !== null it is
2479
- // never null, so no placeholder can reach the wire.
2480
- const result = await (props.api.client as any)?.session?.children?.(
2481
- buildChildrenPath(sessionID),
2482
- )
2483
- const data = (result?.data ?? result) as unknown
2484
- children = Array.isArray(data) ? (data as ChildDelegationLike[]) : []
2485
- } catch (err) {
2486
- children = [] // children API unavailable — the panel shows md only
2487
- panelLog.info('panel: error children fetch', err)
2488
- }
2489
- // 3. live status per child (sync API) + merge children with md.
2490
- const resolveStatus = (childID: unknown): string | undefined => {
2491
- // isValidSessionId guard: a placeholder / foreign id must never
2492
- // reach the status API (same regression class as the children
2493
- // path — "%7BsessionID%7D").
2494
- if (!isValidSessionId(childID)) return undefined
2495
- try {
2496
- return state?.session?.status?.(childID)?.type as string | undefined
2497
- } catch {
2498
- return undefined // status API unavailable — child state fallback
2499
- }
2500
- }
2501
- const withStatus = children.map((c) => ({ ...c, status: resolveStatus(c.id) }))
2502
- const childEntries = childrenToDelegationEntries(withStatus, md, now())
2503
- for (const [k, v] of props.liveStore.map)
2504
- if (v.alias === null && v.taskID === null && Date.now() - v.startedAt > 30_000)
2505
- props.liveStore.map.delete(k)
2506
- // The event channel is optimistic: it renders a job even while the
2507
- // child session/report is still being created. Filter by parent so a
2508
- // different focused session never leaks rows into this sidebar.
2509
- const liveEntries = [...props.liveStore.map.values()].filter(
2510
- (entry) => entry.sessionID === sessionID,
2511
- )
2512
- setChildDelegations(mergeChildDelegationSources(childEntries, liveEntries))
2513
- // 4. diagnostic line — every re-fetch (silence-by-default, hooks.log).
2514
- const counts = countDelegationSources(childEntries)
2515
- panelLog.info(
2516
- formatPanelLogLine(
2517
- children.length,
2518
- counts.pantheon,
2519
- counts.native,
2520
- md.length,
2521
- eventRefreshCount,
2522
- ),
2523
- )
2524
- } finally {
2525
- delegationsInflight = null
2526
- }
2527
- })()
2528
- return delegationsInflight
2529
- }
2530
- // beta.6: active (running/retry) first, then the 8 most recent terminal
2531
- // reports, then the archived tail (paginated). Pagination state lives at
2532
- // module level so sidebar remounts keep the user's page.
2533
- const delegationSplit = createMemo(() => splitDelegationList(childDelegations()))
2534
- const visibleDelegations = createMemo(() => [
2535
- ...delegationSplit().active,
2536
- ...delegationSplit().recent,
2537
- ])
2538
- // Header breakdown: native task() rows vs pantheon_delegate rows, so
2539
- // Sessions(3) with 3 native children reads "Delegations (3 native + 0 pantheon)".
2540
- const delegationCounts = createMemo(() => countDelegationSources(visibleDelegations()))
2541
- const [archivedPage, setArchivedPage] = createSignal(archivedUiState.page)
2542
- const clampArchivedPage = (page: number, pages: number) => {
2543
- const clamped = Math.max(0, Math.min(page, Math.max(0, pages - 1)))
2544
- archivedUiState.page = clamped
2545
- setArchivedPage(clamped)
2546
- }
2547
-
2548
- // ── Event subscriptions for live session/delegation updates ──
2549
- onMount(() => {
2550
- const cleanup: (() => void)[] = []
2551
-
2552
- // Session events — triggers the sessions resource refetch.
2553
- try {
2554
- cleanup.push(props.api.event.on('session.status', refetchSessions))
2555
- cleanup.push(props.api.event.on('session.created', refetchSessions))
2556
- cleanup.push(props.api.event.on('session.updated', refetchSessions))
2557
- cleanup.push(props.api.event.on('session.deleted', refetchSessions))
2558
- } catch {
2559
- /* events API not available in this runtime */
2560
- }
2561
-
2562
- // Delegation panel: children are born/die with session lifecycle events
2563
- // (a delegate spawns a child → session.created fires) — re-fetch on all
2564
- // of them. `session.status` re-syncs busy→idle state transitions.
2565
- try {
2566
- const eventRefresh = () => {
2567
- eventRefreshCount += 1
2568
- void refreshDelegations()
2569
- }
2570
- cleanup.push(props.api.event.on('session.created', eventRefresh))
2571
- cleanup.push(props.api.event.on('session.updated', eventRefresh))
2572
- cleanup.push(props.api.event.on('session.deleted', eventRefresh))
2573
- cleanup.push(props.api.event.on('session.status', eventRefresh))
2574
- } catch {
2575
- /* events API not available — the 1s poll still covers it */
2576
- }
2577
-
2578
- // message.part.updated/removed → liveStore.version() bumps (tui()):
2579
- // subscribe here so the panel ALSO re-fetches children when tool-part
2580
- // events DO arrive and the updated live row is rendered immediately.
2581
- createEffect(() => {
2582
- props.liveStore.version() // subscribe to live mutations
2583
- eventRefreshCount += 1
2584
- void refreshDelegations()
2585
- })
2586
-
2587
- // Safety poll (OMO-slim pattern): 1s re-fetch children + md + tick the
2588
- // elapsed counter. Guarantees the panel updates even with zero events.
2589
- const poll = setInterval(() => {
2590
- setNow(Date.now())
2591
- void refreshDelegations()
2592
- }, 1_000)
2593
- cleanup.push(() => clearInterval(poll))
2594
- const animation = setInterval(() => setAnimationNow(Date.now()), 140)
2595
- cleanup.push(() => clearInterval(animation))
2596
-
2597
- // Compaction recovery: `message.part.removed` clears live entries while
2598
- // compacting, so after a compaction/attach the live map would start
2599
- // empty even though the session still holds the delegation tool parts.
2600
- // Re-seed the live map from the session's existing parts (in message
2601
- // order) right after the subscriptions are registered — the version
2602
- // bump re-triggers the children fetch. Fail-open: if the SDK access is
2603
- // unavailable we skip — the children API + the 1s poll keep the panel
2604
- // working.
2605
- try {
2606
- const sdk = (props.api.state as any)?.session
2607
- const mountSessionID = resolveCurrentSessionID({ sessionID: props.sessionID, api: props.api })
2608
- if (mountSessionID !== null && typeof sdk?.messages === 'function') {
2609
- const messages: readonly { id?: string; parts?: unknown[] }[] =
2610
- sdk.messages(mountSessionID) ?? []
2611
- const state = props.api.state as any
2612
- const getParts =
2613
- typeof state?.part === 'function'
2614
- ? (messageID: string) => state.part(messageID)
2615
- : undefined
2616
- const parts = collectDelegationToolParts(messages, getParts)
2617
- if (parts.length > 0 && seedLiveDelegationMap(props.liveStore.map, parts) > 0) {
2618
- props.liveStore.bump()
2619
- }
2620
- }
2621
- } catch {
2622
- /* re-scan unavailable — children API + 1s poll still cover it */
2623
- }
2624
-
2625
- onCleanup(() =>
2626
- cleanup.forEach((fn) => {
2627
- fn()
2628
- }),
2629
- )
2630
- })
2631
-
2632
- const HR = () => <text fg={theme().textMuted}>{'\u2500'.repeat(28)}</text>
2633
-
2634
- return (
2635
- <box flexDirection="column" width="100%">
2636
- {/* ── Header ── */}
2637
- <text fg={theme().accent} attributes={1}>
2638
- {`Pantheon${props.version ? ` v${props.version}` : ''}`}
2639
- </text>
2640
- <Show when={branch()}>{(b) => <text fg={theme().textMuted}>{b()}</text>}</Show>
2641
-
2642
- {/* ── Active preset indicator ── */}
2643
- <Show
2644
- when={preset().name}
2645
- fallback={
2646
- <box flexDirection="row" gap={1}>
2647
- <text fg={theme().textMuted}>Preset: default</text>
2648
- </box>
2649
- }
2650
- >
2651
- {(name) => (
2652
- <box flexDirection="row" gap={1}>
2653
- <text fg={theme().textMuted}>{'\u26a1 Preset:'}</text>
2654
- <text fg={theme().accent}>{name()}</text>
2655
- <text fg={theme().textMuted}>{`(${preset().source ?? ''})`}</text>
2656
- </box>
2657
- )}
2658
- </Show>
2659
-
2660
- <HR />
2661
-
2662
- {/* ── Sessions ── */}
2663
- <box onMouseDown={() => setShowSessions((x) => !x)}>
2664
- <text fg={theme().text} attributes={1}>
2665
- {`${showSessions() ? '\u25bc' : '\u25b6'} Sessions`}
2666
- </text>
2667
- <text fg={theme().textMuted}>{` (${String(totalSessions())})`}</text>
2668
- </box>
2669
- <Show when={showSessions()}>
2670
- <Show
2671
- when={recentSessions().length > 0}
2672
- fallback={
2673
- <box marginLeft={1}>
2674
- <text fg={theme().textMuted}>No recent sessions</text>
2675
- </box>
2676
- }
2677
- >
2678
- <box marginLeft={1} flexDirection="column">
2679
- <For each={recentSessions()}>
2680
- {(ses: any) => <SessionRow api={props.api} session={ses} />}
2681
- </For>
2682
- </box>
2683
- </Show>
2684
- </Show>
2685
-
2686
- {/* ── Delegations (session.children primary + .pantheon/delegations md enrichment) ── */}
2687
- <box onMouseDown={() => setShowDelegations((x) => !x)}>
2688
- <text fg={theme().text} attributes={1}>
2689
- {`${showDelegations() ? '▼' : '▶'} Delegations`}
2690
- </text>
2691
- <text
2692
- fg={theme().textMuted}
2693
- >{` (${String(delegationCounts().native)} native + ${String(delegationCounts().pantheon)} pantheon)`}</text>
2694
- </box>
2695
- <Show when={showDelegations()}>
2696
- <Show
2697
- when={visibleDelegations().length > 0}
2698
- fallback={
2699
- <box marginLeft={1}>
2700
- <text fg={theme().textMuted}>No delegations</text>
2701
- </box>
2702
- }
2703
- >
2704
- <box marginLeft={1} flexDirection="column">
2705
- <For each={visibleDelegations()}>
2706
- {(job) => (
2707
- <DelegationRow
2708
- api={props.api}
2709
- job={job}
2710
- now={now()}
2711
- animationNow={animationNow()}
2712
- />
2713
- )}
2714
- </For>
2715
- <Show when={delegationSplit().archived.length > 0}>
2716
- {(() => {
2717
- const archived = delegationSplit().archived
2718
- const pageSize = 8
2719
- const pages = Math.ceil(archived.length / pageSize)
2720
- const page = Math.min(archivedPage(), pages - 1)
2721
- const slice = archived.slice(page * pageSize, page * pageSize + pageSize)
2722
- return (
2723
- <box flexDirection="column">
2724
- <box flexDirection="row" marginLeft={0}>
2725
- <text
2726
- fg={theme().textMuted}
2727
- onMouseDown={() => clampArchivedPage(page - 1, pages)}
2728
- >{`\u2039 `}</text>
2729
- <text fg={theme().textMuted}>{`Archived (${archived.length}) `}</text>
2730
- <text fg={theme().textMuted}>{`${page + 1}/${pages}`}</text>
2731
- <text
2732
- fg={theme().textMuted}
2733
- onMouseDown={() => clampArchivedPage(page + 1, pages)}
2734
- >{` \u203a`}</text>
2735
- </box>
2736
- <For each={slice}>
2737
- {(job) => (
2738
- <DelegationRow
2739
- api={props.api}
2740
- job={job}
2741
- now={now()}
2742
- animationNow={animationNow()}
2743
- />
2744
- )}
2745
- </For>
2746
- </box>
2747
- )
2748
- })()}
2749
- </Show>
2750
- </box>
2751
- </Show>
2752
- </Show>
2753
- </box>
2754
- )
2755
- }
2756
-
2757
- /* ─── Plugin Registration ────────────────────────────────── */
2758
-
2759
- const tui: TuiPlugin = (api, _options, _meta) => {
2760
- if (pantheonPluginOnce('pantheon:tui')) return
2761
- // Do not await project file/process probes here. OpenCode waits for the TUI
2762
- // factory before it finishes startup, and a Windows host opening a WSL
2763
- // project can leave those probes pending while the project bridge comes up.
2764
- // Register the sidebar immediately and fill in the optional version later.
2765
- const [version, setVersion] = createSignal<string | null>(null)
2766
- void detectVersion(api)
2767
- .then((detected) => setVersion(detected))
2768
- .catch(() => setVersion(null))
2769
-
2770
- // Vendored feature (MIT): AI subscription usage gauges.
2771
- void setupUsageBar(api) // async init — never blocks sidebar registration
2772
-
2773
- // ── Live delegation store (legacy tool-part tracker, kept as a REFRESH
2774
- // TRIGGER) ──
2775
- // The Delegations panel's PRIMARY source is `api.client.session.children`
2776
- // (delegations-sidebar pattern) — `message.part.updated` may not fire for
2777
- // pantheon_delegate on runtime 1.18.13 (the "(0)" symptom). The tool-part
2778
- // lifecycle below still tracks pantheon_delegate / pantheon_delegation_read
2779
- // parts and bumps a version signal the View subscribes to: when part
2780
- // events DO arrive, the panel re-fetches children. Fail-open: if the
2781
- // events API is unavailable nothing subscribes and the 1s safety poll
2782
- // keeps the panel working (never crash).
2783
- const [liveVersion, setLiveVersion] = createSignal(0)
2784
- const liveStore: LiveDelegationStore = {
2785
- map: new Map<string, LiveDelegationEntry>(),
2786
- version: liveVersion,
2787
- bump: () => setLiveVersion((v) => v + 1),
2788
- }
2789
- const unsubLive: (() => void)[] = []
2790
-
2791
- try {
2792
- unsubLive.push(
2793
- api.event.on('message.part.updated', (event: any) => {
2794
- // SDK v2 shape: properties.part (v1 drift: properties.info.part).
2795
- const props = (event?.properties ?? {}) as { part?: unknown; info?: { part?: unknown } }
2796
- const part = (props.part ?? props.info?.part) as DelegationToolPart | undefined
2797
- if (part === undefined) return
2798
- // beta.6: track the live tool call per child session (panel's
2799
- // activity line). Fire-and-forget — display-only state.
2800
- const sample = extractToolActivity(part as any)
2801
- if (sample !== null)
2802
- trackToolActivity(latestToolActivity, sample.sessionID, sample.activity)
2803
- if (reduceDelegationToolPart(liveStore.map, part)) liveStore.bump()
2804
- }),
2805
- )
2806
- } catch {
2807
- /* events API unavailable — children API + 1s poll cover the panel */
2808
- }
2809
- try {
2810
- unsubLive.push(
2811
- api.event.on('message.part.removed', (event: any) => {
2812
- // SDK v2 shape: properties.partID (v1 drift: properties.part.id).
2813
- const props = (event?.properties ?? {}) as { partID?: string; part?: { id?: string } }
2814
- const partID = props.partID ?? props.part?.id
2815
- if (partID !== undefined && removeDelegationEntry(liveStore.map, partID)) liveStore.bump()
2816
- }),
2817
- )
2818
- } catch {
2819
- /* events API unavailable — children API + 1s poll cover the panel */
2820
- }
2821
- api.lifecycle.onDispose(() => {
2822
- for (const unsub of unsubLive) {
2823
- try {
2824
- unsub()
2825
- } catch {
2826
- /* ignore */
2827
- }
2828
- }
2829
- liveStore.map.clear()
2830
- })
2831
-
2832
- api.slots.register({
2833
- order: 900,
2834
- slots: {
2835
- sidebar_content(_ctx, props) {
2836
- return (
2837
- <View api={api} sessionID={props.session_id} version={version()} liveStore={liveStore} />
2838
- )
2839
- },
2840
- },
2841
- })
2842
- }
2843
-
2844
- const plugin: TuiPluginModule & { id: string; setup: () => Promise<void> } = {
2845
- id: 'pantheon.tui',
2846
- tui,
2847
- // Beta loader contract: every `plugins` directory entry must expose a
2848
- // no-op `setup` so the entry loads as `pantheon.tui` with zero errors
2849
- // (sandbox probe evidence). The TUI itself boots via `tui()`.
2850
- setup: async () => {},
2851
- }
2852
-
2853
- export default plugin