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.
Files changed (68) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +34 -60
  3. package/README.pt-BR.md +10 -12
  4. package/bin/pantheon-init.mjs +22 -32
  5. package/package.json +3 -3
  6. package/plugin.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/scripts/decision-router.mjs +41 -56
  9. package/scripts/install/decision-router-config.mjs +67 -1
  10. package/scripts/install/npx-cache-sweep.mjs +103 -0
  11. package/scripts/install/opencode.mjs +7 -7
  12. package/scripts/install/plugin.mjs +4 -3
  13. package/scripts/install/strings.mjs +4 -0
  14. package/scripts/release-gates.mjs +6 -82
  15. package/scripts/sync-tui.mjs +3 -3
  16. package/src/agents/zeus.md +4 -2
  17. package/src/pantheon/jev-decision-tool.ts +366 -114
  18. package/src/pantheon/jev-decisions.ts +11 -13
  19. package/src/pantheon/jev-escalation.ts +639 -0
  20. package/src/pantheon/jev-quality-score.ts +432 -0
  21. package/src/pantheon/jev-risk-gate.ts +479 -0
  22. package/src/pantheon/local-decision-prompt.ts +12 -18
  23. package/src/pantheon/v2-decision-telemetry.ts +14 -4
  24. package/src/pantheon/v2-native-decisions.ts +1 -1
  25. package/src/plugin-v2.ts +201 -24
  26. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  27. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  28. package/src/plugins/tui/dist/server-v2.js +19 -789
  29. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  30. package/src/plugins/tui/dist/tui-v2.d.ts +12 -331
  31. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  32. package/src/plugins/tui/dist/tui-v2.js +257 -5370
  33. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  34. package/src/plugins/tui/dist/tui.js +1 -1
  35. package/src/plugins/tui/package-lock.json +2 -2
  36. package/src/plugins/tui/package.json +1 -1
  37. package/src/plugins/tui/src/index-v2.tsx +213 -86
  38. package/src/plugins/tui/src/server-v2.ts +18 -982
  39. package/src/plugins/tui/tsconfig.typecheck.json +1 -6
  40. package/src/plugins/tui/tsdown.config.ts +1 -11
  41. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +0 -749
  42. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +0 -1
  43. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  44. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  45. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  46. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  47. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  48. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  49. package/src/plugins/tui/dist/quota-cli.js +0 -184
  50. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  51. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +0 -684
  52. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +0 -1
  53. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +0 -118
  54. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +0 -1
  55. package/src/plugins/tui/dist/usage-history-worker.js +0 -25
  56. package/src/plugins/tui/dist/usage-history-worker.js.map +0 -1
  57. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  58. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  59. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  60. package/src/plugins/tui/src/quota-cli.ts +0 -237
  61. package/src/plugins/tui/src/quota-rpc.ts +0 -373
  62. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  63. package/src/plugins/tui/src/quota-v2.tsx +0 -1238
  64. package/src/plugins/tui/src/usage-history-contract.ts +0 -217
  65. package/src/plugins/tui/src/usage-history-validation.ts +0 -104
  66. package/src/plugins/tui/src/usage-history-view.tsx +0 -236
  67. package/src/plugins/tui/src/usage-history-worker.ts +0 -25
  68. package/src/plugins/tui/src/usage-view-model.ts +0 -272
