pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +23 -14
  3. package/README.pt-BR.md +12 -1
  4. package/package.json +1 -1
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/src/pantheon/cost-command.ts +30 -133
  8. package/src/pantheon/model-pricing.ts +1 -536
  9. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  10. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
  11. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
  12. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -1
  13. package/src/plugins/tui/dist/quota-adapters.js +1 -1
  14. package/src/plugins/tui/dist/{quota-rpc-UL2HuFRJ.js → quota-rpc-DMmXBhBe.js} +295 -1
  15. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
  16. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  17. package/src/plugins/tui/dist/server-v2.js +135 -12
  18. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  19. package/src/plugins/tui/dist/tui-v2.d.ts +132 -5
  20. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  21. package/src/plugins/tui/dist/tui-v2.js +3720 -337
  22. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  23. package/src/plugins/tui/dist/tui.js +1 -1
  24. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
  25. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
  26. package/src/plugins/tui/dist/usage-history-worker.js +25 -0
  27. package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
  28. package/src/plugins/tui/package-lock.json +17 -2
  29. package/src/plugins/tui/package.json +4 -2
  30. package/src/plugins/tui/src/cost-data.ts +607 -0
  31. package/src/plugins/tui/src/index-v2.tsx +32 -0
  32. package/src/plugins/tui/src/model-pricing.ts +536 -0
  33. package/src/plugins/tui/src/quota-rpc.ts +164 -0
  34. package/src/plugins/tui/src/quota-v2-model.ts +2 -2
  35. package/src/plugins/tui/src/quota-v2.tsx +338 -86
  36. package/src/plugins/tui/src/server-v2.ts +159 -15
  37. package/src/plugins/tui/src/usage-history-contract.ts +217 -0
  38. package/src/plugins/tui/src/usage-history-validation.ts +104 -0
  39. package/src/plugins/tui/src/usage-history-view.tsx +236 -0
  40. package/src/plugins/tui/src/usage-history-worker.ts +25 -0
  41. package/src/plugins/tui/src/usage-view-model.ts +272 -0
  42. package/src/plugins/tui/tsconfig.typecheck.json +6 -1
  43. package/src/plugins/tui/tsdown.config.ts +36 -4
  44. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
