pantheon-opencode 1.6.2-beta.9 → 1.6.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.
- package/CHANGELOG.md +101 -0
- package/README.md +34 -60
- package/README.pt-BR.md +10 -12
- package/bin/pantheon-init.mjs +22 -32
- package/package.json +3 -3
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/decision-router.mjs +41 -56
- package/scripts/install/decision-router-config.mjs +67 -1
- package/scripts/install/npx-cache-sweep.mjs +103 -0
- package/scripts/install/opencode.mjs +7 -7
- package/scripts/install/plugin.mjs +4 -3
- package/scripts/install/strings.mjs +4 -0
- package/scripts/release-gates.mjs +6 -82
- package/scripts/sync-tui.mjs +3 -3
- package/src/agents/zeus.md +4 -2
- package/src/pantheon/jev-decision-tool.ts +366 -114
- package/src/pantheon/jev-decisions.ts +11 -13
- package/src/pantheon/jev-escalation.ts +639 -0
- package/src/pantheon/jev-quality-score.ts +432 -0
- package/src/pantheon/jev-risk-gate.ts +479 -0
- package/src/pantheon/local-decision-prompt.ts +12 -18
- package/src/pantheon/v2-decision-telemetry.ts +14 -4
- package/src/pantheon/v2-native-decisions.ts +1 -1
- package/src/plugin-v2.ts +201 -24
- package/src/plugins/tui/dist/server-v2.d.ts +19 -11
- package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/server-v2.js +19 -789
- package/src/plugins/tui/dist/server-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui-v2.d.ts +12 -331
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +257 -5370
- package/src/plugins/tui/dist/tui-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
- package/src/plugins/tui/src/index-v2.tsx +213 -86
- package/src/plugins/tui/src/server-v2.ts +18 -982
- package/src/plugins/tui/tsconfig.typecheck.json +1 -6
- package/src/plugins/tui/tsdown.config.ts +1 -11
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +0 -749
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +0 -1
- package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
- package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
- package/src/plugins/tui/dist/quota-adapters.js +0 -1142
- package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
- package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
- package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
- package/src/plugins/tui/dist/quota-cli.js +0 -184
- package/src/plugins/tui/dist/quota-cli.js.map +0 -1
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +0 -684
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +0 -1
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +0 -118
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +0 -1
- package/src/plugins/tui/dist/usage-history-worker.js +0 -25
- package/src/plugins/tui/dist/usage-history-worker.js.map +0 -1
- package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
- package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
- package/src/plugins/tui/src/quota-adapters.ts +0 -1598
- package/src/plugins/tui/src/quota-cli.ts +0 -237
- package/src/plugins/tui/src/quota-rpc.ts +0 -373
- package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
- package/src/plugins/tui/src/quota-v2.tsx +0 -1238
- package/src/plugins/tui/src/usage-history-contract.ts +0 -217
- package/src/plugins/tui/src/usage-history-validation.ts +0 -104
- package/src/plugins/tui/src/usage-history-view.tsx +0 -236
- package/src/plugins/tui/src/usage-history-worker.ts +0 -25
- package/src/plugins/tui/src/usage-view-model.ts +0 -272
|
@@ -1,1032 +0,0 @@
|
|
|
1
|
-
import type { Context } from '@opencode/plugin/tui/context'
|
|
2
|
-
import { MODEL_USAGE_MESSAGE_LIMIT } from './model-usage-limits'
|
|
3
|
-
import { type OpenCodeGoRouteKind, QUOTA_PROVIDER_IDS, quotaRpc } from './quota-rpc'
|
|
4
|
-
|
|
5
|
-
export type QuotaDisplay = 'used' | 'remaining'
|
|
6
|
-
export type QuotaPreferences = { enabled: boolean; display: QuotaDisplay }
|
|
7
|
-
export const DEFAULT_QUOTA_PREFERENCES: QuotaPreferences = { enabled: true, display: 'remaining' }
|
|
8
|
-
|
|
9
|
-
export type QuotaMetric =
|
|
10
|
-
| {
|
|
11
|
-
kind: 'provider_quota'
|
|
12
|
-
used: number
|
|
13
|
-
remaining: number
|
|
14
|
-
unit: string
|
|
15
|
-
label?: string
|
|
16
|
-
period?: string
|
|
17
|
-
resetsAt?: number
|
|
18
|
-
}
|
|
19
|
-
| { kind: 'balance'; amount: number; currency: string; label?: string; status?: string }
|
|
20
|
-
| { kind: 'estimate'; amount: number; unit: string; label?: string }
|
|
21
|
-
| { kind: 'key_usage'; amount: number; currency: string; label?: string; period?: string }
|
|
22
|
-
| { kind: 'session_usage'; amount: number; unit: string; label?: string }
|
|
23
|
-
| {
|
|
24
|
-
kind: 'provider_status'
|
|
25
|
-
status: 'available' | 'unavailable' | 'active' | 'inactive'
|
|
26
|
-
label: string
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export type QuotaProviderView = {
|
|
30
|
-
id: string
|
|
31
|
-
label: string
|
|
32
|
-
quotaState: 'available' | 'unavailable'
|
|
33
|
-
message?: string
|
|
34
|
-
metrics: QuotaMetric[]
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export type QuotaProviderDetail = {
|
|
38
|
-
id: string
|
|
39
|
-
label: string
|
|
40
|
-
authentication: 'connected' | 'not_connected' | 'unavailable'
|
|
41
|
-
state: 'available' | 'needs_setup' | 'unavailable'
|
|
42
|
-
message?: string
|
|
43
|
-
metrics: QuotaMetric[]
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export type QuotaSnapshotStatus =
|
|
47
|
-
| 'loading'
|
|
48
|
-
| 'ready'
|
|
49
|
-
| 'partial'
|
|
50
|
-
| 'connected_unavailable'
|
|
51
|
-
| 'needs_setup'
|
|
52
|
-
| 'unavailable'
|
|
53
|
-
| 'stale'
|
|
54
|
-
| 'disabled'
|
|
55
|
-
|
|
56
|
-
export type QuotaSnapshot = {
|
|
57
|
-
status: QuotaSnapshotStatus
|
|
58
|
-
providers: QuotaProviderView[]
|
|
59
|
-
details: QuotaProviderDetail[]
|
|
60
|
-
updatedAt: number | null
|
|
61
|
-
/** Short diagnostic of the latest transport/RPC failure; absent after a successful refresh. */
|
|
62
|
-
error?: string | undefined
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export const QUOTA_CLOCK_INTERVAL_MS = 60_000
|
|
66
|
-
|
|
67
|
-
export type QuotaClockOptions = {
|
|
68
|
-
now?: () => number
|
|
69
|
-
setInterval?: typeof globalThis.setInterval
|
|
70
|
-
clearInterval?: typeof globalThis.clearInterval
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export type QuotaClock = {
|
|
74
|
-
subscribe: (listener: (now: number) => void) => () => void
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** Create a shared local clock for countdown displays; it never refreshes quota data. */
|
|
78
|
-
export function createQuotaClock(options: QuotaClockOptions = {}): QuotaClock {
|
|
79
|
-
const now = options.now ?? Date.now
|
|
80
|
-
const schedule = options.setInterval ?? globalThis.setInterval
|
|
81
|
-
const cancel = options.clearInterval ?? globalThis.clearInterval
|
|
82
|
-
const listeners = new Set<(now: number) => void>()
|
|
83
|
-
let timer: ReturnType<typeof setInterval> | undefined
|
|
84
|
-
|
|
85
|
-
const notify = (): void => {
|
|
86
|
-
const currentTime = now()
|
|
87
|
-
for (const listener of [...listeners]) listener(currentTime)
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
return {
|
|
91
|
-
subscribe(listener): () => void {
|
|
92
|
-
listeners.add(listener)
|
|
93
|
-
if (timer === undefined) {
|
|
94
|
-
timer = schedule(notify, QUOTA_CLOCK_INTERVAL_MS)
|
|
95
|
-
timer.unref?.()
|
|
96
|
-
}
|
|
97
|
-
listener(now())
|
|
98
|
-
|
|
99
|
-
let subscribed = true
|
|
100
|
-
return () => {
|
|
101
|
-
if (!subscribed) return
|
|
102
|
-
subscribed = false
|
|
103
|
-
listeners.delete(listener)
|
|
104
|
-
if (listeners.size === 0 && timer !== undefined) {
|
|
105
|
-
cancel(timer)
|
|
106
|
-
timer = undefined
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
},
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** Module-local clock shared by all countdown consumers in the TUI bundle. */
|
|
114
|
-
export const quotaClock = createQuotaClock()
|
|
115
|
-
|
|
116
|
-
/** Format a provider-reported reset timestamp using the caller's local clock. */
|
|
117
|
-
export function formatQuotaCountdown(
|
|
118
|
-
resetsAt: number | undefined,
|
|
119
|
-
now: number,
|
|
120
|
-
): string | null | undefined {
|
|
121
|
-
if (resetsAt === undefined || !Number.isFinite(resetsAt) || !Number.isFinite(now)) {
|
|
122
|
-
return undefined
|
|
123
|
-
}
|
|
124
|
-
const remainingMs = resetsAt - now
|
|
125
|
-
if (remainingMs <= 0) return null
|
|
126
|
-
if (remainingMs < 60_000) return '<1m'
|
|
127
|
-
|
|
128
|
-
const remainingMinutes = Math.ceil(remainingMs / 60_000)
|
|
129
|
-
const days = Math.floor(remainingMinutes / (24 * 60))
|
|
130
|
-
if (days > 0) {
|
|
131
|
-
const hours = Math.floor((remainingMinutes % (24 * 60)) / 60)
|
|
132
|
-
return hours > 0 ? `${days}d ${hours}h` : `${days}d`
|
|
133
|
-
}
|
|
134
|
-
const hours = Math.floor(remainingMinutes / 60)
|
|
135
|
-
if (hours > 0) {
|
|
136
|
-
const minutes = remainingMinutes % 60
|
|
137
|
-
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`
|
|
138
|
-
}
|
|
139
|
-
return `${remainingMinutes}m`
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export type QuotaSidebarEntry =
|
|
143
|
-
| {
|
|
144
|
-
kind: 'quota'
|
|
145
|
-
key: string
|
|
146
|
-
providerID: string
|
|
147
|
-
providerLabel: string
|
|
148
|
-
metric: Extract<QuotaMetric, { kind: 'provider_quota' }>
|
|
149
|
-
progress: { usedPercent: number; remainingPercent: number }
|
|
150
|
-
}
|
|
151
|
-
| {
|
|
152
|
-
kind: 'status'
|
|
153
|
-
key: string
|
|
154
|
-
providerID: string
|
|
155
|
-
providerLabel: string
|
|
156
|
-
message: string
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export type ModelContextSnapshot = { tokens: number; percent: number; limit: number }
|
|
160
|
-
export type RecentModelUsageRow = {
|
|
161
|
-
providerID: string | null
|
|
162
|
-
modelID: string | null
|
|
163
|
-
label: string
|
|
164
|
-
tokens: number | null
|
|
165
|
-
cost: number | null
|
|
166
|
-
context: ModelContextSnapshot | null
|
|
167
|
-
active: boolean
|
|
168
|
-
}
|
|
169
|
-
export type CollectRecentModelUsageInput = {
|
|
170
|
-
activeModel: unknown
|
|
171
|
-
activeMessages: readonly unknown[]
|
|
172
|
-
usageMessages: readonly unknown[]
|
|
173
|
-
usageSessions?: readonly { messages: readonly unknown[]; revertMessageID?: string | null }[]
|
|
174
|
-
models: readonly unknown[]
|
|
175
|
-
revertMessageID?: string | null
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
const SETTINGS_KEY = 'pantheon.quota.preferences.v1'
|
|
179
|
-
const SNAPSHOT_KEY = 'pantheon.quota.live.v1'
|
|
180
|
-
const REFRESH_INTERVAL_MS = 60_000
|
|
181
|
-
const QUOTA_PROVIDER_ID_SET: ReadonlySet<string> = new Set(QUOTA_PROVIDER_IDS)
|
|
182
|
-
|
|
183
|
-
const INITIAL_SNAPSHOT: QuotaSnapshot = {
|
|
184
|
-
status: 'loading',
|
|
185
|
-
providers: [],
|
|
186
|
-
details: [],
|
|
187
|
-
updatedAt: null,
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
191
|
-
return typeof value === 'object' && value !== null
|
|
192
|
-
? (value as Record<string, unknown>)
|
|
193
|
-
: undefined
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function modelID(ref: unknown): string | null {
|
|
197
|
-
const record = asRecord(ref)
|
|
198
|
-
const id = typeof ref === 'string' ? ref : (record?.id ?? record?.modelID)
|
|
199
|
-
return typeof id === 'string' && id.trim() !== '' ? id : null
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function messageModelRef(message: Record<string, unknown>): unknown {
|
|
203
|
-
return message.model ?? message
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
function modelProvider(ref: unknown, models: readonly unknown[]): string | null {
|
|
207
|
-
const direct = asRecord(ref)?.providerID
|
|
208
|
-
if (typeof direct === 'string' && direct.trim() !== '') return direct.trim()
|
|
209
|
-
const id = modelID(ref)
|
|
210
|
-
if (id === null) return null
|
|
211
|
-
const segment = id.slice(id.lastIndexOf('/') + 1)
|
|
212
|
-
const providers = new Set<string>()
|
|
213
|
-
for (const candidate of models) {
|
|
214
|
-
const item = asRecord(candidate)
|
|
215
|
-
if (!item) continue
|
|
216
|
-
if (item.id !== id && item.modelID !== id && item.id !== segment && item.modelID !== segment)
|
|
217
|
-
continue
|
|
218
|
-
if (typeof item.providerID === 'string' && item.providerID.trim() !== '') {
|
|
219
|
-
providers.add(item.providerID.trim())
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
const explicitProvider = id.includes('/') ? id.slice(0, id.indexOf('/')) : null
|
|
223
|
-
if (explicitProvider && providers.has(explicitProvider)) return explicitProvider
|
|
224
|
-
return providers.size === 1 ? ([...providers][0] ?? null) : null
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
function modelIdentity(
|
|
228
|
-
ref: unknown,
|
|
229
|
-
models: readonly unknown[],
|
|
230
|
-
): {
|
|
231
|
-
key: string
|
|
232
|
-
id: string
|
|
233
|
-
providerID: string | null
|
|
234
|
-
label: string
|
|
235
|
-
} | null {
|
|
236
|
-
const id = modelID(ref)
|
|
237
|
-
if (id === null) return null
|
|
238
|
-
const providerID = modelProvider(ref, models)
|
|
239
|
-
const segment = id.slice(id.lastIndexOf('/') + 1)
|
|
240
|
-
return {
|
|
241
|
-
key: `${providerID ?? ''}\u0000${id}`,
|
|
242
|
-
id,
|
|
243
|
-
providerID,
|
|
244
|
-
label: segment || id,
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
function tokenCount(message: Record<string, unknown>): number | null {
|
|
249
|
-
const tokens = asRecord(message.tokens)
|
|
250
|
-
if (!tokens) return null
|
|
251
|
-
const cache = asRecord(tokens.cache)
|
|
252
|
-
const values = [tokens.input, tokens.output, tokens.reasoning, cache?.read, cache?.write]
|
|
253
|
-
const reported = values.filter(
|
|
254
|
-
(value): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0,
|
|
255
|
-
)
|
|
256
|
-
return reported.length === 0 ? null : reported.reduce((sum, value) => sum + value, 0)
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function validCost(message: Record<string, unknown>): number | null {
|
|
260
|
-
const cost = message.cost
|
|
261
|
-
return typeof cost === 'number' && Number.isFinite(cost) && cost >= 0 ? cost : null
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
function contextLimit(ref: unknown, models: readonly unknown[]): number | null {
|
|
265
|
-
const id = modelID(ref)
|
|
266
|
-
if (id === null) return null
|
|
267
|
-
const providerID = modelProvider(ref, models)
|
|
268
|
-
if (providerID === null) return null
|
|
269
|
-
const segment = id.slice(id.lastIndexOf('/') + 1)
|
|
270
|
-
const matches = models.filter((value) => {
|
|
271
|
-
const model = asRecord(value)
|
|
272
|
-
if (!model) return false
|
|
273
|
-
const idMatches =
|
|
274
|
-
model.id === id || model.modelID === id || model.id === segment || model.modelID === segment
|
|
275
|
-
return idMatches && model.providerID === providerID
|
|
276
|
-
})
|
|
277
|
-
const limits = new Set<number>()
|
|
278
|
-
for (const candidate of matches) {
|
|
279
|
-
const limit = asRecord(asRecord(candidate)?.limit)?.context
|
|
280
|
-
if (typeof limit === 'number' && Number.isFinite(limit) && limit > 0) limits.add(limit)
|
|
281
|
-
}
|
|
282
|
-
return limits.size === 1 ? ([...limits][0] ?? null) : null
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
function liveTranscriptWindow(
|
|
286
|
-
messages: readonly unknown[],
|
|
287
|
-
revertMessageID: string | null | undefined,
|
|
288
|
-
): { start: number; end: number } {
|
|
289
|
-
let end = messages.length
|
|
290
|
-
if (revertMessageID) {
|
|
291
|
-
const boundary = messages.findIndex((message) => asRecord(message)?.id === revertMessageID)
|
|
292
|
-
if (boundary >= 0) end = boundary
|
|
293
|
-
}
|
|
294
|
-
let start = 0
|
|
295
|
-
for (let index = end - 1; index >= 0; index -= 1) {
|
|
296
|
-
if (asRecord(messages[index])?.type === 'compaction') {
|
|
297
|
-
start = index + 1
|
|
298
|
-
break
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
return { start, end }
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function latestContext(
|
|
305
|
-
messages: readonly unknown[],
|
|
306
|
-
modelRef: unknown,
|
|
307
|
-
models: readonly unknown[],
|
|
308
|
-
revertMessageID?: string | null,
|
|
309
|
-
): ModelContextSnapshot | null {
|
|
310
|
-
const target = modelIdentity(modelRef, models)
|
|
311
|
-
if (target === null || target.providerID === null) return null
|
|
312
|
-
const limit = contextLimit(modelRef, models)
|
|
313
|
-
if (limit === null || limit <= 0) return null
|
|
314
|
-
const { start, end } = liveTranscriptWindow(messages, revertMessageID)
|
|
315
|
-
for (let index = end - 1; index >= start; index -= 1) {
|
|
316
|
-
const message = asRecord(messages[index])
|
|
317
|
-
if (message?.type !== 'assistant') continue
|
|
318
|
-
const identity = modelIdentity(messageModelRef(message), models)
|
|
319
|
-
if (identity?.id !== target.id || identity.providerID !== target.providerID) continue
|
|
320
|
-
const tokens = tokenCount(message)
|
|
321
|
-
if (tokens === null || tokens <= 0) continue
|
|
322
|
-
return { tokens, percent: Math.round((tokens / limit) * 100), limit }
|
|
323
|
-
}
|
|
324
|
-
return null
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/** Snapshot for one exact model identity in the bounded active transcript. */
|
|
328
|
-
export function resolveModelContextSnapshot(
|
|
329
|
-
messages: readonly unknown[],
|
|
330
|
-
modelRef: unknown,
|
|
331
|
-
models: readonly unknown[],
|
|
332
|
-
revertMessageID?: string | null,
|
|
333
|
-
): ModelContextSnapshot | null {
|
|
334
|
-
return latestContext(
|
|
335
|
-
messages.slice(-MODEL_USAGE_MESSAGE_LIMIT),
|
|
336
|
-
modelRef,
|
|
337
|
-
models,
|
|
338
|
-
revertMessageID,
|
|
339
|
-
)
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
/** Select the pinned chat model before transcript or configured-agent fallbacks. */
|
|
343
|
-
export function resolveActiveModelRef(
|
|
344
|
-
sessionModel: unknown,
|
|
345
|
-
activeMessages: readonly unknown[],
|
|
346
|
-
fallbackModel: unknown = null,
|
|
347
|
-
): unknown {
|
|
348
|
-
if (modelID(sessionModel) !== null) return sessionModel
|
|
349
|
-
|
|
350
|
-
const firstMessage = Math.max(0, activeMessages.length - MODEL_USAGE_MESSAGE_LIMIT)
|
|
351
|
-
for (let index = activeMessages.length - 1; index >= firstMessage; index -= 1) {
|
|
352
|
-
const message = asRecord(activeMessages[index])
|
|
353
|
-
if (message?.type !== 'assistant') continue
|
|
354
|
-
const ref = messageModelRef(message)
|
|
355
|
-
if (modelID(ref) !== null) return ref
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
return modelID(fallbackModel) === null ? null : fallbackModel
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
/** Pin the active chat first, then rank two distinct models by summed reported
|
|
362
|
-
* tokens from the already-cached, bounded session-family messages. */
|
|
363
|
-
export function collectRecentModelUsageRows(
|
|
364
|
-
input: CollectRecentModelUsageInput,
|
|
365
|
-
): RecentModelUsageRow[] {
|
|
366
|
-
const models = Array.isArray(input.models) ? input.models : []
|
|
367
|
-
const activeMessages = input.activeMessages.slice(-MODEL_USAGE_MESSAGE_LIMIT)
|
|
368
|
-
const contextSessions = input.usageSessions
|
|
369
|
-
? input.usageSessions.map((session) => ({
|
|
370
|
-
...session,
|
|
371
|
-
messages: session.messages.slice(-MODEL_USAGE_MESSAGE_LIMIT),
|
|
372
|
-
}))
|
|
373
|
-
: [{ messages: input.usageMessages.slice(-MODEL_USAGE_MESSAGE_LIMIT), revertMessageID: null }]
|
|
374
|
-
const usageMessages = contextSessions.flatMap((session) => session.messages)
|
|
375
|
-
const active = modelIdentity(input.activeModel, models)
|
|
376
|
-
const totals = new Map<
|
|
377
|
-
string,
|
|
378
|
-
{
|
|
379
|
-
identity: NonNullable<ReturnType<typeof modelIdentity>>
|
|
380
|
-
tokens: number | null
|
|
381
|
-
cost: number | null
|
|
382
|
-
}
|
|
383
|
-
>()
|
|
384
|
-
|
|
385
|
-
for (const value of usageMessages) {
|
|
386
|
-
const message = asRecord(value)
|
|
387
|
-
if (message?.type !== 'assistant') continue
|
|
388
|
-
const identity = modelIdentity(messageModelRef(message), models)
|
|
389
|
-
if (!identity) continue
|
|
390
|
-
const current = totals.get(identity.key) ?? {
|
|
391
|
-
identity,
|
|
392
|
-
tokens: null,
|
|
393
|
-
cost: null,
|
|
394
|
-
}
|
|
395
|
-
const tokens = tokenCount(message)
|
|
396
|
-
const cost = validCost(message)
|
|
397
|
-
if (tokens !== null) current.tokens = (current.tokens ?? 0) + tokens
|
|
398
|
-
if (cost !== null) current.cost = (current.cost ?? 0) + cost
|
|
399
|
-
totals.set(identity.key, current)
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
const latestContextMessages = new Map<
|
|
403
|
-
string,
|
|
404
|
-
{ message: Record<string, unknown>; timestamp: number | null; index: number }
|
|
405
|
-
>()
|
|
406
|
-
let contextIndex = 0
|
|
407
|
-
for (const session of contextSessions) {
|
|
408
|
-
const messages = session.messages
|
|
409
|
-
const { start, end } = liveTranscriptWindow(messages, session.revertMessageID)
|
|
410
|
-
for (let index = start; index < end; index += 1) {
|
|
411
|
-
const order = contextIndex
|
|
412
|
-
contextIndex += 1
|
|
413
|
-
const message = asRecord(messages[index])
|
|
414
|
-
if (message?.type !== 'assistant' || (tokenCount(message) ?? 0) <= 0) continue
|
|
415
|
-
const identity = modelIdentity(messageModelRef(message), models)
|
|
416
|
-
if (!identity) continue
|
|
417
|
-
const time = asRecord(message.time)
|
|
418
|
-
const timestamp =
|
|
419
|
-
typeof time?.created === 'number' && Number.isFinite(time.created) ? time.created : null
|
|
420
|
-
const current = latestContextMessages.get(identity.key)
|
|
421
|
-
if (
|
|
422
|
-
current === undefined ||
|
|
423
|
-
(timestamp !== null && current.timestamp !== null
|
|
424
|
-
? timestamp >= current.timestamp
|
|
425
|
-
: order > current.index)
|
|
426
|
-
) {
|
|
427
|
-
latestContextMessages.set(identity.key, { message, timestamp, index: order })
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
const activeUsage = active === null ? undefined : totals.get(active.key)
|
|
433
|
-
const activeRow: RecentModelUsageRow = {
|
|
434
|
-
providerID: active?.providerID ?? null,
|
|
435
|
-
modelID: active?.id ?? null,
|
|
436
|
-
label: active?.label ?? 'Modelo atual',
|
|
437
|
-
tokens: activeUsage?.tokens ?? null,
|
|
438
|
-
cost: activeUsage?.cost ?? null,
|
|
439
|
-
context:
|
|
440
|
-
active === null
|
|
441
|
-
? null
|
|
442
|
-
: resolveModelContextSnapshot(
|
|
443
|
-
activeMessages,
|
|
444
|
-
input.activeModel,
|
|
445
|
-
models,
|
|
446
|
-
input.revertMessageID,
|
|
447
|
-
),
|
|
448
|
-
active: true,
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const ranked = [...totals.values()]
|
|
452
|
-
.filter((entry) => entry.tokens !== null)
|
|
453
|
-
.filter((entry) => {
|
|
454
|
-
if (!active) return true
|
|
455
|
-
return !(
|
|
456
|
-
entry.identity.id === active.id &&
|
|
457
|
-
(entry.identity.providerID === null ||
|
|
458
|
-
active.providerID === null ||
|
|
459
|
-
entry.identity.providerID === active.providerID)
|
|
460
|
-
)
|
|
461
|
-
})
|
|
462
|
-
.sort(
|
|
463
|
-
(left, right) =>
|
|
464
|
-
(right.tokens ?? 0) - (left.tokens ?? 0) ||
|
|
465
|
-
left.identity.label.localeCompare(right.identity.label) ||
|
|
466
|
-
(left.identity.providerID ?? '').localeCompare(right.identity.providerID ?? ''),
|
|
467
|
-
)
|
|
468
|
-
.slice(0, 2)
|
|
469
|
-
.map((entry): RecentModelUsageRow => {
|
|
470
|
-
const latest = latestContextMessages.get(entry.identity.key)?.message
|
|
471
|
-
const modelRef = latest === undefined ? undefined : messageModelRef(latest)
|
|
472
|
-
const context = latest === undefined ? null : latestContext([latest], modelRef, models)
|
|
473
|
-
return {
|
|
474
|
-
providerID: entry.identity.providerID,
|
|
475
|
-
modelID: entry.identity.id,
|
|
476
|
-
label: entry.identity.label,
|
|
477
|
-
tokens: entry.tokens,
|
|
478
|
-
cost: entry.cost,
|
|
479
|
-
context,
|
|
480
|
-
active: false,
|
|
481
|
-
}
|
|
482
|
-
})
|
|
483
|
-
|
|
484
|
-
return [activeRow, ...ranked]
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
export function normalizeQuotaPreferences(value: unknown): QuotaPreferences {
|
|
488
|
-
const settings = asRecord(value)
|
|
489
|
-
return {
|
|
490
|
-
enabled:
|
|
491
|
-
typeof settings?.enabled === 'boolean' ? settings.enabled : DEFAULT_QUOTA_PREFERENCES.enabled,
|
|
492
|
-
display: settings?.display === 'used' ? 'used' : 'remaining',
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
function providerLabel(id: string): string {
|
|
497
|
-
return id
|
|
498
|
-
.split(/[._-]+/)
|
|
499
|
-
.filter((part) => part.length > 0)
|
|
500
|
-
.map((part) => `${part.charAt(0).toLocaleUpperCase()}${part.slice(1)}`)
|
|
501
|
-
.join(' ')
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
type ProviderStatusRecord = {
|
|
505
|
-
provider: string
|
|
506
|
-
label: string
|
|
507
|
-
scope: 'account' | 'selected_key' | 'team' | 'session'
|
|
508
|
-
authentication: 'connected' | 'not_connected' | 'unavailable'
|
|
509
|
-
state: 'available' | 'needs_setup' | 'unavailable'
|
|
510
|
-
reason: string
|
|
511
|
-
route_kind?: OpenCodeGoRouteKind
|
|
512
|
-
metrics: QuotaMetric[]
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
function providerStatus(value: unknown): ProviderStatusRecord | undefined {
|
|
516
|
-
const item = asRecord(value)
|
|
517
|
-
if (
|
|
518
|
-
typeof item?.provider !== 'string' ||
|
|
519
|
-
typeof item.label !== 'string' ||
|
|
520
|
-
(item.scope !== 'account' &&
|
|
521
|
-
item.scope !== 'selected_key' &&
|
|
522
|
-
item.scope !== 'team' &&
|
|
523
|
-
item.scope !== 'session') ||
|
|
524
|
-
(item.authentication !== 'connected' &&
|
|
525
|
-
item.authentication !== 'not_connected' &&
|
|
526
|
-
item.authentication !== 'unavailable') ||
|
|
527
|
-
(item.state !== 'available' && item.state !== 'needs_setup' && item.state !== 'unavailable') ||
|
|
528
|
-
typeof item.reason !== 'string' ||
|
|
529
|
-
(item.route_kind !== undefined &&
|
|
530
|
-
item.route_kind !== 'api_key' &&
|
|
531
|
-
item.route_kind !== 'console_oauth' &&
|
|
532
|
-
item.route_kind !== 'none' &&
|
|
533
|
-
item.route_kind !== 'unsupported') ||
|
|
534
|
-
!Array.isArray(item.metrics)
|
|
535
|
-
) {
|
|
536
|
-
return undefined
|
|
537
|
-
}
|
|
538
|
-
if (!QUOTA_PROVIDER_ID_SET.has(item.provider)) return undefined
|
|
539
|
-
return {
|
|
540
|
-
provider: item.provider,
|
|
541
|
-
label: item.label,
|
|
542
|
-
scope: item.scope,
|
|
543
|
-
authentication: item.authentication,
|
|
544
|
-
state: item.state,
|
|
545
|
-
reason: item.reason,
|
|
546
|
-
...(item.route_kind === undefined ? {} : { route_kind: item.route_kind }),
|
|
547
|
-
metrics: item.metrics as QuotaMetric[],
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
function unavailableMessage(reason: string, provider?: string): string | undefined {
|
|
552
|
-
if (provider === 'opencode-go' && reason === 'unauthorized') {
|
|
553
|
-
return 'Pedido recusado; uso indisponível. Verifique o Console oficial.'
|
|
554
|
-
}
|
|
555
|
-
if (provider === 'opencode-go' && reason === 'not_subscribed') {
|
|
556
|
-
return 'sem assinatura OpenCode Go nesta conta'
|
|
557
|
-
}
|
|
558
|
-
switch (reason) {
|
|
559
|
-
case 'not_connected':
|
|
560
|
-
return 'setup necessário'
|
|
561
|
-
case 'unsupported':
|
|
562
|
-
return 'fonte de credencial não suportada'
|
|
563
|
-
case 'private_endpoint':
|
|
564
|
-
return 'endpoint privado não validado'
|
|
565
|
-
case 'eligibility_unverified':
|
|
566
|
-
return 'elegibilidade da conta não comprovada'
|
|
567
|
-
case 'runtime_accounting_unavailable':
|
|
568
|
-
return 'dados de uso do runtime não disponíveis'
|
|
569
|
-
case 'cli_identity_unavailable':
|
|
570
|
-
return 'identidade do CLI não validada'
|
|
571
|
-
case 'unsupported_credential_method':
|
|
572
|
-
return 'método de autenticação não suportado'
|
|
573
|
-
case 'rate_limited':
|
|
574
|
-
return 'limite de consultas; aguarde'
|
|
575
|
-
case 'unauthorized':
|
|
576
|
-
return 'credencial rejeitada; reconecte o provedor'
|
|
577
|
-
case 'forbidden':
|
|
578
|
-
return 'acesso negado pelo provedor'
|
|
579
|
-
case 'timeout':
|
|
580
|
-
return 'tempo limite da consulta'
|
|
581
|
-
case 'network_error':
|
|
582
|
-
return 'falha de rede ao consultar'
|
|
583
|
-
case 'invalid_response':
|
|
584
|
-
return 'resposta inválida do provedor'
|
|
585
|
-
case 'provider_error':
|
|
586
|
-
return 'provedor temporariamente indisponível'
|
|
587
|
-
default:
|
|
588
|
-
return undefined
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
function metricIsAvailable(metric: QuotaMetric): boolean {
|
|
593
|
-
switch (metric.kind) {
|
|
594
|
-
case 'provider_quota':
|
|
595
|
-
return (
|
|
596
|
-
Number.isFinite(metric.used) &&
|
|
597
|
-
Number.isFinite(metric.remaining) &&
|
|
598
|
-
metric.unit.trim().length > 0
|
|
599
|
-
)
|
|
600
|
-
case 'balance':
|
|
601
|
-
case 'key_usage':
|
|
602
|
-
return Number.isFinite(metric.amount) && metric.currency.trim().length > 0
|
|
603
|
-
case 'estimate':
|
|
604
|
-
case 'session_usage':
|
|
605
|
-
return Number.isFinite(metric.amount) && metric.unit.trim().length > 0
|
|
606
|
-
case 'provider_status':
|
|
607
|
-
return metric.status !== 'unavailable'
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
function providerHasAvailableMetrics(provider: ProviderStatusRecord): boolean {
|
|
612
|
-
return provider.state === 'available' && provider.metrics.some(metricIsAvailable)
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
export function quotaSnapshotStatusLabel(
|
|
616
|
-
status: QuotaSnapshotStatus,
|
|
617
|
-
error?: string | undefined,
|
|
618
|
-
): string {
|
|
619
|
-
switch (status) {
|
|
620
|
-
case 'loading':
|
|
621
|
-
return 'Buscando status…'
|
|
622
|
-
case 'ready':
|
|
623
|
-
return 'Quota disponível'
|
|
624
|
-
case 'partial':
|
|
625
|
-
return 'Quota parcialmente disponível'
|
|
626
|
-
case 'connected_unavailable':
|
|
627
|
-
return 'Credencial local · dados indisponíveis'
|
|
628
|
-
case 'needs_setup':
|
|
629
|
-
return 'Nenhum provedor elegível'
|
|
630
|
-
case 'unavailable':
|
|
631
|
-
return error !== undefined ? `Erro: ${error}` : 'Status indisponível'
|
|
632
|
-
case 'stale':
|
|
633
|
-
return 'Dados desatualizados'
|
|
634
|
-
case 'disabled':
|
|
635
|
-
return 'Desativado'
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Short, UI-safe summary of a failed status request. OpenCode rejects plugin RPC calls
|
|
641
|
-
* with a plain `{ type, message }` object (not an `Error`), so both shapes are handled;
|
|
642
|
-
* `rpc.unavailable` means no server side registered the quota RPC in this run — the
|
|
643
|
-
* historical "Status indisponível" blind spot.
|
|
644
|
-
*/
|
|
645
|
-
export function quotaRpcFaultMessage(error: unknown): string {
|
|
646
|
-
const message =
|
|
647
|
-
error instanceof Error
|
|
648
|
-
? error.message
|
|
649
|
-
: typeof error === 'object' && error !== null && 'message' in error
|
|
650
|
-
? String((error as { message: unknown }).message)
|
|
651
|
-
: String(error)
|
|
652
|
-
const type =
|
|
653
|
-
typeof error === 'object' && error !== null ? (error as { type?: unknown }).type : undefined
|
|
654
|
-
const cleaned = message.trim().replace(/^Error:\s*/i, '')
|
|
655
|
-
if (type === 'rpc.unavailable' || cleaned === 'rpc.unavailable') {
|
|
656
|
-
return 'rpc de quota indisponível no servidor'
|
|
657
|
-
}
|
|
658
|
-
if (cleaned.length === 0) return 'erro desconhecido na consulta de quota'
|
|
659
|
-
return cleaned.length > 80 ? `${cleaned.slice(0, 79)}…` : cleaned
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
/** Map the current typed RPC status into a provider-neutral, data-only UI model. */
|
|
663
|
-
export function quotaSnapshotFromStatus(response: unknown, now = Date.now()): QuotaSnapshot {
|
|
664
|
-
const statusResponse = asRecord(response)
|
|
665
|
-
const credentialResolutionFailed = statusResponse?.credential_resolution_failed === true
|
|
666
|
-
const providersValue = statusResponse?.providers
|
|
667
|
-
const providerList = Array.isArray(providersValue) ? providersValue : undefined
|
|
668
|
-
const statuses = providerList
|
|
669
|
-
? providerList
|
|
670
|
-
.map(providerStatus)
|
|
671
|
-
.filter((item): item is ProviderStatusRecord => item !== undefined)
|
|
672
|
-
: []
|
|
673
|
-
const connected = statuses.filter((item) => item.authentication === 'connected')
|
|
674
|
-
const availableConnected = connected.filter(providerHasAvailableMetrics)
|
|
675
|
-
const status: QuotaSnapshotStatus = credentialResolutionFailed
|
|
676
|
-
? connected.length > 0
|
|
677
|
-
? availableConnected.length > 0
|
|
678
|
-
? 'partial'
|
|
679
|
-
: 'connected_unavailable'
|
|
680
|
-
: 'unavailable'
|
|
681
|
-
: connected.length > 0
|
|
682
|
-
? availableConnected.length === connected.length
|
|
683
|
-
? 'ready'
|
|
684
|
-
: availableConnected.length > 0
|
|
685
|
-
? 'partial'
|
|
686
|
-
: 'connected_unavailable'
|
|
687
|
-
: (statuses.length === 0 && providerList?.length !== 0) ||
|
|
688
|
-
statuses.some((item) => item.authentication === 'unavailable')
|
|
689
|
-
? 'unavailable'
|
|
690
|
-
: 'needs_setup'
|
|
691
|
-
|
|
692
|
-
const details = statuses.map((item): QuotaProviderDetail => {
|
|
693
|
-
const hasMetrics = item.authentication === 'connected' && providerHasAvailableMetrics(item)
|
|
694
|
-
const message =
|
|
695
|
-
unavailableMessage(item.reason, item.provider) ??
|
|
696
|
-
(item.authentication === 'connected' && !hasMetrics
|
|
697
|
-
? 'dados de quota indisponíveis'
|
|
698
|
-
: undefined)
|
|
699
|
-
return {
|
|
700
|
-
id: item.provider,
|
|
701
|
-
label: item.label || providerLabel(item.provider),
|
|
702
|
-
authentication: item.authentication,
|
|
703
|
-
state:
|
|
704
|
-
item.authentication === 'not_connected'
|
|
705
|
-
? 'needs_setup'
|
|
706
|
-
: hasMetrics
|
|
707
|
-
? 'available'
|
|
708
|
-
: 'unavailable',
|
|
709
|
-
...(message === undefined ? {} : { message }),
|
|
710
|
-
metrics: item.metrics,
|
|
711
|
-
}
|
|
712
|
-
})
|
|
713
|
-
|
|
714
|
-
return {
|
|
715
|
-
status,
|
|
716
|
-
providers: connected.map((item) => {
|
|
717
|
-
const hasMetrics = providerHasAvailableMetrics(item)
|
|
718
|
-
const message =
|
|
719
|
-
unavailableMessage(item.reason, item.provider) ??
|
|
720
|
-
(!hasMetrics ? 'dados de quota indisponíveis' : undefined)
|
|
721
|
-
return {
|
|
722
|
-
id: item.provider,
|
|
723
|
-
label: item.label || providerLabel(item.provider),
|
|
724
|
-
quotaState: hasMetrics ? 'available' : 'unavailable',
|
|
725
|
-
...(message === undefined ? {} : { message }),
|
|
726
|
-
metrics: item.metrics,
|
|
727
|
-
}
|
|
728
|
-
}),
|
|
729
|
-
details,
|
|
730
|
-
// A flagged credential-resolution failure is the server's diagnosed cause of an
|
|
731
|
-
// aggregated unavailable status; surface it instead of a blind "Status indisponível".
|
|
732
|
-
...(status === 'unavailable' && credentialResolutionFailed
|
|
733
|
-
? { error: 'resolução de credenciais falhou no servidor' }
|
|
734
|
-
: {}),
|
|
735
|
-
updatedAt: now,
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
function numeric(value: number): string | undefined {
|
|
740
|
-
if (!Number.isFinite(value)) return undefined
|
|
741
|
-
return new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(value)
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
function amount(value: number, unit: string): string | undefined {
|
|
745
|
-
const formatted = numeric(value)
|
|
746
|
-
const safeUnit = unit.trim()
|
|
747
|
-
return formatted && safeUnit ? `${formatted} ${safeUnit}` : undefined
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
/** Return complementary whole percentages only when both quota values define a real range. */
|
|
751
|
-
export function quotaProgress(
|
|
752
|
-
metric: Extract<QuotaMetric, { kind: 'provider_quota' }>,
|
|
753
|
-
): { usedPercent: number; remainingPercent: number } | undefined {
|
|
754
|
-
if (
|
|
755
|
-
!Number.isFinite(metric.used) ||
|
|
756
|
-
!Number.isFinite(metric.remaining) ||
|
|
757
|
-
metric.used < 0 ||
|
|
758
|
-
metric.remaining < 0
|
|
759
|
-
) {
|
|
760
|
-
return undefined
|
|
761
|
-
}
|
|
762
|
-
const total = metric.used + metric.remaining
|
|
763
|
-
if (!Number.isFinite(total) || total <= 0) return undefined
|
|
764
|
-
const usedPercent = Math.round((metric.used / total) * 100)
|
|
765
|
-
return { usedPercent, remainingPercent: 100 - usedPercent }
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
/** Connected-provider rows for the compact sidebar; only reported quota windows are shown. */
|
|
769
|
-
export function quotaSidebarEntries(snapshot: QuotaSnapshot): QuotaSidebarEntry[] {
|
|
770
|
-
const entries: QuotaSidebarEntry[] = []
|
|
771
|
-
for (const provider of snapshot.providers) {
|
|
772
|
-
let quotaCount = 0
|
|
773
|
-
let hasQuotaMetric = false
|
|
774
|
-
provider.metrics.forEach((metric, index) => {
|
|
775
|
-
if (metric.kind !== 'provider_quota') return
|
|
776
|
-
hasQuotaMetric = true
|
|
777
|
-
if (metric.unit.trim() === '') return
|
|
778
|
-
const progress = quotaProgress(metric)
|
|
779
|
-
if (!progress) return
|
|
780
|
-
quotaCount += 1
|
|
781
|
-
entries.push({
|
|
782
|
-
kind: 'quota',
|
|
783
|
-
key: `${provider.id}:quota:${index}`,
|
|
784
|
-
providerID: provider.id,
|
|
785
|
-
providerLabel: provider.label,
|
|
786
|
-
metric,
|
|
787
|
-
progress,
|
|
788
|
-
})
|
|
789
|
-
})
|
|
790
|
-
if (quotaCount === 0 && (provider.quotaState === 'unavailable' || hasQuotaMetric)) {
|
|
791
|
-
entries.push({
|
|
792
|
-
kind: 'status',
|
|
793
|
-
key: `${provider.id}:status`,
|
|
794
|
-
providerID: provider.id,
|
|
795
|
-
providerLabel: provider.label,
|
|
796
|
-
message: provider.message ?? 'dados de quota indisponíveis',
|
|
797
|
-
})
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
return entries
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
/** Render each measurement with its source/category label; no category is inferred. */
|
|
804
|
-
export function formatQuotaMetric(metric: QuotaMetric, display: QuotaDisplay): string | undefined {
|
|
805
|
-
switch (metric.kind) {
|
|
806
|
-
case 'provider_quota': {
|
|
807
|
-
const used = amount(metric.used, metric.unit)
|
|
808
|
-
const remaining = amount(metric.remaining, metric.unit)
|
|
809
|
-
if (!used || !remaining) return undefined
|
|
810
|
-
const label = metric.label ?? 'Quota do provedor'
|
|
811
|
-
const period = metric.period ? ` · ${metric.period}` : ''
|
|
812
|
-
return display === 'remaining'
|
|
813
|
-
? `${label} · restante ${remaining} · usado ${used}${period}`
|
|
814
|
-
: `${label} · usado ${used} · restante ${remaining}${period}`
|
|
815
|
-
}
|
|
816
|
-
case 'balance': {
|
|
817
|
-
const balance = amount(metric.amount, metric.currency)
|
|
818
|
-
if (!balance) return undefined
|
|
819
|
-
const status = metric.status?.trim()
|
|
820
|
-
return `${metric.label ?? 'Saldo'} · ${balance}${status ? ` · ${status}` : ''}`
|
|
821
|
-
}
|
|
822
|
-
case 'estimate': {
|
|
823
|
-
const estimate = amount(metric.amount, metric.unit)
|
|
824
|
-
return estimate ? `${metric.label ?? 'Estimativa'} · ${estimate}` : undefined
|
|
825
|
-
}
|
|
826
|
-
case 'key_usage': {
|
|
827
|
-
const usage = amount(metric.amount, metric.currency)
|
|
828
|
-
const period = metric.period ? ` · ${metric.period}` : ''
|
|
829
|
-
return usage ? `${metric.label ?? 'Uso da chave'} · ${usage}${period}` : undefined
|
|
830
|
-
}
|
|
831
|
-
case 'provider_status':
|
|
832
|
-
return `${metric.label} · ${metric.status}`
|
|
833
|
-
case 'session_usage': {
|
|
834
|
-
const usage = amount(metric.amount, metric.unit)
|
|
835
|
-
return usage ? `${metric.label ?? 'Uso da sessão'} · ${usage}` : undefined
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
/** Compact one-value summary for the footer; quota display follows the setting. */
|
|
841
|
-
export function compactQuotaMetric(metric: QuotaMetric, display: QuotaDisplay): string | undefined {
|
|
842
|
-
switch (metric.kind) {
|
|
843
|
-
case 'provider_quota': {
|
|
844
|
-
const value = display === 'remaining' ? metric.remaining : metric.used
|
|
845
|
-
const formatted = amount(value, metric.unit)
|
|
846
|
-
return formatted
|
|
847
|
-
? `${metric.label ?? (display === 'remaining' ? 'restante' : 'usado')} ${formatted}`
|
|
848
|
-
: undefined
|
|
849
|
-
}
|
|
850
|
-
case 'balance': {
|
|
851
|
-
const formatted = amount(metric.amount, metric.currency)
|
|
852
|
-
return formatted ? `${metric.label ?? 'saldo'} ${formatted}` : undefined
|
|
853
|
-
}
|
|
854
|
-
case 'estimate': {
|
|
855
|
-
const formatted = amount(metric.amount, metric.unit)
|
|
856
|
-
return formatted ? `${metric.label ?? 'estimativa'} ${formatted}` : undefined
|
|
857
|
-
}
|
|
858
|
-
case 'key_usage': {
|
|
859
|
-
const formatted = amount(metric.amount, metric.currency)
|
|
860
|
-
return formatted ? `${metric.label ?? 'uso da chave'} ${formatted}` : undefined
|
|
861
|
-
}
|
|
862
|
-
case 'provider_status':
|
|
863
|
-
return `${metric.label} ${metric.status}`
|
|
864
|
-
case 'session_usage': {
|
|
865
|
-
const formatted = amount(metric.amount, metric.unit)
|
|
866
|
-
return formatted ? `${metric.label ?? 'sessão'} ${formatted}` : undefined
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
export type QuotaRuntime = {
|
|
872
|
-
preferences: () => QuotaPreferences
|
|
873
|
-
snapshot: () => QuotaSnapshot
|
|
874
|
-
toggleEnabled: () => Promise<void>
|
|
875
|
-
toggleDisplay: () => Promise<void>
|
|
876
|
-
refresh: () => Promise<void>
|
|
877
|
-
dispose: () => void
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
/** One storage-backed source of truth for all quota TUI surfaces. */
|
|
881
|
-
export function createQuotaRuntime(
|
|
882
|
-
context: Pick<Context, 'client' | 'data' | 'location' | 'storage'>,
|
|
883
|
-
): QuotaRuntime {
|
|
884
|
-
const [settings, persistSettings] = context.storage.store<QuotaPreferences>(SETTINGS_KEY, {
|
|
885
|
-
initial: { ...DEFAULT_QUOTA_PREFERENCES },
|
|
886
|
-
})
|
|
887
|
-
const [snapshot, setSnapshot] = context.storage.memory<QuotaSnapshot>(SNAPSHOT_KEY, {
|
|
888
|
-
initial: { ...INITIAL_SNAPSHOT, providers: [] },
|
|
889
|
-
})
|
|
890
|
-
const client = context.client.rpc(quotaRpc)
|
|
891
|
-
let unsubscribeCredentialChanges: (() => void) | undefined
|
|
892
|
-
let requestController: AbortController | undefined
|
|
893
|
-
let refreshTimer: ReturnType<typeof setTimeout> | undefined
|
|
894
|
-
let requestVersion = 0
|
|
895
|
-
let disposed = false
|
|
896
|
-
|
|
897
|
-
const preferences = (): QuotaPreferences =>
|
|
898
|
-
normalizeQuotaPreferences({ enabled: settings.enabled, display: settings.display })
|
|
899
|
-
const currentSnapshot = (): QuotaSnapshot => ({
|
|
900
|
-
status: snapshot.status,
|
|
901
|
-
providers: snapshot.providers,
|
|
902
|
-
details: snapshot.details ?? [],
|
|
903
|
-
updatedAt: snapshot.updatedAt,
|
|
904
|
-
error: snapshot.error,
|
|
905
|
-
})
|
|
906
|
-
const updateSnapshot = (next: QuotaSnapshot): void => {
|
|
907
|
-
setSnapshot((draft) => {
|
|
908
|
-
draft.status = next.status
|
|
909
|
-
draft.providers = next.providers
|
|
910
|
-
draft.details = next.details
|
|
911
|
-
draft.updatedAt = next.updatedAt
|
|
912
|
-
draft.error = next.error
|
|
913
|
-
})
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
const cancelScheduledRefresh = (): void => {
|
|
917
|
-
if (refreshTimer) clearTimeout(refreshTimer)
|
|
918
|
-
refreshTimer = undefined
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
const scheduleRefresh = (): void => {
|
|
922
|
-
cancelScheduledRefresh()
|
|
923
|
-
if (disposed || !preferences().enabled) return
|
|
924
|
-
refreshTimer = setTimeout(() => {
|
|
925
|
-
void refresh()
|
|
926
|
-
}, REFRESH_INTERVAL_MS)
|
|
927
|
-
refreshTimer.unref?.()
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
const refresh = async (): Promise<void> => {
|
|
931
|
-
if (disposed) return
|
|
932
|
-
if (!preferences().enabled) {
|
|
933
|
-
updateSnapshot({ status: 'disabled', providers: [], details: [], updatedAt: null })
|
|
934
|
-
return
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
requestController?.abort()
|
|
938
|
-
const controller = new AbortController()
|
|
939
|
-
requestController = controller
|
|
940
|
-
const version = ++requestVersion
|
|
941
|
-
const previous = currentSnapshot()
|
|
942
|
-
updateSnapshot({
|
|
943
|
-
...previous,
|
|
944
|
-
status: previous.updatedAt === null ? 'loading' : 'stale',
|
|
945
|
-
})
|
|
946
|
-
|
|
947
|
-
try {
|
|
948
|
-
const response = await client.status(
|
|
949
|
-
{},
|
|
950
|
-
{
|
|
951
|
-
signal: controller.signal,
|
|
952
|
-
location: context.location ?? context.data.location.default(),
|
|
953
|
-
},
|
|
954
|
-
)
|
|
955
|
-
if (!disposed && version === requestVersion) {
|
|
956
|
-
updateSnapshot(quotaSnapshotFromStatus(response))
|
|
957
|
-
}
|
|
958
|
-
} catch (error) {
|
|
959
|
-
if (!disposed && version === requestVersion && !controller.signal.aborted) {
|
|
960
|
-
// A failed refresh keeps the last valid snapshot (providers, details, updatedAt)
|
|
961
|
-
// instead of wiping it, and records the real cause so the UI never shows a blind
|
|
962
|
-
// "Status indisponível". Without prior data the status stays unavailable.
|
|
963
|
-
const fault = quotaRpcFaultMessage(error)
|
|
964
|
-
console.warn(`[pantheon-tui quota] status request failed: ${fault}`)
|
|
965
|
-
updateSnapshot({
|
|
966
|
-
...previous,
|
|
967
|
-
status: previous.updatedAt === null ? 'unavailable' : 'stale',
|
|
968
|
-
error: fault,
|
|
969
|
-
})
|
|
970
|
-
}
|
|
971
|
-
} finally {
|
|
972
|
-
if (requestController === controller) {
|
|
973
|
-
requestController = undefined
|
|
974
|
-
scheduleRefresh()
|
|
975
|
-
}
|
|
976
|
-
}
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
const runtime: QuotaRuntime = {
|
|
980
|
-
preferences,
|
|
981
|
-
snapshot: currentSnapshot,
|
|
982
|
-
async toggleEnabled(): Promise<void> {
|
|
983
|
-
const enabled = !preferences().enabled
|
|
984
|
-
if (!enabled) {
|
|
985
|
-
requestVersion += 1
|
|
986
|
-
requestController?.abort()
|
|
987
|
-
requestController = undefined
|
|
988
|
-
cancelScheduledRefresh()
|
|
989
|
-
}
|
|
990
|
-
await persistSettings((draft) => {
|
|
991
|
-
draft.enabled = enabled
|
|
992
|
-
})
|
|
993
|
-
if (enabled) {
|
|
994
|
-
updateSnapshot({ status: 'loading', providers: [], details: [], updatedAt: null })
|
|
995
|
-
await refresh()
|
|
996
|
-
} else {
|
|
997
|
-
updateSnapshot({ status: 'disabled', providers: [], details: [], updatedAt: null })
|
|
998
|
-
}
|
|
999
|
-
},
|
|
1000
|
-
async toggleDisplay(): Promise<void> {
|
|
1001
|
-
const display = preferences().display === 'remaining' ? 'used' : 'remaining'
|
|
1002
|
-
await persistSettings((draft) => {
|
|
1003
|
-
draft.display = display
|
|
1004
|
-
})
|
|
1005
|
-
},
|
|
1006
|
-
refresh,
|
|
1007
|
-
dispose(): void {
|
|
1008
|
-
disposed = true
|
|
1009
|
-
requestVersion += 1
|
|
1010
|
-
requestController?.abort()
|
|
1011
|
-
requestController = undefined
|
|
1012
|
-
cancelScheduledRefresh()
|
|
1013
|
-
unsubscribeCredentialChanges?.()
|
|
1014
|
-
},
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
unsubscribeCredentialChanges = client.events?.on('credentials_changed', () => {
|
|
1018
|
-
updateSnapshot({ status: 'loading', providers: [], details: [], updatedAt: null })
|
|
1019
|
-
void refresh()
|
|
1020
|
-
})
|
|
1021
|
-
|
|
1022
|
-
if (preferences().enabled) {
|
|
1023
|
-
// `memory()` survives plugin hot reloads. Do not expose quota rows written by
|
|
1024
|
-
// older versions until the current RPC confirms the eligible provider set.
|
|
1025
|
-
updateSnapshot({ status: 'loading', providers: [], details: [], updatedAt: null })
|
|
1026
|
-
void refresh()
|
|
1027
|
-
} else {
|
|
1028
|
-
updateSnapshot({ status: 'disabled', providers: [], details: [], updatedAt: null })
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
return runtime
|
|
1032
|
-
}
|