@@ -1,1598 +0,0 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { queryAlibabaTokenPlanUsage } from './quota-cli'
3
- import { MAX_PROVIDER_METRICS, type QuotaProviderId } from './quota-rpc'
4
-
5
- // Source: OpenCode v2.0.22 packages/core/src/plugin/provider/openai.ts.
6
- export const OPENAI_CODEX_OAUTH_METHOD_IDS = ['chatgpt-browser', 'chatgpt-headless'] as const
7
- type OpenAICodexOAuthMethodID = (typeof OPENAI_CODEX_OAUTH_METHOD_IDS)[number]
8
-
9
- export function isOpenAICodexOAuthMethod(value: unknown): value is OpenAICodexOAuthMethodID {
10
- return (
11
- typeof value === 'string' &&
12
- OPENAI_CODEX_OAUTH_METHOD_IDS.includes(value as OpenAICodexOAuthMethodID)
13
- )
14
- }
15
-
16
- // OpenCode registers its Console account with Integration.MethodID.make("device").
17
- export const OPENCODE_CONSOLE_OAUTH_METHOD_IDS = ['device'] as const
18
- type OpenCodeConsoleOAuthMethodID = (typeof OPENCODE_CONSOLE_OAUTH_METHOD_IDS)[number]
19
-
20
- export function isOpenCodeConsoleOAuthMethod(
21
- value: unknown,
22
- ): value is OpenCodeConsoleOAuthMethodID {
23
- return (
24
- typeof value === 'string' &&
25
- OPENCODE_CONSOLE_OAUTH_METHOD_IDS.includes(value as OpenCodeConsoleOAuthMethodID)
26
- )
27
- }
28
-
29
- type OAuthMethodID = OpenAICodexOAuthMethodID | OpenCodeConsoleOAuthMethodID
30
-
31
- export type QuotaAdapterContext = {
32
- readonly projectId?: string
33
- readonly accountId?: string
34
- readonly orgId?: string
35
- readonly methodID?: OAuthMethodID
36
- }
37
-
38
- export type QuotaAudience = 'us_personal' | 'us_business' | 'china_personal' | 'china_business'
39
- export type QuotaMetric =
40
- | {
41
- kind: 'provider_quota'
42
- used: number
43
- remaining: number
44
- unit: string
45
- label: string
46
- period?: string
47
- resetsAt?: number
48
- }
49
- | {
50
- kind: 'balance'
51
- amount: number
52
- currency: 'USD' | 'CNY'
53
- label: string
54
- status?: 'available' | 'unavailable' | 'active' | 'inactive'
55
- }
56
- | { kind: 'estimate'; amount: number; unit: string; label: string }
57
- | {
58
- kind: 'provider_status'
59
- status: 'available' | 'unavailable' | 'active' | 'inactive'
60
- label: string
61
- }
62
- | {
63
- kind: 'key_usage'
64
- amount: number
65
- currency: 'USD' | 'CNY'
66
- label: string
67
- period?: string
68
- }
69
- | { kind: 'session_usage'; amount: number; unit: string; label: string }
70
-
71
- export type AdapterFailureReason =
72
- | 'provider_error'
73
- | 'not_subscribed'
74
- | 'rate_limited'
75
- | 'unauthorized'
76
- | 'forbidden'
77
- | 'timeout'
78
- | 'network_error'
79
- | 'invalid_response'
80
- | 'cli_identity_unavailable'
81
- | 'eligibility_unverified'
82
- export type AdapterFailure = {
83
- readonly reason: AdapterFailureReason
84
- readonly retryAfterMs?: number
85
- }
86
-
87
- type ProviderDefinition = {
88
- readonly label: string
89
- readonly integrationID: string
90
- readonly fallbackIntegrationIDs?: readonly string[]
91
- readonly audiences: readonly QuotaAudience[]
92
- readonly scope: 'account' | 'selected_key' | 'team' | 'session'
93
- readonly methods: readonly ('key' | 'oauth' | 'cli')[]
94
- readonly source?: 'integration' | 'local-cli'
95
- readonly adapter?:
96
- | 'anthropic'
97
- | 'chutes'
98
- | 'copilot'
99
- | 'deepseek'
100
- | 'google-agy'
101
- | 'alibaba-token-plan-cli'
102
- | 'kilo-gateway'
103
- | 'kimi-global'
104
- | 'kimi-cn'
105
- | 'minimax-global'
106
- | 'minimax-cn'
107
- | 'nanogpt'
108
- | 'ollama-cloud'
109
- | 'openai'
110
- | 'openrouter'
111
- | 'opencode-go'
112
- | 'opencode-zen'
113
- | 'synthetic'
114
- | 'xai-supergrok'
115
- | 'zai'
116
- | 'zhipu'
117
- readonly blockedReason?:
118
- | 'unsupported'
119
- | 'private_endpoint'
120
- | 'eligibility_unverified'
121
- | 'runtime_accounting_unavailable'
122
- | 'cli_identity_unavailable'
123
- }
124
-
125
- const usBoth = ['us_personal', 'us_business'] as const
126
- const chinaPersonal = ['china_personal'] as const
127
- const chinaBoth = ['china_personal', 'china_business'] as const
128
- const blocked = (
129
- provider: Omit<ProviderDefinition, 'blockedReason'>,
130
- blockedReason: NonNullable<ProviderDefinition['blockedReason']>,
131
- ): ProviderDefinition => ({ ...provider, blockedReason })
132
-
133
- /**
134
- * Closed provider/integration/method allowlist. Only rows with a reviewed
135
- * adapter may make a network request; remaining rows are explicitly blocked.
136
- * Audience lists describe the approved matrix and do not claim that account
137
- * type was inferred from credentials.
138
- */
139
- export const QUOTA_PROVIDER_CATALOG: Record<QuotaProviderId, ProviderDefinition> = {
140
- anthropic: {
141
- label: 'Anthropic / Claude',
142
- integrationID: 'anthropic',
143
- audiences: usBoth,
144
- scope: 'account',
145
- methods: ['oauth'],
146
- adapter: 'anthropic',
147
- },
148
- chutes: {
149
- label: 'Chutes AI',
150
- integrationID: 'chutes',
151
- audiences: usBoth,
152
- scope: 'account',
153
- methods: ['key'],
154
- adapter: 'chutes',
155
- },
156
- cursor: blocked(
157
- {
158
- label: 'Cursor',
159
- integrationID: 'cursor',
160
- audiences: usBoth,
161
- scope: 'account',
162
- methods: ['oauth', 'key'],
163
- },
164
- 'runtime_accounting_unavailable',
165
- ),
166
- 'github-copilot': {
167
- label: 'GitHub Copilot',
168
- integrationID: 'github-copilot',
169
- audiences: ['us_personal'],
170
- scope: 'account',
171
- methods: ['oauth'],
172
- adapter: 'copilot',
173
- },
174
- 'google-agy': {
175
- label: 'Google AGY',
176
- integrationID: 'google-agy',
177
- audiences: usBoth,
178
- scope: 'account',
179
- methods: ['oauth'],
180
- adapter: 'google-agy',
181
- },
182
- 'kilo-gateway': {
183
- label: 'Kilo Gateway',
184
- integrationID: 'kilo-gateway',
185
- audiences: ['us_personal'],
186
- scope: 'account',
187
- methods: ['key'],
188
- adapter: 'kilo-gateway',
189
- },
190
- nanogpt: {
191
- label: 'NanoGPT',
192
- integrationID: 'nanogpt',
193
- audiences: usBoth,
194
- scope: 'account',
195
- methods: ['key'],
196
- adapter: 'nanogpt',
197
- },
198
- 'ollama-cloud': {
199
- label: 'Ollama Cloud',
200
- integrationID: 'ollama-cloud',
201
- audiences: ['us_personal'],
202
- scope: 'account',
203
- methods: ['key'],
204
- adapter: 'ollama-cloud',
205
- },
206
- openai: {
207
- label: 'OpenAI / Codex',
208
- integrationID: 'openai',
209
- audiences: usBoth,
210
- scope: 'account',
211
- methods: ['oauth'],
212
- adapter: 'openai',
213
- },
214
- 'opencode-go': {
215
- label: 'OpenCode Go',
216
- integrationID: 'opencode-go',
217
- fallbackIntegrationIDs: ['opencode'],
218
- audiences: ['us_personal'],
219
- scope: 'account',
220
- methods: ['key', 'oauth'],
221
- adapter: 'opencode-go',
222
- },
223
- 'opencode-zen': {
224
- label: 'OpenCode Zen',
225
- integrationID: 'opencode',
226
- audiences: usBoth,
227
- scope: 'account',
228
- methods: ['oauth'],
229
- adapter: 'opencode-zen',
230
- },
231
- openrouter: {
232
- label: 'OpenRouter',
233
- integrationID: 'openrouter',
234
- audiences: usBoth,
235
- scope: 'selected_key',
236
- methods: ['key'],
237
- adapter: 'openrouter',
238
- },
239
- synthetic: {
240
- label: 'Synthetic',
241
- integrationID: 'synthetic',
242
- audiences: usBoth,
243
- scope: 'account',
244
- methods: ['key'],
245
- adapter: 'synthetic',
246
- },
247
- 'xai-supergrok': {
248
- label: 'xAI SuperGrok',
249
- integrationID: 'xai',
250
- audiences: usBoth,
251
- scope: 'account',
252
- methods: ['oauth'],
253
- adapter: 'xai-supergrok',
254
- },
255
- 'gemini-cli': blocked(
256
- {
257
- label: 'Gemini CLI / Code Assist',
258
- integrationID: 'google-gemini-cli',
259
- audiences: ['us_business'],
260
- scope: 'team',
261
- methods: ['oauth'],
262
- },
263
- 'eligibility_unverified',
264
- ),
265
- 'alibaba-coding-plan': blocked(
266
- {
267
- label: 'Alibaba Coding Plan',
268
- integrationID: 'alibaba-coding-plan',
269
- audiences: chinaPersonal,
270
- scope: 'account',
271
- methods: ['key'],
272
- },
273
- 'runtime_accounting_unavailable',
274
- ),
275
- 'alibaba-token-plan': {
276
- label: 'Alibaba Token Plan',
277
- integrationID: 'alibaba-token-plan',
278
- audiences: chinaPersonal,
279
- scope: 'account',
280
- methods: ['cli'],
281
- source: 'local-cli',
282
- adapter: 'alibaba-token-plan-cli',
283
- },
284
- deepseek: {
285
- label: 'DeepSeek',
286
- integrationID: 'deepseek',
287
- audiences: chinaPersonal,
288
- scope: 'account',
289
- methods: ['key'],
290
- adapter: 'deepseek',
291
- },
292
- 'kimi-code-global': {
293
- label: 'Kimi Code (Global)',
294
- integrationID: 'kimi-code-global',
295
- audiences: chinaBoth,
296
- scope: 'account',
297
- methods: ['key'],
298
- adapter: 'kimi-global',
299
- },
300
- 'kimi-code-cn': {
301
- label: 'Kimi Code (China)',
302
- integrationID: 'kimi-code-cn',
303
- audiences: chinaBoth,
304
- scope: 'account',
305
- methods: ['key'],
306
- adapter: 'kimi-cn',
307
- },
308
- 'minimax-plan-global': {
309
- label: 'MiniMax Token Plan (Global)',
310
- integrationID: 'minimax-coding-plan',
311
- audiences: chinaBoth,
312
- scope: 'account',
313
- methods: ['key'],
314
- adapter: 'minimax-global',
315
- },
316
- 'minimax-plan-cn': {
317
- label: 'MiniMax Token Plan (China)',
318
- integrationID: 'minimax-china-coding-plan',
319
- audiences: chinaBoth,
320
- scope: 'account',
321
- methods: ['key'],
322
- adapter: 'minimax-cn',
323
- },
324
- 'xiaomi-mimo': blocked(
325
- {
326
- label: 'Xiaomi MiMo',
327
- integrationID: 'xiaomi-mimo',
328
- audiences: chinaPersonal,
329
- scope: 'account',
330
- methods: ['key'],
331
- },
332
- 'unsupported',
333
- ),
334
- 'zai-coding-plan': {
335
- label: 'Z.ai Coding Plan',
336
- integrationID: 'zai-coding-plan',
337
- audiences: chinaPersonal,
338
- scope: 'account',
339
- methods: ['key'],
340
- adapter: 'zai',
341
- },
342
- 'zhipu-coding-plan': {
343
- label: 'Zhipu Coding Plan',
344
- integrationID: 'zhipu-coding-plan',
345
- audiences: chinaBoth,
346
- scope: 'account',
347
- methods: ['key'],
348
- adapter: 'zhipu',
349
- },
350
- }
351
-
352
- export type AdapterResult =
353
- | {
354
- readonly state: 'available'
355
- readonly metrics: QuotaMetric[]
356
- readonly routeKind?: 'api_key' | 'console_oauth'
357
- }
358
- | (AdapterFailure & { readonly routeKind?: 'api_key' | 'console_oauth' })
359
-
360
- const MAX_RESPONSE_BYTES = 64 * 1024
361
- const REQUEST_TIMEOUT_MS = 5_000
362
- const MAX_AMOUNT = 1_000_000_000_000
363
-
364
- class SafeAdapterError extends Error {
365
- constructor(
366
- readonly reason: AdapterFailureReason,
367
- readonly retryAfterMs?: number,
368
- readonly httpStatus?: number,
369
- ) {
370
- super(reason)
371
- }
372
- }
373
-
374
- function isRecord(value: unknown): value is Record<string, unknown> {
375
- return typeof value === 'object' && value !== null && !Array.isArray(value)
376
- }
377
-
378
- function available(metrics: QuotaMetric[]): AdapterResult {
379
- if (metrics.length === 0 || metrics.length > MAX_PROVIDER_METRICS) {
380
- throw new SafeAdapterError('provider_error')
381
- }
382
- return { state: 'available', metrics }
383
- }
384
-
385
- function finiteAmount(value: unknown): number | undefined {
386
- const amount = typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value) ? Number(value) : value
387
- return typeof amount === 'number' &&
388
- Number.isFinite(amount) &&
389
- amount >= 0 &&
390
- amount <= MAX_AMOUNT
391
- ? amount
392
- : undefined
393
- }
394
-
395
- function retryAfterMs(value: string | null, now = Date.now()): number | undefined {
396
- if (!value) return undefined
397
- const seconds = Number(value)
398
- const retryAt =
399
- Number.isFinite(seconds) && seconds >= 0 ? now + seconds * 1_000 : Date.parse(value)
400
- if (!Number.isFinite(retryAt)) return undefined
401
- return Math.ceil(Math.min(3_600_000, Math.max(0, retryAt - now)))
402
- }
403
-
404
- async function readJson(response: Response): Promise<unknown> {
405
- const announced = Number(response.headers.get('content-length'))
406
- if (Number.isFinite(announced) && announced > MAX_RESPONSE_BYTES) {
407
- await response.body?.cancel()
408
- throw new SafeAdapterError('invalid_response')
409
- }
410
- if (!response.body) throw new SafeAdapterError('invalid_response')
411
- const reader = response.body.getReader()
412
- const chunks: Uint8Array[] = []
413
- let size = 0
414
- try {
415
- while (true) {
416
- const { done, value } = await reader.read()
417
- if (done) break
418
- size += value.byteLength
419
- if (size > MAX_RESPONSE_BYTES) {
420
- await reader.cancel()
421
- throw new SafeAdapterError('invalid_response')
422
- }
423
- chunks.push(value)
424
- }
425
- } finally {
426
- reader.releaseLock()
427
- }
428
- const bytes = new Uint8Array(size)
429
- let offset = 0
430
- for (const chunk of chunks) {
431
- bytes.set(chunk, offset)
432
- offset += chunk.byteLength
433
- }
434
- try {
435
- return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown
436
- } catch {
437
- throw new SafeAdapterError('invalid_response')
438
- }
439
- }
440
-
441
- function transportFailure(
442
- error: unknown,
443
- timeoutSignal: AbortSignal,
444
- shutdownSignal: AbortSignal,
445
- ): SafeAdapterError {
446
- if (error instanceof SafeAdapterError) return error
447
- if (shutdownSignal.aborted) return new SafeAdapterError('provider_error')
448
- const errorName =
449
- typeof error === 'object' && error !== null && 'name' in error ? error.name : undefined
450
- return new SafeAdapterError(
451
- timeoutSignal.aborted || errorName === 'TimeoutError' ? 'timeout' : 'network_error',
452
- )
453
- }
454
-
455
- async function requestJson(
456
- url: string,
457
- secret: string,
458
- shutdownSignal: AbortSignal,
459
- authStyle: 'bearer' | 'direct' = 'bearer',
460
- options: {
461
- readonly method?: 'GET' | 'POST'
462
- readonly body?: string
463
- readonly headers?: Readonly<Record<string, string>>
464
- } = {},
465
- ): Promise<unknown> {
466
- const timeoutSignal = AbortSignal.timeout(REQUEST_TIMEOUT_MS)
467
- const signal = AbortSignal.any([shutdownSignal, timeoutSignal])
468
- let response: Response
469
- try {
470
- response = await fetch(url, {
471
- method: options.method ?? 'GET',
472
- headers: {
473
- accept: 'application/json',
474
- authorization: authStyle === 'bearer' ? `Bearer ${secret}` : secret,
475
- ...options.headers,
476
- },
477
- ...(options.body === undefined ? {} : { body: options.body }),
478
- redirect: 'error',
479
- signal,
480
- })
481
- } catch (error) {
482
- throw transportFailure(error, timeoutSignal, shutdownSignal)
483
- }
484
- if (response.status === 401) {
485
- await response.body?.cancel()
486
- throw new SafeAdapterError('unauthorized')
487
- }
488
- if (response.status === 403) {
489
- await response.body?.cancel()
490
- throw new SafeAdapterError('forbidden')
491
- }
492
- if (response.status === 429) {
493
- await response.body?.cancel()
494
- throw new SafeAdapterError(
495
- 'rate_limited',
496
- retryAfterMs(response.headers.get('retry-after')) ?? 30_000,
497
- )
498
- }
499
- if (response.status === 404) {
500
- await response.body?.cancel()
501
- throw new SafeAdapterError('provider_error', undefined, 404)
502
- }
503
- if (!response.ok) {
504
- await response.body?.cancel()
505
- throw new SafeAdapterError('provider_error')
506
- }
507
- try {
508
- return await readJson(response)
509
- } catch (error) {
510
- throw transportFailure(error, timeoutSignal, shutdownSignal)
511
- }
512
- }
513
-
514
- function deepseekMetrics(payload: unknown): QuotaMetric[] {
515
- if (
516
- !isRecord(payload) ||
517
- typeof payload.is_available !== 'boolean' ||
518
- !Array.isArray(payload.balance_infos)
519
- ) {
520
- throw new SafeAdapterError('provider_error')
521
- }
522
- if (payload.balance_infos.length > 8) throw new SafeAdapterError('provider_error')
523
- const metrics: QuotaMetric[] = [
524
- {
525
- kind: 'provider_status',
526
- status: payload.is_available ? 'available' : 'unavailable',
527
- label: 'Service status',
528
- },
529
- ]
530
- for (const value of payload.balance_infos) {
531
- if (!isRecord(value) || (value.currency !== 'USD' && value.currency !== 'CNY')) {
532
- throw new SafeAdapterError('provider_error')
533
- }
534
- const amount = finiteAmount(value.total_balance)
535
- if (amount === undefined) throw new SafeAdapterError('provider_error')
536
- metrics.push({
537
- kind: 'balance',
538
- amount,
539
- currency: value.currency,
540
- label: 'Total balance',
541
- })
542
- }
543
- return metrics
544
- }
545
-
546
- function ollamaMetrics(payload: unknown): QuotaMetric[] {
547
- if (!isRecord(payload) || !isRecord(payload.included) || !isRecord(payload.purchased)) {
548
- throw new SafeAdapterError('provider_error')
549
- }
550
- const metrics: QuotaMetric[] = []
551
- const included = finiteAmount(payload.included.balance_usd)
552
- const purchased = finiteAmount(payload.purchased.balance_usd)
553
- if (included !== undefined)
554
- metrics.push({ kind: 'balance', amount: included, currency: 'USD', label: 'Included balance' })
555
- if (purchased !== undefined)
556
- metrics.push({
557
- kind: 'balance',
558
- amount: purchased,
559
- currency: 'USD',
560
- label: 'Purchased balance',
561
- })
562
-
563
- for (const window of ['session', 'weekly'] as const) {
564
- const item = payload.included[window]
565
- if (!isRecord(item)) continue
566
- const remainingPercent = finiteAmount(item.remaining_percent)
567
- if (remainingPercent === undefined || remainingPercent > 100)
568
- throw new SafeAdapterError('provider_error')
569
- const resetsAt = isoResetAt(item.resets_at)
570
- metrics.push({
571
- kind: 'provider_quota',
572
- used: 100 - remainingPercent,
573
- remaining: remainingPercent,
574
- unit: '%',
575
- label: window === 'session' ? 'Session quota' : 'Weekly quota',
576
- period: window,
577
- ...(resetsAt === undefined ? {} : { resetsAt }),
578
- })
579
- }
580
- if (metrics.length === 0) throw new SafeAdapterError('provider_error')
581
- return metrics
582
- }
583
-
584
- function openRouterMetrics(payload: unknown): QuotaMetric[] {
585
- if (!isRecord(payload) || !isRecord(payload.data)) throw new SafeAdapterError('provider_error')
586
- const data = payload.data
587
- const usage = finiteAmount(data.usage)
588
- if (usage === undefined) throw new SafeAdapterError('provider_error')
589
- const limit =
590
- data.limit === null || data.limit === undefined ? undefined : finiteAmount(data.limit)
591
- const remaining =
592
- data.limit_remaining === null || data.limit_remaining === undefined
593
- ? undefined
594
- : finiteAmount(data.limit_remaining)
595
- if (data.limit !== null && data.limit !== undefined && limit === undefined) {
596
- throw new SafeAdapterError('provider_error')
597
- }
598
- if (
599
- data.limit_remaining !== null &&
600
- data.limit_remaining !== undefined &&
601
- remaining === undefined
602
- ) {
603
- throw new SafeAdapterError('provider_error')
604
- }
605
- if (limit !== undefined && remaining !== undefined) {
606
- if (remaining > limit || usage > limit + 0.01) throw new SafeAdapterError('provider_error')
607
- return [
608
- { kind: 'provider_quota', used: usage, remaining, unit: 'USD', label: 'Selected key budget' },
609
- ]
610
- }
611
- return [
612
- {
613
- kind: 'key_usage',
614
- amount: usage,
615
- currency: 'USD',
616
- label: 'Selected key spend',
617
- period: 'reported',
618
- },
619
- ]
620
- }
621
-
622
- function chutesMetrics(payload: unknown): QuotaMetric[] {
623
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
624
- const quota = finiteAmount(payload.quota)
625
- const used = finiteAmount(payload.used)
626
- if (quota === undefined || used === undefined) throw new SafeAdapterError('provider_error')
627
- return [
628
- {
629
- kind: 'provider_quota',
630
- used,
631
- remaining: Math.max(0, quota - used),
632
- unit: 'units',
633
- label: 'Daily quota',
634
- },
635
- ]
636
- }
637
-
638
- function kimiMetrics(payload: unknown): QuotaMetric[] {
639
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
640
- const data = isRecord(payload.data) ? payload.data : payload
641
- const rows: Record<string, unknown>[] = []
642
- if (isRecord(data.usage)) rows.push(data.usage)
643
- if (Array.isArray(data.limits)) {
644
- if (data.limits.length > 12) throw new SafeAdapterError('provider_error')
645
- for (const item of data.limits) {
646
- if (!isRecord(item)) continue
647
- rows.push(isRecord(item.detail) ? item.detail : item)
648
- }
649
- }
650
- const metrics: QuotaMetric[] = []
651
- for (const row of rows) {
652
- const limit = finiteAmount(row.limit)
653
- let used = finiteAmount(row.used)
654
- const remaining = finiteAmount(row.remaining)
655
- if (
656
- used === undefined &&
657
- limit !== undefined &&
658
- remaining !== undefined &&
659
- remaining <= limit
660
- ) {
661
- used = limit - remaining
662
- }
663
- if (limit === undefined || used === undefined || limit <= 0) continue
664
- metrics.push({
665
- kind: 'provider_quota',
666
- used,
667
- remaining: Math.max(0, limit - used),
668
- unit: 'units',
669
- label: 'Provider-reported window',
670
- })
671
- }
672
- if (metrics.length === 0) throw new SafeAdapterError('provider_error')
673
- return metrics
674
- }
675
-
676
- function minimaxMetrics(payload: unknown, endpoint: 'global' | 'cn'): QuotaMetric[] {
677
- if (
678
- !isRecord(payload) ||
679
- !isRecord(payload.base_resp) ||
680
- payload.base_resp.status_code !== 0 ||
681
- !Array.isArray(payload.model_remains) ||
682
- payload.model_remains.length > 64
683
- ) {
684
- throw new SafeAdapterError('provider_error')
685
- }
686
- const candidates = payload.model_remains.filter(
687
- (row): row is Record<string, unknown> =>
688
- isRecord(row) &&
689
- typeof row.model_name === 'string' &&
690
- (/^minimax-m/i.test(row.model_name.trim()) ||
691
- row.model_name.trim().toLowerCase() === 'general'),
692
- )
693
- candidates.sort((left, right) => {
694
- const leftWildcard = left.model_name === 'minimax-m*' ? 0 : 1
695
- const rightWildcard = right.model_name === 'minimax-m*' ? 0 : 1
696
- return leftWildcard - rightWildcard
697
- })
698
- const model = candidates[0]
699
- if (!model) throw new SafeAdapterError('provider_error')
700
- const specs = [
701
- {
702
- total: model.current_interval_total_count,
703
- count: model.current_interval_usage_count,
704
- percent: model.current_interval_remaining_percent,
705
- label: '5-hour token-plan quota',
706
- },
707
- {
708
- total: model.current_weekly_total_count,
709
- count: model.current_weekly_usage_count,
710
- percent: model.current_weekly_remaining_percent,
711
- label: 'Weekly token-plan quota',
712
- },
713
- ]
714
- const metrics: QuotaMetric[] = []
715
- for (const spec of specs) {
716
- const total = finiteAmount(spec.total)
717
- const count = finiteAmount(spec.count)
718
- const percent = finiteAmount(spec.percent)
719
- if (total !== undefined && total > 0 && count !== undefined) {
720
- const used = endpoint === 'cn' ? count : Math.max(0, total - Math.min(total, count))
721
- const remaining = endpoint === 'cn' ? Math.max(0, total - count) : Math.min(total, count)
722
- metrics.push({ kind: 'provider_quota', used, remaining, unit: 'requests', label: spec.label })
723
- } else if (percent !== undefined && percent <= 100) {
724
- metrics.push({
725
- kind: 'provider_quota',
726
- used: 100 - percent,
727
- remaining: percent,
728
- unit: '%',
729
- label: spec.label,
730
- })
731
- }
732
- }
733
- if (metrics.length === 0) throw new SafeAdapterError('provider_error')
734
- return metrics
735
- }
736
-
737
- function glmMetrics(payload: unknown, provider: 'zai' | 'zhipu'): QuotaMetric[] {
738
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
739
- const envelope = isRecord(payload.data) ? payload.data : provider === 'zai' ? payload : undefined
740
- if (!envelope || !Array.isArray(envelope.limits) || envelope.limits.length > 16) {
741
- throw new SafeAdapterError('provider_error')
742
- }
743
- const metrics: QuotaMetric[] = []
744
- for (const limit of envelope.limits) {
745
- if (!isRecord(limit) || (limit.type !== 'TOKENS_LIMIT' && limit.type !== 'CREDIT_LIMIT'))
746
- continue
747
- const percentage = finiteAmount(limit.percentage)
748
- if (percentage === undefined || percentage > 100) continue
749
- const label =
750
- limit.unit === 3
751
- ? '5-hour coding-plan quota'
752
- : limit.unit === 6
753
- ? 'Weekly coding-plan quota'
754
- : 'Coding-plan quota'
755
- const resetsAt = epochResetAt(limit.nextResetTime, 'milliseconds')
756
- metrics.push({
757
- kind: 'provider_quota',
758
- used: percentage,
759
- remaining: 100 - percentage,
760
- unit: '%',
761
- label,
762
- ...(resetsAt === undefined ? {} : { resetsAt }),
763
- })
764
- }
765
- if (metrics.length === 0) throw new SafeAdapterError('provider_error')
766
- return metrics
767
- }
768
-
769
- function kiloPassMetrics(payload: unknown): QuotaMetric[] | null {
770
- const item = Array.isArray(payload) ? payload[0] : payload
771
- if (!isRecord(item) || !isRecord(item.result) || !isRecord(item.result.data)) {
772
- throw new SafeAdapterError('provider_error')
773
- }
774
- const data = item.result.data
775
- if ('json' in data && !isRecord(data.json)) throw new SafeAdapterError('provider_error')
776
- const root = isRecord(data.json) ? data.json : data
777
- if (!('subscription' in root) || root.subscription === null) return null
778
- if (!isRecord(root.subscription)) throw new SafeAdapterError('provider_error')
779
- const subscription = root.subscription
780
- const base = finiteAmount(subscription.currentPeriodBaseCreditsUsd)
781
- const usage = finiteAmount(subscription.currentPeriodUsageUsd)
782
- const bonus =
783
- subscription.currentPeriodBonusCreditsUsd === undefined ||
784
- subscription.currentPeriodBonusCreditsUsd === null
785
- ? 0
786
- : finiteAmount(subscription.currentPeriodBonusCreditsUsd)
787
- if (base === undefined || usage === undefined || bonus === undefined) {
788
- throw new SafeAdapterError('provider_error')
789
- }
790
- const total = base + bonus
791
- if (total > MAX_AMOUNT) throw new SafeAdapterError('provider_error')
792
- return [
793
- {
794
- kind: 'provider_quota',
795
- used: usage,
796
- remaining: Math.max(0, total - usage),
797
- unit: 'USD',
798
- label: 'Kilo Pass credits',
799
- },
800
- ]
801
- }
802
-
803
- function kiloBalanceMetrics(payload: unknown): QuotaMetric[] {
804
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
805
- const balance = finiteAmount(payload.balance)
806
- if (balance === undefined) throw new SafeAdapterError('provider_error')
807
- return [{ kind: 'balance', amount: balance, currency: 'USD', label: 'Gateway balance' }]
808
- }
809
-
810
- async function nanoGptMetrics(secret: string, shutdownSignal: AbortSignal): Promise<QuotaMetric[]> {
811
- const usagePayload = await requestJson(
812
- 'https://nano-gpt.com/api/subscription/v1/usage',
813
- secret,
814
- shutdownSignal,
815
- )
816
- const balancePayload = await requestJson(
817
- 'https://nano-gpt.com/api/check-balance',
818
- secret,
819
- shutdownSignal,
820
- )
821
- if (!isRecord(usagePayload) || !isRecord(balancePayload)) {
822
- throw new SafeAdapterError('provider_error')
823
- }
824
- const metrics: QuotaMetric[] = []
825
- if (typeof usagePayload.active === 'boolean') {
826
- metrics.push({
827
- kind: 'provider_status',
828
- status: usagePayload.active ? 'active' : 'inactive',
829
- label: 'Subscription status',
830
- })
831
- }
832
-
833
- const limits = isRecord(usagePayload.limits) ? usagePayload.limits : {}
834
- for (const window of ['daily', 'monthly'] as const) {
835
- const details = isRecord(usagePayload[window]) ? usagePayload[window] : undefined
836
- const limit = finiteAmount(limits[window])
837
- if (!details || limit === undefined || limit <= 0) continue
838
- let used = finiteAmount(details.used)
839
- let remaining = finiteAmount(details.remaining)
840
- const percentUsed = finiteAmount(details.percentUsed)
841
- if (used === undefined && remaining !== undefined && remaining <= limit)
842
- used = limit - remaining
843
- if (used === undefined && percentUsed !== undefined && percentUsed <= 1)
844
- used = limit * percentUsed
845
- if (remaining === undefined && used !== undefined && used <= limit) remaining = limit - used
846
- if (used === undefined || remaining === undefined || used > limit || remaining > limit) {
847
- throw new SafeAdapterError('provider_error')
848
- }
849
- metrics.push({
850
- kind: 'provider_quota',
851
- used,
852
- remaining,
853
- unit: 'units',
854
- label: window === 'daily' ? 'Daily subscription limit' : 'Monthly subscription limit',
855
- period: window,
856
- })
857
- }
858
- const usdBalance = finiteAmount(balancePayload.usd_balance)
859
- if (usdBalance !== undefined) {
860
- metrics.push({ kind: 'balance', amount: usdBalance, currency: 'USD', label: 'Account balance' })
861
- }
862
- if (metrics.length === 0) throw new SafeAdapterError('provider_error')
863
- return metrics
864
- }
865
-
866
- function syntheticMetrics(payload: unknown): QuotaMetric[] {
867
- if (
868
- !isRecord(payload) ||
869
- !isRecord(payload.rollingFiveHourLimit) ||
870
- !isRecord(payload.weeklyTokenLimit)
871
- ) {
872
- throw new SafeAdapterError('provider_error')
873
- }
874
- const fiveHourLimit = finiteAmount(payload.rollingFiveHourLimit.max)
875
- const fiveHourRemaining = finiteAmount(payload.rollingFiveHourLimit.remaining)
876
- if (
877
- fiveHourLimit === undefined ||
878
- fiveHourLimit <= 0 ||
879
- fiveHourRemaining === undefined ||
880
- fiveHourRemaining > fiveHourLimit
881
- ) {
882
- throw new SafeAdapterError('provider_error')
883
- }
884
- const creditAmount = (value: unknown): number | undefined => {
885
- if (typeof value !== 'string') return undefined
886
- const match = /^\$(\d+)(?:\.(\d{1,2}))?$/.exec(value.trim())
887
- if (!match) return undefined
888
- return finiteAmount(`${match[1]}.${(match[2] ?? '').padEnd(2, '0')}`)
889
- }
890
- const weeklyLimit = creditAmount(payload.weeklyTokenLimit.maxCredits)
891
- const weeklyRemaining = creditAmount(payload.weeklyTokenLimit.remainingCredits)
892
- if (
893
- weeklyLimit === undefined ||
894
- weeklyLimit <= 0 ||
895
- weeklyRemaining === undefined ||
896
- weeklyRemaining > weeklyLimit
897
- ) {
898
- throw new SafeAdapterError('provider_error')
899
- }
900
- return [
901
- {
902
- kind: 'provider_quota',
903
- used: fiveHourLimit - fiveHourRemaining,
904
- remaining: fiveHourRemaining,
905
- unit: 'units',
906
- label: 'Rolling five-hour limit',
907
- },
908
- {
909
- kind: 'provider_quota',
910
- used: weeklyLimit - weeklyRemaining,
911
- remaining: weeklyRemaining,
912
- unit: 'USD',
913
- label: 'Weekly credit limit',
914
- },
915
- ]
916
- }
917
-
918
- function percentage(value: unknown): number | undefined {
919
- const parsed = finiteAmount(value)
920
- return parsed !== undefined && parsed <= 100 ? parsed : undefined
921
- }
922
-
923
- function isoResetAt(value: unknown): number | undefined {
924
- return typeof value === 'string' && isValidResetDate(value) ? Date.parse(value) : undefined
925
- }
926
-
927
- function epochResetAt(value: unknown, unit: 'seconds' | 'milliseconds'): number | undefined {
928
- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined
929
- const timestamp = unit === 'seconds' ? value * 1_000 : value
930
- return Number.isFinite(new Date(timestamp).getTime()) ? timestamp : undefined
931
- }
932
-
933
- function anthropicMetrics(payload: unknown): QuotaMetric[] {
934
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
935
- const metrics: QuotaMetric[] = []
936
- const windows = [
937
- { key: 'five_hour', label: '5-hour quota', period: '5h' },
938
- { key: 'seven_day', label: 'Weekly quota', period: 'week' },
939
- ] as const
940
- for (const window of windows) {
941
- const value = payload[window.key]
942
- if (value === undefined || value === null) continue
943
- if (!isRecord(value)) throw new SafeAdapterError('provider_error')
944
- const used = percentage(
945
- value.utilization ??
946
- value.used_percentage ??
947
- value.usedPercentage ??
948
- value.used_percent ??
949
- value.usedPercent ??
950
- value.percent_used ??
951
- value.percentUsed,
952
- )
953
- if (used === undefined) throw new SafeAdapterError('provider_error')
954
- const resetsAt = isoResetAt(value.resets_at)
955
- metrics.push({
956
- kind: 'provider_quota',
957
- used,
958
- remaining: 100 - used,
959
- unit: '%',
960
- label: window.label,
961
- period: window.period,
962
- ...(resetsAt === undefined ? {} : { resetsAt }),
963
- })
964
- }
965
- const extra = payload.extra_usage
966
- if (isRecord(extra) && extra.is_enabled === true) {
967
- const used = percentage(extra.utilization)
968
- if (used === undefined) throw new SafeAdapterError('provider_error')
969
- metrics.push({
970
- kind: 'provider_quota',
971
- used,
972
- remaining: 100 - used,
973
- unit: '%',
974
- label: 'Extra usage limit',
975
- period: 'reported',
976
- })
977
- }
978
- return metrics
979
- }
980
-
981
- function copilotMetrics(payload: unknown): QuotaMetric[] {
982
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
983
- const snapshots = isRecord(payload.quota_snapshots) ? payload.quota_snapshots : undefined
984
- const quota =
985
- snapshots && isRecord(snapshots.premium_interactions)
986
- ? snapshots.premium_interactions
987
- : undefined
988
- if (!quota) throw new SafeAdapterError('provider_error')
989
- if (quota.unlimited === true) {
990
- return [{ kind: 'provider_status', status: 'active', label: 'Unlimited Copilot plan' }]
991
- }
992
- const total = finiteAmount(quota.entitlement)
993
- const remaining = finiteAmount(quota.quota_remaining ?? quota.remaining)
994
- const resetsAt = isoResetAt(payload.quota_reset_date_utc)
995
- if (total !== undefined && total > 0 && remaining !== undefined && remaining <= total) {
996
- return [
997
- {
998
- kind: 'provider_quota',
999
- used: total - remaining,
1000
- remaining,
1001
- unit: 'premium interactions',
1002
- label: 'Copilot user quota',
1003
- period: 'month',
1004
- ...(resetsAt === undefined ? {} : { resetsAt }),
1005
- },
1006
- ]
1007
- }
1008
- if (quota.percent_remaining !== undefined) {
1009
- const percentRemaining = percentage(quota.percent_remaining)
1010
- if (percentRemaining !== undefined) {
1011
- return [
1012
- {
1013
- kind: 'provider_quota',
1014
- used: 100 - percentRemaining,
1015
- remaining: percentRemaining,
1016
- unit: '%',
1017
- label: 'Copilot user quota',
1018
- period: 'month',
1019
- ...(resetsAt === undefined ? {} : { resetsAt }),
1020
- },
1021
- ]
1022
- }
1023
- }
1024
- throw new SafeAdapterError('provider_error')
1025
- }
1026
-
1027
- function googleAgyMetrics(payload: unknown): QuotaMetric[] {
1028
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
1029
- const rows: Record<string, unknown>[] = []
1030
- if (Array.isArray(payload.buckets)) {
1031
- if (payload.buckets.length > MAX_PROVIDER_METRICS) throw new SafeAdapterError('provider_error')
1032
- for (const bucket of payload.buckets) {
1033
- if (isRecord(bucket)) rows.push(bucket)
1034
- }
1035
- }
1036
- if (Array.isArray(payload.groups)) {
1037
- if (payload.groups.length > MAX_PROVIDER_METRICS) throw new SafeAdapterError('provider_error')
1038
- for (const group of payload.groups) {
1039
- if (!isRecord(group) || !Array.isArray(group.buckets)) continue
1040
- if (group.buckets.length > MAX_PROVIDER_METRICS) throw new SafeAdapterError('provider_error')
1041
- for (const bucket of group.buckets) {
1042
- if (isRecord(bucket)) rows.push(bucket)
1043
- }
1044
- }
1045
- }
1046
- if (rows.length > MAX_PROVIDER_METRICS) throw new SafeAdapterError('provider_error')
1047
- const metrics: QuotaMetric[] = []
1048
- for (const bucket of rows) {
1049
- const remainingFraction = bucket.remainingFraction
1050
- if (
1051
- typeof remainingFraction !== 'number' ||
1052
- !Number.isFinite(remainingFraction) ||
1053
- remainingFraction < 0 ||
1054
- remainingFraction > 1
1055
- ) {
1056
- continue
1057
- }
1058
- const label = `AGY quota ${metrics.length + 1}`
1059
- const period =
1060
- typeof bucket.window === 'string' &&
1061
- ['weekly', 'five_hour', 'monthly', 'daily'].includes(bucket.window.trim())
1062
- ? bucket.window.trim()
1063
- : undefined
1064
- metrics.push({
1065
- kind: 'provider_quota',
1066
- used: 100 - Math.round(remainingFraction * 100),
1067
- remaining: Math.round(remainingFraction * 100),
1068
- unit: '%',
1069
- label,
1070
- ...(period ? { period } : {}),
1071
- })
1072
- }
1073
- if (metrics.length === 0) throw new SafeAdapterError('provider_error')
1074
- return metrics
1075
- }
1076
-
1077
- function openCodeGoMetrics(payload: unknown): QuotaMetric[] {
1078
- if (!isRecord(payload) || !isRecord(payload.usage)) throw new SafeAdapterError('invalid_response')
1079
- const windows = [
1080
- { key: 'rolling', label: '5-hour quota' },
1081
- { key: 'weekly', label: 'Weekly quota' },
1082
- { key: 'monthly', label: 'Monthly quota' },
1083
- ] as const
1084
- const metrics: QuotaMetric[] = []
1085
- for (const window of windows) {
1086
- const value = payload.usage[window.key]
1087
- if (!isRecord(value) || (value.status !== 'ok' && value.status !== 'rate-limited')) {
1088
- throw new SafeAdapterError('invalid_response')
1089
- }
1090
- const used = percentage(value.percent)
1091
- if (used === undefined) throw new SafeAdapterError('invalid_response')
1092
- const resetValue = value.resetsAt
1093
- const resetsAt =
1094
- typeof resetValue === 'string' && isValidResetDate(resetValue)
1095
- ? Date.parse(resetValue)
1096
- : undefined
1097
- const normalizedUsed = value.status === 'rate-limited' ? 100 : used
1098
- metrics.push({
1099
- kind: 'provider_quota',
1100
- used: normalizedUsed,
1101
- remaining: 100 - normalizedUsed,
1102
- unit: '%',
1103
- label: window.label,
1104
- period: window.key,
1105
- ...(resetsAt === undefined ? {} : { resetsAt }),
1106
- })
1107
- }
1108
- return metrics
1109
- }
1110
-
1111
- const OPENCODE_GO_KEY_USAGE_URL = 'https://opencode.ai/zen/go/v1/usage'
1112
- const OPENCODE_GO_KEY_USAGE_HEADERS = {
1113
- 'x-opencode-session': 'pantheon-quota',
1114
- 'user-agent': 'Pantheon-Quota/1.0',
1115
- } as const
1116
- const OPENCODE_GO_CONSOLE_STATUS_URL = 'https://opencode.ai/console/api/go/status'
1117
- const RESET_DATE_PATTERN =
1118
- /^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/
1119
-
1120
- function isValidResetDate(value: string): boolean {
1121
- const match = RESET_DATE_PATTERN.exec(value)
1122
- if (!match) return false
1123
-
1124
- const year = Number(match[1])
1125
- const month = Number(match[2])
1126
- const day = Number(match[3])
1127
- const isLeapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
1128
- const daysInMonth = [31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
1129
- const maxDay = daysInMonth[month - 1]
1130
-
1131
- return (
1132
- month >= 1 &&
1133
- month <= 12 &&
1134
- day >= 1 &&
1135
- maxDay !== undefined &&
1136
- day <= maxDay &&
1137
- Number.isFinite(Date.parse(value))
1138
- )
1139
- }
1140
-
1141
- function openCodeGoConsoleMetrics(payload: unknown): QuotaMetric[] {
1142
- if (!isRecord(payload)) {
1143
- throw new SafeAdapterError('invalid_response')
1144
- }
1145
- if (!Object.hasOwn(payload, 'access') || payload.access === null) {
1146
- throw new SafeAdapterError('not_subscribed')
1147
- }
1148
- if (!isRecord(payload.access)) throw new SafeAdapterError('invalid_response')
1149
- if (!isRecord(payload.access.meters)) throw new SafeAdapterError('invalid_response')
1150
-
1151
- const accessEndsAt = payload.access.endsAt
1152
- const monthlyFallbackReset =
1153
- typeof accessEndsAt === 'string' && isValidResetDate(accessEndsAt)
1154
- ? Date.parse(accessEndsAt)
1155
- : undefined
1156
- const meters = payload.access.meters
1157
- const windows = [
1158
- { key: 'fiveHour', label: '5-hour quota', period: 'rolling' },
1159
- { key: 'week', label: 'Weekly quota', period: 'weekly' },
1160
- { key: 'month', label: 'Monthly quota', period: 'monthly' },
1161
- ] as const
1162
- const metrics: QuotaMetric[] = []
1163
- for (const window of windows) {
1164
- const meter = meters[window.key]
1165
- if (!isRecord(meter)) throw new SafeAdapterError('invalid_response')
1166
- const limit = finiteAmount(meter.limitMicroCents)
1167
- const used = finiteAmount(meter.usedMicroCents)
1168
- if (limit === undefined || used === undefined) throw new SafeAdapterError('invalid_response')
1169
-
1170
- const resetValue = meter.resetsAt
1171
- const meterReset =
1172
- typeof resetValue === 'string' && isValidResetDate(resetValue)
1173
- ? Date.parse(resetValue)
1174
- : undefined
1175
- const resetsAt = meterReset ?? (window.period === 'monthly' ? monthlyFallbackReset : undefined)
1176
-
1177
- const usedPercent =
1178
- limit === 0
1179
- ? used > 0
1180
- ? 100
1181
- : 0
1182
- : Math.min(100, Math.max(0, Math.round((used / limit) * 100)))
1183
- metrics.push({
1184
- kind: 'provider_quota',
1185
- used: usedPercent,
1186
- remaining: 100 - usedPercent,
1187
- unit: '%',
1188
- label: window.label,
1189
- period: window.period,
1190
- ...(resetsAt === undefined ? {} : { resetsAt }),
1191
- })
1192
- }
1193
- return metrics
1194
- }
1195
-
1196
- function openAIMetrics(payload: unknown): QuotaMetric[] {
1197
- if (!isRecord(payload) || !isRecord(payload.rate_limit)) {
1198
- throw new SafeAdapterError('invalid_response')
1199
- }
1200
- const windows = [
1201
- { key: 'primary_window', fallback: '5-hour ChatGPT quota', period: '5h' },
1202
- { key: 'secondary_window', fallback: 'Weekly ChatGPT quota', period: 'week' },
1203
- ] as const
1204
- const metrics: QuotaMetric[] = []
1205
- for (const window of windows) {
1206
- const value = payload.rate_limit[window.key]
1207
- if (value === undefined || value === null) continue
1208
- if (!isRecord(value)) throw new SafeAdapterError('invalid_response')
1209
- const used = percentage(value.used_percent)
1210
- if (used === undefined) continue
1211
- const period =
1212
- value.limit_window_seconds === 18000
1213
- ? '5h'
1214
- : value.limit_window_seconds === 604800
1215
- ? 'week'
1216
- : value.limit_window_seconds === 2628000
1217
- ? 'month'
1218
- : window.period
1219
- const label =
1220
- period === 'month'
1221
- ? 'Monthly ChatGPT quota'
1222
- : period === 'week'
1223
- ? 'Weekly ChatGPT quota'
1224
- : window.fallback
1225
- const resetsAt = epochResetAt(value.reset_at, 'seconds')
1226
- metrics.push({
1227
- kind: 'provider_quota',
1228
- used,
1229
- remaining: 100 - used,
1230
- unit: '%',
1231
- label,
1232
- period,
1233
- ...(resetsAt === undefined ? {} : { resetsAt }),
1234
- })
1235
- }
1236
- if (metrics.length === 0) throw new SafeAdapterError('invalid_response')
1237
- return metrics
1238
- }
1239
-
1240
- const OPENCODE_ZEN_BASE_URL = 'https://opencode.ai/console/api'
1241
- const BILLING_UNITS_PER_DOLLAR = 100_000_000
1242
-
1243
- function parseConsoleBalance(payload: unknown): number {
1244
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
1245
- const value = finiteAmount(payload.balanceMicroCents)
1246
- if (value === undefined) throw new SafeAdapterError('provider_error')
1247
- return value / BILLING_UNITS_PER_DOLLAR
1248
- }
1249
-
1250
- function parseConsoleCreditLimit(payload: unknown): number | undefined {
1251
- if (!isRecord(payload)) throw new SafeAdapterError('provider_error')
1252
- if (payload.creditLimitMicroCents === null) return undefined
1253
- const value = finiteAmount(payload.creditLimitMicroCents)
1254
- if (value === undefined) throw new SafeAdapterError('provider_error')
1255
- return value / BILLING_UNITS_PER_DOLLAR
1256
- }
1257
-
1258
- function parseConsoleMonthlyUsage(payload: unknown, now = new Date()): number {
1259
- if (!Array.isArray(payload) || payload.length > 366) throw new SafeAdapterError('provider_error')
1260
- const month = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`
1261
- let total = 0
1262
- for (const row of payload) {
1263
- if (!isRecord(row) || typeof row.date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(row.date)) {
1264
- throw new SafeAdapterError('provider_error')
1265
- }
1266
- const amount = finiteAmount(row.totalCostMicroCents)
1267
- if (amount === undefined) throw new SafeAdapterError('provider_error')
1268
- if (row.date.startsWith(month)) total += amount
1269
- }
1270
- const amount = finiteAmount(total)
1271
- if (amount === undefined) throw new SafeAdapterError('provider_error')
1272
- return amount / BILLING_UNITS_PER_DOLLAR
1273
- }
1274
-
1275
- async function openCodeZenMetrics(
1276
- secret: string,
1277
- shutdownSignal: AbortSignal,
1278
- context: QuotaAdapterContext,
1279
- ): Promise<QuotaMetric[]> {
1280
- const headers =
1281
- context.orgId && /^[A-Za-z0-9_-]{1,128}$/.test(context.orgId)
1282
- ? { 'x-org-id': context.orgId }
1283
- : {}
1284
- const routes = await Promise.allSettled([
1285
- requestJson(`${OPENCODE_ZEN_BASE_URL}/billing/status`, secret, shutdownSignal, 'bearer', {
1286
- headers,
1287
- }),
1288
- requestJson(`${OPENCODE_ZEN_BASE_URL}/billing/account`, secret, shutdownSignal, 'bearer', {
1289
- headers,
1290
- }),
1291
- requestJson(`${OPENCODE_ZEN_BASE_URL}/usage/cost-by-day`, secret, shutdownSignal, 'bearer', {
1292
- headers,
1293
- }),
1294
- ])
1295
- const balance = routes[0]
1296
- if (balance?.status !== 'fulfilled') throw new SafeAdapterError('provider_error')
1297
- const metrics: QuotaMetric[] = [
1298
- {
1299
- kind: 'balance',
1300
- amount: parseConsoleBalance(balance.value),
1301
- currency: 'USD',
1302
- label: 'Console balance',
1303
- },
1304
- ]
1305
- const account = routes[1]
1306
- const usage = routes[2]
1307
- if (account?.status === 'fulfilled' && usage?.status === 'fulfilled') {
1308
- const limit = parseConsoleCreditLimit(account.value)
1309
- if (limit !== undefined) {
1310
- const spent = parseConsoleMonthlyUsage(usage.value)
1311
- metrics.push({
1312
- kind: 'provider_quota',
1313
- used: spent,
1314
- remaining: Math.max(0, limit - spent),
1315
- unit: 'USD',
1316
- label: 'Monthly credit limit',
1317
- period: 'month',
1318
- })
1319
- }
1320
- }
1321
- return metrics
1322
- }
1323
-
1324
- const XAI_SUBSCRIPTIONS_URL = 'https://grok.com/rest/subscriptions'
1325
- const XAI_BILLING_URL = 'https://cli-chat-proxy.grok.com/v1/billing?format=credits'
1326
- const XAI_HEADERS = {
1327
- 'user-agent': 'OpenCode-Quota-Toast/1.0',
1328
- 'x-grok-client-surface': 'grok-build',
1329
- 'x-grok-client-version': '1.0.0',
1330
- }
1331
-
1332
- async function xaiSuperGrokMetrics(
1333
- secret: string,
1334
- shutdownSignal: AbortSignal,
1335
- ): Promise<QuotaMetric[]> {
1336
- const subscriptionPayload = await requestJson(
1337
- XAI_SUBSCRIPTIONS_URL,
1338
- secret,
1339
- shutdownSignal,
1340
- 'bearer',
1341
- { headers: XAI_HEADERS },
1342
- )
1343
- if (!isRecord(subscriptionPayload) || !Array.isArray(subscriptionPayload.subscriptions)) {
1344
- throw new SafeAdapterError('eligibility_unverified')
1345
- }
1346
- const eligible = subscriptionPayload.subscriptions.some(
1347
- (subscription) =>
1348
- isRecord(subscription) &&
1349
- subscription.status === 'SUBSCRIPTION_STATUS_ACTIVE' &&
1350
- typeof subscription.tier === 'string' &&
1351
- /^SUBSCRIPTION_TIER_SUPER_GROK(?:_PRO|_LITE|_HEAVY)?$/.test(subscription.tier),
1352
- )
1353
- if (!eligible) throw new SafeAdapterError('eligibility_unverified')
1354
-
1355
- const billingPayload = await requestJson(XAI_BILLING_URL, secret, shutdownSignal, 'bearer', {
1356
- headers: XAI_HEADERS,
1357
- })
1358
- if (!isRecord(billingPayload) || !isRecord(billingPayload.config)) {
1359
- throw new SafeAdapterError('provider_error')
1360
- }
1361
- const config = billingPayload.config
1362
- const usage = config.creditUsagePercent
1363
- const used = usage === undefined ? undefined : percentage(usage)
1364
- if (used === undefined) throw new SafeAdapterError('provider_error')
1365
- return [
1366
- {
1367
- kind: 'provider_quota',
1368
- used,
1369
- remaining: 100 - used,
1370
- unit: '%',
1371
- label: 'SuperGrok billing period',
1372
- period: 'billing period',
1373
- },
1374
- ]
1375
- }
1376
-
1377
- export async function runQuotaAdapter(
1378
- provider: QuotaProviderId,
1379
- secret: string | undefined,
1380
- shutdownSignal: AbortSignal,
1381
- queryCli: typeof queryAlibabaTokenPlanUsage = queryAlibabaTokenPlanUsage,
1382
- adapterContext: QuotaAdapterContext = {},
1383
- fallbackSecret?: string,
1384
- ): Promise<AdapterResult> {
1385
- const definition = QUOTA_PROVIDER_CATALOG[provider]
1386
- if (!definition.adapter) return { reason: 'provider_error' }
1387
- if (definition.adapter === 'openai' && !isOpenAICodexOAuthMethod(adapterContext?.methodID)) {
1388
- return { reason: 'eligibility_unverified' }
1389
- }
1390
- if (definition.adapter === 'alibaba-token-plan-cli') {
1391
- const result = await queryCli(shutdownSignal)
1392
- if ('reason' in result) return result
1393
- return available([
1394
- {
1395
- kind: 'provider_quota',
1396
- used: result.percentage * 100,
1397
- remaining: (1 - result.percentage) * 100,
1398
- unit: '%',
1399
- label: 'Monthly token-plan quota',
1400
- period: 'month',
1401
- },
1402
- ])
1403
- }
1404
- if (!secret) return { reason: 'provider_error' }
1405
- try {
1406
- if (definition.adapter === 'anthropic') {
1407
- const payload = await requestJson(
1408
- 'https://api.anthropic.com/api/oauth/usage',
1409
- secret,
1410
- shutdownSignal,
1411
- 'bearer',
1412
- { headers: { 'anthropic-beta': 'oauth-2025-04-20' } },
1413
- )
1414
- return available(anthropicMetrics(payload))
1415
- }
1416
- if (definition.adapter === 'copilot') {
1417
- const payload = await requestJson(
1418
- 'https://api.github.com/copilot_internal/user',
1419
- secret,
1420
- shutdownSignal,
1421
- 'bearer',
1422
- {
1423
- headers: {
1424
- 'x-github-api-version': '2026-03-10',
1425
- 'user-agent': 'opencode-quota/copilot-billing',
1426
- },
1427
- },
1428
- )
1429
- return available(copilotMetrics(payload))
1430
- }
1431
- if (definition.adapter === 'google-agy') {
1432
- if (!adapterContext.projectId || !/^[A-Za-z0-9._:-]{1,128}$/.test(adapterContext.projectId)) {
1433
- throw new SafeAdapterError('eligibility_unverified')
1434
- }
1435
- const payload = await requestJson(
1436
- 'https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary',
1437
- secret,
1438
- shutdownSignal,
1439
- 'bearer',
1440
- {
1441
- method: 'POST',
1442
- body: JSON.stringify({ project: adapterContext.projectId }),
1443
- headers: {
1444
- 'content-type': 'application/json',
1445
- 'user-agent': 'antigravity/cli/1.3.5',
1446
- 'x-activity-request-id': randomUUID(),
1447
- },
1448
- },
1449
- )
1450
- return available(googleAgyMetrics(payload))
1451
- }
1452
- if (definition.adapter === 'opencode-go') {
1453
- if (
1454
- adapterContext?.methodID !== undefined &&
1455
- !isOpenCodeConsoleOAuthMethod(adapterContext.methodID)
1456
- ) {
1457
- throw new SafeAdapterError('eligibility_unverified')
1458
- }
1459
- if (isOpenCodeConsoleOAuthMethod(adapterContext?.methodID)) {
1460
- const headers = adapterContext.orgId ? { 'x-org-id': adapterContext.orgId } : {}
1461
- try {
1462
- const payload = await requestJson(
1463
- OPENCODE_GO_CONSOLE_STATUS_URL,
1464
- secret,
1465
- shutdownSignal,
1466
- 'bearer',
1467
- { headers },
1468
- )
1469
- return { ...available(openCodeGoConsoleMetrics(payload)), routeKind: 'console_oauth' }
1470
- } catch (error) {
1471
- const failure =
1472
- error instanceof SafeAdapterError ? error : new SafeAdapterError('provider_error')
1473
- if (failure.reason === 'not_subscribed' || failure.httpStatus === 404) {
1474
- return { reason: 'not_subscribed', routeKind: 'console_oauth' }
1475
- }
1476
- if (!fallbackSecret || shutdownSignal.aborted) {
1477
- return {
1478
- reason: failure.reason,
1479
- ...(failure.retryAfterMs === undefined ? {} : { retryAfterMs: failure.retryAfterMs }),
1480
- routeKind: 'console_oauth',
1481
- }
1482
- }
1483
- }
1484
-
1485
- try {
1486
- const payload = await requestJson(
1487
- OPENCODE_GO_KEY_USAGE_URL,
1488
- fallbackSecret,
1489
- shutdownSignal,
1490
- 'bearer',
1491
- { headers: OPENCODE_GO_KEY_USAGE_HEADERS },
1492
- )
1493
- return { ...available(openCodeGoMetrics(payload)), routeKind: 'api_key' }
1494
- } catch (error) {
1495
- const failure =
1496
- error instanceof SafeAdapterError ? error : new SafeAdapterError('provider_error')
1497
- return {
1498
- reason: failure.reason,
1499
- ...(failure.retryAfterMs === undefined ? {} : { retryAfterMs: failure.retryAfterMs }),
1500
- routeKind: 'api_key',
1501
- }
1502
- }
1503
- }
1504
- const payload = await requestJson(
1505
- OPENCODE_GO_KEY_USAGE_URL,
1506
- secret,
1507
- shutdownSignal,
1508
- 'bearer',
1509
- { headers: OPENCODE_GO_KEY_USAGE_HEADERS },
1510
- )
1511
- return { ...available(openCodeGoMetrics(payload)), routeKind: 'api_key' }
1512
- }
1513
- if (definition.adapter === 'openai') {
1514
- const payload = await requestJson(
1515
- 'https://chatgpt.com/backend-api/wham/usage',
1516
- secret,
1517
- shutdownSignal,
1518
- 'bearer',
1519
- { headers: { 'user-agent': 'OpenCode-Quota-Toast/1.0' } },
1520
- )
1521
- return available(openAIMetrics(payload))
1522
- }
1523
- if (definition.adapter === 'opencode-zen') {
1524
- return available(await openCodeZenMetrics(secret, shutdownSignal, adapterContext))
1525
- }
1526
- if (definition.adapter === 'xai-supergrok') {
1527
- return available(await xaiSuperGrokMetrics(secret, shutdownSignal))
1528
- }
1529
- } catch (error) {
1530
- if (error instanceof SafeAdapterError) {
1531
- return {
1532
- reason: error.reason,
1533
- ...(error.retryAfterMs === undefined ? {} : { retryAfterMs: error.retryAfterMs }),
1534
- }
1535
- }
1536
- return { reason: 'provider_error' }
1537
- }
1538
- const url = {
1539
- chutes: 'https://api.chutes.ai/users/me/quota_usage/me',
1540
- deepseek: 'https://api.deepseek.com/user/balance',
1541
- 'kilo-gateway':
1542
- 'https://app.kilo.ai/api/trpc/kiloPass.getState?batch=1&input=%7B%220%22%3Anull%7D',
1543
- 'kimi-global': 'https://api.kimi.ai/coding/v1/usages',
1544
- 'kimi-cn': 'https://api.kimi.com/coding/v1/usages',
1545
- 'minimax-global': 'https://api.minimax.io/v1/api/openplatform/coding_plan/remains',
1546
- 'minimax-cn': 'https://api.minimaxi.com/v1/token_plan/remains',
1547
- nanogpt: 'https://nano-gpt.com/api/subscription/v1/usage',
1548
- 'ollama-cloud': 'https://ollama.com/api/balance',
1549
- openrouter: 'https://openrouter.ai/api/v1/key',
1550
- synthetic: 'https://api.synthetic.new/v2/quotas',
1551
- zai: 'https://api.z.ai/api/monitor/usage/quota/limit',
1552
- zhipu: 'https://bigmodel.cn/api/monitor/usage/quota/limit',
1553
- }[definition.adapter]
1554
- try {
1555
- if (definition.adapter === 'kilo-gateway') {
1556
- const subscriptionPayload = await requestJson(url, secret, shutdownSignal)
1557
- const passMetrics = kiloPassMetrics(subscriptionPayload)
1558
- if (passMetrics) return available(passMetrics)
1559
- const balancePayload = await requestJson(
1560
- 'https://api.kilo.ai/api/profile/balance',
1561
- secret,
1562
- shutdownSignal,
1563
- )
1564
- return available(kiloBalanceMetrics(balancePayload))
1565
- }
1566
- if (definition.adapter === 'nanogpt') {
1567
- return available(await nanoGptMetrics(secret, shutdownSignal))
1568
- }
1569
- const payload = await requestJson(
1570
- url,
1571
- secret,
1572
- shutdownSignal,
1573
- definition.adapter === 'zai' || definition.adapter === 'zhipu' ? 'direct' : 'bearer',
1574
- )
1575
- const metrics = {
1576
- chutes: chutesMetrics,
1577
- deepseek: deepseekMetrics,
1578
- 'kimi-global': kimiMetrics,
1579
- 'kimi-cn': kimiMetrics,
1580
- 'minimax-global': (value: unknown) => minimaxMetrics(value, 'global'),
1581
- 'minimax-cn': (value: unknown) => minimaxMetrics(value, 'cn'),
1582
- 'ollama-cloud': ollamaMetrics,
1583
- openrouter: openRouterMetrics,
1584
- synthetic: syntheticMetrics,
1585
- zai: (value: unknown) => glmMetrics(value, 'zai'),
1586
- zhipu: (value: unknown) => glmMetrics(value, 'zhipu'),
1587
- }[definition.adapter](payload)
1588
- return available(metrics)
1589
- } catch (error) {
1590
- if (error instanceof SafeAdapterError) {
1591
- return {
1592
- reason: error.reason,
1593
- ...(error.retryAfterMs === undefined ? {} : { retryAfterMs: error.retryAfterMs }),
1594
- }
1595
- }
1596
- return { reason: 'provider_error' }
1597
- }
1598
- }