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.
- package/CHANGELOG.md +13 -0
- package/README.md +23 -14
- package/README.pt-BR.md +12 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/src/pantheon/cost-command.ts +30 -133
- package/src/pantheon/model-pricing.ts +1 -536
- package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -1
- package/src/plugins/tui/dist/quota-adapters.js +1 -1
- package/src/plugins/tui/dist/{quota-rpc-UL2HuFRJ.js → quota-rpc-DMmXBhBe.js} +295 -1
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
- package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/server-v2.js +135 -12
- package/src/plugins/tui/dist/server-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui-v2.d.ts +132 -5
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +3720 -337
- package/src/plugins/tui/dist/tui-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
- package/src/plugins/tui/dist/usage-history-worker.js +25 -0
- package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
- package/src/plugins/tui/package-lock.json +17 -2
- package/src/plugins/tui/package.json +4 -2
- package/src/plugins/tui/src/cost-data.ts +607 -0
- package/src/plugins/tui/src/index-v2.tsx +32 -0
- package/src/plugins/tui/src/model-pricing.ts +536 -0
- package/src/plugins/tui/src/quota-rpc.ts +164 -0
- package/src/plugins/tui/src/quota-v2-model.ts +2 -2
- package/src/plugins/tui/src/quota-v2.tsx +338 -86
- package/src/plugins/tui/src/server-v2.ts +159 -15
- package/src/plugins/tui/src/usage-history-contract.ts +217 -0
- package/src/plugins/tui/src/usage-history-validation.ts +104 -0
- package/src/plugins/tui/src/usage-history-view.tsx +236 -0
- package/src/plugins/tui/src/usage-history-worker.ts +25 -0
- package/src/plugins/tui/src/usage-view-model.ts +272 -0
- package/src/plugins/tui/tsconfig.typecheck.json +6 -1
- package/src/plugins/tui/tsdown.config.ts +36 -4
- package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads'
|
|
1
2
|
import { Plugin } from '@opencode/plugin'
|
|
2
3
|
import type { Context } from '@opencode/plugin/promise/plugin'
|
|
3
4
|
import type { RpcCallContext, RpcRegistration } from '@opencode/plugin/promise/rpc'
|
|
5
|
+
import { estimateActiveContextCost } from './cost-data'
|
|
4
6
|
import { createGoKeyDiagnostic } from './go-key-diagnostic'
|
|
5
7
|
import {
|
|
6
8
|
isOpenAICodexOAuthMethod,
|
|
@@ -17,10 +19,80 @@ import {
|
|
|
17
19
|
type QuotaProviderId,
|
|
18
20
|
quotaRpc,
|
|
19
21
|
} from './quota-rpc'
|
|
22
|
+
import {
|
|
23
|
+
isUsageHistoryPeriod,
|
|
24
|
+
MAX_HISTORY_QUERY_MS,
|
|
25
|
+
type UsageHistoryRpcResult,
|
|
26
|
+
} from './usage-history-contract'
|
|
20
27
|
|
|
21
28
|
const CREDENTIAL_CACHE_TTL_MS = 30_000
|
|
22
29
|
const ADAPTER_CACHE_TTL_MS = 20_000
|
|
23
30
|
|
|
31
|
+
function queryUsageHistoryInWorker(
|
|
32
|
+
period: string,
|
|
33
|
+
signal: AbortSignal,
|
|
34
|
+
): Promise<UsageHistoryRpcResult> {
|
|
35
|
+
if (!isUsageHistoryPeriod(period)) {
|
|
36
|
+
return Promise.resolve({ status: 'unavailable', reason: 'invalid_period' })
|
|
37
|
+
}
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
let settled = false
|
|
40
|
+
let worker: Worker
|
|
41
|
+
try {
|
|
42
|
+
worker = new Worker(new URL('./usage-history-worker.js', import.meta.url), {
|
|
43
|
+
workerData: { period },
|
|
44
|
+
resourceLimits: { maxOldGenerationSizeMb: 64, stackSizeMb: 2 },
|
|
45
|
+
})
|
|
46
|
+
} catch {
|
|
47
|
+
resolve({ status: 'unavailable', reason: 'history_unavailable' })
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
let timer: ReturnType<typeof setTimeout>
|
|
51
|
+
|
|
52
|
+
const onAbort = (): void => {
|
|
53
|
+
if (settled) return
|
|
54
|
+
settled = true
|
|
55
|
+
clearTimeout(timer)
|
|
56
|
+
signal.removeEventListener('abort', onAbort)
|
|
57
|
+
void worker.terminate()
|
|
58
|
+
reject(new DOMException('Usage history request aborted', 'AbortError'))
|
|
59
|
+
}
|
|
60
|
+
const finish = (result: UsageHistoryRpcResult): void => {
|
|
61
|
+
if (settled) return
|
|
62
|
+
settled = true
|
|
63
|
+
clearTimeout(timer)
|
|
64
|
+
signal.removeEventListener('abort', onAbort)
|
|
65
|
+
void worker.terminate()
|
|
66
|
+
resolve(result)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
timer = setTimeout(() => {
|
|
70
|
+
finish({ status: 'unavailable', reason: 'history_timeout' })
|
|
71
|
+
}, MAX_HISTORY_QUERY_MS)
|
|
72
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
73
|
+
worker.once('message', (message: unknown) => {
|
|
74
|
+
if (
|
|
75
|
+
typeof message === 'object' &&
|
|
76
|
+
message !== null &&
|
|
77
|
+
'ok' in message &&
|
|
78
|
+
message.ok === true &&
|
|
79
|
+
'result' in message &&
|
|
80
|
+
typeof message.result === 'object' &&
|
|
81
|
+
message.result !== null
|
|
82
|
+
) {
|
|
83
|
+
finish(message.result as UsageHistoryRpcResult)
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
finish({ status: 'unavailable', reason: 'history_unavailable' })
|
|
87
|
+
})
|
|
88
|
+
worker.once('error', () => finish({ status: 'unavailable', reason: 'history_unavailable' }))
|
|
89
|
+
worker.once('exit', () => {
|
|
90
|
+
if (!settled) finish({ status: 'unavailable', reason: 'history_unavailable' })
|
|
91
|
+
})
|
|
92
|
+
if (signal.aborted) onAbort()
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
24
96
|
type ResolvedCredential = {
|
|
25
97
|
readonly method?: 'oauth' | 'key' | 'unsupported'
|
|
26
98
|
readonly routeKind?: OpenCodeGoRouteKind
|
|
@@ -158,6 +230,39 @@ function routeKindField(
|
|
|
158
230
|
: {}
|
|
159
231
|
}
|
|
160
232
|
|
|
233
|
+
/**
|
|
234
|
+
* OpenCode Go follows the upstream quota plugin's key order: process environment, the
|
|
235
|
+
* effective OpenCode provider settings, then a selected OpenCode API-key connection.
|
|
236
|
+
* Provider settings are read through the host API; Pantheon never parses OpenCode files.
|
|
237
|
+
*/
|
|
238
|
+
async function configuredOpenCodeGoApiKey(context: Context): Promise<string | undefined> {
|
|
239
|
+
const environmentKey = process.env.OPENCODE_API_KEY?.trim()
|
|
240
|
+
if (environmentKey) return environmentKey
|
|
241
|
+
|
|
242
|
+
for (const providerID of ['opencode-go', 'opencode']) {
|
|
243
|
+
let value: unknown
|
|
244
|
+
try {
|
|
245
|
+
value = (await context.provider.get({ providerID })).data.settings?.apiKey
|
|
246
|
+
} catch {
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
if (typeof value !== 'string') continue
|
|
250
|
+
const configured = value.trim()
|
|
251
|
+
if (!configured) continue
|
|
252
|
+
|
|
253
|
+
const environmentTemplate = configured.match(/^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/)
|
|
254
|
+
if (environmentTemplate) {
|
|
255
|
+
if (environmentTemplate[1] !== 'OPENCODE_API_KEY') continue
|
|
256
|
+
const resolved = process.env.OPENCODE_API_KEY?.trim()
|
|
257
|
+
if (resolved) return resolved
|
|
258
|
+
continue
|
|
259
|
+
}
|
|
260
|
+
if (configured.startsWith('{env:')) continue
|
|
261
|
+
return configured
|
|
262
|
+
}
|
|
263
|
+
return undefined
|
|
264
|
+
}
|
|
265
|
+
|
|
161
266
|
/**
|
|
162
267
|
* Resolve only listed, selected credential connections in the closed provider
|
|
163
268
|
* catalog. Only the minimum access-token/key field is retained in memory.
|
|
@@ -212,8 +317,21 @@ function createCredentialResolver(context: Context) {
|
|
|
212
317
|
// Quota visibility is tied to a selected OpenCode credential connection;
|
|
213
318
|
// local CLI identity is outside that credential context.
|
|
214
319
|
if (definition.source === 'local-cli') return {}
|
|
320
|
+
const configuredGoKey =
|
|
321
|
+
provider === 'opencode-go' ? await configuredOpenCodeGoApiKey(context) : undefined
|
|
322
|
+
if (goKeyOnly && configuredGoKey) {
|
|
323
|
+
return { method: 'key', secret: configuredGoKey, routeKind: 'api_key' }
|
|
324
|
+
}
|
|
215
325
|
try {
|
|
216
|
-
|
|
326
|
+
let listedConnections: Map<string, Set<string>>
|
|
327
|
+
try {
|
|
328
|
+
listedConnections = await listCredentialConnections()
|
|
329
|
+
} catch (error) {
|
|
330
|
+
// A configured OpenCode Go key can still be used if integration discovery fails.
|
|
331
|
+
// Without it, retain the normal selected-connection error behavior.
|
|
332
|
+
if (provider !== 'opencode-go' || !configuredGoKey) throw error
|
|
333
|
+
listedConnections = new Map()
|
|
334
|
+
}
|
|
217
335
|
if (provider === 'opencode-go') {
|
|
218
336
|
const activeListed = async (integrationID: string) => {
|
|
219
337
|
const connections = listedConnections.get(integrationID)
|
|
@@ -270,15 +388,17 @@ function createCredentialResolver(context: Context) {
|
|
|
270
388
|
}
|
|
271
389
|
|
|
272
390
|
let activePrimary: Awaited<ReturnType<typeof activeListed>>
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
391
|
+
if (!configuredGoKey) {
|
|
392
|
+
try {
|
|
393
|
+
activePrimary = await activeListed('opencode-go')
|
|
394
|
+
} catch {
|
|
395
|
+
// An API-key lookup failure must not discard an already resolved Console login.
|
|
396
|
+
}
|
|
277
397
|
}
|
|
278
398
|
const unsupportedPrimaryLogin =
|
|
279
|
-
activePrimary !== undefined && activePrimary.method !== 'key'
|
|
280
|
-
let apiKey
|
|
281
|
-
for (const integrationID of ['opencode-go', 'opencode']) {
|
|
399
|
+
!configuredGoKey && activePrimary !== undefined && activePrimary.method !== 'key'
|
|
400
|
+
let apiKey = configuredGoKey
|
|
401
|
+
for (const integrationID of configuredGoKey ? [] : ['opencode-go', 'opencode']) {
|
|
282
402
|
let active: Awaited<ReturnType<typeof activeListed>>
|
|
283
403
|
try {
|
|
284
404
|
active =
|
|
@@ -367,10 +487,9 @@ function createCredentialResolver(context: Context) {
|
|
|
367
487
|
return {}
|
|
368
488
|
}
|
|
369
489
|
return {}
|
|
370
|
-
} catch
|
|
371
|
-
// Host errors may contain
|
|
372
|
-
|
|
373
|
-
console.warn('[pantheon-tui quota] credential resolution failed:', error)
|
|
490
|
+
} catch {
|
|
491
|
+
// Host errors may contain credentials, provider data, or arbitrary thrown metadata.
|
|
492
|
+
console.warn('[pantheon-tui quota] credential resolution failed (exception)')
|
|
374
493
|
throw new Error('Credential resolution failed')
|
|
375
494
|
}
|
|
376
495
|
}
|
|
@@ -437,11 +556,12 @@ function createCredentialResolver(context: Context) {
|
|
|
437
556
|
}
|
|
438
557
|
}
|
|
439
558
|
|
|
440
|
-
function
|
|
559
|
+
function isQuotaSourceInvalidationEvent(type: string): boolean {
|
|
441
560
|
return (
|
|
442
561
|
type === 'credential.updated' ||
|
|
443
562
|
type === 'credential.switched' ||
|
|
444
|
-
type === 'integration.updated'
|
|
563
|
+
type === 'integration.updated' ||
|
|
564
|
+
type === 'provider.updated'
|
|
445
565
|
)
|
|
446
566
|
}
|
|
447
567
|
|
|
@@ -784,7 +904,7 @@ export function createQuotaPlugin(
|
|
|
784
904
|
const eventTask = (async () => {
|
|
785
905
|
try {
|
|
786
906
|
for await (const event of context.event.subscribe({ signal: eventController.signal })) {
|
|
787
|
-
if (
|
|
907
|
+
if (isQuotaSourceInvalidationEvent(event.type)) {
|
|
788
908
|
resolver.invalidate()
|
|
789
909
|
adapters.invalidate()
|
|
790
910
|
if (registration) {
|
|
@@ -815,6 +935,30 @@ export function createQuotaPlugin(
|
|
|
815
935
|
),
|
|
816
936
|
status: async (_input, callContext: RpcCallContext<typeof quotaRpc.methods.status>) =>
|
|
817
937
|
getProviderStatus(resolver, adapters, callContext.signal),
|
|
938
|
+
usage_history: async (
|
|
939
|
+
input,
|
|
940
|
+
callContext: RpcCallContext<typeof quotaRpc.methods.usage_history>,
|
|
941
|
+
) => {
|
|
942
|
+
callContext.signal.throwIfAborted()
|
|
943
|
+
const period = (input as { period: string }).period
|
|
944
|
+
return queryUsageHistoryInWorker(
|
|
945
|
+
period,
|
|
946
|
+
AbortSignal.any([callContext.signal, shutdownController.signal]),
|
|
947
|
+
)
|
|
948
|
+
},
|
|
949
|
+
active_context_cost: async (
|
|
950
|
+
input,
|
|
951
|
+
callContext: RpcCallContext<typeof quotaRpc.methods.active_context_cost>,
|
|
952
|
+
) => {
|
|
953
|
+
callContext.signal.throwIfAborted()
|
|
954
|
+
return estimateActiveContextCost(
|
|
955
|
+
input as {
|
|
956
|
+
providerID: string | null
|
|
957
|
+
modelID: string | null
|
|
958
|
+
contextTokens: number | null
|
|
959
|
+
},
|
|
960
|
+
)
|
|
961
|
+
},
|
|
818
962
|
})
|
|
819
963
|
} catch (error) {
|
|
820
964
|
console.warn('[pantheon-tui quota] quota RPC registration failed:', error)
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
export const MAX_HISTORY_BUCKETS = 366
|
|
2
|
+
export const MAX_HISTORY_MODELS = 64
|
|
3
|
+
export const MAX_HISTORY_QUERY_MS = 5_000
|
|
4
|
+
|
|
5
|
+
export type UsageHistoryRpcPeriod = '7d' | '15d' | '30d' | 'total'
|
|
6
|
+
|
|
7
|
+
interface UsageHistorySourceTotals {
|
|
8
|
+
input: number
|
|
9
|
+
output: number
|
|
10
|
+
cacheRead: number
|
|
11
|
+
cacheWrite: number
|
|
12
|
+
total: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface UsageHistorySourceBucket extends UsageHistorySourceTotals {
|
|
16
|
+
date: string
|
|
17
|
+
estimatedUsd?: number
|
|
18
|
+
pricingComplete: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface UsageHistorySourceModel {
|
|
22
|
+
providerID: string
|
|
23
|
+
modelID: string
|
|
24
|
+
totals: UsageHistorySourceTotals
|
|
25
|
+
buckets: UsageHistorySourceBucket[]
|
|
26
|
+
estimatedUsd?: number
|
|
27
|
+
pricingComplete: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface UsageHistorySourceResult {
|
|
31
|
+
period: UsageHistoryRpcPeriod
|
|
32
|
+
coverageStart: string | null
|
|
33
|
+
partial: boolean
|
|
34
|
+
rows: number
|
|
35
|
+
buckets: UsageHistorySourceBucket[]
|
|
36
|
+
totals: UsageHistorySourceTotals
|
|
37
|
+
models: UsageHistorySourceModel[]
|
|
38
|
+
pricing: {
|
|
39
|
+
status: 'empty' | 'unavailable' | 'partial' | 'complete'
|
|
40
|
+
complete: boolean
|
|
41
|
+
estimatedUsd?: number
|
|
42
|
+
unpricedModels: number
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface UsageHistoryRpcTotals {
|
|
47
|
+
input: number
|
|
48
|
+
output: number
|
|
49
|
+
cacheRead: number
|
|
50
|
+
cacheWrite: number
|
|
51
|
+
total: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface UsageHistoryRpcBucket extends UsageHistoryRpcTotals {
|
|
55
|
+
date: string
|
|
56
|
+
estimatedUsd?: number
|
|
57
|
+
pricingComplete: boolean
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface UsageHistoryRpcModel {
|
|
61
|
+
providerID: string
|
|
62
|
+
modelID: string
|
|
63
|
+
totals: UsageHistoryRpcTotals
|
|
64
|
+
estimatedUsd?: number
|
|
65
|
+
pricingComplete: boolean
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface UsageHistoryRpcAvailable {
|
|
69
|
+
status: 'available' | 'partial'
|
|
70
|
+
period: UsageHistoryRpcPeriod
|
|
71
|
+
coverageStart: string | null
|
|
72
|
+
partial: boolean
|
|
73
|
+
truncated: boolean
|
|
74
|
+
rows: number
|
|
75
|
+
buckets: UsageHistoryRpcBucket[]
|
|
76
|
+
totals: UsageHistoryRpcTotals
|
|
77
|
+
models: UsageHistoryRpcModel[]
|
|
78
|
+
pricing: {
|
|
79
|
+
status: 'empty' | 'unavailable' | 'partial' | 'complete'
|
|
80
|
+
complete: boolean
|
|
81
|
+
billed: false
|
|
82
|
+
estimatedUsd?: number
|
|
83
|
+
unpricedModels: number
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface UsageHistoryRpcUnavailable {
|
|
88
|
+
status: 'unavailable'
|
|
89
|
+
reason: 'invalid_period' | 'history_unavailable' | 'history_timeout'
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type UsageHistoryRpcResult = UsageHistoryRpcAvailable | UsageHistoryRpcUnavailable
|
|
93
|
+
|
|
94
|
+
export const USAGE_HISTORY_PERIODS: readonly UsageHistoryRpcPeriod[] = ['7d', '15d', '30d', 'total']
|
|
95
|
+
|
|
96
|
+
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
|
|
97
|
+
const SAFE_LABEL = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/
|
|
98
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
|
|
99
|
+
|
|
100
|
+
function safeCount(value: number, markTruncated: () => void): number {
|
|
101
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
102
|
+
markTruncated()
|
|
103
|
+
return 0
|
|
104
|
+
}
|
|
105
|
+
if (!Number.isSafeInteger(value)) {
|
|
106
|
+
markTruncated()
|
|
107
|
+
return Math.min(Math.floor(value), MAX_SAFE_INTEGER)
|
|
108
|
+
}
|
|
109
|
+
return value
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function safeEstimate(value: number | undefined, markTruncated: () => void): number | undefined {
|
|
113
|
+
if (value === undefined) return undefined
|
|
114
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
115
|
+
markTruncated()
|
|
116
|
+
return undefined
|
|
117
|
+
}
|
|
118
|
+
const rounded = Math.round(value * 1e8) / 1e8
|
|
119
|
+
if (!Number.isFinite(rounded)) {
|
|
120
|
+
markTruncated()
|
|
121
|
+
return undefined
|
|
122
|
+
}
|
|
123
|
+
return rounded
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function safeLabel(value: string, markTruncated: () => void): string {
|
|
127
|
+
if (!SAFE_LABEL.test(value)) {
|
|
128
|
+
markTruncated()
|
|
129
|
+
return 'unknown'
|
|
130
|
+
}
|
|
131
|
+
return value
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function projectTotals(
|
|
135
|
+
value: UsageHistorySourceTotals,
|
|
136
|
+
markTruncated: () => void,
|
|
137
|
+
): UsageHistoryRpcTotals {
|
|
138
|
+
return {
|
|
139
|
+
input: safeCount(value.input, markTruncated),
|
|
140
|
+
output: safeCount(value.output, markTruncated),
|
|
141
|
+
cacheRead: safeCount(value.cacheRead, markTruncated),
|
|
142
|
+
cacheWrite: safeCount(value.cacheWrite, markTruncated),
|
|
143
|
+
total: safeCount(value.total, markTruncated),
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Project cost-command output to a bounded, non-identifying TUI contract. */
|
|
148
|
+
export function projectUsageHistoryResult(
|
|
149
|
+
result: UsageHistorySourceResult,
|
|
150
|
+
): UsageHistoryRpcAvailable {
|
|
151
|
+
let unsafeOrTruncated = false
|
|
152
|
+
const markTruncated = (): void => {
|
|
153
|
+
unsafeOrTruncated = true
|
|
154
|
+
}
|
|
155
|
+
const sourceBuckets = result.buckets
|
|
156
|
+
const sourceModels = result.models
|
|
157
|
+
if (sourceBuckets.length > MAX_HISTORY_BUCKETS || sourceModels.length > MAX_HISTORY_MODELS) {
|
|
158
|
+
markTruncated()
|
|
159
|
+
}
|
|
160
|
+
const buckets = sourceBuckets.slice(-MAX_HISTORY_BUCKETS).flatMap((bucket) => {
|
|
161
|
+
if (!ISO_DATE.test(bucket.date)) {
|
|
162
|
+
markTruncated()
|
|
163
|
+
return []
|
|
164
|
+
}
|
|
165
|
+
const estimatedUsd = safeEstimate(bucket.estimatedUsd, markTruncated)
|
|
166
|
+
return [
|
|
167
|
+
{
|
|
168
|
+
date: bucket.date,
|
|
169
|
+
...projectTotals(bucket, markTruncated),
|
|
170
|
+
...(estimatedUsd === undefined ? {} : { estimatedUsd }),
|
|
171
|
+
pricingComplete: bucket.pricingComplete === true,
|
|
172
|
+
},
|
|
173
|
+
]
|
|
174
|
+
})
|
|
175
|
+
const models = sourceModels.slice(0, MAX_HISTORY_MODELS).map((model) => {
|
|
176
|
+
const estimatedUsd = safeEstimate(model.estimatedUsd, markTruncated)
|
|
177
|
+
return {
|
|
178
|
+
providerID: safeLabel(model.providerID, markTruncated),
|
|
179
|
+
modelID: safeLabel(model.modelID, markTruncated),
|
|
180
|
+
totals: projectTotals(model.totals, markTruncated),
|
|
181
|
+
...(estimatedUsd === undefined ? {} : { estimatedUsd }),
|
|
182
|
+
pricingComplete: model.pricingComplete === true,
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
let coverageStart = result.coverageStart
|
|
186
|
+
if (coverageStart !== null && !ISO_DATE.test(coverageStart)) {
|
|
187
|
+
markTruncated()
|
|
188
|
+
coverageStart = null
|
|
189
|
+
}
|
|
190
|
+
const pricingEstimate = safeEstimate(result.pricing.estimatedUsd, markTruncated)
|
|
191
|
+
const rows = safeCount(result.rows, markTruncated)
|
|
192
|
+
const totals = projectTotals(result.totals, markTruncated)
|
|
193
|
+
const unpricedModels = safeCount(result.pricing.unpricedModels, markTruncated)
|
|
194
|
+
const truncated = unsafeOrTruncated
|
|
195
|
+
return {
|
|
196
|
+
status: result.partial || truncated ? 'partial' : 'available',
|
|
197
|
+
period: result.period,
|
|
198
|
+
coverageStart,
|
|
199
|
+
partial: result.partial,
|
|
200
|
+
truncated,
|
|
201
|
+
rows,
|
|
202
|
+
buckets,
|
|
203
|
+
totals,
|
|
204
|
+
models,
|
|
205
|
+
pricing: {
|
|
206
|
+
status: result.pricing.status,
|
|
207
|
+
complete: result.pricing.complete === true,
|
|
208
|
+
billed: false,
|
|
209
|
+
...(pricingEstimate === undefined ? {} : { estimatedUsd: pricingEstimate }),
|
|
210
|
+
unpricedModels,
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function isUsageHistoryPeriod(value: unknown): value is UsageHistoryRpcPeriod {
|
|
216
|
+
return typeof value === 'string' && USAGE_HISTORY_PERIODS.includes(value as UsageHistoryRpcPeriod)
|
|
217
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
UsageHistoryRpcBucket,
|
|
3
|
+
UsageHistoryRpcModel,
|
|
4
|
+
UsageHistoryRpcResult,
|
|
5
|
+
UsageHistoryRpcTotals,
|
|
6
|
+
} from './usage-history-contract'
|
|
7
|
+
import type { ActiveContextCostResult } from './usage-view-model'
|
|
8
|
+
|
|
9
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
10
|
+
return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function isTotals(value: unknown): value is UsageHistoryRpcTotals {
|
|
14
|
+
const totals = asRecord(value)
|
|
15
|
+
return (
|
|
16
|
+
totals !== null &&
|
|
17
|
+
['input', 'output', 'cacheRead', 'cacheWrite', 'total'].every(
|
|
18
|
+
(key) =>
|
|
19
|
+
typeof totals[key] === 'number' && Number.isSafeInteger(totals[key]) && totals[key] >= 0,
|
|
20
|
+
)
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function isHistoryBucket(value: unknown): value is UsageHistoryRpcBucket {
|
|
25
|
+
const bucket = asRecord(value)
|
|
26
|
+
return (
|
|
27
|
+
bucket !== null &&
|
|
28
|
+
typeof bucket.date === 'string' &&
|
|
29
|
+
/^\d{4}-\d{2}-\d{2}$/.test(bucket.date) &&
|
|
30
|
+
isTotals(bucket) &&
|
|
31
|
+
typeof bucket.pricingComplete === 'boolean' &&
|
|
32
|
+
(bucket.estimatedUsd === undefined ||
|
|
33
|
+
(typeof bucket.estimatedUsd === 'number' && Number.isFinite(bucket.estimatedUsd)))
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isHistoryModel(value: unknown): value is UsageHistoryRpcModel {
|
|
38
|
+
const model = asRecord(value)
|
|
39
|
+
return (
|
|
40
|
+
model !== null &&
|
|
41
|
+
typeof model.providerID === 'string' &&
|
|
42
|
+
typeof model.modelID === 'string' &&
|
|
43
|
+
isTotals(model.totals) &&
|
|
44
|
+
typeof model.pricingComplete === 'boolean' &&
|
|
45
|
+
(model.estimatedUsd === undefined ||
|
|
46
|
+
(typeof model.estimatedUsd === 'number' && Number.isFinite(model.estimatedUsd)))
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isUsageHistoryRpcResult(value: unknown): value is UsageHistoryRpcResult {
|
|
51
|
+
const result = asRecord(value)
|
|
52
|
+
if (!result) return false
|
|
53
|
+
if (result.status === 'unavailable') {
|
|
54
|
+
return ['invalid_period', 'history_unavailable', 'history_timeout'].includes(
|
|
55
|
+
String(result.reason),
|
|
56
|
+
)
|
|
57
|
+
}
|
|
58
|
+
if (result.status !== 'available' && result.status !== 'partial') return false
|
|
59
|
+
const pricing = asRecord(result.pricing)
|
|
60
|
+
return (
|
|
61
|
+
['7d', '15d', '30d', 'total'].includes(String(result.period)) &&
|
|
62
|
+
(result.coverageStart === null || typeof result.coverageStart === 'string') &&
|
|
63
|
+
typeof result.partial === 'boolean' &&
|
|
64
|
+
typeof result.truncated === 'boolean' &&
|
|
65
|
+
typeof result.rows === 'number' &&
|
|
66
|
+
Number.isSafeInteger(result.rows) &&
|
|
67
|
+
result.rows >= 0 &&
|
|
68
|
+
Array.isArray(result.buckets) &&
|
|
69
|
+
result.buckets.every(isHistoryBucket) &&
|
|
70
|
+
isTotals(result.totals) &&
|
|
71
|
+
Array.isArray(result.models) &&
|
|
72
|
+
result.models.every(isHistoryModel) &&
|
|
73
|
+
pricing !== null &&
|
|
74
|
+
['empty', 'unavailable', 'partial', 'complete'].includes(String(pricing.status)) &&
|
|
75
|
+
typeof pricing.complete === 'boolean' &&
|
|
76
|
+
pricing.billed === false &&
|
|
77
|
+
typeof pricing.unpricedModels === 'number' &&
|
|
78
|
+
Number.isSafeInteger(pricing.unpricedModels) &&
|
|
79
|
+
pricing.unpricedModels >= 0 &&
|
|
80
|
+
(pricing.estimatedUsd === undefined ||
|
|
81
|
+
(typeof pricing.estimatedUsd === 'number' && Number.isFinite(pricing.estimatedUsd)))
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function isActiveContextCostResult(value: unknown): value is ActiveContextCostResult {
|
|
86
|
+
const result = asRecord(value)
|
|
87
|
+
if (result?.billed !== false) return false
|
|
88
|
+
if (result.cacheDiscountApplied !== false) return false
|
|
89
|
+
if (result.basis !== 'pre-cache-context-tokens-times-input-price') return false
|
|
90
|
+
if (result.status === 'estimated') {
|
|
91
|
+
return typeof result.estimatedUsd === 'number' && Number.isFinite(result.estimatedUsd)
|
|
92
|
+
}
|
|
93
|
+
return (
|
|
94
|
+
result.status === 'unavailable' &&
|
|
95
|
+
[
|
|
96
|
+
'invalid-context-token-count',
|
|
97
|
+
'missing-model-identity',
|
|
98
|
+
'no-pricing',
|
|
99
|
+
'unknown-model',
|
|
100
|
+
'ambiguous-model',
|
|
101
|
+
'missing-cache-price',
|
|
102
|
+
].includes(String(result.reason))
|
|
103
|
+
)
|
|
104
|
+
}
|