@@ -0,0 +1,236 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import type { Context, KeymapLayer, PanelInput } from '@opencode/plugin/tui/context'
4
+ import { createEffect, createSignal, For, type JSX, onCleanup, Show } from 'solid-js'
5
+ import { quotaRpc } from './quota-rpc'
6
+ import type { UsageHistoryRpcPeriod, UsageHistoryRpcResult } from './usage-history-contract'
7
+ import { isActiveContextCostResult, isUsageHistoryRpcResult } from './usage-history-validation'
8
+ import {
9
+ type ActiveContextCostResult,
10
+ activeContextEstimateErrorLines,
11
+ activeContextEstimateLines,
12
+ activeContextEstimateMissingLines,
13
+ activeContextEstimatePendingLines,
14
+ USAGE_HISTORY_PERIOD_BINDINGS,
15
+ usageHistoryChartLines,
16
+ usageHistoryControlsLines,
17
+ usageHistoryCoverageLabel,
18
+ usageHistoryPartialWarning,
19
+ usageHistoryPricingLabel,
20
+ usageHistorySelectorLines,
21
+ usageHistoryTextLines,
22
+ usageHistoryUnavailableMessage,
23
+ } from './usage-view-model'
24
+
25
+ function location(context: Context): ReturnType<Context['data']['location']['default']> {
26
+ return context.location ?? context.data.location.default()
27
+ }
28
+
29
+ export function ActiveContextEstimate(props: {
30
+ context: Context
31
+ providerID: string | null
32
+ modelID: string | null
33
+ contextTokens: number | null
34
+ width: number
35
+ }): JSX.Element {
36
+ const [result, setResult] = createSignal<ActiveContextCostResult | null>(null)
37
+ const [loading, setLoading] = createSignal(false)
38
+ const [failed, setFailed] = createSignal(false)
39
+ const client = props.context.client.rpc(quotaRpc)
40
+
41
+ createEffect(() => {
42
+ const providerID = props.providerID
43
+ const modelID = props.modelID
44
+ const contextTokens = props.contextTokens
45
+ if (contextTokens === null) {
46
+ setResult(null)
47
+ setFailed(false)
48
+ setLoading(false)
49
+ return
50
+ }
51
+ if (!providerID || !modelID) {
52
+ setResult({
53
+ status: 'unavailable',
54
+ billed: false,
55
+ basis: 'pre-cache-context-tokens-times-input-price',
56
+ cacheDiscountApplied: false,
57
+ reason: 'missing-model-identity',
58
+ })
59
+ setFailed(false)
60
+ setLoading(false)
61
+ return
62
+ }
63
+
64
+ const controller = new AbortController()
65
+ let current = true
66
+ setResult(null)
67
+ setFailed(false)
68
+ setLoading(true)
69
+ try {
70
+ void client
71
+ .active_context_cost(
72
+ { providerID, modelID, contextTokens },
73
+ { signal: controller.signal, location: location(props.context) },
74
+ )
75
+ .then((response) => {
76
+ if (!current) return
77
+ if (isActiveContextCostResult(response)) setResult(response)
78
+ else setFailed(true)
79
+ })
80
+ .catch(() => {
81
+ if (current) setFailed(true)
82
+ })
83
+ .finally(() => {
84
+ if (current) setLoading(false)
85
+ })
86
+ } catch {
87
+ setFailed(true)
88
+ setLoading(false)
89
+ }
90
+
91
+ onCleanup(() => {
92
+ current = false
93
+ controller.abort()
94
+ })
95
+ })
96
+
97
+ const lines = (): string[] => {
98
+ if (loading()) return activeContextEstimatePendingLines(props.width)
99
+ if (failed()) return activeContextEstimateErrorLines(props.width)
100
+ const current = result()
101
+ if (current) return activeContextEstimateLines(current, props.width)
102
+ return activeContextEstimateMissingLines(props.width)
103
+ }
104
+
105
+ return (
106
+ <box flexDirection="column">
107
+ <For each={lines()}>{(line) => <text>{line}</text>}</For>
108
+ </box>
109
+ )
110
+ }
111
+
112
+ export function UsageHistorySection(props: {
113
+ context: Context
114
+ panel: PanelInput
115
+ width: number
116
+ }): JSX.Element {
117
+ const [period, setPeriod] = createSignal<UsageHistoryRpcPeriod>('7d')
118
+ const [result, setResult] = createSignal<UsageHistoryRpcResult | null>(null)
119
+ const [loading, setLoading] = createSignal(true)
120
+ const [requestFailed, setRequestFailed] = createSignal(false)
121
+ const client = props.context.client.rpc(quotaRpc)
122
+
123
+ const keymap = (): KeymapLayer => ({
124
+ mode: 'global',
125
+ enabled: () => props.panel.focused === true,
126
+ commands: USAGE_HISTORY_PERIOD_BINDINGS.map(({ period: selected, bind, label }) => ({
127
+ id: `pantheon.quota.history.${selected}`,
128
+ title: `Histórico de uso: ${label}`,
129
+ bind,
130
+ run: () => {
131
+ if (props.panel.focused !== true) return false
132
+ setPeriod(selected)
133
+ return undefined
134
+ },
135
+ })),
136
+ })
137
+ props.context.keymap.layer(keymap)
138
+
139
+ createEffect(() => {
140
+ const selectedPeriod = period()
141
+ const controller = new AbortController()
142
+ let current = true
143
+ setLoading(true)
144
+ setRequestFailed(false)
145
+ setResult(null)
146
+
147
+ try {
148
+ void client
149
+ .usage_history(
150
+ { period: selectedPeriod },
151
+ { signal: controller.signal, location: location(props.context) },
152
+ )
153
+ .then((response) => {
154
+ if (!current) return
155
+ if (isUsageHistoryRpcResult(response)) setResult(response)
156
+ else setRequestFailed(true)
157
+ })
158
+ .catch(() => {
159
+ if (current) setRequestFailed(true)
160
+ })
161
+ .finally(() => {
162
+ if (current) setLoading(false)
163
+ })
164
+ } catch {
165
+ setRequestFailed(true)
166
+ setLoading(false)
167
+ }
168
+
169
+ onCleanup(() => {
170
+ current = false
171
+ controller.abort()
172
+ })
173
+ })
174
+
175
+ const chartLines = (): string[] => {
176
+ const current = result()
177
+ return current?.status === 'available' || current?.status === 'partial'
178
+ ? usageHistoryChartLines(current, props.width)
179
+ : []
180
+ }
181
+ const unavailable = (): string | null => {
182
+ const current = result()
183
+ return current ? usageHistoryUnavailableMessage(current) : null
184
+ }
185
+ const available = ():
186
+ | Extract<UsageHistoryRpcResult, { status: 'available' | 'partial' }>
187
+ | undefined => {
188
+ const current = result()
189
+ return current?.status === 'available' || current?.status === 'partial' ? current : undefined
190
+ }
191
+ const warning = (): string[] => {
192
+ const current = result()
193
+ if (current?.status !== 'available' && current?.status !== 'partial') return []
194
+ const message = usageHistoryPartialWarning(current)
195
+ return message ? usageHistoryTextLines(message, props.width) : []
196
+ }
197
+
198
+ return (
199
+ <box flexDirection="column" paddingTop={1}>
200
+ <text attributes={1}>Histórico de uso</text>
201
+ <For each={usageHistorySelectorLines(period(), props.width)}>
202
+ {(line) => <text>{line}</text>}
203
+ </For>
204
+ <For each={usageHistoryControlsLines(props.width)}>{(line) => <text>{line}</text>}</For>
205
+ <Show when={loading()}>
206
+ <text>Carregando histórico…</text>
207
+ </Show>
208
+ <Show when={!loading() && requestFailed()}>
209
+ <For each={usageHistoryTextLines('Falha ao consultar o histórico.', props.width)}>
210
+ {(line) => <text>{line}</text>}
211
+ </For>
212
+ </Show>
213
+ <Show when={!loading() && unavailable()}>
214
+ {(message) => (
215
+ <For each={usageHistoryTextLines(message(), props.width)}>
216
+ {(line) => <text>{line}</text>}
217
+ </For>
218
+ )}
219
+ </Show>
220
+ <Show when={!loading() && !requestFailed() && available()}>
221
+ {(history) => (
222
+ <box flexDirection="column">
223
+ <For each={usageHistoryTextLines(usageHistoryCoverageLabel(history()), props.width)}>
224
+ {(line) => <text>{line}</text>}
225
+ </For>
226
+ <For each={warning()}>{(line) => <text>{line}</text>}</For>
227
+ <For each={usageHistoryTextLines(usageHistoryPricingLabel(history()), props.width)}>
228
+ {(line) => <text>{line}</text>}
229
+ </For>
230
+ <For each={chartLines()}>{(line) => <text>{line}</text>}</For>
231
+ </box>
232
+ )}
233
+ </Show>
234
+ </box>
235
+ )
236
+ }
@@ -0,0 +1,25 @@
1
+ import { parentPort, workerData } from 'node:worker_threads'
2
+ import { queryUsageHistory, resolveCostDbPath } from './cost-data'
3
+ import { isUsageHistoryPeriod, projectUsageHistoryResult } from './usage-history-contract'
4
+
5
+ interface UsageHistoryWorkerInput {
6
+ period?: unknown
7
+ }
8
+
9
+ const port = parentPort
10
+ if (port) {
11
+ void (async () => {
12
+ try {
13
+ const input = workerData as UsageHistoryWorkerInput
14
+ if (!isUsageHistoryPeriod(input.period)) {
15
+ port.postMessage({ ok: false })
16
+ return
17
+ }
18
+ const result = await queryUsageHistory(resolveCostDbPath(), input.period)
19
+ port.postMessage({ ok: true, result: projectUsageHistoryResult(result) })
20
+ } catch {
21
+ // Database errors may contain the local path, SQL, or private ledger data.
22
+ port.postMessage({ ok: false })
23
+ }
24
+ })()
25
+ }
@@ -0,0 +1,272 @@
1
+ import { cellWidth } from './sidebar-width'
2
+ import type {
3
+ UsageHistoryRpcAvailable,
4
+ UsageHistoryRpcPeriod,
5
+ UsageHistoryRpcResult,
6
+ } from './usage-history-contract'
7
+
8
+ export type ActiveContextCostResult =
9
+ | {
10
+ status: 'estimated'
11
+ estimatedUsd: number
12
+ billed: false
13
+ basis: 'pre-cache-context-tokens-times-input-price'
14
+ cacheDiscountApplied: false
15
+ }
16
+ | {
17
+ status: 'unavailable'
18
+ billed: false
19
+ basis: 'pre-cache-context-tokens-times-input-price'
20
+ cacheDiscountApplied: false
21
+ reason:
22
+ | 'invalid-context-token-count'
23
+ | 'missing-model-identity'
24
+ | 'no-pricing'
25
+ | 'unknown-model'
26
+ | 'ambiguous-model'
27
+ | 'missing-cache-price'
28
+ }
29
+
30
+ const HISTORY_PERIODS: readonly UsageHistoryRpcPeriod[] = ['7d', '15d', '30d', 'total']
31
+ export const USAGE_HISTORY_PERIOD_BINDINGS = [
32
+ { period: '7d', bind: '7', label: '7d' },
33
+ { period: '15d', bind: '1', label: '15d' },
34
+ { period: '30d', bind: '3', label: '30d' },
35
+ { period: 'total', bind: 't', label: 'total' },
36
+ ] as const satisfies readonly {
37
+ period: UsageHistoryRpcPeriod
38
+ bind: string
39
+ label: string
40
+ }[]
41
+
42
+ function wrapText(value: string, width: number): string[] {
43
+ const maxWidth = Number.isFinite(width) ? Math.max(1, Math.floor(width)) : 1
44
+ const lines: string[] = []
45
+ const segmenter = new Intl.Segmenter()
46
+ let line = ''
47
+
48
+ for (const word of value.trim().split(/\s+/)) {
49
+ if (!word) continue
50
+ if (line && cellWidth(line) + 1 + cellWidth(word) > maxWidth) {
51
+ lines.push(line)
52
+ line = ''
53
+ }
54
+ if (line) line += ' '
55
+ for (const { segment } of segmenter.segment(word)) {
56
+ if (cellWidth(line) + cellWidth(segment) > maxWidth) {
57
+ if (line) lines.push(line)
58
+ line = ''
59
+ }
60
+ line += segment
61
+ }
62
+ }
63
+
64
+ if (line) lines.push(line)
65
+ return lines
66
+ }
67
+
68
+ export function usageHistoryTextLines(value: string, width: number): string[] {
69
+ return wrapText(value, width)
70
+ }
71
+
72
+ function formatCount(value: number): string {
73
+ return Math.max(0, value).toLocaleString('en-US')
74
+ }
75
+
76
+ function formatUsd(value: number): string | undefined {
77
+ if (!Number.isFinite(value) || value < 0) return undefined
78
+ return `$${new Intl.NumberFormat('en-US', {
79
+ minimumFractionDigits: 2,
80
+ maximumFractionDigits: 8,
81
+ }).format(value)}`
82
+ }
83
+
84
+ function chartBar(value: number, maxValue: number, width: number): string {
85
+ const cells = Math.max(0, Math.floor(width))
86
+ if (cells === 0 || value <= 0 || maxValue <= 0) return ''
87
+ return '#'.repeat(Math.max(1, Math.min(cells, Math.round((value / maxValue) * cells))))
88
+ }
89
+
90
+ function chartValueLine(value: number, maximum: number, width: number): string {
91
+ const count = `${formatCount(value)} tokens`
92
+ const barWidth = Math.max(0, width - cellWidth(count) - 3)
93
+ const bar = chartBar(value, maximum, Math.min(12, barWidth))
94
+ const line = ` ${bar ? `${bar} ` : ''}${count}`
95
+ return wrapText(line, width).join('\n')
96
+ }
97
+
98
+ function appendWrapped(target: string[], value: string, width: number): void {
99
+ target.push(...wrapText(value, width))
100
+ }
101
+
102
+ export function usageHistorySelectorLabel(selected: UsageHistoryRpcPeriod): string {
103
+ return `Período: ${HISTORY_PERIODS.map((period) => {
104
+ const label = period === 'total' ? 'Total' : period
105
+ return period === selected ? `[${label}]` : label
106
+ }).join(' · ')}`
107
+ }
108
+
109
+ export function usageHistorySelectorLines(
110
+ selected: UsageHistoryRpcPeriod,
111
+ width: number,
112
+ ): string[] {
113
+ return wrapText(usageHistorySelectorLabel(selected), width)
114
+ }
115
+
116
+ export function usageHistoryPeriodForKey(key: string): UsageHistoryRpcPeriod | undefined {
117
+ return USAGE_HISTORY_PERIOD_BINDINGS.find((binding) => binding.bind === key)?.period
118
+ }
119
+
120
+ export function usageHistoryControlsLines(width: number): string[] {
121
+ return wrapText('7 · 7d 1 · 15d 3 · 30d T · total', width)
122
+ }
123
+
124
+ export function usageHistoryCoverageLabel(result: UsageHistoryRpcAvailable): string {
125
+ return result.coverageStart === null
126
+ ? 'Início da cobertura indisponível'
127
+ : `Cobertura desde ${result.coverageStart}`
128
+ }
129
+
130
+ export function usageHistoryPartialWarning(result: UsageHistoryRpcAvailable): string | null {
131
+ if (result.partial && result.truncated) return 'Histórico parcial e truncado pelo limite seguro.'
132
+ if (result.partial) return 'Histórico parcial segundo a consulta.'
133
+ if (result.truncated) return 'Histórico truncado pelo limite seguro.'
134
+ return null
135
+ }
136
+
137
+ export function usageHistoryPricingLabel(result: UsageHistoryRpcAvailable): string {
138
+ const amount =
139
+ result.pricing.estimatedUsd === undefined ? undefined : formatUsd(result.pricing.estimatedUsd)
140
+ const value = amount ? ` · ${amount}` : ''
141
+ switch (result.pricing.status) {
142
+ case 'complete':
143
+ return `Estimativa pelo catálogo${value} · não cobrada`
144
+ case 'partial':
145
+ return `Estimativa parcial pelo catálogo${value} · não cobrada · ${result.pricing.unpricedModels} modelo(s) sem preço`
146
+ case 'unavailable':
147
+ return 'Estimativa de preço indisponível · nenhum valor cobrado'
148
+ case 'empty':
149
+ return 'Sem dados de preço para estimar · nenhum valor cobrado'
150
+ }
151
+ }
152
+
153
+ export function usageHistoryUnavailableMessage(result: UsageHistoryRpcResult): string | null {
154
+ if (result.status !== 'unavailable') return null
155
+ switch (result.reason) {
156
+ case 'invalid_period':
157
+ return 'Período de histórico inválido.'
158
+ case 'history_timeout':
159
+ return 'Consulta de histórico excedeu o tempo limite.'
160
+ case 'history_unavailable':
161
+ return 'Histórico indisponível neste momento.'
162
+ }
163
+ }
164
+
165
+ export function usageHistoryEmptyMessage(): string {
166
+ return 'Sem histórico neste período.'
167
+ }
168
+
169
+ export function usageHistoryChartLines(result: UsageHistoryRpcAvailable, width: number): string[] {
170
+ const maxWidth = Math.max(1, Math.floor(width))
171
+ if (result.rows === 0 && result.buckets.length === 0 && result.models.length === 0) {
172
+ return wrapText(usageHistoryEmptyMessage(), maxWidth)
173
+ }
174
+ const lines: string[] = []
175
+ appendWrapped(lines, `GERAL · ${formatCount(result.totals.total)} tokens`, maxWidth)
176
+
177
+ if (result.buckets.length > 0) {
178
+ lines.push('Uso diário')
179
+ const maxBucket = Math.max(0, ...result.buckets.map((bucket) => bucket.total))
180
+ for (const bucket of result.buckets) {
181
+ appendWrapped(lines, bucket.date, maxWidth)
182
+ lines.push(...chartValueLine(bucket.total, maxBucket, maxWidth).split('\n'))
183
+ }
184
+ } else {
185
+ lines.push('Sem buckets diários neste período.')
186
+ }
187
+
188
+ lines.push('Modelos no período')
189
+ if (result.models.length === 0) {
190
+ lines.push('Sem totais por modelo.')
191
+ return lines.flatMap((line) => wrapText(line, maxWidth))
192
+ }
193
+
194
+ const maxModel = Math.max(0, ...result.models.map((model) => model.totals.total))
195
+ for (const model of result.models) {
196
+ appendWrapped(lines, `${model.providerID}/${model.modelID}`, maxWidth)
197
+ lines.push(...chartValueLine(model.totals.total, maxModel, maxWidth).split('\n'))
198
+ }
199
+ return lines.flatMap((line) => wrapText(line, maxWidth))
200
+ }
201
+
202
+ export function activeModelIdentity(model: {
203
+ providerID: string | null
204
+ modelID: string | null
205
+ label: string
206
+ }): string {
207
+ if (model.providerID && model.modelID) return `${model.providerID}/${model.modelID}`
208
+ if (model.modelID) return model.modelID
209
+ return model.label || 'identidade indisponível'
210
+ }
211
+
212
+ export function sessionSpendLabel(cost: number): string | null {
213
+ if (!Number.isFinite(cost) || cost < 0) return null
214
+ return `Gasto da sessão (relatado) · $${cost.toFixed(2)}`
215
+ }
216
+
217
+ function unavailableContextReason(
218
+ reason: Extract<ActiveContextCostResult, { status: 'unavailable' }>['reason'],
219
+ ): string {
220
+ switch (reason) {
221
+ case 'invalid-context-token-count':
222
+ return 'contagem de tokens de contexto inválida'
223
+ case 'missing-model-identity':
224
+ return 'identidade do modelo indisponível'
225
+ case 'no-pricing':
226
+ case 'missing-cache-price':
227
+ return 'preço de entrada indisponível'
228
+ case 'unknown-model':
229
+ case 'ambiguous-model':
230
+ return 'modelo não identificado na tabela de preços'
231
+ }
232
+ }
233
+
234
+ export function activeContextEstimateLines(
235
+ result: ActiveContextCostResult,
236
+ width: number,
237
+ ): string[] {
238
+ const maxWidth = Math.max(1, Math.floor(width))
239
+ if (result.status === 'unavailable') {
240
+ return wrapText(
241
+ `Estimativa de contexto (pré-cache) indisponível · ${unavailableContextReason(result.reason)}`,
242
+ maxWidth,
243
+ )
244
+ }
245
+
246
+ const amount = formatUsd(result.estimatedUsd)
247
+ if (!amount) {
248
+ return wrapText('Estimativa de contexto (pré-cache) indisponível · valor inválido', maxWidth)
249
+ }
250
+ return [
251
+ ...wrapText(`Estimativa de contexto (pré-cache) · ${amount}`, maxWidth),
252
+ ...wrapText(
253
+ 'Preço de entrada × tokens pré-cache; sem desconto de cache; não é valor cobrado.',
254
+ maxWidth,
255
+ ),
256
+ ]
257
+ }
258
+
259
+ export function activeContextEstimatePendingLines(width: number): string[] {
260
+ return wrapText('Estimativa de contexto (pré-cache) · calculando…', width)
261
+ }
262
+
263
+ export function activeContextEstimateMissingLines(width: number): string[] {
264
+ return wrapText(
265
+ 'Estimativa de contexto (pré-cache) indisponível · contexto não reportado.',
266
+ width,
267
+ )
268
+ }
269
+
270
+ export function activeContextEstimateErrorLines(width: number): string[] {
271
+ return wrapText('Estimativa de contexto (pré-cache) indisponível · falha na consulta.', width)
272
+ }
@@ -1,5 +1,10 @@
1
1
  {
2
2
  "//": "Typecheck gate for the V2 TUI entry only. `tsc --noEmit` at the package root was a no-op: with no tsconfig in this directory tsc walked up to the repo tsconfig.json, which excludes src/plugins/tui entirely — so nothing here was checked. tsdown bundles without type-checking, which is how an invalid event name (session.updated, absent from the OpenCode V2 event union) shipped in the V2 rewrite. This config points tsc at the V2 entry plus its ambient declarations so a type error in src/index-v2.tsx fails `npm run typecheck`. The V1 entry (src/index.tsx) is intentionally NOT included: it carries pre-existing type errors out of scope for the V2 gate. Keep this file strict JSON — the repo pre-commit `check-json` hook rejects comments.",
3
3
  "extends": "./tsconfig.build.json",
4
- "include": ["src/index-v2.tsx", "src/server-v2.ts", "src/opencode-v2.d.ts"]
4
+ "include": [
5
+ "src/index-v2.tsx",
6
+ "src/server-v2.ts",
7
+ "src/usage-history-worker.ts",
8
+ "src/opencode-v2.d.ts"
9
+ ]
5
10
  }
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from 'node:fs'
2
- import { appendFile, readdir, readFile } from 'node:fs/promises'
2
+ import { readdir, readFile, writeFile } from 'node:fs/promises'
3
3
  import { join } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import solid from 'rolldown-plugin-solid'
