pantheon-opencode 1.6.1 → 1.6.2-beta.1

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 (99) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +16 -0
  4. package/README.md +91 -19
  5. package/README.pt-BR.md +14 -9
  6. package/bin/pantheon-init.mjs +106 -19
  7. package/package.json +3 -2
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +1 -1
  11. package/scripts/doctor.mjs +213 -45
  12. package/scripts/install/agents-md.mjs +2 -1
  13. package/scripts/install/config-migration.mjs +344 -393
  14. package/scripts/install/config-paths.mjs +15 -0
  15. package/scripts/install/mcp-permissions.mjs +164 -0
  16. package/scripts/install/opencode-version.mjs +31 -13
  17. package/scripts/install/opencode-wildcard.mjs +106 -0
  18. package/scripts/install/opencode.mjs +240 -69
  19. package/scripts/install/plan-artifact.mjs +12 -1
  20. package/scripts/install/plugin.mjs +17 -1
  21. package/scripts/install/v2-capabilities.mjs +5 -6
  22. package/scripts/package-evidence.mjs +1 -0
  23. package/scripts/sandbox-env.sh +174 -0
  24. package/scripts/setup-v2-config.mjs +1703 -0
  25. package/scripts/setup.mjs +415 -0
  26. package/scripts/sync-tui.mjs +9 -1
  27. package/scripts/test-opencode-v2-sandbox.sh +438 -151
  28. package/scripts/update-skills-lock.mjs +30 -0
  29. package/skills-lock.json +10 -10
  30. package/src/agents/aphrodite.md +5 -2
  31. package/src/agents/apollo.md +5 -0
  32. package/src/agents/athena.md +6 -1
  33. package/src/agents/demeter.md +5 -1
  34. package/src/agents/gaia.md +4 -0
  35. package/src/agents/hephaestus.md +6 -1
  36. package/src/agents/hermes.md +6 -3
  37. package/src/agents/iris.md +5 -1
  38. package/src/agents/mnemosyne.md +20 -50
  39. package/src/agents/nyx.md +5 -1
  40. package/src/agents/prometheus.md +4 -0
  41. package/src/agents/talos.md +4 -0
  42. package/src/agents/themis.md +4 -0
  43. package/src/agents/zeus.md +9 -3
  44. package/src/instructions/agent-return-format.instructions.md +1 -1
  45. package/src/instructions/memory-protocol.instructions.md +3 -3
  46. package/src/instructions/test-economy.instructions.md +6 -6
  47. package/src/mcp/pantheon_vision.py +37 -36
  48. package/src/pantheon/v2-vision.ts +34 -29
  49. package/src/pantheon/vision.ts +43 -10
  50. package/src/plugin-v2.ts +30 -53
  51. package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
  52. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
  53. package/src/plugins/tui/dist/quota-adapters.js +1142 -0
  54. package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
  55. package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
  56. package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
  57. package/src/plugins/tui/dist/quota-cli.js +184 -0
  58. package/src/plugins/tui/dist/quota-cli.js.map +1 -0
  59. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +390 -0
  60. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +1 -0
  61. package/src/plugins/tui/dist/server-v2.d.ts +14 -0
  62. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  63. package/src/plugins/tui/dist/server-v2.js +673 -0
  64. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  65. package/src/plugins/tui/dist/tui-v2.d.ts +247 -52
  66. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  67. package/src/plugins/tui/dist/tui-v2.js +2492 -529
  68. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  69. package/src/plugins/tui/dist/tui.js +1 -1
  70. package/src/plugins/tui/index-v2.ts +3 -6
  71. package/src/plugins/tui/package-lock.json +2 -2
  72. package/src/plugins/tui/package.json +3 -2
  73. package/src/plugins/tui/src/context-gauge.ts +59 -0
  74. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
  75. package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
  76. package/src/plugins/tui/src/index-v2.tsx +199 -240
  77. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  78. package/src/plugins/tui/src/quota-adapters.ts +1598 -0
  79. package/src/plugins/tui/src/quota-cli.ts +237 -0
  80. package/src/plugins/tui/src/quota-rpc.ts +209 -0
  81. package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
  82. package/src/plugins/tui/src/quota-v2.tsx +986 -0
  83. package/src/plugins/tui/src/server-v2.ts +841 -0
  84. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  85. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  86. package/src/plugins/tui/tsdown.config.ts +8 -1
  87. package/src/routing.yml +72 -13
  88. package/src/skills/README.md +4 -0
  89. package/src/skills/agent-coordination/SKILL.md +0 -3
  90. package/src/skills/artifact-management/SKILL.md +0 -3
  91. package/src/skills/auto-continue/SKILL.md +0 -3
  92. package/src/skills/code-review-checklist/SKILL.md +0 -3
  93. package/src/skills/context-compression/SKILL.md +0 -3
  94. package/src/skills/memory-bank/SKILL.md +6 -28
  95. package/src/skills/session-goal/SKILL.md +0 -3
  96. package/src/skills/simplify/SKILL.md +5 -4
  97. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  98. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  99. package/src/pantheon/memory-context.ts +0 -1017
