pantheon-opencode 1.5.0-beta.2 → 1.5.0-beta.20

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