@@ -10,7 +10,7 @@ const pkg = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf8')) as
10
10
  version: string
11
11
  }
12
12
 
13
- async function ensureDistArtifactsEndWithNewline(): Promise<void> {
13
+ async function finalizeDistArtifacts(): Promise<void> {
14
14
  const dist = join(__dirname, 'dist')
15
15
  const entries = await readdir(dist, { withFileTypes: true })
16
16
 
@@ -20,11 +20,33 @@ async function ensureDistArtifactsEndWithNewline(): Promise<void> {
20
20
  .map(async ({ name }) => {
21
21
  const path = join(dist, name)
22
22
  const contents = await readFile(path, 'utf8')
23
- if (!contents.endsWith('\n')) await appendFile(path, '\n')
23
+ const normalized = normalizeHqtuiBundlePaths(name, contents)
24
+ const finalContents = normalized.endsWith('\n') ? normalized : `${normalized}\n`
25
+ if (contents !== finalContents) await writeFile(path, finalContents)
24
26
  }),
25
27
  )
26
28
  }
27
29
 
30
+ /** Keep Rolldown's vendor source labels stable when a clean build uses a node_modules symlink. */
31
+ function normalizeHqtuiBundlePaths(name: string, contents: string): string {
32
+ if (name === 'tui-v2.js') {
33
+ return contents.replace(
34
+ /\/\/#region [^\n]*node_modules\/@profullstack\/hqtui\/dist\//g,
35
+ '//#region ../../../node_modules/@profullstack/hqtui/dist/',
36
+ )
37
+ }
38
+ if (name !== 'tui-v2.js.map') return contents
39
+
40
+ const map = JSON.parse(contents) as { sources?: string[]; [key: string]: unknown }
41
+ if (!Array.isArray(map.sources)) return contents
42
+ map.sources = map.sources.map((source) => {
43
+ const packagePath = 'node_modules/@profullstack/hqtui/'
44
+ const packageIndex = source.lastIndexOf(packagePath)
45
+ return packageIndex < 0 ? source : `../../../../${source.slice(packageIndex)}`
46
+ })
47
+ return JSON.stringify(map)
48
+ }
49
+
28
50
  export default defineConfig({
29
51
  entry: {
30
52
  tui: 'src/index.tsx',
@@ -33,6 +55,7 @@ export default defineConfig({
33
55
  'server-v2': 'src/server-v2.ts',
34
56
  'quota-cli': 'src/quota-cli.ts',
35
57
  'quota-adapters': 'src/quota-adapters.ts',
58
+ 'usage-history-worker': 'src/usage-history-worker.ts',
36
59
  },
37
60
  format: ['esm'],
38
61
  platform: 'node',
@@ -41,6 +64,14 @@ export default defineConfig({
41
64
  outExtensions: () => ({ js: '.js' }),
42
65
  dts: {
43
66
  tsconfig: join(__dirname, 'tsconfig.build.json'),
67
+ entry: [
68
+ 'src/index.tsx',
69
+ 'src/index-v2.tsx',
70
+ 'src/server.ts',
71
+ 'src/server-v2.ts',
72
+ 'src/quota-cli.ts',
73
+ 'src/quota-adapters.ts',
74
+ ],
44
75
  },
45
76
  define: {
46
77
  __PANTHEON_VERSION__: JSON.stringify(pkg.version),
@@ -55,6 +86,7 @@ export default defineConfig({
55
86
  ],
56
87
  deps: {
57
88
  neverBundle: [/^@opencode-ai\//, /^@opencode\//, /^@opentui\//, /^solid-js/],
89
+ alwaysBundle: [/^@profullstack\/hqtui$/],
58
90
  },
59
- onSuccess: ensureDistArtifactsEndWithNewline,
91
+ onSuccess: finalizeDistArtifacts,
60
92
  })
@@ -1 +0,0 @@
1
- {"version":3,"file":"quota-rpc-UL2HuFRJ.js","names":[],"sources":["../src/quota-rpc.ts"],"sourcesContent":["import { Rpc } from '@opencode/plugin/promise/index'\n\n/** Full provider matrix approved for the V2 quota surface. */\nexport const QUOTA_PROVIDER_IDS = [\n 'anthropic',\n 'chutes',\n 'cursor',\n 'github-copilot',\n 'google-agy',\n 'kilo-gateway',\n 'nanogpt',\n 'ollama-cloud',\n 'openai',\n 'opencode-go',\n 'opencode-zen',\n 'openrouter',\n 'synthetic',\n 'xai-supergrok',\n 'gemini-cli',\n 'alibaba-coding-plan',\n 'alibaba-token-plan',\n 'deepseek',\n 'kimi-code-global',\n 'kimi-code-cn',\n 'minimax-plan-global',\n 'minimax-plan-cn',\n 'xiaomi-mimo',\n 'zai-coding-plan',\n 'zhipu-coding-plan',\n] as const\n\nexport type QuotaProviderId = (typeof QUOTA_PROVIDER_IDS)[number]\n\n/** Safe route labels are limited to OpenCode Go and never contain request data. */\nexport type OpenCodeGoRouteKind = 'api_key' | 'console_oauth' | 'none' | 'unsupported'\n\n/** GLM plans may report up to 16 distinct quota windows in one response. */\nexport const MAX_PROVIDER_METRICS = 16\n\nconst metricSchema = {\n oneOf: [\n {\n type: 'object',\n properties: {\n kind: { const: 'provider_quota' },\n used: { type: 'number', minimum: 0 },\n remaining: { type: 'number', minimum: 0 },\n unit: { type: 'string', minLength: 1, maxLength: 16 },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n period: { type: 'string', maxLength: 32 },\n resetsAt: { type: 'number', minimum: 0, maximum: 8_640_000_000_000_000 },\n },\n required: ['kind', 'used', 'remaining', 'unit', 'label'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'balance' },\n amount: { type: 'number', minimum: 0 },\n currency: { type: 'string', enum: ['USD', 'CNY'] },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n status: { type: 'string', enum: ['available', 'unavailable', 'active', 'inactive'] },\n },\n required: ['kind', 'amount', 'currency', 'label'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'estimate' },\n amount: { type: 'number', minimum: 0 },\n unit: { type: 'string', minLength: 1, maxLength: 16 },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n },\n required: ['kind', 'amount', 'unit', 'label'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'key_usage' },\n amount: { type: 'number', minimum: 0 },\n currency: { type: 'string', enum: ['USD', 'CNY'] },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n period: { type: 'string', maxLength: 32 },\n },\n required: ['kind', 'amount', 'currency', 'label'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'session_usage' },\n amount: { type: 'number', minimum: 0 },\n unit: { type: 'string', minLength: 1, maxLength: 16 },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n },\n required: ['kind', 'amount', 'unit', 'label'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'provider_status' },\n status: { type: 'string', enum: ['available', 'unavailable', 'active', 'inactive'] },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n },\n required: ['kind', 'status', 'label'],\n additionalProperties: false,\n },\n ],\n} as const\n\nconst providerStatusSchema = {\n type: 'object',\n properties: {\n provider: { type: 'string', enum: QUOTA_PROVIDER_IDS },\n label: { type: 'string', minLength: 1, maxLength: 48 },\n scope: { type: 'string', enum: ['account', 'selected_key', 'team', 'session'] },\n authentication: { type: 'string', enum: ['connected', 'not_connected', 'unavailable'] },\n state: { type: 'string', enum: ['available', 'needs_setup', 'unavailable'] },\n reason: {\n type: 'string',\n enum: [\n 'none',\n 'not_connected',\n 'unsupported',\n 'private_endpoint',\n 'eligibility_unverified',\n 'runtime_accounting_unavailable',\n 'cli_identity_unavailable',\n 'unsupported_credential_method',\n 'provider_error',\n 'not_subscribed',\n 'rate_limited',\n 'unauthorized',\n 'forbidden',\n 'timeout',\n 'network_error',\n 'invalid_response',\n ],\n },\n route_kind: {\n type: 'string',\n enum: ['api_key', 'console_oauth', 'none', 'unsupported'],\n },\n retry_after_ms: { type: 'integer', minimum: 0, maximum: 3_600_000 },\n metrics: { type: 'array', items: metricSchema, maxItems: MAX_PROVIDER_METRICS },\n },\n required: ['provider', 'label', 'scope', 'authentication', 'state', 'reason', 'metrics'],\n additionalProperties: false,\n} as const\n\n/** Shared definition keeps the TUI RPC client aligned with the server contract. */\nexport const quotaRpc = Rpc.define({\n id: 'pantheon.quota',\n methods: {\n go_key_diagnostic: {\n input: { type: 'object', properties: {}, additionalProperties: false },\n output: {\n type: 'object',\n properties: {\n category: {\n type: 'string',\n enum: [\n 'not_run',\n 'already_used',\n 'success',\n 'unauthorized',\n 'redirect',\n 'http_error',\n 'timeout',\n 'network_error',\n ],\n },\n status: { type: 'integer', minimum: 100, maximum: 599 },\n content_type: {\n type: 'string',\n enum: ['application/json', 'text/plain', 'text/html', 'other', 'missing'],\n },\n error_structure: {\n type: 'string',\n enum: ['present', 'absent', 'unavailable'],\n },\n },\n required: ['category'],\n additionalProperties: false,\n },\n },\n status: {\n input: { type: 'object', properties: {}, additionalProperties: false },\n output: {\n type: 'object',\n properties: {\n providers: { type: 'array', items: providerStatusSchema },\n credential_resolution_failed: { const: true },\n },\n required: ['providers'],\n additionalProperties: false,\n },\n },\n },\n events: {\n credentials_changed: {\n schema: { type: 'object', properties: {}, additionalProperties: false },\n },\n },\n})\n"],"mappings":";;;AAGA,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