@@ -0,0 +1,986 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import type { Context, KeymapCommand, KeymapLayer, PanelInput } from '@opencode/plugin/tui/context'
4
+ import { createMemo, createSignal, For, type JSX, onCleanup, onMount, Show } from 'solid-js'
5
+ import {
6
+ contextBar,
7
+ contextUsageTone,
8
+ formatContextWindow,
9
+ formatSpent,
10
+ formatTokenCount,
11
+ } from './context-gauge'
12
+ import { quotaGoCheckCommand } from './go-key-diagnostic-ui'
13
+ import { MODEL_USAGE_MESSAGE_LIMIT, MODEL_USAGE_SESSION_LIMIT } from './model-usage-limits'
14
+ import {
15
+ collectRecentModelUsageRows,
16
+ compactQuotaMetric,
17
+ formatQuotaCountdown,
18
+ type QuotaMetric,
19
+ type QuotaProviderDetail,
20
+ type QuotaRuntime,
21
+ type QuotaSidebarEntry,
22
+ type QuotaSnapshot,
23
+ quotaClock,
24
+ quotaProgress,
25
+ quotaSidebarEntries,
26
+ quotaSnapshotStatusLabel,
27
+ type RecentModelUsageRow,
28
+ resolveActiveModelRef,
29
+ } from './quota-v2-model'
30
+ import { cellWidth, SIDEBAR_CONTENT_WIDTH } from './sidebar-width'
31
+
32
+ export const QUOTA_PANEL_NAME = 'pantheon.quota'
33
+ export const QUOTA_OPEN_COMMAND_ID = 'pantheon.quota.open'
34
+ export const QUOTA_ICON = '\u25A5'
35
+ const QUOTA_PANEL_TOAST = 'Abra uma sessão para ver os detalhes da quota.'
36
+
37
+ type QuotaSurfaceProps = { context: Context; runtime: QuotaRuntime }
38
+
39
+ const MODEL_USAGE_REFRESH_EVENTS = [
40
+ 'session.created',
41
+ 'session.renamed',
42
+ 'session.metadata.updated',
43
+ 'session.moved',
44
+ 'session.idle',
45
+ 'session.status',
46
+ 'session.deleted',
47
+ ] as const satisfies readonly Parameters<Context['data']['on']>[0][]
48
+
49
+ function base(context: Context) {
50
+ return context.theme.text?.base ?? (context.themeMode === 'dark' ? '#ffffff' : '#111111')
51
+ }
52
+
53
+ function muted(context: Context) {
54
+ return context.theme.text?.muted ?? base(context)
55
+ }
56
+
57
+ export function quotaUsageTone(usedPercent: number): 'success' | 'warning' | 'error' {
58
+ return usedPercent > 85 ? 'error' : usedPercent >= 60 ? 'warning' : 'success'
59
+ }
60
+
61
+ function quotaColor(context: Context, usedPercent: number | undefined): string {
62
+ return usedPercent === undefined ? base(context) : tone(context, quotaUsageTone(usedPercent))
63
+ }
64
+
65
+ type QuotaTone = 'info' | 'success' | 'warning' | 'error'
66
+
67
+ function tone(context: Context, color: QuotaTone): string {
68
+ return context.theme.text?.feedback?.[color]?.base ?? base(context)
69
+ }
70
+
71
+ export function snapshotSummary(snapshot: QuotaSnapshot, display: 'used' | 'remaining'): string {
72
+ if (snapshot.status === 'loading') return 'carregando status'
73
+ if (snapshot.status !== 'ready' && snapshot.status !== 'partial') {
74
+ // Reuse the sidebar label map (fault-aware for `unavailable`) so the footer
75
+ // never contradicts the sidebar; lowercase matches the footer style.
76
+ return quotaSnapshotStatusLabel(snapshot.status, snapshot.error).toLowerCase()
77
+ }
78
+ const metrics = snapshot.providers.flatMap((provider) => provider.metrics)
79
+ const metric = metrics.find((item) => item.kind !== 'provider_status') ?? metrics[0]
80
+ if (metric) {
81
+ const value = compactQuotaMetric(metric, display) ?? 'quota indisponível'
82
+ return snapshot.status === 'partial' ? `parcial · ${value}` : value
83
+ }
84
+ if (snapshot.status === 'partial') return 'dados parciais'
85
+ if (snapshot.providers[0]?.message) return snapshot.providers[0].message
86
+ return 'quota indisponível'
87
+ }
88
+
89
+ type FinanceMetric = Extract<QuotaMetric, { kind: 'balance' | 'estimate' | 'key_usage' }>
90
+ type FinanceEntry = { providerID: string; metric: FinanceMetric }
91
+
92
+ export function sidebarFinanceEntries(snapshot: QuotaSnapshot): FinanceEntry[] {
93
+ return snapshot.providers.flatMap((provider) =>
94
+ provider.metrics.flatMap((metric) =>
95
+ (metric.kind === 'balance' || metric.kind === 'estimate' || metric.kind === 'key_usage') &&
96
+ metricRow(metric)
97
+ ? [{ providerID: provider.id, metric }]
98
+ : [],
99
+ ),
100
+ )
101
+ }
102
+
103
+ function QuotaSidebarEntryRow(props: {
104
+ entry: QuotaSidebarEntry
105
+ display: 'used' | 'remaining'
106
+ context: Context
107
+ now: number
108
+ }): JSX.Element {
109
+ return (
110
+ <Show
111
+ when={props.entry.kind === 'quota'}
112
+ fallback={
113
+ <For
114
+ each={
115
+ props.entry.kind === 'status'
116
+ ? quotaTextLines(props.entry.message, SIDEBAR_CONTENT_WIDTH, 2)
117
+ : []
118
+ }
119
+ >
120
+ {(line) => <text fg={muted(props.context)}>{line}</text>}
121
+ </For>
122
+ }
123
+ >
124
+ <For
125
+ each={
126
+ props.entry.kind === 'quota'
127
+ ? quotaWindowLines(
128
+ props.entry.metric,
129
+ props.display,
130
+ SIDEBAR_CONTENT_WIDTH,
131
+ props.now,
132
+ true,
133
+ )
134
+ : []
135
+ }
136
+ >
137
+ {(line) => (
138
+ <text
139
+ fg={quotaColor(
140
+ props.context,
141
+ props.entry.kind === 'quota' ? props.entry.progress.usedPercent : undefined,
142
+ )}
143
+ >
144
+ {line}
145
+ </text>
146
+ )}
147
+ </For>
148
+ </Show>
149
+ )
150
+ }
151
+
152
+ export function QuotaSidebarSummary(props: QuotaSurfaceProps): JSX.Element {
153
+ const entries = createMemo(() => quotaSidebarEntries(props.runtime.snapshot()))
154
+ const finance = createMemo(() => sidebarFinanceEntries(props.runtime.snapshot()))
155
+ const [now, setNow] = createSignal(Date.now())
156
+ onMount(() => onCleanup(quotaClock.subscribe(setNow)))
157
+ return (
158
+ <Show when={props.runtime.preferences().enabled}>
159
+ <box flexDirection="column" marginTop={1}>
160
+ <text fg={base(props.context)}>{`${QUOTA_ICON} Pantheon quota`}</text>
161
+ <Show when={props.runtime.snapshot().status !== 'ready' || entries().length === 0}>
162
+ <text fg={muted(props.context)}>
163
+ {quotaSnapshotStatusLabel(
164
+ props.runtime.snapshot().status,
165
+ props.runtime.snapshot().error,
166
+ )}
167
+ </text>
168
+ </Show>
169
+ <For each={props.runtime.snapshot().providers}>
170
+ {(provider) => (
171
+ <box flexDirection="column">
172
+ <Show
173
+ when={
174
+ entries().some((entry) => entry.providerID === provider.id) ||
175
+ finance().some((entry) => entry.providerID === provider.id) ||
176
+ provider.metrics.some((metric) => metric.kind === 'provider_status')
177
+ }
178
+ >
179
+ <For each={quotaTextLines(provider.label, SIDEBAR_CONTENT_WIDTH, 0)}>
180
+ {(line) => <text fg={muted(props.context)}>{line}</text>}
181
+ </For>
182
+ </Show>
183
+ <For each={entries().filter((entry) => entry.providerID === provider.id)}>
184
+ {(entry) => (
185
+ <QuotaSidebarEntryRow
186
+ entry={entry}
187
+ display={props.runtime.preferences().display}
188
+ context={props.context}
189
+ now={now()}
190
+ />
191
+ )}
192
+ </For>
193
+ <For each={provider.metrics.filter((metric) => metric.kind === 'provider_status')}>
194
+ {(metric) => (
195
+ <For each={quotaMetricLines(metric, SIDEBAR_CONTENT_WIDTH)}>
196
+ {(line) => <text fg={muted(props.context)}>{line}</text>}
197
+ </For>
198
+ )}
199
+ </For>
200
+ <For each={finance().filter((entry) => entry.providerID === provider.id)}>
201
+ {(entry) => (
202
+ <For each={financeMetricLines(entry.metric, SIDEBAR_CONTENT_WIDTH)}>
203
+ {(line) => <text fg={base(props.context)}>{line}</text>}
204
+ </For>
205
+ )}
206
+ </For>
207
+ </box>
208
+ )}
209
+ </For>
210
+ </box>
211
+ </Show>
212
+ )
213
+ }
214
+
215
+ function QuotaFooterSummary(props: QuotaSurfaceProps) {
216
+ const preferences = () => props.runtime.preferences()
217
+ return (
218
+ <Show when={preferences().enabled}>
219
+ <text fg={muted(props.context)}>
220
+ {`Quota · ${snapshotSummary(props.runtime.snapshot(), preferences().display)}`}
221
+ </text>
222
+ </Show>
223
+ )
224
+ }
225
+
226
+ function clipped(value: string, width: number): string {
227
+ const max = Math.max(5, Math.floor(width) - 2)
228
+ return value.length <= max ? value : `${value.slice(0, max - 1)}…`
229
+ }
230
+
231
+ type QuotaWindowMetric = Extract<QuotaMetric, { kind: 'provider_quota' }>
232
+
233
+ function quotaAmount(value: number, unit: string): string | undefined {
234
+ const safeUnit = unit.trim()
235
+ if (!Number.isFinite(value) || !safeUnit) return undefined
236
+ return `${new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(value)} ${safeUnit}`
237
+ }
238
+
239
+ function quotaResetDate(resetsAt: number | undefined, now: number): string | undefined {
240
+ if (resetsAt === undefined || !Number.isFinite(resetsAt) || !Number.isFinite(now))
241
+ return undefined
242
+ const date = new Date(resetsAt)
243
+ if (!Number.isFinite(date.getTime()) || resetsAt <= now) return undefined
244
+ return `Resets on ${date.toISOString().slice(0, 16).replace('T', ' ')} UTC`
245
+ }
246
+
247
+ /** Wrap on grapheme boundaries, measuring terminal cells rather than code units. */
248
+ export function quotaTextLines(text: string, width: number, indent: number): string[] {
249
+ const max = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0
250
+ if (max < 1) return []
251
+ const padding = ' '.repeat(Math.min(Math.max(0, indent), Math.max(0, max - 2)))
252
+ const lines: string[] = []
253
+ let line = padding
254
+ const segmenter = new Intl.Segmenter()
255
+ for (const word of text.trim().split(/\s+/)) {
256
+ if (!word) continue
257
+ if (line.trim() && cellWidth(line) + 1 + cellWidth(word) > max) {
258
+ lines.push(line.trimEnd())
259
+ line = padding
260
+ }
261
+ if (line.trim()) line += ' '
262
+ for (const { segment } of segmenter.segment(word)) {
263
+ const glyphWidth = cellWidth(segment)
264
+ if (glyphWidth > max) continue
265
+ if (cellWidth(line) + glyphWidth > max) {
266
+ if (line.trim()) lines.push(line.trimEnd())
267
+ line = glyphWidth + cellWidth(padding) <= max ? padding : ''
268
+ }
269
+ line += segment
270
+ }
271
+ }
272
+ if (line.trim()) lines.push(line.trimEnd())
273
+ return lines
274
+ }
275
+
276
+ /** Layout uses only a provider-reported reset; a local clock never refreshes data. */
277
+ export function quotaWindowLines(
278
+ metric: QuotaWindowMetric,
279
+ display: 'used' | 'remaining',
280
+ width: number,
281
+ now: number,
282
+ sidebarPercent = false,
283
+ ): string[] {
284
+ const title = metric.period?.trim() || metric.label?.trim() || 'Quota'
285
+ const progress = quotaProgress(metric)
286
+ const amount =
287
+ sidebarPercent && progress
288
+ ? `${display === 'remaining' ? progress.remainingPercent : progress.usedPercent}%`
289
+ : quotaAmount(display === 'remaining' ? metric.remaining : metric.used, metric.unit)
290
+ if (!amount) return []
291
+ const value = `${amount} ${display === 'remaining' ? 'rest.' : 'uso'}`
292
+ const countdown = formatQuotaCountdown(metric.resetsAt, now)
293
+ const reset =
294
+ countdown === null ? '(aguardando atualização)' : countdown ? `(${countdown})` : undefined
295
+ const resetDate =
296
+ countdown !== undefined && countdown !== null ? quotaResetDate(metric.resetsAt, now) : undefined
297
+ const resetDateLines = resetDate ? quotaTextLines(resetDate, width, 4) : []
298
+ const padded = ` ${title.padEnd(8)} ${value}`
299
+ const compact = ` ${title} ${value}`
300
+ const prefix = cellWidth(padded) <= width ? padded : compact
301
+ const suffix = reset ? ` ${reset}` : ''
302
+ const rawBar =
303
+ progress && (sidebarPercent || metric.unit.trim() === '%')
304
+ ? contextBar(progress.usedPercent, 4)
305
+ : undefined
306
+ const bar = rawBar ? { ...rawBar, empty: '░'.repeat(cellWidth(rawBar.empty)) } : undefined
307
+ const secondaryAmount = sidebarPercent
308
+ ? undefined
309
+ : quotaAmount(display === 'remaining' ? metric.used : metric.remaining, metric.unit)
310
+ const secondary = secondaryAmount
311
+ ? quotaTextLines(
312
+ `${display === 'remaining' ? 'Usado' : 'Restante'} ${secondaryAmount}`,
313
+ width,
314
+ 4,
315
+ )
316
+ : []
317
+ if (!sidebarPercent && progress) {
318
+ secondary.push(...quotaTextLines(`${progress.remainingPercent}% restante`, width, 4))
319
+ }
320
+ if (bar && cellWidth(prefix + suffix) + 5 <= width) {
321
+ return [`${prefix} ${bar.filled}${bar.empty}${suffix}`, ...resetDateLines, ...secondary]
322
+ }
323
+ if (cellWidth(prefix + suffix) <= width)
324
+ return [`${prefix}${suffix}`, ...resetDateLines, ...secondary]
325
+ if (cellWidth(prefix) <= width)
326
+ return reset
327
+ ? [prefix, ...quotaTextLines(reset, width, 4), ...resetDateLines, ...secondary]
328
+ : [prefix, ...resetDateLines, ...secondary]
329
+ return [
330
+ ...quotaTextLines(title, width, 2),
331
+ ...quotaTextLines(value, width, 4),
332
+ ...(reset ? quotaTextLines(reset, width, 4) : []),
333
+ ...resetDateLines,
334
+ ...secondary,
335
+ ]
336
+ }
337
+
338
+ function QuotaWindow(props: {
339
+ metric: QuotaWindowMetric
340
+ display: 'used' | 'remaining'
341
+ width: number
342
+ context: Context
343
+ now: number
344
+ }): JSX.Element {
345
+ return (
346
+ <box flexDirection="column">
347
+ <For each={quotaWindowLines(props.metric, props.display, props.width, props.now)}>
348
+ {(line) => (
349
+ <text fg={quotaColor(props.context, quotaProgress(props.metric)?.usedPercent)}>
350
+ {line}
351
+ </text>
352
+ )}
353
+ </For>
354
+ </box>
355
+ )
356
+ }
357
+
358
+ type QuotaMetricRow = { label: string; value: string }
359
+
360
+ function metricRow(
361
+ metric: Exclude<QuotaMetric, { kind: 'provider_quota' }>,
362
+ ): QuotaMetricRow | undefined {
363
+ const label = (fallback: string): string => metric.label?.trim() || fallback
364
+ switch (metric.kind) {
365
+ case 'balance': {
366
+ const value = quotaAmount(metric.amount, metric.currency)
367
+ return value
368
+ ? {
369
+ label: label('Saldo'),
370
+ value: `${value}${metric.status?.trim() ? ` · ${metric.status.trim()}` : ''}`,
371
+ }
372
+ : undefined
373
+ }
374
+ case 'estimate': {
375
+ const value = quotaAmount(metric.amount, metric.unit)
376
+ return value ? { label: label('Estimativa'), value } : undefined
377
+ }
378
+ case 'key_usage': {
379
+ const value = quotaAmount(metric.amount, metric.currency)
380
+ if (!value) return undefined
381
+ const source = label('Uso da chave selecionada')
382
+ const scopedLabel = /selected\s+key|chave selecionada/i.test(source)
383
+ ? source
384
+ : `Chave selecionada · ${source}`
385
+ return {
386
+ label: scopedLabel,
387
+ value: `${value}${metric.period?.trim() ? ` · ${metric.period.trim()}` : ''}`,
388
+ }
389
+ }
390
+ case 'session_usage': {
391
+ const value = quotaAmount(metric.amount, metric.unit)
392
+ return value ? { label: label('Uso da sessão'), value } : undefined
393
+ }
394
+ case 'provider_status':
395
+ return { label: metric.label, value: metric.status }
396
+ }
397
+ }
398
+
399
+ export function financeMetricLines(metric: FinanceMetric, width: number): string[] {
400
+ return quotaMetricLines(metric, width)
401
+ }
402
+
403
+ export function quotaMetricLines(
404
+ metric: Exclude<QuotaMetric, { kind: 'provider_quota' }>,
405
+ width: number,
406
+ ): string[] {
407
+ const row = metricRow(metric)
408
+ if (!row) return []
409
+ const left = ` ${row.label}`
410
+ const spaces = width - cellWidth(left) - cellWidth(row.value)
411
+ if (spaces >= 2) return [`${left}${' '.repeat(spaces)}${row.value}`]
412
+ return [...quotaTextLines(row.label, width, 2), ...quotaTextLines(row.value, width, 4)]
413
+ }
414
+
415
+ function QuotaMetricLine(props: {
416
+ metric: Exclude<QuotaMetric, { kind: 'provider_quota' }>
417
+ width: number
418
+ context: Context
419
+ }) {
420
+ const row = () => metricRow(props.metric)
421
+ return (
422
+ <Show when={row()}>
423
+ <box flexDirection="column">
424
+ <For each={quotaMetricLines(props.metric, props.width)}>
425
+ {(line) => <text fg={base(props.context)}>{line}</text>}
426
+ </For>
427
+ </box>
428
+ </Show>
429
+ )
430
+ }
431
+
432
+ function providerState(provider: QuotaProviderDetail): { label: string; tone: QuotaTone } {
433
+ if (provider.authentication === 'not_connected')
434
+ return { label: '○ Precisa configurar', tone: 'warning' }
435
+ if (provider.authentication === 'unavailable') return { label: '× Indisponível', tone: 'error' }
436
+ return provider.state === 'available'
437
+ ? { label: '✓ Credencial local · há dados', tone: 'success' }
438
+ : { label: '! Credencial local · sem dados', tone: 'warning' }
439
+ }
440
+
441
+ function recentModelUsage(context: Context, sessionID: string): RecentModelUsageRow[] {
442
+ if (!sessionID.startsWith('ses')) {
443
+ return collectRecentModelUsageRows({
444
+ activeModel: null,
445
+ activeMessages: [],
446
+ usageMessages: [],
447
+ models: [],
448
+ })
449
+ }
450
+
451
+ let session: ReturnType<Context['data']['session']['get']>
452
+ let activeMessages: unknown[] = []
453
+ try {
454
+ session = context.data.session.get(sessionID)
455
+ } catch {
456
+ session = undefined
457
+ }
458
+ const messagesBySession = new Map<string, unknown[]>()
459
+ try {
460
+ const messages = context.data.session.message.list(sessionID)
461
+ if (Array.isArray(messages)) {
462
+ activeMessages = messages.slice(-MODEL_USAGE_MESSAGE_LIMIT)
463
+ messagesBySession.set(sessionID, activeMessages)
464
+ }
465
+ } catch {
466
+ /* Cached session metadata can still identify the active model. */
467
+ }
468
+
469
+ const sessionIDs = [sessionID]
470
+ try {
471
+ const family = context.data.session.family(sessionID)
472
+ if (Array.isArray(family)) {
473
+ for (const id of family) {
474
+ if (typeof id !== 'string' || !id.startsWith('ses') || sessionIDs.includes(id)) continue
475
+ sessionIDs.push(id)
476
+ if (sessionIDs.length >= MODEL_USAGE_SESSION_LIMIT) break
477
+ }
478
+ }
479
+ } catch {
480
+ /* The active session still supplies its cached messages when family is absent. */
481
+ }
482
+
483
+ const usageMessages: unknown[] = []
484
+ const usageSessions: Array<{ messages: readonly unknown[]; revertMessageID: string | null }> = []
485
+ for (const id of sessionIDs) {
486
+ let messages = messagesBySession.get(id) ?? []
487
+ if (!messagesBySession.has(id)) {
488
+ try {
489
+ const result = context.data.session.message.list(id)
490
+ if (Array.isArray(result)) messages = result.slice(-MODEL_USAGE_MESSAGE_LIMIT)
491
+ } catch {
492
+ /* One unreadable child must not hide usage from the rest of the family. */
493
+ }
494
+ }
495
+ messagesBySession.set(id, messages)
496
+ usageMessages.push(...messages)
497
+ let familySession = session
498
+ if (id !== sessionID) {
499
+ try {
500
+ familySession = context.data.session.get(id)
501
+ } catch {
502
+ familySession = undefined
503
+ }
504
+ }
505
+ const revert = familySession?.revert
506
+ const revertMessageID =
507
+ typeof revert === 'object' && revert !== null && typeof revert.messageID === 'string'
508
+ ? revert.messageID
509
+ : null
510
+ usageSessions.push({ messages, revertMessageID })
511
+ }
512
+
513
+ let models: unknown[] = []
514
+ let fallbackModel: unknown = null
515
+ try {
516
+ const location = context.location ?? context.data.location.default()
517
+ const result = context.data.location.model.list(location)
518
+ if (Array.isArray(result)) models = result
519
+ const agentID = session?.agent
520
+ if (typeof agentID === 'string' && agentID !== '') {
521
+ const agents = context.data.location.agent?.list?.(location)
522
+ if (Array.isArray(agents)) {
523
+ fallbackModel = agents.find((agent) => agent?.id === agentID)?.model ?? null
524
+ }
525
+ }
526
+ } catch {
527
+ /* Unknown model limits suppress only the context bars. */
528
+ }
529
+
530
+ const activeModel = resolveActiveModelRef(session?.model, activeMessages, fallbackModel)
531
+ const revert = session?.revert
532
+ const revertMessageID =
533
+ typeof revert === 'object' && revert !== null && typeof revert.messageID === 'string'
534
+ ? revert.messageID
535
+ : null
536
+
537
+ return collectRecentModelUsageRows({
538
+ activeModel,
539
+ activeMessages,
540
+ usageMessages,
541
+ usageSessions,
542
+ models,
543
+ revertMessageID,
544
+ })
545
+ }
546
+
547
+ function ModelUsageDetails(props: { context: Context; sessionID: string; width: number }) {
548
+ const [revision, setRevision] = createSignal(0)
549
+ const rows = createMemo(() => {
550
+ revision()
551
+ return recentModelUsage(props.context, props.sessionID)
552
+ })
553
+
554
+ onMount(() => {
555
+ const unsubscribe: Array<() => void> = []
556
+ for (const event of MODEL_USAGE_REFRESH_EVENTS) {
557
+ try {
558
+ unsubscribe.push(props.context.data.on(event, () => setRevision((value) => value + 1)))
559
+ } catch {
560
+ /* Cached values stay renderable if a host event is unavailable. */
561
+ }
562
+ }
563
+ onCleanup(() => {
564
+ for (const dispose of unsubscribe) dispose()
565
+ })
566
+ })
567
+
568
+ const contextTone = (percent: number) => tone(props.context, contextUsageTone(percent))
569
+ const contextCells = () => Math.max(4, Math.min(12, Math.floor((props.width - 30) / 2)))
570
+ const modelLabel = (row: RecentModelUsageRow) =>
571
+ `${row.providerID ? `${row.providerID}/` : ''}${row.label}`
572
+
573
+ return (
574
+ <box flexDirection="column" paddingTop={1}>
575
+ <text fg={tone(props.context, 'info')} attributes={1}>
576
+ Modelos em uso
577
+ </text>
578
+ <text fg={muted(props.context)}>Mensagens recentes da sessão ativa e delegações.</text>
579
+ <For each={rows()}>
580
+ {(row, index) => (
581
+ <>
582
+ <Show when={row.active}>
583
+ <text fg={tone(props.context, 'info')} attributes={1}>
584
+ MODELO ATUAL
585
+ </text>
586
+ </Show>
587
+ <Show when={!row.active && index() === 1}>
588
+ <text fg={muted(props.context)} attributes={1}>
589
+ MAIS USADOS RECENTEMENTE
590
+ </text>
591
+ </Show>
592
+ <box flexDirection="column" paddingTop={1} paddingLeft={1}>
593
+ <text fg={base(props.context)} attributes={1}>
594
+ {clipped(modelLabel(row), props.width - 2)}
595
+ </text>
596
+ <Show
597
+ when={row.tokens !== null}
598
+ fallback={<text fg={muted(props.context)}>dados indisponíveis</text>}
599
+ >
600
+ <box flexDirection="row" justifyContent="space-between" gap={1}>
601
+ <text fg={muted(props.context)}>Tokens nas mensagens recentes</text>
602
+ <text fg={base(props.context)}>{`${formatTokenCount(row.tokens) ?? '—'}`}</text>
603
+ </box>
604
+ </Show>
605
+ <Show when={row.context}>
606
+ {(usage) => {
607
+ const bar = () => contextBar(usage().percent, contextCells())
608
+ return (
609
+ <box flexDirection="column" paddingTop={1}>
610
+ <box flexDirection="row" justifyContent="space-between" gap={1}>
611
+ <text fg={muted(props.context)}>Último contexto reportado</text>
612
+ <text fg={contextTone(usage().percent)}>
613
+ {`${formatTokenCount(usage().tokens) ?? '—'} tokens`}
614
+ </text>
615
+ </box>
616
+ <box flexDirection="row" gap={1}>
617
+ <Show when={bar()}>
618
+ {(cells) => (
619
+ <>
620
+ <text fg={contextTone(usage().percent)}>{cells().filled}</text>
621
+ <text fg={muted(props.context)}>{cells().empty}</text>
622
+ </>
623
+ )}
624
+ </Show>
625
+ <text fg={contextTone(usage().percent)}>
626
+ {`${usage().percent}% de ${formatContextWindow(usage().limit) ?? '—'}`}
627
+ </text>
628
+ </box>
629
+ </box>
630
+ )
631
+ }}
632
+ </Show>
633
+ <Show when={row.cost !== null}>
634
+ <For
635
+ each={quotaTextLines(
636
+ `Custo reportado · mensagens recentes · ${formatSpent(row.cost) ?? '—'}`,
637
+ props.width - 2,
638
+ 0,
639
+ )}
640
+ >
641
+ {(line) => <text fg={muted(props.context)}>{line}</text>}
642
+ </For>
643
+ </Show>
644
+ <Show when={row.tokens !== null && row.context === null}>
645
+ <text fg={muted(props.context)}>Contexto indisponível</text>
646
+ </Show>
647
+ </box>
648
+ </>
649
+ )}
650
+ </For>
651
+ </box>
652
+ )
653
+ }
654
+
655
+ function QuotaProviderDetails(props: {
656
+ provider: QuotaProviderDetail
657
+ display: 'used' | 'remaining'
658
+ width: number
659
+ context: Context
660
+ }) {
661
+ const [now, setNow] = createSignal(Date.now())
662
+ onMount(() => onCleanup(quotaClock.subscribe(setNow)))
663
+ const state = () => providerState(props.provider)
664
+ const quotaMetrics = () =>
665
+ props.provider.metrics.filter(
666
+ (metric): metric is QuotaWindowMetric => metric.kind === 'provider_quota',
667
+ )
668
+ const financeMetrics = () =>
669
+ props.provider.metrics.filter(
670
+ (metric) =>
671
+ metric.kind === 'balance' || metric.kind === 'estimate' || metric.kind === 'key_usage',
672
+ )
673
+ const otherMetrics = () =>
674
+ props.provider.metrics.filter(
675
+ (metric) => metric.kind === 'provider_status' || metric.kind === 'session_usage',
676
+ )
677
+ const safeError = () => {
678
+ const message = props.provider.message
679
+ return message &&
680
+ message !== 'status indisponível' &&
681
+ message !== 'dados de quota indisponíveis' &&
682
+ message !== 'setup necessário'
683
+ ? message
684
+ : undefined
685
+ }
686
+
687
+ return (
688
+ <box flexDirection="column" paddingBottom={1}>
689
+ <For each={quotaTextLines(props.provider.label, props.width, 0)}>
690
+ {(line) => (
691
+ <text fg={tone(props.context, 'info')} attributes={1}>
692
+ {line}
693
+ </text>
694
+ )}
695
+ </For>
696
+ <For each={quotaTextLines(state().label, props.width, 0)}>
697
+ {(line) => <text fg={tone(props.context, state().tone)}>{line}</text>}
698
+ </For>
699
+ <Show when={quotaMetrics().length > 0}>
700
+ <For each={quotaMetrics()}>
701
+ {(metric) => (
702
+ <QuotaWindow
703
+ metric={metric}
704
+ now={now()}
705
+ display={props.display}
706
+ width={props.width}
707
+ context={props.context}
708
+ />
709
+ )}
710
+ </For>
711
+ </Show>
712
+ <Show when={financeMetrics().length > 0}>
713
+ <text fg={muted(props.context)}>GASTOS &amp; SALDO</text>
714
+ <For each={financeMetrics()}>
715
+ {(metric) => (
716
+ <QuotaMetricLine metric={metric} width={props.width} context={props.context} />
717
+ )}
718
+ </For>
719
+ </Show>
720
+ <Show when={otherMetrics().length > 0}>
721
+ <text fg={muted(props.context)}>OUTRAS MÉTRICAS</text>
722
+ <For each={otherMetrics()}>
723
+ {(metric) => (
724
+ <QuotaMetricLine metric={metric} width={props.width} context={props.context} />
725
+ )}
726
+ </For>
727
+ </Show>
728
+ <Show when={safeError()}>
729
+ {(message) => (
730
+ <text fg={tone(props.context, 'warning')}>
731
+ {clipped(`! ${message()}`, props.width - 2)}
732
+ </text>
733
+ )}
734
+ </Show>
735
+ <text fg={muted(props.context)}>
736
+ {'─'.repeat(Math.max(8, Math.min(32, props.width - 4)))}
737
+ </text>
738
+ </box>
739
+ )
740
+ }
741
+
742
+ export type QuotaPanelAction = 'toggle-enabled' | 'toggle-display' | 'refresh' | 'close'
743
+
744
+ export const QUOTA_PANEL_COMMANDS: readonly {
745
+ action: QuotaPanelAction
746
+ id: string
747
+ title: string
748
+ bind: string
749
+ }[] = [
750
+ {
751
+ action: 'toggle-enabled',
752
+ id: 'pantheon.quota.toggle-enabled',
753
+ title: 'Quota: ativar/desativar',
754
+ bind: 'e',
755
+ },
756
+ {
757
+ action: 'toggle-display',
758
+ id: 'pantheon.quota.toggle-display',
759
+ title: 'Quota: alternar usado/restante',
760
+ bind: 'm',
761
+ },
762
+ { action: 'refresh', id: 'pantheon.quota.refresh', title: 'Quota: atualizar', bind: 'r' },
763
+ { action: 'close', id: 'pantheon.quota.close', title: 'Quota: fechar', bind: 'escape,q' },
764
+ ]
765
+
766
+ export function runQuotaPanelCommand(
767
+ action: QuotaPanelAction,
768
+ panel: Pick<PanelInput, 'focused' | 'close'>,
769
+ runtime: QuotaRuntime,
770
+ ): false | Promise<void> | undefined {
771
+ if (panel.focused !== true) return false
772
+ switch (action) {
773
+ case 'toggle-enabled':
774
+ return runtime.toggleEnabled()
775
+ case 'toggle-display':
776
+ return runtime.toggleDisplay()
777
+ case 'refresh':
778
+ return runtime.refresh()
779
+ case 'close':
780
+ panel.close()
781
+ return undefined
782
+ }
783
+ }
784
+
785
+ export function quotaPanelKeymapLayer(
786
+ panel: Pick<PanelInput, 'focused' | 'close'>,
787
+ runtime: QuotaRuntime,
788
+ ): KeymapLayer {
789
+ const focused = () => panel.focused === true
790
+ return {
791
+ mode: 'global',
792
+ enabled: focused,
793
+ commands: QUOTA_PANEL_COMMANDS.map((command) => ({
794
+ id: command.id,
795
+ title: command.title,
796
+ bind: command.bind,
797
+ run: () => (focused() ? runQuotaPanelCommand(command.action, panel, runtime) : false),
798
+ })),
799
+ }
800
+ }
801
+
802
+ export function quotaOpenCommand(context: Pick<Context, 'ui'>): KeymapCommand {
803
+ return {
804
+ id: QUOTA_OPEN_COMMAND_ID,
805
+ title: 'Pantheon: Quota',
806
+ description: 'Painel de quota',
807
+ group: 'Pantheon',
808
+ palette: true,
809
+ slash: { name: 'quota', aliases: ['pantheon-quota'] },
810
+ run: () => {
811
+ openQuotaPanel(context)
812
+ },
813
+ }
814
+ }
815
+
816
+ export function openQuotaPanel(context: Pick<Context, 'ui'>): boolean {
817
+ let opened = false
818
+ try {
819
+ opened = context.ui.panel.open(QUOTA_PANEL_NAME)
820
+ } catch {
821
+ opened = false
822
+ }
823
+ if (opened) return true
824
+ try {
825
+ context.ui.toast.show({ message: QUOTA_PANEL_TOAST, variant: 'warning' })
826
+ } catch {
827
+ /* The details panel remains a no-op if the host also lacks toast support. */
828
+ }
829
+ return false
830
+ }
831
+
832
+ function QuotaPanel(props: QuotaSurfaceProps & { panel: PanelInput }) {
833
+ props.context.keymap.layer(() => quotaPanelKeymapLayer(props.panel, props.runtime))
834
+ const preferences = () => props.runtime.preferences()
835
+ const snapshot = () => props.runtime.snapshot()
836
+ const snapshotTone = (): QuotaTone => {
837
+ switch (snapshot().status) {
838
+ case 'ready':
839
+ return 'success'
840
+ case 'partial':
841
+ case 'connected_unavailable':
842
+ case 'needs_setup':
843
+ case 'stale':
844
+ return 'warning'
845
+ case 'unavailable':
846
+ return 'error'
847
+ case 'loading':
848
+ case 'disabled':
849
+ return 'info'
850
+ }
851
+ }
852
+
853
+ return (
854
+ <box flexDirection="column" width="100%" height="100%" padding={1}>
855
+ <Show
856
+ when={props.panel.width >= 54}
857
+ fallback={
858
+ <box flexDirection="column">
859
+ <text fg={tone(props.context, 'info')} attributes={1}>
860
+ {`${QUOTA_ICON} Pantheon / Quota`}
861
+ </text>
862
+ <text fg={tone(props.context, snapshotTone())}>
863
+ {quotaSnapshotStatusLabel(snapshot().status, snapshot().error)}
864
+ </text>
865
+ </box>
866
+ }
867
+ >
868
+ <box flexDirection="row" justifyContent="space-between" gap={1}>
869
+ <text fg={tone(props.context, 'info')} attributes={1}>
870
+ {`${QUOTA_ICON} Pantheon / Quota`}
871
+ </text>
872
+ <text fg={tone(props.context, snapshotTone())}>
873
+ {quotaSnapshotStatusLabel(snapshot().status, snapshot().error)}
874
+ </text>
875
+ </box>
876
+ </Show>
877
+ <Show when={snapshot().error !== undefined && snapshot().status !== 'ready'}>
878
+ <text fg={muted(props.context)}>{`Último erro: ${snapshot().error}`}</text>
879
+ </Show>
880
+ <Show when={snapshot().status === 'needs_setup' && snapshot().details.length === 0}>
881
+ <text fg={muted(props.context)}>
882
+ Nenhum provedor elegível: verifique conexão ativa e credencial local compatível.
883
+ </text>
884
+ </Show>
885
+ <Show when={snapshot().status === 'unavailable'}>
886
+ <text fg={muted(props.context)}>Não foi possível verificar o status da quota.</text>
887
+ </Show>
888
+ <Show when={snapshot().status === 'stale'}>
889
+ <text fg={muted(props.context)}>
890
+ A última resposta continua visível; atualize para tentar novamente.
891
+ </text>
892
+ </Show>
893
+ <scrollbox
894
+ flexGrow={1}
895
+ flexShrink={1}
896
+ flexBasis={0}
897
+ minHeight={3}
898
+ width="100%"
899
+ scrollY
900
+ focused={props.panel.focused}
901
+ focusable
902
+ border
903
+ borderColor={muted(props.context)}
904
+ focusedBorderColor={tone(props.context, 'info')}
905
+ >
906
+ <box flexDirection="column" paddingX={1} paddingY={1}>
907
+ <For each={snapshot().details}>
908
+ {(provider) => (
909
+ <QuotaProviderDetails
910
+ provider={provider}
911
+ display={preferences().display}
912
+ width={props.panel.width - 4}
913
+ context={props.context}
914
+ />
915
+ )}
916
+ </For>
917
+ <ModelUsageDetails
918
+ context={props.context}
919
+ sessionID={props.panel.sessionID}
920
+ width={props.panel.width - 6}
921
+ />
922
+ </box>
923
+ </scrollbox>
924
+ <box flexDirection="column" flexShrink={0}>
925
+ <text fg={muted(props.context)}>
926
+ {`Quota ${preferences().enabled ? 'ativada' : 'desativada'} · exibição: ${preferences().display === 'remaining' ? 'restante' : 'usado'}`}
927
+ </text>
928
+ <text
929
+ fg={muted(props.context)}
930
+ >{`E ${preferences().enabled ? 'desativar' : 'ativar'} · M alternar usado/restante`}</text>
931
+ <text fg={muted(props.context)}>↑/↓ rolar · R atualizar</text>
932
+ <text fg={muted(props.context)}>Esc/Q fechar</text>
933
+ </box>
934
+ </box>
935
+ )
936
+ }
937
+
938
+ function QuotaCommandLayer(props: QuotaSurfaceProps) {
939
+ const goCheck = quotaGoCheckCommand(props.context)
940
+ props.context.keymap.layer(() => ({
941
+ mode: 'global',
942
+ commands: [quotaOpenCommand(props.context), goCheck],
943
+ }))
944
+ return null
945
+ }
946
+
947
+ /** Register footer/panel controls and own teardown of the shared sidebar runtime. */
948
+ export function registerQuotaTui(context: Context, runtime: QuotaRuntime): () => void {
949
+ const unregister: Array<() => void> = []
950
+ try {
951
+ unregister.push(
952
+ context.ui.slot({
953
+ append: 'prompt.footer',
954
+ render: () => <QuotaFooterSummary context={context} runtime={runtime} />,
955
+ }),
956
+ )
957
+ unregister.push(
958
+ context.ui.slot({
959
+ append: 'session.panel',
960
+ render: (panel: PanelInput) =>
961
+ panel.name === QUOTA_PANEL_NAME ? (
962
+ <QuotaPanel context={context} runtime={runtime} panel={panel} />
963
+ ) : null,
964
+ }),
965
+ )
966
+ unregister.push(
967
+ context.ui.slot({
968
+ append: 'app',
969
+ render: () => <QuotaCommandLayer context={context} runtime={runtime} />,
970
+ }),
971
+ )
972
+ } catch (error) {
973
+ runtime.dispose()
974
+ unregister.reverse().forEach((dispose) => {
975
+ dispose()
976
+ })
977
+ throw error
978
+ }
979
+
980
+ return () => {
981
+ runtime.dispose()
982
+ unregister.reverse().forEach((dispose) => {
983
+ dispose()
984
+ })
985
+ }
986
+ }