pantheon-opencode 1.5.0-beta.8 → 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 +320 -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 +229 -77
  43. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  44. package/src/plugins/tui/dist/tui.js +509 -259
  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 +753 -279
  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 -2777
@@ -1,2777 +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 "panel: children=N md=N events=N"
925
- * to `.pantheon/logs/hooks.log` (silence-by-default, createPantheonLogger
926
- * policy) so the (0) symptom is diagnosable from disk. A children fetch
927
- * failure logs "panel: error <msg>" (previously silenced), and a missing
928
- * current session (null/placeholder sessionID) logs "panel: children=0
929
- * md=N ... (no sessionID — history shown)" — the md HISTORY renders
930
- * instead of erroring.
931
- *
932
- * 5. SESSIONID GUARD (placeholder regression) — the runtime may hand the
933
- * sidebar the UNSUBSTITUTED template literal "{sessionID}" as its
934
- * session_id (no focused session). Forwarding it to session.children
935
- * made opencode's server reject every poll (~1 err/s: "Expected a string
936
- * starting with \"ses\", got \"%7BsessionID%7D\"") and fail-open the
937
- * panel into "(0)". resolveCurrentSessionID (slot prop → api.state →
938
- * route.current) never yields a placeholder (isValidSessionId rejects
939
- * "{sessionID}" and "%7BsessionID%7D" via the startsWith("ses")
940
- * contract); a null resolution SKIPS the children fetch entirely and
941
- * renders the md history — zero errors.
942
- *
943
- * The live tool-part lifecycle helpers below remain (tested, exported) but
944
- * are no longer the source of truth: they feed a version signal that merely
945
- * re-triggers the children fetch. Everything is fail-open: a missing
946
- * children API or directory yields [], and any unreadable input is skipped —
947
- * never crash. */
948
-
949
- export type DelegationEntry = {
950
- /** Job alias, e.g. "apo-1" (from the H1 title, falling back to filename). */
951
- alias: string
952
- /** Parent session the job was launched from (dir name under .pantheon/delegations). */
953
- sessionID: string
954
- /** Child session id (= board task id, from the `Task ID` header). The
955
- * children channel always sets it from the child session itself; the md
956
- * channel parses it so child↔md matching works by taskID. */
957
- taskID?: string
958
- /** Agent name, e.g. "apollo". */
959
- agent: string
960
- state:
961
- | 'running'
962
- | 'retry'
963
- | 'completed'
964
- | 'error'
965
- | 'startup_failed'
966
- | 'startup_unknown'
967
- | 'cancelled'
968
- | 'stale-running'
969
- /** Epoch ms of the `Started` header. */
970
- startedAt: number
971
- /** Epoch ms of the `Finalized` header — null while still running. */
972
- updatedAt: number | null
973
- timedOut: boolean
974
- description: string
975
- /** True while the panel is waiting for pantheon_delegation_read. */
976
- read?: boolean
977
- /** Internal provenance used to keep a finalized md report authoritative.
978
- * 'children-only' = a native task() child session with NO board report
979
- * (rendered with the distinct `[native]` tag); 'md' = board report wins. */
980
- source?: 'child' | 'live' | 'md' | 'children-only'
981
- }
982
-
983
- /** True for `\s` characters (space, tab, newline, CR) — plain char checks so
984
- * the parser stays regex-free (CodeQL flagged the old `\s*`/`\s+` + `(.+)`
985
- * patterns as polynomial ReDoS: 12x HIGH). */
986
- function isWs(ch: string | undefined): boolean {
987
- return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r'
988
- }
989
-
990
- /** Em/en dash + hyphen — the separators accepted after the H1 title. */
991
- const TITLE_SEPARATORS = '—–-'
992
-
993
- /** Parse one delegation report md header into a structured entry.
994
- * Returns null (skip) when the file is not a recognizable report:
995
- * missing agent/state/startedAt, an unknown state, or an unparsable
996
- * Started timestamp. The alias falls back to the file name when the H1
997
- * title is missing. Pure — no I/O.
998
- *
999
- * Linear, single-pass over `raw.split('\n')` with plain string operations
1000
- * (startsWith/indexOf/slice) — zero regex, so worst case is O(bytes) even
1001
- * on adversarial whitespace-heavy input (ReDoS regression, CodeQL 12x HIGH). */
1002
- export function parseDelegationMarkdown(
1003
- raw: string,
1004
- fileAlias?: string,
1005
- sessionID = '',
1006
- ): DelegationEntry | null {
1007
- let title: string | undefined
1008
- let agent: string | undefined
1009
- let description = ''
1010
- let state: string | undefined
1011
- let timedOut = false
1012
- let started: string | undefined
1013
- let finalized: string | undefined
1014
- let taskID: string | undefined
1015
-
1016
- for (const rawLine of raw.split('\n')) {
1017
- // H1 title: `# Delegation Report — <alias>` (empty alias → fallback later).
1018
- if (rawLine[0] === '#' && isWs(rawLine[1])) {
1019
- let i = 2
1020
- while (i < rawLine.length && isWs(rawLine[i])) i++
1021
- if (rawLine.startsWith('Delegation Report', i)) {
1022
- i += 'Delegation Report'.length
1023
- while (i < rawLine.length && isWs(rawLine[i])) i++
1024
- if (i < rawLine.length && TITLE_SEPARATORS.includes(rawLine[i])) {
1025
- const rest = rawLine.slice(i + 1).trim()
1026
- if (rest !== '' && title === undefined) title = rest
1027
- }
1028
- }
1029
- continue
1030
- }
1031
- // Field bullets: `- **Name**: value` — unknown names are ignored.
1032
- if (rawLine[0] !== '-') continue
1033
- let i = 1
1034
- while (i < rawLine.length && isWs(rawLine[i])) i++
1035
- if (!rawLine.startsWith('**', i)) continue
1036
- const nameStart = i + 2
1037
- const valueEnd = rawLine.indexOf('**:', nameStart)
1038
- if (valueEnd < 0) continue
1039
- const name = rawLine.slice(nameStart, valueEnd)
1040
- const value = rawLine.slice(valueEnd + 3).trim()
1041
- switch (name) {
1042
- case 'Task ID':
1043
- // `- **Task ID**: \`ses_x\`` — strip the surrounding backticks.
1044
- if (value !== '' && taskID === undefined) taskID = stripTaskIdTicks(value)
1045
- break
1046
- case 'Agent':
1047
- // Empty value counts as missing (old regex `(.+)` required 1+ chars).
1048
- if (value !== '' && agent === undefined) agent = value
1049
- break
1050
- case 'Description':
1051
- description = value
1052
- break
1053
- case 'State':
1054
- if (value !== '' && state === undefined) state = value
1055
- break
1056
- case 'Timed out':
1057
- // Old `(true|false)` prefix match, case-sensitive — kept verbatim.
1058
- timedOut = value.startsWith('true')
1059
- break
1060
- case 'Started':
1061
- if (value !== '' && started === undefined) started = value
1062
- break
1063
- case 'Finalized':
1064
- finalized = value
1065
- break
1066
- default:
1067
- break // unknown field (e.g. Task ID) → ignore the line
1068
- }
1069
- }
1070
-
1071
- const startedAt = started !== undefined ? Date.parse(started) : NaN
1072
- if (agent === undefined || state === undefined || Number.isNaN(startedAt)) return null
1073
- const normalized = state.toLowerCase()
1074
- // Running state should only come from live channels, never from persisted
1075
- // reports. A stale "running" MD artifact contaminates the panel — skip it.
1076
- if (normalized === 'running') return null
1077
- if (
1078
- normalized !== 'completed' &&
1079
- normalized !== 'error' &&
1080
- normalized !== 'startup_failed' &&
1081
- normalized !== 'startup_unknown' &&
1082
- normalized !== 'cancelled'
1083
- ) {
1084
- return null
1085
- }
1086
- const finalizedAt = finalized !== undefined ? Date.parse(finalized) : NaN
1087
-
1088
- return {
1089
- alias: title ?? (fileAlias !== undefined ? stripMdSuffix(fileAlias) : 'unknown'),
1090
- sessionID,
1091
- ...(taskID !== undefined ? { taskID } : {}),
1092
- agent,
1093
- state: normalized,
1094
- startedAt,
1095
- updatedAt: Number.isNaN(finalizedAt) ? null : finalizedAt,
1096
- timedOut,
1097
- description,
1098
- source: 'md',
1099
- }
1100
- }
1101
-
1102
- /** Strip a trailing `.md` (any case) — linear replacement for /\.md$/i. */
1103
- function stripMdSuffix(name: string): string {
1104
- return name.toLowerCase().endsWith('.md') ? name.slice(0, name.length - 3) : name
1105
- }
1106
-
1107
- /** Strip surrounding backticks from a `Task ID` value: "`ses_x`" → "ses_x". */
1108
- function stripTaskIdTicks(value: string): string {
1109
- const start = value[0] === '`' ? 1 : 0
1110
- const end =
1111
- value.length > start && value[value.length - 1] === '`' ? value.length - 1 : value.length
1112
- return value.slice(start, end)
1113
- }
1114
-
1115
- /** Read every delegation report under `<dir>/<sessionID>/<alias>.md`.
1116
- * Fail-open: a missing/unreadable directory yields [], and each unreadable
1117
- * or malformed file is skipped individually. Entries are sorted running
1118
- * first, then terminal by `updatedAt` (most recent first) so the panel can
1119
- * render them in order directly. */
1120
- export async function readDelegationEntries(dir: string): Promise<DelegationEntry[]> {
1121
- let sessionDirs: Dirent[]
1122
- try {
1123
- sessionDirs = await readdir(dir, { withFileTypes: true })
1124
- } catch {
1125
- return [] // directory absent/unreadable — nothing to show
1126
- }
1127
-
1128
- const entries: DelegationEntry[] = []
1129
- for (const session of sessionDirs) {
1130
- if (!session.isDirectory()) continue
1131
- let files: Dirent[]
1132
- try {
1133
- files = await readdir(join(dir, session.name), { withFileTypes: true })
1134
- } catch {
1135
- continue // unreadable session dir — skip
1136
- }
1137
- for (const file of files) {
1138
- if (!file.isFile() || !file.name.endsWith('.md')) continue
1139
- try {
1140
- const raw = await readFile(join(dir, session.name, file.name), 'utf8')
1141
- const entry = parseDelegationMarkdown(raw, file.name, session.name)
1142
- if (entry !== null) entries.push(entry)
1143
- } catch {
1144
- // unreadable/malformed file — skip, never crash
1145
- }
1146
- }
1147
- }
1148
-
1149
- entries.sort(compareDelegationEntries)
1150
- return entries
1151
- }
1152
-
1153
- /** Read delegation reports from EVERY session under
1154
- * `<root>/.pantheon/delegations/<sessionID>/<alias>.md` — the panel's
1155
- * HISTORY channel. Unlike the children/live channels it does NOT depend on a
1156
- * resolved sessionID: with no focused session (null/placeholder), the panel
1157
- * still shows the reports from all past sessions (running first, Finalized
1158
- * desc — the sort applied by readDelegationEntries). Fail-open: a
1159
- * missing/unreadable directory yields []. */
1160
- export async function readAllDelegationEntries(root: string): Promise<DelegationEntry[]> {
1161
- return readDelegationEntries(join(root, '.pantheon', 'delegations'))
1162
- }
1163
-
1164
- /** Resolve the directory where the job board writes delegation md reports.
1165
- * The board writes `.pantheon/delegations` RELATIVE to the server cwd,
1166
- * which the TUI exposes as `TuiState.path.directory`. `project` does NOT
1167
- * exist on `TuiState.path` (the old `state?.project ?? state?.worktree`
1168
- * resolution was always undefined for the first term) and `worktree` is
1169
- * `/` when there is no git (e.g. the sandbox test project) — a root of
1170
- * `''` or `'/'` must fall back to `process.cwd()`. */
1171
- export function resolveDelegationsDir(
1172
- state: { directory?: string; worktree?: string } | undefined,
1173
- cwd = process.cwd(),
1174
- ): string {
1175
- const root = state?.directory ?? state?.worktree ?? ''
1176
- if (root === '' || root === '/') return join(cwd, '.pantheon', 'delegations')
1177
- return join(root, '.pantheon', 'delegations')
1178
- }
1179
-
1180
- /** Project root derived from the delegations dir: `<root>/.pantheon/delegations`
1181
- * → `<root>`. Used to point the panel logger at the REAL hooks.log — passing
1182
- * the delegations dir (or its dirname) directly made createTuiLogger append
1183
- * to `<root>/.pantheon/.pantheon/logs/hooks.log`, a nested empty dir the real
1184
- * log never saw. Pure — no I/O. */
1185
- export function panelLogDir(delegationsDir: string): string {
1186
- return dirname(dirname(delegationsDir))
1187
- }
1188
-
1189
- /** Where the panel logger appends lines: `<projectRoot>/.pantheon/logs/hooks.log`.
1190
- * Pure — testable without the runtime. */
1191
- export function tuiLogPath(projectRoot: string): string {
1192
- return join(projectRoot, '.pantheon', 'logs', 'hooks.log')
1193
- }
1194
-
1195
- /** Sort delegations: running first, then terminal by recency (updatedAt,
1196
- * falling back to startedAt, descending). Shared by the md reader and
1197
- * mergeDelegationSources. */
1198
- export function compareDelegationEntries(a: DelegationEntry, b: DelegationEntry): number {
1199
- const isActive = (st: DelegationEntry['state']) =>
1200
- st === 'running' || st === 'retry' || st === 'stale-running' ? 1 : 0
1201
- const aRun = isActive(a.state)
1202
- const bRun = isActive(b.state)
1203
- if (aRun !== bRun) return bRun - aRun
1204
- return (b.updatedAt ?? b.startedAt) - (a.updatedAt ?? a.startedAt)
1205
- }
1206
-
1207
- /** Split the panel list: active jobs (running/retry, stale-marked) first,
1208
- * then the most recent terminal reports, then the archived tail (paginated
1209
- * in the View). Pure — so the history-only panel (no sessionID) is testable
1210
- * without the TUI runtime. */
1211
- export function splitDelegationList(
1212
- all: readonly DelegationEntry[],
1213
- maxRecent = 8,
1214
- now = Date.now(),
1215
- staleThresholdMs = 30 * 60 * 1000, // 30 minutes
1216
- ): { active: DelegationEntry[]; recent: DelegationEntry[]; archived: DelegationEntry[] } {
1217
- const active = all
1218
- .filter((d) => d.state === 'running' || d.state === 'retry')
1219
- .map((d) => markStaleIfRunning(d, now, staleThresholdMs))
1220
- const terminal = all.filter((d) => d.state !== 'running' && d.state !== 'retry')
1221
- return {
1222
- active,
1223
- recent: terminal.slice(0, maxRecent),
1224
- archived: terminal.slice(maxRecent),
1225
- }
1226
- }
1227
-
1228
- /** The list the panel actually renders (kept for the header count and
1229
- * existing tests): active jobs first, then the most recent terminal
1230
- * reports (capped) — the archived tail is rendered separately. Pure. */
1231
- export function visibleDelegationList(
1232
- all: readonly DelegationEntry[],
1233
- maxTerminal = 8,
1234
- now = Date.now(),
1235
- staleThresholdMs = 30 * 60 * 1000, // 30 minutes
1236
- ): DelegationEntry[] {
1237
- const { active, recent } = splitDelegationList(all, maxTerminal, now, staleThresholdMs)
1238
- return [...active, ...recent]
1239
- }
1240
-
1241
- /** Default stale-running threshold: 30 minutes. */
1242
- export const STALE_RUNNING_THRESHOLD_MS = 30 * 60 * 1000
1243
-
1244
- /** Idle silence window: if no updatedAt change in this window, the entry is
1245
- * considered stale. Combined with the stale-running threshold to produce the
1246
- * display-only `stale-running` state. */
1247
- export const IDLE_SILENCE_MS = 60 * 1000
1248
-
1249
- /**
1250
- * Mark a running entry as `stale-running` if it has been running longer than
1251
- * the threshold AND has no recent activity (no `updatedAt` change in the last
1252
- * `IDLE_SILENCE_MS`). This is DISPLAY-ONLY — the board state is unchanged.
1253
- *
1254
- * A `stale-running` entry renders with a warning indicator but the underlying
1255
- * delegation is still treated as running by the backend.
1256
- */
1257
- export function markStaleIfRunning(
1258
- entry: DelegationEntry,
1259
- now: number,
1260
- thresholdMs = STALE_RUNNING_THRESHOLD_MS,
1261
- ): DelegationEntry {
1262
- if (entry.state !== 'running') return entry
1263
- const elapsed = now - entry.startedAt
1264
- if (elapsed < thresholdMs) return entry
1265
- // If updatedAt exists and is recent, entry is still active — not stale.
1266
- if (entry.updatedAt !== null && now - entry.updatedAt < IDLE_SILENCE_MS) return entry
1267
- return { ...entry, state: 'stale-running' as const }
1268
- }
1269
-
1270
- /** Compact elapsed-time label: "5m 12s", "1h 30m", "2d 4h" — ticks every
1271
- * second for running jobs. */
1272
- export function fmtElapsed(ms: number): string {
1273
- const total = Math.max(0, Math.floor(ms / 1000))
1274
- const days = Math.floor(total / 86_400)
1275
- const hours = Math.floor((total % 86_400) / 3_600)
1276
- const minutes = Math.floor((total % 3_600) / 60)
1277
- const seconds = total % 60
1278
- if (days > 0) return `${days}d ${hours}h`
1279
- if (hours > 0) return `${hours}h ${minutes}m`
1280
- if (minutes > 0) return `${minutes}m ${seconds}s`
1281
- return `${seconds}s`
1282
- }
1283
-
1284
- /** Elapsed label for one entry: running → ticks `now - startedAt`, terminal
1285
- * → fixed `updatedAt - startedAt` (em dash when no finalized timestamp). */
1286
- export function delegationElapsed(entry: DelegationEntry, now: number): string {
1287
- if (entry.state === 'running' || entry.state === 'stale-running')
1288
- return fmtElapsed(now - entry.startedAt)
1289
- return entry.updatedAt !== null ? fmtElapsed(entry.updatedAt - entry.startedAt) : '\u2014'
1290
- }
1291
-
1292
- /** The activity labels shown by the animated row. Keeping this pure makes the
1293
- * state machine testable without booting OpenCode's renderer. */
1294
- export type DelegationActivity =
1295
- | 'delegating'
1296
- | 'working'
1297
- | 'reading'
1298
- | 'completed'
1299
- | 'error'
1300
- | 'cancelled'
1301
-
1302
- export function delegationActivity(entry: DelegationEntry): DelegationActivity {
1303
- if (entry.state === 'completed') return 'completed'
1304
- if (
1305
- entry.state === 'error' ||
1306
- entry.state === 'startup_failed' ||
1307
- entry.state === 'startup_unknown'
1308
- )
1309
- return 'error'
1310
- if (entry.state === 'cancelled') return 'cancelled'
1311
- if (entry.read) return 'reading'
1312
- if (entry.alias.startsWith('live-') && entry.taskID === undefined) return 'delegating'
1313
- return 'working'
1314
- }
1315
-
1316
- export function delegationActivityLabel(entry: DelegationEntry): string {
1317
- if (entry.state === 'retry') return 'RETRYING'
1318
- switch (delegationActivity(entry)) {
1319
- case 'delegating':
1320
- return 'DELEGATING'
1321
- case 'working':
1322
- return 'WORKING'
1323
- case 'reading':
1324
- return 'READING RESULT'
1325
- case 'completed':
1326
- return entry.timedOut ? 'DONE (TIMED OUT)' : 'DONE'
1327
- case 'error':
1328
- return 'ERROR'
1329
- default:
1330
- return 'CANCELLED'
1331
- }
1332
- }
1333
-
1334
- const DELEGATION_SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
1335
-
1336
- /** Return a deterministic spinner frame. The View ticks this every 140ms. */
1337
- export function delegationSpinnerFrame(now: number): string {
1338
- const index = Math.floor(Math.max(0, now) / 140) % DELEGATION_SPINNER_FRAMES.length
1339
- return DELEGATION_SPINNER_FRAMES[index] ?? DELEGATION_SPINNER_FRAMES[0]
1340
- }
1341
-
1342
- /* ─── Live tool activity per child session (beta.6) ────────────────────────
1343
- * The delegation panel's activity line ("↳ bash npm test") — what the agent
1344
- * is doing RIGHT NOW. Sourced from message.part.updated tool parts: every
1345
- * pending/running tool part updates a per-child-session record (latest wins).
1346
- * Module-level by design: the sidebar remounts on route changes and the
1347
- * "what is each agent doing" state should survive that (OMO pattern). */
1348
-
1349
- export type ToolActivity = {
1350
- tool: string
1351
- summary: string
1352
- at: number
1353
- }
1354
-
1355
- /** Bounded tracker: child session id → latest running tool call. */
1356
- const latestToolActivity = new Map<string, ToolActivity>()
1357
- const MAX_TOOL_ACTIVITY_ENTRIES = 200
1358
- const TOOL_ACTIVITY_TTL_MS = 5 * 60 * 1000
1359
-
1360
- /** Archived-section pagination state — module-level so it survives sidebar
1361
- * remounts (route changes) without leaking into the component tree. */
1362
- const archivedUiState = { page: 0 }
1363
-
1364
- /** First usable summary string from common tool input fields. */
1365
- function summarizeToolInput(input: Record<string, unknown> | undefined): string {
1366
- if (!input) return ''
1367
- const candidates = ['command', 'description', 'prompt', 'filePath', 'pattern', 'url', 'query']
1368
- for (const key of candidates) {
1369
- const value = input[key]
1370
- if (typeof value === 'string' && value.trim() !== '') return value
1371
- }
1372
- return ''
1373
- }
1374
-
1375
- /** Reduce one message.part.updated tool part to displayable activity.
1376
- * Returns null for non-tool parts, completed/error parts (no live activity)
1377
- * or parts without a session id. Pure. */
1378
- export function extractToolActivity(
1379
- part: {
1380
- type?: string
1381
- tool?: string
1382
- sessionID?: string
1383
- state?: { status?: string; input?: Record<string, unknown> }
1384
- },
1385
- now = Date.now(),
1386
- ): { sessionID: string; activity: ToolActivity } | null {
1387
- if (part?.type !== 'tool') return null
1388
- const status = part.state?.status
1389
- if (status !== 'pending' && status !== 'running') return null
1390
- const sessionID = typeof part.sessionID === 'string' ? part.sessionID : ''
1391
- if (sessionID === '') return null
1392
- const tool = typeof part.tool === 'string' && part.tool !== '' ? part.tool : 'tool'
1393
- const summary = summarizeToolInput(part.state?.input).replace(/\s+/g, ' ').trim().slice(0, 48)
1394
- return { sessionID, activity: { tool, summary, at: now } }
1395
- }
1396
-
1397
- /** Record an activity sample (bounded map, oldest dropped). */
1398
- export function trackToolActivity(
1399
- map: Map<string, ToolActivity>,
1400
- sessionID: string,
1401
- activity: ToolActivity,
1402
- ): void {
1403
- if (sessionID === '') return
1404
- if (map.size >= MAX_TOOL_ACTIVITY_ENTRIES) {
1405
- const oldest = map.keys().next().value
1406
- if (oldest !== undefined) map.delete(oldest)
1407
- }
1408
- map.set(sessionID, activity)
1409
- }
1410
-
1411
- /** Latest live activity for a child session, or null when absent/stale. */
1412
- export function latestToolActivityFor(
1413
- map: Map<string, ToolActivity>,
1414
- sessionID: string | undefined,
1415
- now = Date.now(),
1416
- ttlMs = TOOL_ACTIVITY_TTL_MS,
1417
- ): ToolActivity | null {
1418
- if (!sessionID) return null
1419
- const hit = map.get(sessionID)
1420
- if (hit === undefined) return null
1421
- if (now - hit.at > ttlMs) return null
1422
- return hit
1423
- }
1424
-
1425
- /** Merge the immediate tool-event channel into the child-session channel.
1426
- *
1427
- * Children remain the durable source, while live entries make a delegation
1428
- * visible before the child API/report catches up. A finalized md entry wins
1429
- * over a stale live entry; a child-only row is upgraded with live agent,
1430
- * alias, phase and timestamps. */
1431
- export function mergeChildDelegationSources(
1432
- children: readonly DelegationEntry[],
1433
- live: readonly LiveDelegationEntry[],
1434
- ): DelegationEntry[] {
1435
- const result = [...children]
1436
- const byTask = new Map<string, number>()
1437
- const bySessionAlias = new Map<string, number>()
1438
- const key = (sessionID: string, alias: string): string => `${sessionID}\u0000${alias}`
1439
-
1440
- result.forEach((entry, index) => {
1441
- if (entry.taskID !== undefined) byTask.set(entry.taskID, index)
1442
- bySessionAlias.set(key(entry.sessionID, entry.alias), index)
1443
- })
1444
-
1445
- for (const liveEntry of live) {
1446
- if (
1447
- liveEntry.alias === null &&
1448
- liveEntry.taskID === null &&
1449
- Date.now() - liveEntry.startedAt > 30_000
1450
- )
1451
- continue
1452
- const incoming = toDelegationEntry(liveEntry)
1453
- const index =
1454
- (incoming.taskID !== undefined ? byTask.get(incoming.taskID) : undefined) ??
1455
- (incoming.alias !== ''
1456
- ? bySessionAlias.get(key(incoming.sessionID, incoming.alias))
1457
- : undefined)
1458
-
1459
- if (index === undefined) {
1460
- result.push(incoming)
1461
- const newIndex = result.length - 1
1462
- if (incoming.taskID !== undefined) byTask.set(incoming.taskID, newIndex)
1463
- bySessionAlias.set(key(incoming.sessionID, incoming.alias), newIndex)
1464
- continue
1465
- }
1466
-
1467
- const existing = result[index]
1468
- if (existing === undefined) continue
1469
- // Any terminal state is authoritative — a child session that went idle
1470
- // correctly derives 'completed' via childStatusToState before the MD
1471
- // report is written. The live tool-part channel stays 'running' until
1472
- // pantheon_delegation_read fires, so allowing it to overwrite a
1473
- // terminal state would flip completed → running (the bug this fixes).
1474
- //
1475
- // When the existing entry IS terminal, we still absorb live metadata
1476
- // (alias, agent, read) but preserve the terminal state.
1477
- if (existing.state !== 'running') {
1478
- if (liveEntry.alias !== null && existing.alias !== incoming.alias) {
1479
- existing.alias = incoming.alias
1480
- }
1481
- if (incoming.agent !== 'agent' && existing.agent !== incoming.agent) {
1482
- existing.agent = incoming.agent
1483
- }
1484
- if (incoming.read && !existing.read) {
1485
- existing.read = true
1486
- }
1487
- continue
1488
- }
1489
- result[index] = {
1490
- ...existing,
1491
- alias: liveEntry.alias !== null ? incoming.alias : existing.alias,
1492
- sessionID: existing.sessionID || incoming.sessionID,
1493
- taskID: existing.taskID ?? incoming.taskID,
1494
- agent: incoming.agent !== 'agent' ? incoming.agent : existing.agent,
1495
- description: incoming.description !== '' ? incoming.description : existing.description,
1496
- state: incoming.state,
1497
- startedAt: Math.min(existing.startedAt, incoming.startedAt),
1498
- updatedAt: incoming.updatedAt,
1499
- read: incoming.read,
1500
- source: 'live',
1501
- }
1502
- }
1503
-
1504
- result.sort(compareDelegationEntries)
1505
- return result
1506
- }
1507
-
1508
- /* ─── Live tool-call lifecycle (agent-sidebar pattern) ─────
1509
- * Source of truth for jobs born while opencode is open. The TUI event bus
1510
- * (api.event.on) delivers `message.part.updated` for every part change;
1511
- * we only care about tool parts whose `tool` is pantheon_delegate (job
1512
- * launch) or pantheon_delegation_read (blocking until terminal → closes
1513
- * the entry). Shape-adapted from the SDK v2 ToolPart but duck-typed so the
1514
- * pure helpers are testable without the SDK. */
1515
-
1516
- /** Duck-typed subset of a tool part (SDK v2 `ToolPart` / `ToolState`). */
1517
- export type DelegationToolPart = {
1518
- id?: string
1519
- callID?: string
1520
- sessionID?: string
1521
- type?: string
1522
- tool?: string
1523
- state?: {
1524
- status?: string
1525
- input?: Record<string, unknown>
1526
- output?: string
1527
- error?: string
1528
- time?: { start?: number; end?: number }
1529
- }
1530
- }
1531
-
1532
- /** One live delegation tracked in-memory, keyed by the delegate callID. */
1533
- export type LiveDelegationEntry = {
1534
- /** Tool call id of the pantheon_delegate part (stable across events). */
1535
- callID: string
1536
- /** Part id (for message.part.removed cleanup). */
1537
- partID: string
1538
- /** Parent session the delegation was launched from. */
1539
- sessionID: string
1540
- tool: 'pantheon_delegate' | 'pantheon_delegation_read'
1541
- /** Agent name (from the delegate input args). */
1542
- agent: string
1543
- description: string
1544
- /** Known after the delegate tool completes (parsed from its output). */
1545
- alias: string | null
1546
- /** Child session id (parsed from the delegate output). */
1547
- taskID: string | null
1548
- state: 'running' | 'completed' | 'error' | 'cancelled'
1549
- startedAt: number
1550
- updatedAt: number | null
1551
- /** True once a pantheon_delegation_read for this job has been observed. */
1552
- read: boolean
1553
- }
1554
-
1555
- /** Result of parsing one tool part into lifecycle-relevant fields. */
1556
- export type ParsedDelegationToolPart = {
1557
- callID: string
1558
- partID: string
1559
- sessionID: string
1560
- tool: 'pantheon_delegate' | 'pantheon_delegation_read'
1561
- /** null for read parts (no agent arg — the id targets an existing job). */
1562
- agent: string | null
1563
- description: string
1564
- status: 'pending' | 'running' | 'completed' | 'error'
1565
- alias: string | null
1566
- taskID: string | null
1567
- startedAt: number
1568
- endAt: number | null
1569
- }
1570
-
1571
- /** Alias in the delegate output: "Delegated to apollo: [apo-1] (task …)". */
1572
- const DELEGATE_ALIAS_PATTERN = /\[([a-z]{2,8}-\d+)\]/i
1573
- /** Child task id in the delegate output: "(task ses_child_9)". */
1574
- const DELEGATE_TASKID_PATTERN = /\(task\s+([a-z0-9_]+)\)/i
1575
- /** Plain alias, as passed to pantheon_delegation_read input.id: "apo-1". */
1576
- const READ_ALIAS_PATTERN = /^[a-z]{2,8}-\d+$/i
1577
-
1578
- /** Extract the tool name + args from a `message.part.updated` part and
1579
- * reduce it to what the panel needs. Returns null for anything that is
1580
- * not a pantheon delegation tool part (or is missing its callID). */
1581
- export function parseDelegationToolPart(
1582
- part: DelegationToolPart,
1583
- now = Date.now(),
1584
- ): ParsedDelegationToolPart | null {
1585
- if (part.type !== 'tool') return null
1586
- if (part.tool !== 'pantheon_delegate' && part.tool !== 'pantheon_delegation_read') return null
1587
- const callID = part.callID
1588
- if (callID === undefined || callID === '') return null
1589
- const sessionID = part.sessionID ?? ''
1590
- const state = part.state ?? {}
1591
- const status = state.status ?? 'pending'
1592
- if (status !== 'pending' && status !== 'running' && status !== 'completed' && status !== 'error')
1593
- return null
1594
- const input = state.input ?? {}
1595
- const startedAt = state.time?.start ?? now
1596
- const endAt = state.time?.end ?? null
1597
-
1598
- if (part.tool === 'pantheon_delegation_read') {
1599
- const target = typeof input.id === 'string' ? input.id : null
1600
- let alias: string | null = null
1601
- let taskID: string | null = null
1602
- if (target !== null) {
1603
- if (READ_ALIAS_PATTERN.test(target)) alias = target
1604
- else if (target.startsWith('ses_')) taskID = target // raw child session id
1605
- }
1606
- return {
1607
- callID,
1608
- partID: part.id ?? '',
1609
- sessionID,
1610
- tool: 'pantheon_delegation_read',
1611
- agent: null,
1612
- description: '',
1613
- status,
1614
- alias,
1615
- taskID,
1616
- startedAt,
1617
- endAt,
1618
- }
1619
- }
1620
-
1621
- const agent = typeof input.agent === 'string' ? input.agent : 'agent'
1622
- const description = typeof input.description === 'string' ? input.description : ''
1623
- // The alias/taskID only exist once the delegate tool COMPLETES (they are
1624
- // returned in its output); a running/pending part has neither.
1625
- let alias: string | null = null
1626
- let taskID: string | null = null
1627
- if (status === 'completed') {
1628
- const output = state.output ?? ''
1629
- alias = DELEGATE_ALIAS_PATTERN.exec(output)?.[1] ?? null
1630
- taskID = DELEGATE_TASKID_PATTERN.exec(output)?.[1] ?? null
1631
- }
1632
- return {
1633
- callID,
1634
- partID: part.id ?? '',
1635
- sessionID,
1636
- tool: 'pantheon_delegate',
1637
- agent,
1638
- description,
1639
- status,
1640
- alias,
1641
- taskID,
1642
- startedAt,
1643
- endAt,
1644
- }
1645
- }
1646
-
1647
- /** Find a live entry by alias or taskID (read parts resolve by id). */
1648
- function findLiveByTarget(
1649
- map: Map<string, LiveDelegationEntry>,
1650
- alias: string | null,
1651
- taskID: string | null,
1652
- ): LiveDelegationEntry | undefined {
1653
- if (alias === null && taskID === null) return undefined
1654
- for (const entry of map.values()) {
1655
- if (alias !== null && entry.alias === alias) return entry
1656
- if (taskID !== null && entry.taskID === taskID) return entry
1657
- }
1658
- return undefined
1659
- }
1660
-
1661
- /** Apply one tool part to the live map. Returns true when the map changed.
1662
- * Pure w.r.t. I/O — only mutates `map`. */
1663
- export function reduceDelegationToolPart(
1664
- map: Map<string, LiveDelegationEntry>,
1665
- part: DelegationToolPart,
1666
- now = Date.now(),
1667
- ): boolean {
1668
- const parsed = parseDelegationToolPart(part, now)
1669
- if (parsed === null) return false
1670
-
1671
- // Read tool: never creates a row — it resolves a delegation by id. It
1672
- // marks the target `read` and (because it blocks until terminal) closes
1673
- // the entry on completed/error with its end timestamp.
1674
- if (parsed.tool === 'pantheon_delegation_read') {
1675
- const target = findLiveByTarget(map, parsed.alias, parsed.taskID)
1676
- if (target === undefined) return false
1677
- let changed = false
1678
- if (!target.read) {
1679
- target.read = true
1680
- changed = true
1681
- }
1682
- if (parsed.status === 'completed' && target.state === 'running') {
1683
- target.state = 'completed'
1684
- target.updatedAt = parsed.endAt ?? now
1685
- changed = true
1686
- } else if (parsed.status === 'error' && target.state === 'running') {
1687
- target.state = 'error'
1688
- target.updatedAt = parsed.endAt ?? now
1689
- changed = true
1690
- }
1691
- return changed
1692
- }
1693
-
1694
- // Delegate tool: pending/running → job launched (running). A COMPLETED
1695
- // delegate tool only means the job was registered — it stays running and
1696
- // we pick up alias + taskID from the output.
1697
- const existing = map.get(parsed.callID)
1698
- if (parsed.status === 'error') {
1699
- if (existing !== undefined && existing.state === 'error' && existing.updatedAt === parsed.endAt)
1700
- return false
1701
- map.set(parsed.callID, {
1702
- callID: parsed.callID,
1703
- partID: parsed.partID,
1704
- sessionID: parsed.sessionID,
1705
- tool: 'pantheon_delegate',
1706
- agent: parsed.agent ?? 'agent',
1707
- description: parsed.description,
1708
- alias: existing?.alias ?? null,
1709
- taskID: existing?.taskID ?? null,
1710
- state: 'error',
1711
- startedAt: existing?.startedAt ?? parsed.startedAt,
1712
- updatedAt: parsed.endAt ?? now,
1713
- read: existing?.read ?? false,
1714
- })
1715
- return true
1716
- }
1717
- if (existing === undefined) {
1718
- map.set(parsed.callID, {
1719
- callID: parsed.callID,
1720
- partID: parsed.partID,
1721
- sessionID: parsed.sessionID,
1722
- tool: 'pantheon_delegate',
1723
- agent: parsed.agent ?? 'agent',
1724
- description: parsed.description,
1725
- alias: parsed.alias,
1726
- taskID: parsed.taskID,
1727
- state: 'running',
1728
- startedAt: parsed.startedAt,
1729
- updatedAt: null,
1730
- read: false,
1731
- })
1732
- return true
1733
- }
1734
- // Existing entry: absorb newly-discovered alias/taskID/agent/description.
1735
- let changed = false
1736
- if (parsed.alias !== null && existing.alias !== parsed.alias) {
1737
- existing.alias = parsed.alias
1738
- changed = true
1739
- }
1740
- if (parsed.taskID !== null && existing.taskID !== parsed.taskID) {
1741
- existing.taskID = parsed.taskID
1742
- changed = true
1743
- }
1744
- if (parsed.agent !== null && existing.agent !== parsed.agent) {
1745
- existing.agent = parsed.agent
1746
- changed = true
1747
- }
1748
- if (parsed.description !== '' && existing.description !== parsed.description) {
1749
- existing.description = parsed.description
1750
- changed = true
1751
- }
1752
- if (existing.partID === '' && parsed.partID !== '') {
1753
- existing.partID = parsed.partID
1754
- changed = true
1755
- }
1756
- return changed
1757
- }
1758
-
1759
- /** Remove a live entry by part id (message.part.removed) or call id.
1760
- * Returns true when something was removed. */
1761
- export function removeDelegationEntry(
1762
- map: Map<string, LiveDelegationEntry>,
1763
- partIDOrCallID: string,
1764
- ): boolean {
1765
- if (map.delete(partIDOrCallID)) return true
1766
- for (const [key, entry] of map) {
1767
- if (entry.partID === partIDOrCallID) {
1768
- map.delete(key)
1769
- return true
1770
- }
1771
- }
1772
- return false
1773
- }
1774
-
1775
- /** Collect pantheon delegation tool parts from a session's messages.
1776
- * Messages may carry their parts inline (duck-typed `msg.parts`); when
1777
- * they don't, the optional `getParts(messageID)` callback is used (the TUI
1778
- * SDK exposes `api.state.part(messageID)`). Pure w.r.t. I/O — used by the
1779
- * mount re-scan to re-seed the live map after compaction/attach. */
1780
- export function collectDelegationToolParts(
1781
- messages: readonly { id?: string; parts?: unknown[] }[] | undefined,
1782
- getParts?: (messageID: string) => readonly unknown[] | undefined,
1783
- ): DelegationToolPart[] {
1784
- const out: DelegationToolPart[] = []
1785
- for (const msg of messages ?? []) {
1786
- let parts: readonly unknown[] | undefined
1787
- if (Array.isArray(msg?.parts)) {
1788
- parts = msg.parts
1789
- } else if (msg?.id !== undefined && typeof getParts === 'function') {
1790
- parts = getParts(msg.id)
1791
- }
1792
- if (!parts) continue
1793
- for (const raw of parts) {
1794
- const part = raw as DelegationToolPart
1795
- if (
1796
- part?.type === 'tool' &&
1797
- (part.tool === 'pantheon_delegate' || part.tool === 'pantheon_delegation_read')
1798
- ) {
1799
- out.push(part)
1800
- }
1801
- }
1802
- }
1803
- return out
1804
- }
1805
-
1806
- /** Apply a batch of tool parts (in message order) to the live map. Used on
1807
- * mount to re-seed entries that `message.part.removed` (compaction) wiped,
1808
- * from the session's existing tool parts. Returns how many parts changed
1809
- * the map (0 on the second identical seed — idempotent, no extra bumps). */
1810
- export function seedLiveDelegationMap(
1811
- map: Map<string, LiveDelegationEntry>,
1812
- parts: readonly DelegationToolPart[],
1813
- now = Date.now(),
1814
- ): number {
1815
- let changed = 0
1816
- for (const part of parts) {
1817
- if (reduceDelegationToolPart(map, part, now)) changed++
1818
- }
1819
- return changed
1820
- }
1821
-
1822
- /** Convert a live entry into the shared display shape. Alias falls back to
1823
- * a `live-<callID>` prefix while the delegate tool has not completed yet. */
1824
- export function toDelegationEntry(live: LiveDelegationEntry): DelegationEntry {
1825
- return {
1826
- alias: live.alias ?? `live-${live.callID.slice(0, 8)}`,
1827
- sessionID: live.sessionID,
1828
- ...(live.taskID !== null ? { taskID: live.taskID } : {}),
1829
- agent: live.agent,
1830
- state: live.state,
1831
- startedAt: live.startedAt,
1832
- updatedAt: live.updatedAt,
1833
- timedOut: false,
1834
- description: live.description,
1835
- read: live.read,
1836
- source: 'live',
1837
- }
1838
- }
1839
-
1840
- /** Combine the live channel with the md (historical) channel into one
1841
- * display list. Dedupes by (sessionID, alias) — aliases are per-parent-
1842
- * session, so the same alias in different sessions stays separate. A
1843
- * terminal md entry is authoritative over a live running entry for the
1844
- * same job (it carries Finalized/timedOut/cancelled from finalize). */
1845
- export function mergeDelegationSources(
1846
- live: readonly LiveDelegationEntry[],
1847
- md: readonly DelegationEntry[],
1848
- ): DelegationEntry[] {
1849
- const keyOf = (sessionID: string, alias: string): string => `${sessionID}\u0000${alias}`
1850
- const byKey = new Map<string, DelegationEntry>()
1851
- for (const m of md) {
1852
- const key = keyOf(m.sessionID, m.alias)
1853
- const existing = byKey.get(key)
1854
- if (existing === undefined || (existing.state === 'running' && m.state !== 'running'))
1855
- byKey.set(key, m)
1856
- }
1857
- const aliasless: DelegationEntry[] = []
1858
- for (const l of live) {
1859
- const e = toDelegationEntry(l)
1860
- if (l.alias === null) {
1861
- aliasless.push(e)
1862
- continue
1863
- }
1864
- const key = keyOf(l.sessionID, l.alias)
1865
- const mdEntry = byKey.get(key)
1866
- if (mdEntry !== undefined && mdEntry.state !== 'running') continue // md terminal wins
1867
- byKey.set(key, e)
1868
- }
1869
- const all = [...aliasless, ...byKey.values()]
1870
- all.sort(compareDelegationEntries)
1871
- return all
1872
- }
1873
-
1874
- /* ─── Children channel (primary source, delegations-sidebar pattern) ────
1875
- * `api.client.session.children` returns the child sessions of the current
1876
- * session — every pantheon_delegate spawns one (parentID = caller). The
1877
- * pure helpers here turn those children + the md reports into the display
1878
- * list, and navigate to a child session on click. */
1879
-
1880
- /* ─── Current-session resolution + path guard (placeholder regression) ──
1881
- * The sidebar forwarded `props.session_id` verbatim into
1882
- * `session.children({ path: { id } })`. When the TUI runtime renders the
1883
- * sidebar without a focused session it leaves the route template
1884
- * UNSUBSTITUTED — the literal "{sessionID}" string — which opencode's server
1885
- * rejected every poll (SchemaError: Expected a string starting with "ses",
1886
- * got "%7BsessionID%7D"), ~1 error/s from the 1s safety poll, and the failed
1887
- * call fail-opened into "Delegations (0)".
1888
- *
1889
- * Contract: resolution NEVER yields a placeholder — an invalid/absent id is
1890
- * null, and a null resolution means the children fetch is SKIPPED (empty
1891
- * panel, ZERO errors). Sources, in order:
1892
- * 1. the sidebar_content slot prop (`session_id`);
1893
- * 2. `api.state.sessionID` (duck-typed: the typed TuiState has no such
1894
- * field, but the runtime state is a superset — the delegations-sidebar
1895
- * reference reads the current session from api.state);
1896
- * 3. `api.route.current.params.sessionID` (typed: TuiRouteCurrent's
1897
- * `{ name: 'session', params: { sessionID } }` variant).
1898
- * Each source passes the same server-aligned validity check (non-empty
1899
- * string starting with "ses"), so a placeholder or garbage at any position
1900
- * falls through to the next source instead of hitting the wire. */
1901
-
1902
- /** Server-aligned session id validity: opencode rejects anything not starting
1903
- * with "ses" (SchemaError). This deliberately mirrors that exact contract —
1904
- * nothing stricter, nothing looser — so a template placeholder ("{sessionID}"),
1905
- * its URL-encoded form ("%7BsessionID%7D", what the server reported in the
1906
- * schema error), an empty/undefined value, or a foreign id (e.g. "wrk_") can
1907
- * never reach a path and error-spam the log. Confirmed: "{sessionID}" starts
1908
- * with "{" and "%7BsessionID%7D" with "%" — both fail startsWith("ses"), so
1909
- * the placeholder is rejected WITHOUT an explicit denylist (covered by tests). */
1910
- export function isValidSessionId(id: unknown): id is string {
1911
- return typeof id === 'string' && id.startsWith('ses')
1912
- }
1913
-
1914
- /** Sources the sidebar can resolve the CURRENT session id from. Duck-typed
1915
- * subsets of TuiPluginApi / TuiState / TuiRouteCurrent so the helper stays
1916
- * pure and testable without the TUI runtime. */
1917
- export type TuiSessionSources = {
1918
- /** sidebar_content slot prop (`session_id`). */
1919
- sessionID?: string | null
1920
- api?: {
1921
- /** Runtime state superset — may expose the current session id. */
1922
- state?: { sessionID?: unknown }
1923
- /** Typed route: { name: 'session', params: { sessionID } } when in one. */
1924
- route?: { current?: { name?: string; params?: Record<string, unknown> } }
1925
- } | null
1926
- }
1927
-
1928
- /** Resolve the current session id for the sidebar. Order: slot prop →
1929
- * api.state.sessionID (runtime superset) → api.route.current.params.sessionID
1930
- * (typed route). Every source is validated; invalid/absent → next source.
1931
- * NEVER returns a placeholder or non-ses id. Null → callers MUST skip the
1932
- * fetch (empty panel, zero errors). Pure — no I/O, no runtime required. */
1933
- export function resolveCurrentSessionID(sources: TuiSessionSources): string | null {
1934
- const candidates: unknown[] = [
1935
- sources?.sessionID,
1936
- sources?.api?.state?.sessionID,
1937
- sources?.api?.route?.current?.params?.sessionID,
1938
- ]
1939
- for (const candidate of candidates) {
1940
- if (isValidSessionId(candidate)) return candidate
1941
- }
1942
- return null
1943
- }
1944
-
1945
- /** THE single choke point for every `session.children` / session-API path.
1946
- * Returns `{ path: { id } }` ONLY for a server-valid session id; returns
1947
- * null for anything else (placeholder, empty, foreign id) so the caller
1948
- * skips the call entirely instead of sending an unsubstituted placeholder
1949
- * (the "%7BsessionID%7D" regression). Every session-API call site MUST go
1950
- * through this function (enforced by the source-scan test in
1951
- * tests/pantheon/tui-delegations.test.ts). */
1952
- export function safeSessionPath(id: unknown): { path: { id: string } } | null {
1953
- if (!isValidSessionId(id)) return null
1954
- return { path: { id } }
1955
- }
1956
-
1957
- /** Build the `session.children` path ONLY from a validated session id.
1958
- * Delegates to {@link safeSessionPath} — the single choke point. Returns
1959
- * null for null/invalid ids so the caller skips the fetch instead of
1960
- * sending an unsubstituted placeholder (the "%7BsessionID%7D" regression). */
1961
- export function buildChildrenPath(id: string | null | undefined): { path: { id: string } } | null {
1962
- return safeSessionPath(id)
1963
- }
1964
-
1965
- /** Duck-typed subset of a child Session (+ its live status type). */
1966
- export type ChildDelegationLike = {
1967
- /** Child session id (= board task id). */
1968
- id: string
1969
- /** Session title — the delegate's description or prompt prefix. */
1970
- title?: string
1971
- /** Agent name when the child session carries one (duck-typed; native
1972
- * task() children may expose it, board reports always do). */
1973
- agent?: string
1974
- /** Status type from api.state.session.status: 'busy' | 'retry' | 'idle',
1975
- * or undefined when the status API is unavailable. */
1976
- status?: string
1977
- time?: {
1978
- created?: number
1979
- updated?: number
1980
- }
1981
- }
1982
-
1983
- /** Map a child status type to a display state. busy/retry → running
1984
- * (the child is actively working), idle → completed, unknown → running
1985
- * (fail-open: a freshly-seen child is assumed active; the 1s poll + md
1986
- * correct it as soon as terminal data exists). */
1987
- export function childStatusToState(status: string | undefined): 'running' | 'completed' | 'retry' {
1988
- if (status === 'idle') return 'completed'
1989
- if (status === 'retry') return 'retry'
1990
- return 'running' // busy or unknown
1991
- }
1992
-
1993
- /** Row tag for a delegation entry: `[native]` for native task() children
1994
- * (source 'children-only' — no board report), `[pantheon:<alias>]` for board
1995
- * rows ([pantheon:apo-1]) — the same tags the manager prints in
1996
- * pantheon_delegation_list, so panel rows and CLI list lines match. The
1997
- * panel renders the tag with a distinct style so native task() children are
1998
- * visually separable from pantheon_delegate jobs. */
1999
- export function delegationTag(entry: DelegationEntry): string {
2000
- return entry.source === 'children-only' ? '[native]' : `[pantheon:${entry.alias}]`
2001
- }
2002
-
2003
- /** Turn child sessions (PRIMARY) enriched with md reports into the display
2004
- * list. One entry per child id (duplicates across re-fetches collapse).
2005
- * The md report is matched by `Task ID` (== child.id) and supplies alias,
2006
- * agent, description, terminal state and duration. A child without a
2007
- * report still renders: description from its title, agent from the child
2008
- * itself (fallback 'agent'), state derived from its status, startedAt from
2009
- * time.created. A report-less child is a NATIVE task() child (every
2010
- * child of the current session — pantheon_delegate OR the native `task()`
2011
- * tool — carries parentID = caller), so it gets source 'children-only'
2012
- * and the `[native]` tag instead of a board alias.
2013
- * Terminal md state wins over the derived state; a running md defers to
2014
- * the child's live status. Sorted running-first (compareDelegationEntries).
2015
- * Pure — no I/O. */
2016
- export function childrenToDelegationEntries(
2017
- children: readonly ChildDelegationLike[] | undefined,
2018
- md: readonly DelegationEntry[],
2019
- now = Date.now(),
2020
- ): DelegationEntry[] {
2021
- const byTaskID = new Map<string, DelegationEntry>()
2022
- for (const m of md) {
2023
- if (m.taskID !== undefined && !byTaskID.has(m.taskID)) byTaskID.set(m.taskID, m)
2024
- }
2025
- const out: DelegationEntry[] = []
2026
- const seen = new Set<string>()
2027
- for (const child of children ?? []) {
2028
- if (child.id === '' || seen.has(child.id)) continue
2029
- seen.add(child.id)
2030
- const mdEntry = byTaskID.get(child.id)
2031
- const state =
2032
- mdEntry !== undefined && mdEntry.state !== 'running'
2033
- ? mdEntry.state
2034
- : childStatusToState(child.status)
2035
- out.push({
2036
- alias: mdEntry?.alias ?? 'task',
2037
- sessionID: mdEntry?.sessionID ?? '',
2038
- taskID: child.id,
2039
- agent: mdEntry?.agent ?? child.agent ?? 'agent',
2040
- state,
2041
- startedAt: mdEntry?.startedAt ?? child.time?.created ?? now,
2042
- updatedAt:
2043
- mdEntry?.updatedAt ??
2044
- (state === 'running' || state === 'stale-running' ? null : (child.time?.updated ?? null)),
2045
- timedOut: mdEntry?.timedOut ?? false,
2046
- description:
2047
- mdEntry !== undefined && mdEntry.description !== ''
2048
- ? mdEntry.description
2049
- : (child.title ?? ''),
2050
- source: mdEntry !== undefined ? 'md' : 'children-only',
2051
- })
2052
- }
2053
- out.sort(compareDelegationEntries)
2054
- return out
2055
- }
2056
-
2057
- /** Navigate the TUI to a child session (click/Enter on a delegation row).
2058
- * Returns false when the route API is unavailable or the target id is
2059
- * missing/placeholder — the row stays inert instead of crashing. Only a
2060
- * server-valid session id ("ses...") ever reaches the router, so an
2061
- * unsubstituted "{sessionID}" placeholder can never be routed. */
2062
- export function navigateToDelegationSession(
2063
- route: { navigate?: (name: string, params?: Record<string, unknown>) => void } | undefined,
2064
- taskID: string | undefined,
2065
- ): boolean {
2066
- if (typeof route?.navigate !== 'function' || !isValidSessionId(taskID)) return false
2067
- route.navigate('session', { sessionID: taskID })
2068
- return true
2069
- }
2070
-
2071
- /* ─── Silence-by-default panel logger ──────────────────────
2072
- * Mirrors src/pantheon/logger.ts createPantheonLogger (the TUI plugin is
2073
- * self-contained — dist/tui.tsx is a raw copy with no relative imports):
2074
- * every line is ALWAYS appended to `<logDir>/.pantheon/logs/hooks.log` and
2075
- * echoed to the console ONLY when PANTHEON_HOOKS_LOG is truthy (opencode
2076
- * renders plugin console output directly into the TUI — the pollution bug).
2077
- * Best-effort and fire-and-forget: a logging failure must never break the
2078
- * panel. */
2079
- type TuiLogger = { info: (message: string, ...args: unknown[]) => void }
2080
-
2081
- /** Silence-by-default panel logger.
2082
- * @param projectRoot the PROJECT ROOT — the logger appends to
2083
- * `<projectRoot>/.pantheon/logs/hooks.log` (tuiLogPath). Passing anything
2084
- * deeper (e.g. the delegations dir) used to double-nest the path into
2085
- * `<root>/.pantheon/.pantheon/logs/hooks.log` and never reach the real log;
2086
- * derive the root with {@link panelLogDir}. */
2087
- function createTuiLogger(projectRoot: string | undefined, module = 'pantheon-tui'): TuiLogger {
2088
- const echo = (process.env.PANTHEON_HOOKS_LOG ?? '').trim() !== ''
2089
- const logPath = tuiLogPath(projectRoot ?? process.cwd())
2090
- const formatArg = (arg: unknown): string => {
2091
- if (arg instanceof Error) return arg.stack ?? arg.message
2092
- if (typeof arg === 'string') return arg
2093
- try {
2094
- return JSON.stringify(arg)
2095
- } catch {
2096
- return String(arg)
2097
- }
2098
- }
2099
- const write = (message: string, args: unknown[]) => {
2100
- const lines = [message, ...args.map(formatArg)]
2101
- .join(' ')
2102
- .split('\n')
2103
- .map((p) => p.trim())
2104
- .filter((p) => p !== '')
2105
- if (lines.length === 0) return
2106
- void (async () => {
2107
- try {
2108
- await mkdir(dirname(logPath), { recursive: true })
2109
- const stamp = new Date().toISOString()
2110
- await appendFile(
2111
- logPath,
2112
- `${lines.map((l) => `[${stamp}] [${module}] ${l}`).join('\n')}\n`,
2113
- 'utf8',
2114
- )
2115
- } catch {
2116
- /* best-effort file log — never break the panel over logging */
2117
- }
2118
- })()
2119
- if (echo) {
2120
- for (const line of lines) console.log(`[${module}] ${line}`)
2121
- }
2122
- }
2123
- return { info: (message, ...args) => write(message, args) }
2124
- }
2125
-
2126
- /* ─── Session Row (single session with live status indicator) ─ */
2127
-
2128
- function SessionRow(props: { api: TuiPluginApi; session: any }) {
2129
- const theme = () => props.api.theme.current
2130
-
2131
- const status = createMemo(() => {
2132
- // isValidSessionId guard: a placeholder / foreign session id must never
2133
- // reach the status API (same "%7BsessionID%7D" regression class as the
2134
- // children path). Invalid id → no status call, no icon.
2135
- if (!isValidSessionId(props.session?.id)) return null
2136
- try {
2137
- const s = (props.api.state as any).session?.status?.(props.session.id)
2138
- if (s?.type) return s.type as string
2139
- } catch {
2140
- /* ignore */
2141
- }
2142
- return null
2143
- })
2144
-
2145
- const statusIcon = createMemo(() => {
2146
- switch (status()) {
2147
- case 'busy':
2148
- return '\u25cf ' // ● — running
2149
- case 'retry':
2150
- return '\u26a0 ' // ⚠ — needs attention
2151
- default:
2152
- return '' // idle/unknown — no icon
2153
- }
2154
- })
2155
-
2156
- return (
2157
- <text fg={theme().textMuted}>
2158
- {`${statusIcon()}${props.session?.id?.slice(0, 8) ?? '????'}... ${props.session?.title?.slice(0, 26) ?? '(untitled)'}`}
2159
- </text>
2160
- )
2161
- }
2162
-
2163
- /* ─── Delegation Row (single job from the children/md channels) ─ */
2164
-
2165
- function DelegationRow(props: {
2166
- api: TuiPluginApi
2167
- job: DelegationEntry
2168
- now: number
2169
- animationNow: number
2170
- }) {
2171
- const theme = () => props.api.theme.current
2172
-
2173
- const color = createMemo(() => {
2174
- const t = theme()
2175
- switch (props.job.state) {
2176
- case 'running':
2177
- return t.warning
2178
- case 'retry':
2179
- return t.warning
2180
- case 'stale-running':
2181
- return t.error // warning color for stale delegations
2182
- case 'completed':
2183
- return t.success
2184
- case 'error':
2185
- return t.error
2186
- default:
2187
- return t.textMuted // cancelled
2188
- }
2189
- })
2190
-
2191
- const marker = createMemo(() => {
2192
- if (props.job.state === 'running') return `${delegationSpinnerFrame(props.animationNow)} `
2193
- if (props.job.state === 'retry') return '\u27f3 ' // ⟳ retrying
2194
- if (props.job.state === 'stale-running') return '\u26a0 ' // warning triangle
2195
- switch (props.job.state) {
2196
- case 'completed':
2197
- return '\u2713 '
2198
- case 'error':
2199
- return '\u2715 '
2200
- default:
2201
- return '\u25cb '
2202
- }
2203
- })
2204
-
2205
- // The row tag: `[native]` for native task() children (no board report),
2206
- // `[pantheon:apo-1]`-style alias for pantheon_delegate board rows. Rendered with
2207
- // the info color so task() children are visually distinct from delegates.
2208
- const tagColor = createMemo(() => (props.job.source === 'children-only' ? theme().info : color()))
2209
-
2210
- const detail = createMemo(() => {
2211
- const elapsed = delegationElapsed(props.job, props.now)
2212
- const description = props.job.description !== '' ? ` \u2014 ${props.job.description}` : ''
2213
- const line = `${elapsed}${description}`
2214
- return line.length > 180 ? `${line.slice(0, 177)}\u2026` : line
2215
- })
2216
-
2217
- // beta.6: live tool call the child is running RIGHT NOW ("↳ bash npm test"),
2218
- // fed by message.part.updated activity tracking. Null while idle/done.
2219
- const activity = createMemo(() =>
2220
- latestToolActivityFor(latestToolActivity, props.job.taskID, props.now),
2221
- )
2222
-
2223
- // Click a row → navigate to the child session (route API guarded in the
2224
- // helper). Enter-key binding is left out (per-row keymap wiring is not
2225
- // worth the complexity in this sidebar); mouse is enabled in tui.json.
2226
- const open = () => {
2227
- navigateToDelegationSession(props.api.route, props.job.taskID)
2228
- }
2229
-
2230
- return (
2231
- <box onMouseDown={open}>
2232
- <box flexDirection="row">
2233
- <text fg={color()}>{marker()}</text>
2234
- <text fg={tagColor()}>{delegationTag(props.job)}</text>
2235
- <text
2236
- fg={color()}
2237
- >{` ${props.job.agent} \u2014 ${delegationActivityLabel(props.job)}`}</text>
2238
- </box>
2239
- <text fg={theme().textMuted}>{detail()}</text>
2240
- <Show when={activity()}>
2241
- {(a) => (
2242
- <text
2243
- fg={theme().textMuted}
2244
- >{` \u21b3 ${a().tool}${a().summary !== '' ? ' ' + a().summary : ''}`}</text>
2245
- )}
2246
- </Show>
2247
- </box>
2248
- )
2249
- }
2250
-
2251
- /* ─── Main Sidebar View ──────────────────────────────────── */
2252
-
2253
- /** Plugin-level live delegation store shared with the event subscriptions
2254
- * in `tui()`: the map of live entries + a version signal bumped on every
2255
- * mutation. The View subscribes to the version (in an effect) to refresh the
2256
- * durable child list and also reads the map as an optimistic live source. */
2257
- export type LiveDelegationStore = {
2258
- map: Map<string, LiveDelegationEntry>
2259
- /** Reactive version getter — View reads it inside an effect to re-fetch. */
2260
- version: () => number
2261
- /** Bump the version after a live mutation. */
2262
- bump: () => void
2263
- }
2264
-
2265
- function View(props: {
2266
- api: TuiPluginApi
2267
- sessionID: string | undefined
2268
- version: string | null
2269
- liveStore: LiveDelegationStore
2270
- }) {
2271
- const [showSessions, setShowSessions] = createSignal(false)
2272
- // Show live work immediately; the header remains clickable to collapse it.
2273
- const [showDelegations, setShowDelegations] = createSignal(true)
2274
-
2275
- const theme = () => props.api.theme.current
2276
-
2277
- const branch = createMemo(() =>
2278
- props.api.state.vcs?.branch ? `\u2387 ${props.api.state.vcs.branch}` : null,
2279
- )
2280
-
2281
- // ── Active preset indicator ──
2282
- // Seeded synchronously from env (never blocks first paint), then re-checked
2283
- // against .pantheon/active-preset.json on mount and every 30s so `set-tier`
2284
- // changes made while opencode is open become visible.
2285
- const [preset, setPreset] = createSignal<PresetInfo>(presetFromEnv(process.env))
2286
-
2287
- onMount(() => {
2288
- const cwd = ((props.api.state as any).path?.worktree ?? '') || process.cwd()
2289
- let cancelled = false
2290
- const refresh = async () => {
2291
- try {
2292
- const info = await resolvePresetForTui(process.env, cwd)
2293
- if (!cancelled) setPreset(info)
2294
- } catch {
2295
- // transient read error — keep the last known value
2296
- }
2297
- }
2298
- void refresh()
2299
- const timer = setInterval(() => void refresh(), PRESET_REFRESH_MS)
2300
- onCleanup(() => {
2301
- cancelled = true
2302
- clearInterval(timer)
2303
- })
2304
- })
2305
-
2306
- // ── Sessions: fetch via api.client.session.list (not proc.exec) ──
2307
- const [sessionList, { refetch: refetchSessions }] = createResource(async () => {
2308
- try {
2309
- const result = await (props.api.client as any)?.session?.list?.({ limit: 100 })
2310
- return result ?? { data: [] }
2311
- } catch {
2312
- return { data: [] }
2313
- }
2314
- })
2315
-
2316
- // Total top-level sessions (excludes subagent sessions)
2317
- const totalSessions = createMemo(() => {
2318
- const result = sessionList()
2319
- if (!result) return 0
2320
- const data: any[] = (result as any).data ?? result
2321
- if (!Array.isArray(data)) return 0
2322
- return data.filter((s: any) => !s.parentID).length
2323
- })
2324
-
2325
- // Recent top-level sessions, sorted by time.updated descending
2326
- const recentSessions = createMemo(() => {
2327
- const result = sessionList()
2328
- if (!result) return []
2329
- const data: any[] = (result as any).data ?? result
2330
- if (!Array.isArray(data)) return []
2331
- return data
2332
- .filter(
2333
- (s: any) =>
2334
- !s.parentID &&
2335
- s.id !== resolveCurrentSessionID({ sessionID: props.sessionID, api: props.api }),
2336
- )
2337
- .sort((a: any, b: any) => {
2338
- const ta = a.time?.updated ?? a.updated ?? 0
2339
- const tb = b.time?.updated ?? b.updated ?? 0
2340
- return tb - ta
2341
- })
2342
- .slice(0, 8)
2343
- })
2344
-
2345
- // ── Delegations: session.children (PRIMARY) + md reports (enrichment) ──
2346
- // The panel's source of truth is the SDK child-session API
2347
- // (`api.client.session.children`) — every pantheon_delegate spawns a child
2348
- // session with parentID = this session, so children ARE the delegation
2349
- // list (delegations-sidebar pattern). The md channel
2350
- // (.pantheon/delegations) enriches each child with alias/agent/description
2351
- // and terminal duration via the `Task ID` match. Live tool-call events are
2352
- // merged optimistically so the row appears before those channels catch up.
2353
- const delegationsDir = createMemo(() => resolveDelegationsDir((props.api.state as any).path))
2354
- // Silence-by-default panel logger → the REAL <root>/.pantheon/logs/hooks.log.
2355
- // panelLogDir(<root>/.pantheon/delegations) = <root>: the old code passed
2356
- // dirname(delegationsDir()) (= <root>/.pantheon), which createTuiLogger
2357
- // re-joined with `.pantheon/logs/hooks.log` → a nested
2358
- // <root>/.pantheon/.pantheon/logs/hooks.log that never reached the real
2359
- // hooks.log (the empty nested dirs observed in production).
2360
- const panelLog = createTuiLogger(panelLogDir(delegationsDir()))
2361
- // The rendered list is childDelegations (children enriched with md);
2362
- // there is no separate md-only signal — the md channel only feeds
2363
- // childrenToDelegationEntries below.
2364
- const [childDelegations, setChildDelegations] = createSignal<DelegationEntry[]>([])
2365
- // 1s ticker drives the running-jobs elapsed counter AND the safety poll
2366
- // (oh-my-opencode-slim pattern): re-fetch children + re-read the md every
2367
- // second so the panel updates even when NO event ever fires.
2368
- const [now, setNow] = createSignal(Date.now())
2369
- // Separate fast ticker for the spinner. The elapsed label intentionally
2370
- // remains on the 1s ticker to avoid unnecessary work.
2371
- const [animationNow, setAnimationNow] = createSignal(Date.now())
2372
- // Cumulative count of event-triggered refreshes — logged with every fetch
2373
- // ("panel: children=N md=N events=N") so the (0) symptom is diagnosable:
2374
- // children>0 means the source works; events=0 means the event bus isn't
2375
- // delivering, and the 1s poll is what keeps the panel honest.
2376
- let eventRefreshCount = 0
2377
- // In-flight guard: overlap between the poll, events and the version effect
2378
- // collapses into one fetch — no duplicate work, no duplicate entries.
2379
- let delegationsInflight: Promise<void> | null = null
2380
- const refreshDelegations = () => {
2381
- if (delegationsInflight !== null) return delegationsInflight
2382
- delegationsInflight = (async () => {
2383
- try {
2384
- const state = props.api.state as any
2385
- // 0. md reports from EVERY session under .pantheon/delegations — the
2386
- // HISTORY channel. Read BEFORE the sessionID guard so the panel shows
2387
- // past reports (running first, Finalized desc) even when no session
2388
- // is focused (null/placeholder sessionID): the "(0)" symptom becomes
2389
- // the full historical list. Fail-open: a missing dir yields [].
2390
- let md: DelegationEntry[] = []
2391
- try {
2392
- md = await readAllDelegationEntries(panelLogDir(delegationsDir()))
2393
- } catch {
2394
- md = [] // fail-open: never crash the sidebar on a read error
2395
- }
2396
- // 1. current session — resolve + GUARD (placeholder regression). The
2397
- // runtime may render the sidebar with an unsubstituted "{sessionID}"
2398
- // slot prop; forwarding it to session.children made the server reject
2399
- // every poll (~1 err/s: "Expected a string starting with \"ses\", got
2400
- // \"%7BsessionID%7D\"") and fail-open the panel into "(0)". A null
2401
- // resolution SKIPS the fetch entirely: the md history is shown alone
2402
- // (zero children, zero errors).
2403
- const sessionID = resolveCurrentSessionID({ sessionID: props.sessionID, api: props.api })
2404
- if (sessionID === null) {
2405
- setChildDelegations(md)
2406
- panelLog.info(
2407
- `panel: children=0 md=${md.length} events=${eventRefreshCount} (no sessionID — history shown)`,
2408
- )
2409
- return
2410
- }
2411
- // 2. children — PRIMARY source (SDK: api.client.session.children).
2412
- let children: ChildDelegationLike[] = []
2413
- try {
2414
- // buildChildrenPath re-validates: with sessionID !== null it is
2415
- // never null, so no placeholder can reach the wire.
2416
- const result = await (props.api.client as any)?.session?.children?.(
2417
- buildChildrenPath(sessionID),
2418
- )
2419
- const data = (result?.data ?? result) as unknown
2420
- children = Array.isArray(data) ? (data as ChildDelegationLike[]) : []
2421
- } catch (err) {
2422
- children = [] // children API unavailable — the panel shows md only
2423
- panelLog.info('panel: error children fetch', err)
2424
- }
2425
- // 3. live status per child (sync API) + merge children with md.
2426
- const resolveStatus = (childID: unknown): string | undefined => {
2427
- // isValidSessionId guard: a placeholder / foreign id must never
2428
- // reach the status API (same regression class as the children
2429
- // path — "%7BsessionID%7D").
2430
- if (!isValidSessionId(childID)) return undefined
2431
- try {
2432
- return state?.session?.status?.(childID)?.type as string | undefined
2433
- } catch {
2434
- return undefined // status API unavailable — child state fallback
2435
- }
2436
- }
2437
- const withStatus = children.map((c) => ({ ...c, status: resolveStatus(c.id) }))
2438
- const childEntries = childrenToDelegationEntries(withStatus, md, now())
2439
- for (const [k, v] of props.liveStore.map)
2440
- if (v.alias === null && v.taskID === null && Date.now() - v.startedAt > 30_000)
2441
- props.liveStore.map.delete(k)
2442
- // The event channel is optimistic: it renders a job even while the
2443
- // child session/report is still being created. Filter by parent so a
2444
- // different focused session never leaks rows into this sidebar.
2445
- const liveEntries = [...props.liveStore.map.values()].filter(
2446
- (entry) => entry.sessionID === sessionID,
2447
- )
2448
- setChildDelegations(mergeChildDelegationSources(childEntries, liveEntries))
2449
- // 4. diagnostic line — every re-fetch (silence-by-default, hooks.log).
2450
- panelLog.info(
2451
- `panel: children=${children.length} md=${md.length} events=${eventRefreshCount}`,
2452
- )
2453
- } finally {
2454
- delegationsInflight = null
2455
- }
2456
- })()
2457
- return delegationsInflight
2458
- }
2459
- // beta.6: active (running/retry) first, then the 8 most recent terminal
2460
- // reports, then the archived tail (paginated). Pagination state lives at
2461
- // module level so sidebar remounts keep the user's page.
2462
- const delegationSplit = createMemo(() => splitDelegationList(childDelegations()))
2463
- const visibleDelegations = createMemo(() => [
2464
- ...delegationSplit().active,
2465
- ...delegationSplit().recent,
2466
- ])
2467
- const [archivedPage, setArchivedPage] = createSignal(archivedUiState.page)
2468
- const clampArchivedPage = (page: number, pages: number) => {
2469
- const clamped = Math.max(0, Math.min(page, Math.max(0, pages - 1)))
2470
- archivedUiState.page = clamped
2471
- setArchivedPage(clamped)
2472
- }
2473
-
2474
- // ── Event subscriptions for live session/delegation updates ──
2475
- onMount(() => {
2476
- const cleanup: (() => void)[] = []
2477
-
2478
- // Session events — triggers the sessions resource refetch.
2479
- try {
2480
- cleanup.push(props.api.event.on('session.status', refetchSessions))
2481
- cleanup.push(props.api.event.on('session.created', refetchSessions))
2482
- cleanup.push(props.api.event.on('session.updated', refetchSessions))
2483
- cleanup.push(props.api.event.on('session.deleted', refetchSessions))
2484
- } catch {
2485
- /* events API not available in this runtime */
2486
- }
2487
-
2488
- // Delegation panel: children are born/die with session lifecycle events
2489
- // (a delegate spawns a child → session.created fires) — re-fetch on all
2490
- // of them. `session.status` re-syncs busy→idle state transitions.
2491
- try {
2492
- const eventRefresh = () => {
2493
- eventRefreshCount += 1
2494
- void refreshDelegations()
2495
- }
2496
- cleanup.push(props.api.event.on('session.created', eventRefresh))
2497
- cleanup.push(props.api.event.on('session.updated', eventRefresh))
2498
- cleanup.push(props.api.event.on('session.deleted', eventRefresh))
2499
- cleanup.push(props.api.event.on('session.status', eventRefresh))
2500
- } catch {
2501
- /* events API not available — the 1s poll still covers it */
2502
- }
2503
-
2504
- // message.part.updated/removed → liveStore.version() bumps (tui()):
2505
- // subscribe here so the panel ALSO re-fetches children when tool-part
2506
- // events DO arrive and the updated live row is rendered immediately.
2507
- createEffect(() => {
2508
- props.liveStore.version() // subscribe to live mutations
2509
- eventRefreshCount += 1
2510
- void refreshDelegations()
2511
- })
2512
-
2513
- // Safety poll (OMO-slim pattern): 1s re-fetch children + md + tick the
2514
- // elapsed counter. Guarantees the panel updates even with zero events.
2515
- const poll = setInterval(() => {
2516
- setNow(Date.now())
2517
- void refreshDelegations()
2518
- }, 1_000)
2519
- cleanup.push(() => clearInterval(poll))
2520
- const animation = setInterval(() => setAnimationNow(Date.now()), 140)
2521
- cleanup.push(() => clearInterval(animation))
2522
-
2523
- // Compaction recovery: `message.part.removed` clears live entries while
2524
- // compacting, so after a compaction/attach the live map would start
2525
- // empty even though the session still holds the delegation tool parts.
2526
- // Re-seed the live map from the session's existing parts (in message
2527
- // order) right after the subscriptions are registered — the version
2528
- // bump re-triggers the children fetch. Fail-open: if the SDK access is
2529
- // unavailable we skip — the children API + the 1s poll keep the panel
2530
- // working.
2531
- try {
2532
- const sdk = (props.api.state as any)?.session
2533
- const mountSessionID = resolveCurrentSessionID({ sessionID: props.sessionID, api: props.api })
2534
- if (mountSessionID !== null && typeof sdk?.messages === 'function') {
2535
- const messages: readonly { id?: string; parts?: unknown[] }[] =
2536
- sdk.messages(mountSessionID) ?? []
2537
- const state = props.api.state as any
2538
- const getParts =
2539
- typeof state?.part === 'function'
2540
- ? (messageID: string) => state.part(messageID)
2541
- : undefined
2542
- const parts = collectDelegationToolParts(messages, getParts)
2543
- if (parts.length > 0 && seedLiveDelegationMap(props.liveStore.map, parts) > 0) {
2544
- props.liveStore.bump()
2545
- }
2546
- }
2547
- } catch {
2548
- /* re-scan unavailable — children API + 1s poll still cover it */
2549
- }
2550
-
2551
- onCleanup(() =>
2552
- cleanup.forEach((fn) => {
2553
- fn()
2554
- }),
2555
- )
2556
- })
2557
-
2558
- const HR = () => <text fg={theme().textMuted}>{'\u2500'.repeat(28)}</text>
2559
-
2560
- return (
2561
- <box flexDirection="column" width="100%">
2562
- {/* ── Header ── */}
2563
- <text fg={theme().accent} attributes={1}>
2564
- {`Pantheon${props.version ? ` v${props.version}` : ''}`}
2565
- </text>
2566
- <Show when={branch()}>{(b) => <text fg={theme().textMuted}>{b()}</text>}</Show>
2567
-
2568
- {/* ── Active preset indicator ── */}
2569
- <Show
2570
- when={preset().name}
2571
- fallback={
2572
- <box flexDirection="row" gap={1}>
2573
- <text fg={theme().textMuted}>Preset: default</text>
2574
- </box>
2575
- }
2576
- >
2577
- {(name) => (
2578
- <box flexDirection="row" gap={1}>
2579
- <text fg={theme().textMuted}>{'\u26a1 Preset:'}</text>
2580
- <text fg={theme().accent}>{name()}</text>
2581
- <text fg={theme().textMuted}>{`(${preset().source ?? ''})`}</text>
2582
- </box>
2583
- )}
2584
- </Show>
2585
-
2586
- <HR />
2587
-
2588
- {/* ── Sessions ── */}
2589
- <box onMouseDown={() => setShowSessions((x) => !x)}>
2590
- <text fg={theme().text} attributes={1}>
2591
- {`${showSessions() ? '\u25bc' : '\u25b6'} Sessions`}
2592
- </text>
2593
- <text fg={theme().textMuted}>{` (${String(totalSessions())})`}</text>
2594
- </box>
2595
- <Show when={showSessions()}>
2596
- <Show
2597
- when={recentSessions().length > 0}
2598
- fallback={
2599
- <box marginLeft={1}>
2600
- <text fg={theme().textMuted}>No recent sessions</text>
2601
- </box>
2602
- }
2603
- >
2604
- <box marginLeft={1} flexDirection="column">
2605
- <For each={recentSessions()}>
2606
- {(ses: any) => <SessionRow api={props.api} session={ses} />}
2607
- </For>
2608
- </box>
2609
- </Show>
2610
- </Show>
2611
-
2612
- {/* ── Delegations (session.children primary + .pantheon/delegations md enrichment) ── */}
2613
- <box onMouseDown={() => setShowDelegations((x) => !x)}>
2614
- <text fg={theme().text} attributes={1}>
2615
- {`${showDelegations() ? '\u25bc' : '\u25b6'} Delegations`}
2616
- </text>
2617
- <text fg={theme().textMuted}>{` (${String(visibleDelegations().length)})`}</text>
2618
- </box>
2619
- <Show when={showDelegations()}>
2620
- <Show
2621
- when={visibleDelegations().length > 0}
2622
- fallback={
2623
- <box marginLeft={1}>
2624
- <text fg={theme().textMuted}>No delegations</text>
2625
- </box>
2626
- }
2627
- >
2628
- <box marginLeft={1} flexDirection="column">
2629
- <For each={visibleDelegations()}>
2630
- {(job) => (
2631
- <DelegationRow
2632
- api={props.api}
2633
- job={job}
2634
- now={now()}
2635
- animationNow={animationNow()}
2636
- />
2637
- )}
2638
- </For>
2639
- <Show when={delegationSplit().archived.length > 0}>
2640
- {(() => {
2641
- const archived = delegationSplit().archived
2642
- const pageSize = 8
2643
- const pages = Math.ceil(archived.length / pageSize)
2644
- const page = Math.min(archivedPage(), pages - 1)
2645
- const slice = archived.slice(page * pageSize, page * pageSize + pageSize)
2646
- return (
2647
- <box flexDirection="column">
2648
- <box flexDirection="row" marginLeft={0}>
2649
- <text
2650
- fg={theme().textMuted}
2651
- onMouseDown={() => clampArchivedPage(page - 1, pages)}
2652
- >{`\u2039 `}</text>
2653
- <text fg={theme().textMuted}>{`Archived (${archived.length}) `}</text>
2654
- <text fg={theme().textMuted}>{`${page + 1}/${pages}`}</text>
2655
- <text
2656
- fg={theme().textMuted}
2657
- onMouseDown={() => clampArchivedPage(page + 1, pages)}
2658
- >{` \u203a`}</text>
2659
- </box>
2660
- <For each={slice}>
2661
- {(job) => (
2662
- <DelegationRow
2663
- api={props.api}
2664
- job={job}
2665
- now={now()}
2666
- animationNow={animationNow()}
2667
- />
2668
- )}
2669
- </For>
2670
- </box>
2671
- )
2672
- })()}
2673
- </Show>
2674
- </box>
2675
- </Show>
2676
- </Show>
2677
- </box>
2678
- )
2679
- }
2680
-
2681
- /* ─── Plugin Registration ────────────────────────────────── */
2682
-
2683
- const tui: TuiPlugin = (api, _options, _meta) => {
2684
- if (pantheonPluginOnce('pantheon:tui')) return
2685
- // Do not await project file/process probes here. OpenCode waits for the TUI
2686
- // factory before it finishes startup, and a Windows host opening a WSL
2687
- // project can leave those probes pending while the project bridge comes up.
2688
- // Register the sidebar immediately and fill in the optional version later.
2689
- const [version, setVersion] = createSignal<string | null>(null)
2690
- void detectVersion(api)
2691
- .then((detected) => setVersion(detected))
2692
- .catch(() => setVersion(null))
2693
-
2694
- // Vendored feature (MIT): AI subscription usage gauges.
2695
- void setupUsageBar(api) // async init — never blocks sidebar registration
2696
-
2697
- // ── Live delegation store (legacy tool-part tracker, kept as a REFRESH
2698
- // TRIGGER) ──
2699
- // The Delegations panel's PRIMARY source is `api.client.session.children`
2700
- // (delegations-sidebar pattern) — `message.part.updated` may not fire for
2701
- // pantheon_delegate on runtime 1.18.13 (the "(0)" symptom). The tool-part
2702
- // lifecycle below still tracks pantheon_delegate / pantheon_delegation_read
2703
- // parts and bumps a version signal the View subscribes to: when part
2704
- // events DO arrive, the panel re-fetches children. Fail-open: if the
2705
- // events API is unavailable nothing subscribes and the 1s safety poll
2706
- // keeps the panel working (never crash).
2707
- const [liveVersion, setLiveVersion] = createSignal(0)
2708
- const liveStore: LiveDelegationStore = {
2709
- map: new Map<string, LiveDelegationEntry>(),
2710
- version: liveVersion,
2711
- bump: () => setLiveVersion((v) => v + 1),
2712
- }
2713
- const unsubLive: (() => void)[] = []
2714
-
2715
- try {
2716
- unsubLive.push(
2717
- api.event.on('message.part.updated', (event: any) => {
2718
- // SDK v2 shape: properties.part (v1 drift: properties.info.part).
2719
- const props = (event?.properties ?? {}) as { part?: unknown; info?: { part?: unknown } }
2720
- const part = (props.part ?? props.info?.part) as DelegationToolPart | undefined
2721
- if (part === undefined) return
2722
- // beta.6: track the live tool call per child session (panel's
2723
- // activity line). Fire-and-forget — display-only state.
2724
- const sample = extractToolActivity(part as any)
2725
- if (sample !== null)
2726
- trackToolActivity(latestToolActivity, sample.sessionID, sample.activity)
2727
- if (reduceDelegationToolPart(liveStore.map, part)) liveStore.bump()
2728
- }),
2729
- )
2730
- } catch {
2731
- /* events API unavailable — children API + 1s poll cover the panel */
2732
- }
2733
- try {
2734
- unsubLive.push(
2735
- api.event.on('message.part.removed', (event: any) => {
2736
- // SDK v2 shape: properties.partID (v1 drift: properties.part.id).
2737
- const props = (event?.properties ?? {}) as { partID?: string; part?: { id?: string } }
2738
- const partID = props.partID ?? props.part?.id
2739
- if (partID !== undefined && removeDelegationEntry(liveStore.map, partID)) liveStore.bump()
2740
- }),
2741
- )
2742
- } catch {
2743
- /* events API unavailable — children API + 1s poll cover the panel */
2744
- }
2745
- api.lifecycle.onDispose(() => {
2746
- for (const unsub of unsubLive) {
2747
- try {
2748
- unsub()
2749
- } catch {
2750
- /* ignore */
2751
- }
2752
- }
2753
- liveStore.map.clear()
2754
- })
2755
-
2756
- api.slots.register({
2757
- order: 900,
2758
- slots: {
2759
- sidebar_content(_ctx, props) {
2760
- return (
2761
- <View api={api} sessionID={props.session_id} version={version()} liveStore={liveStore} />
2762
- )
2763
- },
2764
- },
2765
- })
2766
- }
2767
-
2768
- const plugin: TuiPluginModule & { id: string; setup: () => Promise<void> } = {
2769
- id: 'pantheon.tui',
2770
- tui,
2771
- // Beta loader contract: every `plugins` directory entry must expose a
2772
- // no-op `setup` so the entry loads as `pantheon.tui` with zero errors
2773
- // (sandbox probe evidence). The TUI itself boots via `tui()`.
2774
- setup: async () => {},
2775
- }
2776
-
2777
- export default plugin