pantheon-opencode 1.6.1 → 1.6.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +29 -0
  4. package/README.md +100 -19
  5. package/README.pt-BR.md +27 -11
  6. package/bin/pantheon-init.mjs +106 -19
  7. package/package.json +3 -2
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +1 -1
  11. package/scripts/doctor.mjs +213 -45
  12. package/scripts/install/agents-md.mjs +2 -1
  13. package/scripts/install/config-migration.mjs +344 -393
  14. package/scripts/install/config-paths.mjs +15 -0
  15. package/scripts/install/mcp-permissions.mjs +164 -0
  16. package/scripts/install/opencode-version.mjs +31 -13
  17. package/scripts/install/opencode-wildcard.mjs +106 -0
  18. package/scripts/install/opencode.mjs +240 -69
  19. package/scripts/install/plan-artifact.mjs +12 -1
  20. package/scripts/install/plugin.mjs +17 -1
  21. package/scripts/install/v2-capabilities.mjs +5 -6
  22. package/scripts/package-evidence.mjs +1 -0
  23. package/scripts/sandbox-env.sh +174 -0
  24. package/scripts/setup-v2-config.mjs +1703 -0
  25. package/scripts/setup.mjs +415 -0
  26. package/scripts/sync-tui.mjs +9 -1
  27. package/scripts/test-opencode-v2-sandbox.sh +438 -151
  28. package/scripts/update-skills-lock.mjs +30 -0
  29. package/skills-lock.json +10 -10
  30. package/src/agents/aphrodite.md +5 -2
  31. package/src/agents/apollo.md +5 -0
  32. package/src/agents/athena.md +6 -1
  33. package/src/agents/demeter.md +5 -1
  34. package/src/agents/gaia.md +4 -0
  35. package/src/agents/hephaestus.md +6 -1
  36. package/src/agents/hermes.md +6 -3
  37. package/src/agents/iris.md +5 -1
  38. package/src/agents/mnemosyne.md +20 -50
  39. package/src/agents/nyx.md +5 -1
  40. package/src/agents/prometheus.md +4 -0
  41. package/src/agents/talos.md +4 -0
  42. package/src/agents/themis.md +4 -0
  43. package/src/agents/zeus.md +9 -3
  44. package/src/instructions/agent-return-format.instructions.md +1 -1
  45. package/src/instructions/memory-protocol.instructions.md +3 -3
  46. package/src/instructions/test-economy.instructions.md +6 -6
  47. package/src/mcp/pantheon_vision.py +37 -36
  48. package/src/pantheon/cost-command.ts +30 -133
  49. package/src/pantheon/model-pricing.ts +1 -536
  50. package/src/pantheon/v2-vision.ts +34 -29
  51. package/src/pantheon/vision.ts +43 -10
  52. package/src/plugin-v2.ts +30 -53
  53. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  54. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
  55. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
  56. package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
  57. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
  58. package/src/plugins/tui/dist/quota-adapters.js +1142 -0
  59. package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
  60. package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
  61. package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
  62. package/src/plugins/tui/dist/quota-cli.js +184 -0
  63. package/src/plugins/tui/dist/quota-cli.js.map +1 -0
  64. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +684 -0
  65. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
  66. package/src/plugins/tui/dist/server-v2.d.ts +14 -0
  67. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  68. package/src/plugins/tui/dist/server-v2.js +796 -0
  69. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  70. package/src/plugins/tui/dist/tui-v2.d.ts +375 -53
  71. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  72. package/src/plugins/tui/dist/tui-v2.js +5876 -530
  73. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  74. package/src/plugins/tui/dist/tui.js +1 -1
  75. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
  76. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
  77. package/src/plugins/tui/dist/usage-history-worker.js +25 -0
  78. package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
  79. package/src/plugins/tui/index-v2.ts +3 -6
  80. package/src/plugins/tui/package-lock.json +17 -2
  81. package/src/plugins/tui/package.json +6 -3
  82. package/src/plugins/tui/src/context-gauge.ts +59 -0
  83. package/src/plugins/tui/src/cost-data.ts +607 -0
  84. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
  85. package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
  86. package/src/plugins/tui/src/index-v2.tsx +231 -240
  87. package/src/plugins/tui/src/model-pricing.ts +536 -0
  88. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  89. package/src/plugins/tui/src/quota-adapters.ts +1598 -0
  90. package/src/plugins/tui/src/quota-cli.ts +237 -0
  91. package/src/plugins/tui/src/quota-rpc.ts +373 -0
  92. package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
  93. package/src/plugins/tui/src/quota-v2.tsx +1238 -0
  94. package/src/plugins/tui/src/server-v2.ts +985 -0
  95. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  96. package/src/plugins/tui/src/usage-history-contract.ts +217 -0
  97. package/src/plugins/tui/src/usage-history-validation.ts +104 -0
  98. package/src/plugins/tui/src/usage-history-view.tsx +236 -0
  99. package/src/plugins/tui/src/usage-history-worker.ts +25 -0
  100. package/src/plugins/tui/src/usage-view-model.ts +272 -0
  101. package/src/plugins/tui/tsconfig.typecheck.json +6 -1
  102. package/src/plugins/tui/tsdown.config.ts +44 -5
  103. package/src/routing.yml +72 -13
  104. package/src/skills/README.md +4 -0
  105. package/src/skills/agent-coordination/SKILL.md +0 -3
  106. package/src/skills/artifact-management/SKILL.md +0 -3
  107. package/src/skills/auto-continue/SKILL.md +0 -3
  108. package/src/skills/code-review-checklist/SKILL.md +0 -3
  109. package/src/skills/context-compression/SKILL.md +0 -3
  110. package/src/skills/memory-bank/SKILL.md +6 -28
  111. package/src/skills/session-goal/SKILL.md +0 -3
  112. package/src/skills/simplify/SKILL.md +5 -4
  113. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  114. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  115. package/src/pantheon/memory-context.ts +0 -1017
@@ -0,0 +1,985 @@
1
+ import { Worker } from 'node:worker_threads'
2
+ import { Plugin } from '@opencode/plugin'
3
+ import type { Context } from '@opencode/plugin/promise/plugin'
4
+ import type { RpcCallContext, RpcRegistration } from '@opencode/plugin/promise/rpc'
5
+ import { estimateActiveContextCost } from './cost-data'
6
+ import { createGoKeyDiagnostic } from './go-key-diagnostic'
7
+ import {
8
+ isOpenAICodexOAuthMethod,
9
+ isOpenCodeConsoleOAuthMethod,
10
+ QUOTA_PROVIDER_CATALOG,
11
+ type QuotaAdapterContext,
12
+ type QuotaMetric,
13
+ runQuotaAdapter,
14
+ } from './quota-adapters'
15
+ import { queryAlibabaTokenPlanUsage } from './quota-cli'
16
+ import {
17
+ type OpenCodeGoRouteKind,
18
+ QUOTA_PROVIDER_IDS,
19
+ type QuotaProviderId,
20
+ quotaRpc,
21
+ } from './quota-rpc'
22
+ import {
23
+ isUsageHistoryPeriod,
24
+ MAX_HISTORY_QUERY_MS,
25
+ type UsageHistoryRpcResult,
26
+ } from './usage-history-contract'
27
+
28
+ const CREDENTIAL_CACHE_TTL_MS = 30_000
29
+ const ADAPTER_CACHE_TTL_MS = 20_000
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
+
96
+ type ResolvedCredential = {
97
+ readonly method?: 'oauth' | 'key' | 'unsupported'
98
+ readonly routeKind?: OpenCodeGoRouteKind
99
+ /** Only adapters receive this secret; blocked sources retain only method status. */
100
+ readonly secret?: string
101
+ /** OpenCode Go's fixed API-key fallback after its Console OAuth request fails. */
102
+ readonly fallbackSecret?: string
103
+ /** A tiny, non-secret projection of OAuth metadata required by fixed adapters. */
104
+ readonly adapterContext?: QuotaAdapterContext
105
+ }
106
+ type CachedCredential = {
107
+ readonly result: ResolvedCredential
108
+ readonly expiresAt: number
109
+ readonly expiryTimer: ReturnType<typeof setTimeout>
110
+ }
111
+ type ProviderStatus = {
112
+ provider: QuotaProviderId
113
+ label: string
114
+ scope: 'account' | 'selected_key' | 'team' | 'session'
115
+ authentication: 'connected' | 'not_connected' | 'unavailable'
116
+ state: 'available' | 'needs_setup' | 'unavailable'
117
+ reason:
118
+ | 'none'
119
+ | 'not_connected'
120
+ | 'unsupported'
121
+ | 'private_endpoint'
122
+ | 'eligibility_unverified'
123
+ | 'runtime_accounting_unavailable'
124
+ | 'cli_identity_unavailable'
125
+ | 'unsupported_credential_method'
126
+ | 'provider_error'
127
+ | 'not_subscribed'
128
+ | 'rate_limited'
129
+ | 'unauthorized'
130
+ | 'forbidden'
131
+ | 'timeout'
132
+ | 'network_error'
133
+ | 'invalid_response'
134
+ retry_after_ms?: number
135
+ route_kind?: OpenCodeGoRouteKind
136
+ metrics: QuotaMetric[]
137
+ }
138
+
139
+ const PROVIDER_IDS = QUOTA_PROVIDER_IDS
140
+
141
+ function safeMetadataValue(
142
+ metadata: Record<string, unknown> | undefined,
143
+ names: readonly string[],
144
+ ): string | undefined {
145
+ if (!metadata) return undefined
146
+ for (const name of names) {
147
+ const value = metadata[name]
148
+ if (typeof value === 'string' && value.length <= 128 && /^[A-Za-z0-9._:-]+$/.test(value)) {
149
+ return value
150
+ }
151
+ }
152
+ return undefined
153
+ }
154
+
155
+ function projectAdapterContext(
156
+ provider: QuotaProviderId,
157
+ metadata: unknown,
158
+ methodID: unknown,
159
+ ): QuotaAdapterContext | undefined {
160
+ if (provider === 'openai') {
161
+ if (isOpenAICodexOAuthMethod(methodID)) return { methodID }
162
+ return undefined
163
+ }
164
+ if (provider === 'opencode-go') {
165
+ if (!isOpenCodeConsoleOAuthMethod(methodID)) return undefined
166
+ if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) {
167
+ return { methodID }
168
+ }
169
+ const record = metadata as Record<string, unknown>
170
+ if (record.orgID === undefined || record.orgID === null) return { methodID }
171
+ if (typeof record.orgID !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(record.orgID)) {
172
+ return undefined
173
+ }
174
+ return { methodID, orgId: record.orgID }
175
+ }
176
+ if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) return undefined
177
+ const record = metadata as Record<string, unknown>
178
+ const projectId = safeMetadataValue(record, ['projectID', 'projectId', 'quotaProjectId'])
179
+ const accountId = safeMetadataValue(record, ['accountID', 'accountId'])
180
+ const orgId = safeMetadataValue(record, ['orgID', 'orgId'])
181
+ if (!projectId && !accountId && !orgId) return undefined
182
+ return {
183
+ ...(projectId ? { projectId } : {}),
184
+ ...(accountId ? { accountId } : {}),
185
+ ...(orgId ? { orgId } : {}),
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Accept only the official OpenCode Console default and its retired alias.
191
+ * The selected Console token is never sent to a credential-supplied host.
192
+ */
193
+ function isApprovedOpenCodeConsoleServer(metadata: unknown): boolean {
194
+ if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) return true
195
+ const record = metadata as Record<string, unknown>
196
+ if (!Object.hasOwn(record, 'server')) return true
197
+ const server = record.server
198
+ if (typeof server !== 'string' || server.length === 0 || server.length > 2_048) return false
199
+ if (server.trim() !== server) return false
200
+
201
+ let url: URL
202
+ try {
203
+ url = new URL(server)
204
+ } catch {
205
+ return false
206
+ }
207
+ if (
208
+ url.protocol !== 'https:' ||
209
+ url.username !== '' ||
210
+ url.password !== '' ||
211
+ url.port !== '' ||
212
+ url.search !== '' ||
213
+ url.hash !== ''
214
+ ) {
215
+ return false
216
+ }
217
+
218
+ const path = url.pathname.replace(/\/$/, '')
219
+ if (url.hostname === 'opencode.ai') return path === '/console'
220
+ return url.hostname === 'console.opencode.ai' && (path === '' || path === '/console')
221
+ }
222
+
223
+ function routeKindField(
224
+ provider: QuotaProviderId,
225
+ credential?: ResolvedCredential,
226
+ effectiveRouteKind?: OpenCodeGoRouteKind,
227
+ ): { route_kind?: OpenCodeGoRouteKind } {
228
+ return provider === 'opencode-go'
229
+ ? { route_kind: effectiveRouteKind ?? credential?.routeKind ?? 'none' }
230
+ : {}
231
+ }
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
+
266
+ /**
267
+ * Resolve only listed, selected credential connections in the closed provider
268
+ * catalog. Only the minimum access-token/key field is retained in memory.
269
+ */
270
+ function createCredentialResolver(context: Context) {
271
+ const cache = new Map<QuotaProviderId, CachedCredential>()
272
+ const pending = new Map<QuotaProviderId, Promise<ResolvedCredential>>()
273
+ let integrations: Map<string, Set<string>> | undefined
274
+ let integrationListPending: Promise<Map<string, Set<string>>> | undefined
275
+ let generation = 0
276
+ let disposed = false
277
+
278
+ function clearCache(): void {
279
+ for (const cached of cache.values()) clearTimeout(cached.expiryTimer)
280
+ cache.clear()
281
+ integrations = undefined
282
+ integrationListPending = undefined
283
+ }
284
+
285
+ async function listCredentialConnections(): Promise<Map<string, Set<string>>> {
286
+ if (integrations) return integrations
287
+ if (integrationListPending) return integrationListPending
288
+ const startedAtGeneration = generation
289
+ let request: Promise<Map<string, Set<string>>>
290
+ request = context.integration
291
+ .list()
292
+ .then((value) => {
293
+ const connectionsByIntegration = new Map<string, Set<string>>()
294
+ for (const integration of value.data) {
295
+ const connections = new Set<string>()
296
+ if (Array.isArray(integration.connections)) {
297
+ for (const connection of integration.connections) {
298
+ if (connection.type === 'credential') {
299
+ connections.add(`${connection.id}\0${connection.method}`)
300
+ }
301
+ }
302
+ }
303
+ connectionsByIntegration.set(integration.id, connections)
304
+ }
305
+ if (!disposed && generation === startedAtGeneration) integrations = connectionsByIntegration
306
+ return connectionsByIntegration
307
+ })
308
+ .finally(() => {
309
+ if (integrationListPending === request) integrationListPending = undefined
310
+ })
311
+ integrationListPending = request
312
+ return request
313
+ }
314
+
315
+ async function load(provider: QuotaProviderId, goKeyOnly = false): Promise<ResolvedCredential> {
316
+ const definition = QUOTA_PROVIDER_CATALOG[provider]
317
+ // Quota visibility is tied to a selected OpenCode credential connection;
318
+ // local CLI identity is outside that credential context.
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
+ }
325
+ try {
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
+ }
335
+ if (provider === 'opencode-go') {
336
+ const activeListed = async (integrationID: string) => {
337
+ const connections = listedConnections.get(integrationID)
338
+ if (!connections || connections.size === 0) return undefined
339
+ const active = await context.integration.connection.active(integrationID)
340
+ if (active?.type !== 'credential' || !connections.has(`${active.id}\0${active.method}`)) {
341
+ return undefined
342
+ }
343
+ return active
344
+ }
345
+
346
+ let consoleCredential: ResolvedCredential | undefined
347
+ let unsupportedConsoleLogin = false
348
+ if (!goKeyOnly) {
349
+ let activeConsole: Awaited<ReturnType<typeof activeListed>>
350
+ try {
351
+ activeConsole = await activeListed('opencode')
352
+ } catch {
353
+ // A Console lookup failure must not prevent using a selected Go API key.
354
+ }
355
+ if (activeConsole?.method === 'oauth' && activeConsole.status?.status !== 'needs_auth') {
356
+ try {
357
+ const resolved = await context.integration.connection.resolve(activeConsole)
358
+ if (
359
+ resolved?.type === 'oauth' &&
360
+ resolved.access.trim().length > 0 &&
361
+ isOpenCodeConsoleOAuthMethod(resolved.methodID) &&
362
+ isApprovedOpenCodeConsoleServer(resolved.metadata)
363
+ ) {
364
+ const adapterContext = projectAdapterContext(
365
+ provider,
366
+ resolved.metadata,
367
+ resolved.methodID,
368
+ )
369
+ if (adapterContext) {
370
+ consoleCredential = {
371
+ method: 'oauth',
372
+ secret: resolved.access.trim(),
373
+ routeKind: 'console_oauth',
374
+ adapterContext,
375
+ }
376
+ } else {
377
+ unsupportedConsoleLogin = true
378
+ }
379
+ } else if (resolved?.type === 'oauth') {
380
+ unsupportedConsoleLogin = true
381
+ }
382
+ } catch {
383
+ // A failed Console sign-in is allowed to fall through to a listed API key.
384
+ }
385
+ } else if (activeConsole?.method === 'oauth') {
386
+ unsupportedConsoleLogin = activeConsole.status?.status !== 'needs_auth'
387
+ }
388
+ }
389
+
390
+ let activePrimary: Awaited<ReturnType<typeof activeListed>>
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
+ }
397
+ }
398
+ const unsupportedPrimaryLogin =
399
+ !configuredGoKey && activePrimary !== undefined && activePrimary.method !== 'key'
400
+ let apiKey = configuredGoKey
401
+ for (const integrationID of configuredGoKey ? [] : ['opencode-go', 'opencode']) {
402
+ let active: Awaited<ReturnType<typeof activeListed>>
403
+ try {
404
+ active =
405
+ integrationID === 'opencode-go' ? activePrimary : await activeListed(integrationID)
406
+ } catch {
407
+ // A failed key lookup does not invalidate another selected credential.
408
+ continue
409
+ }
410
+ if (!active) continue
411
+ if (goKeyOnly && active.method !== 'key') return {}
412
+ if (active.method !== 'key' || active.status?.status === 'needs_auth') continue
413
+ try {
414
+ const resolved = await context.integration.connection.resolve(active)
415
+ if (resolved?.type === 'key' && resolved.key.trim().length > 0) {
416
+ apiKey = resolved.key.trim()
417
+ break
418
+ }
419
+ } catch {
420
+ // Try the next explicitly selected OpenCode API-key integration.
421
+ }
422
+ }
423
+
424
+ if (consoleCredential) {
425
+ return {
426
+ ...consoleCredential,
427
+ ...(apiKey ? { fallbackSecret: apiKey } : {}),
428
+ }
429
+ }
430
+ if (apiKey) return { method: 'key', secret: apiKey, routeKind: 'api_key' }
431
+ if (unsupportedConsoleLogin || unsupportedPrimaryLogin) {
432
+ return { method: 'unsupported', routeKind: 'unsupported' }
433
+ }
434
+ return {}
435
+ }
436
+
437
+ const integrationIDs = [
438
+ definition.integrationID,
439
+ ...(definition.fallbackIntegrationIDs ?? []),
440
+ ]
441
+ for (const integrationID of integrationIDs) {
442
+ const integrationConnections = listedConnections.get(integrationID)
443
+ if (!integrationConnections || integrationConnections.size === 0) continue
444
+
445
+ const active = await context.integration.connection.active(integrationID)
446
+ if (active?.type !== 'credential') continue
447
+ const isListedActiveConnection = integrationConnections.has(
448
+ `${active.id}\0${active.method}`,
449
+ )
450
+ if (!isListedActiveConnection) continue
451
+ // The manual diagnostic must not even resolve an OAuth connection.
452
+ if (goKeyOnly && active.method !== 'key') return {}
453
+ if (active.status?.status === 'needs_auth') continue
454
+
455
+ if (active.method !== 'oauth' && active.method !== 'key') {
456
+ continue
457
+ }
458
+ if (!definition.methods.includes(active.method)) continue
459
+
460
+ const resolved = await context.integration.connection.resolve(active)
461
+ if (
462
+ active.method === 'oauth' &&
463
+ resolved?.type === 'oauth' &&
464
+ resolved.access.trim().length > 0
465
+ ) {
466
+ const accessToken = resolved.access
467
+ if (!accessToken) return {}
468
+ if (provider === 'opencode-zen' && !isApprovedOpenCodeConsoleServer(resolved.metadata)) {
469
+ return { method: 'unsupported' }
470
+ }
471
+ const adapterContext = projectAdapterContext(
472
+ provider,
473
+ resolved.metadata,
474
+ resolved.methodID,
475
+ )
476
+ return {
477
+ method: 'oauth',
478
+ ...(definition.adapter ? { secret: accessToken } : {}),
479
+ ...(adapterContext ? { adapterContext } : {}),
480
+ }
481
+ }
482
+ if (active.method === 'key' && resolved?.type === 'key') {
483
+ if (resolved.key.trim().length === 0) return {}
484
+ if (!definition.adapter) return { method: 'key' }
485
+ if (resolved.key.length > 0) return { method: 'key', secret: resolved.key }
486
+ }
487
+ return {}
488
+ }
489
+ return {}
490
+ } catch {
491
+ // Host errors may contain credentials, provider data, or arbitrary thrown metadata.
492
+ console.warn('[pantheon-tui quota] credential resolution failed (exception)')
493
+ throw new Error('Credential resolution failed')
494
+ }
495
+ }
496
+
497
+ return {
498
+ async resolveActiveGoKey(): Promise<string | undefined> {
499
+ if (disposed) return undefined
500
+ // Fresh resolution avoids a stale selected key and never falls back to Console OAuth.
501
+ const startedAtGeneration = generation
502
+ const credential = await load('opencode-go', true)
503
+ if (disposed || generation !== startedAtGeneration) return undefined
504
+ return credential.method === 'key' && credential.routeKind === 'api_key'
505
+ ? credential.secret
506
+ : undefined
507
+ },
508
+ async resolve(provider: QuotaProviderId): Promise<ResolvedCredential> {
509
+ if (disposed) return {}
510
+ const now = Date.now()
511
+ const cached = cache.get(provider)
512
+ if (cached && cached.expiresAt > now) return cached.result
513
+ if (cached) {
514
+ clearTimeout(cached.expiryTimer)
515
+ cache.delete(provider)
516
+ }
517
+ const existing = pending.get(provider)
518
+ if (existing) return existing
519
+
520
+ const startedAtGeneration = generation
521
+ let resolution: Promise<ResolvedCredential>
522
+ resolution = load(provider)
523
+ .then((result) => {
524
+ if (disposed || generation !== startedAtGeneration) return {}
525
+ const expiresAt = Date.now() + CREDENTIAL_CACHE_TTL_MS
526
+ const expiryTimer = setTimeout(() => {
527
+ if (cache.get(provider)?.expiryTimer === expiryTimer) cache.delete(provider)
528
+ }, CREDENTIAL_CACHE_TTL_MS)
529
+ expiryTimer.unref()
530
+ cache.set(provider, { result, expiresAt, expiryTimer })
531
+ return result
532
+ })
533
+ .finally(() => {
534
+ if (pending.get(provider) === resolution) pending.delete(provider)
535
+ })
536
+ pending.set(provider, resolution)
537
+ return resolution
538
+ },
539
+ currentGeneration(): number {
540
+ return generation
541
+ },
542
+ isCurrent(version: number): boolean {
543
+ return !disposed && generation === version
544
+ },
545
+ invalidate(): void {
546
+ generation += 1
547
+ clearCache()
548
+ pending.clear()
549
+ },
550
+ dispose(): void {
551
+ disposed = true
552
+ generation += 1
553
+ clearCache()
554
+ pending.clear()
555
+ },
556
+ }
557
+ }
558
+
559
+ function isQuotaSourceInvalidationEvent(type: string): boolean {
560
+ return (
561
+ type === 'credential.updated' ||
562
+ type === 'credential.switched' ||
563
+ type === 'integration.updated' ||
564
+ type === 'provider.updated'
565
+ )
566
+ }
567
+
568
+ function createAdapterExecutor(
569
+ shutdownSignal: AbortSignal,
570
+ queryCli: typeof queryAlibabaTokenPlanUsage,
571
+ ) {
572
+ const MAX_CONCURRENCY = 3
573
+ type AdapterOutcome = Awaited<ReturnType<typeof runQuotaAdapter>>
574
+ type PendingAdapter = {
575
+ controller: AbortController
576
+ callers: Set<symbol>
577
+ settled: boolean
578
+ promise: Promise<AdapterOutcome>
579
+ }
580
+ const cache = new Map<QuotaProviderId, { expiresAt: number; result: AdapterOutcome }>()
581
+ const pending = new Map<QuotaProviderId, PendingAdapter>()
582
+ const cooldown = new Map<QuotaProviderId, number>()
583
+ let activeRequests = 0
584
+ let generation = 0
585
+ const waiters: Array<{
586
+ signal: AbortSignal
587
+ resolve: (release: (() => void) | undefined) => void
588
+ onAbort: () => void
589
+ }> = []
590
+ let invalidationController = new AbortController()
591
+
592
+ function releaseRequest(): () => void {
593
+ let released = false
594
+ return () => {
595
+ if (released) return
596
+ released = true
597
+ while (waiters.length > 0) {
598
+ const waiter = waiters.shift()
599
+ if (!waiter) break
600
+ waiter.signal.removeEventListener('abort', waiter.onAbort)
601
+ if (waiter.signal.aborted) {
602
+ waiter.resolve(undefined)
603
+ continue
604
+ }
605
+ waiter.resolve(releaseRequest())
606
+ return
607
+ }
608
+ activeRequests -= 1
609
+ }
610
+ }
611
+
612
+ function acquireRequest(signal: AbortSignal): Promise<(() => void) | undefined> {
613
+ if (signal.aborted) return Promise.resolve(undefined)
614
+ if (activeRequests < MAX_CONCURRENCY) {
615
+ activeRequests += 1
616
+ return Promise.resolve(releaseRequest())
617
+ }
618
+ return new Promise((resolve) => {
619
+ const waiter = {
620
+ signal,
621
+ resolve,
622
+ onAbort: () => {
623
+ const index = waiters.indexOf(waiter)
624
+ if (index >= 0) waiters.splice(index, 1)
625
+ resolve(undefined)
626
+ },
627
+ }
628
+ waiters.push(waiter)
629
+ signal.addEventListener('abort', waiter.onAbort, { once: true })
630
+ })
631
+ }
632
+
633
+ function subscribe(entry: PendingAdapter, requestSignal: AbortSignal): Promise<AdapterOutcome> {
634
+ requestSignal.throwIfAborted()
635
+ const caller = Symbol()
636
+ entry.callers.add(caller)
637
+ return new Promise((resolve, reject) => {
638
+ let detached = false
639
+ const detach = () => {
640
+ if (detached) return
641
+ detached = true
642
+ requestSignal.removeEventListener('abort', onAbort)
643
+ entry.callers.delete(caller)
644
+ if (!entry.settled && entry.callers.size === 0) entry.controller.abort()
645
+ }
646
+ const onAbort = () => {
647
+ detach()
648
+ reject(requestSignal.reason)
649
+ }
650
+ requestSignal.addEventListener('abort', onAbort, { once: true })
651
+ if (requestSignal.aborted) {
652
+ onAbort()
653
+ return
654
+ }
655
+ entry.promise.then(
656
+ (result) => {
657
+ detach()
658
+ resolve(result)
659
+ },
660
+ (error: unknown) => {
661
+ detach()
662
+ reject(error)
663
+ },
664
+ )
665
+ })
666
+ }
667
+
668
+ return {
669
+ async run(
670
+ provider: QuotaProviderId,
671
+ secret: string | undefined,
672
+ requestSignal: AbortSignal,
673
+ adapterContext?: QuotaAdapterContext,
674
+ fallbackSecret?: string,
675
+ ) {
676
+ requestSignal.throwIfAborted()
677
+ const now = Date.now()
678
+ const until = cooldown.get(provider)
679
+ if (until !== undefined && until > now) {
680
+ return { reason: 'rate_limited' as const, retryAfterMs: until - now }
681
+ }
682
+ const cached = cache.get(provider)
683
+ if (cached && cached.expiresAt > now) return cached.result
684
+ const existing = pending.get(provider)
685
+ if (existing && !existing.controller.signal.aborted) return subscribe(existing, requestSignal)
686
+ if (existing) pending.delete(provider)
687
+
688
+ const startedAtGeneration = generation
689
+ const controller = new AbortController()
690
+ const signal = AbortSignal.any([
691
+ shutdownSignal,
692
+ invalidationController.signal,
693
+ controller.signal,
694
+ ])
695
+ const entry: PendingAdapter = {
696
+ controller,
697
+ callers: new Set(),
698
+ settled: false,
699
+ promise: Promise.resolve({ reason: 'provider_error' }),
700
+ }
701
+ pending.set(provider, entry)
702
+ entry.promise = acquireRequest(signal)
703
+ .then(async (release) => {
704
+ if (!release) return { reason: 'provider_error' as const }
705
+ try {
706
+ return await runQuotaAdapter(
707
+ provider,
708
+ secret,
709
+ signal,
710
+ queryCli,
711
+ adapterContext,
712
+ fallbackSecret,
713
+ )
714
+ } finally {
715
+ release()
716
+ }
717
+ })
718
+ .then((result) => {
719
+ if (generation === startedAtGeneration && !signal.aborted && 'state' in result) {
720
+ cache.set(provider, {
721
+ expiresAt: Date.now() + ADAPTER_CACHE_TTL_MS,
722
+ result,
723
+ })
724
+ } else if (
725
+ generation === startedAtGeneration &&
726
+ 'reason' in result &&
727
+ result.reason === 'rate_limited' &&
728
+ result.retryAfterMs !== undefined
729
+ ) {
730
+ cooldown.set(provider, Date.now() + result.retryAfterMs)
731
+ }
732
+ return result
733
+ })
734
+ .finally(() => {
735
+ entry.settled = true
736
+ if (pending.get(provider) === entry) pending.delete(provider)
737
+ })
738
+ return subscribe(entry, requestSignal)
739
+ },
740
+ invalidate(): void {
741
+ generation += 1
742
+ invalidationController.abort()
743
+ invalidationController = new AbortController()
744
+ cache.clear()
745
+ pending.clear()
746
+ cooldown.clear()
747
+ },
748
+ }
749
+ }
750
+
751
+ async function getProviderStatus(
752
+ resolver: ReturnType<typeof createCredentialResolver>,
753
+ adapters: ReturnType<typeof createAdapterExecutor>,
754
+ requestSignal: AbortSignal,
755
+ ): Promise<{ providers: ProviderStatus[]; credential_resolution_failed?: true }> {
756
+ requestSignal.throwIfAborted()
757
+ let credentialResolutionFailed = false
758
+ const results = await Promise.all(
759
+ PROVIDER_IDS.map(async (provider): Promise<ProviderStatus | undefined> => {
760
+ const definition = QUOTA_PROVIDER_CATALOG[provider]
761
+ try {
762
+ requestSignal.throwIfAborted()
763
+ const credentialGeneration = resolver.currentGeneration()
764
+ let credential: ResolvedCredential
765
+ try {
766
+ credential = await resolver.resolve(provider)
767
+ } catch {
768
+ requestSignal.throwIfAborted()
769
+ credentialResolutionFailed = true
770
+ return undefined
771
+ }
772
+ requestSignal.throwIfAborted()
773
+ if (!credential.method) return undefined
774
+ if (!resolver.isCurrent(credentialGeneration)) {
775
+ return {
776
+ provider,
777
+ label: definition.label,
778
+ scope: definition.scope,
779
+ authentication: 'unavailable',
780
+ state: 'unavailable',
781
+ reason: 'provider_error',
782
+ ...routeKindField(provider, credential),
783
+ metrics: [],
784
+ }
785
+ }
786
+ if (
787
+ credential.method === 'unsupported' ||
788
+ !definition.methods.includes(credential.method)
789
+ ) {
790
+ return {
791
+ provider,
792
+ label: definition.label,
793
+ scope: definition.scope,
794
+ authentication: 'connected',
795
+ state: 'unavailable',
796
+ reason: 'unsupported_credential_method',
797
+ ...routeKindField(provider, credential),
798
+ metrics: [],
799
+ }
800
+ }
801
+ if (!definition.adapter) {
802
+ return {
803
+ provider,
804
+ label: definition.label,
805
+ scope: definition.scope,
806
+ authentication: 'connected',
807
+ state: 'unavailable',
808
+ reason: definition.blockedReason ?? 'unsupported',
809
+ ...routeKindField(provider, credential),
810
+ metrics: [],
811
+ }
812
+ }
813
+ if (!credential.secret) {
814
+ return {
815
+ provider,
816
+ label: definition.label,
817
+ scope: definition.scope,
818
+ authentication: 'unavailable',
819
+ state: 'unavailable',
820
+ reason: 'provider_error',
821
+ ...routeKindField(provider, credential),
822
+ metrics: [],
823
+ }
824
+ }
825
+ const result = await adapters.run(
826
+ provider,
827
+ credential.secret,
828
+ requestSignal,
829
+ credential.adapterContext,
830
+ credential.fallbackSecret,
831
+ )
832
+ requestSignal.throwIfAborted()
833
+ if (!resolver.isCurrent(credentialGeneration)) {
834
+ return {
835
+ provider,
836
+ label: definition.label,
837
+ scope: definition.scope,
838
+ authentication: 'unavailable',
839
+ state: 'unavailable',
840
+ reason: 'provider_error',
841
+ ...routeKindField(provider, credential),
842
+ metrics: [],
843
+ }
844
+ }
845
+ if ('state' in result) {
846
+ return {
847
+ provider,
848
+ label: definition.label,
849
+ scope: definition.scope,
850
+ authentication: 'connected',
851
+ state: 'available',
852
+ reason: 'none',
853
+ ...routeKindField(provider, credential, result.routeKind),
854
+ metrics: result.metrics,
855
+ }
856
+ }
857
+ return {
858
+ provider,
859
+ label: definition.label,
860
+ scope: definition.scope,
861
+ authentication: 'connected',
862
+ state: 'unavailable',
863
+ reason: result.reason,
864
+ ...routeKindField(provider, credential, result.routeKind),
865
+ ...(result.retryAfterMs === undefined
866
+ ? {}
867
+ : { retry_after_ms: Math.ceil(result.retryAfterMs) }),
868
+ metrics: [],
869
+ }
870
+ } catch {
871
+ requestSignal.throwIfAborted()
872
+ return {
873
+ provider,
874
+ label: definition.label,
875
+ scope: definition.scope,
876
+ authentication: 'unavailable',
877
+ state: 'unavailable',
878
+ reason: 'provider_error',
879
+ ...routeKindField(provider),
880
+ metrics: [],
881
+ }
882
+ }
883
+ }),
884
+ )
885
+ const providers = results.filter((provider): provider is ProviderStatus => provider !== undefined)
886
+ return {
887
+ providers,
888
+ ...(credentialResolutionFailed ? { credential_resolution_failed: true as const } : {}),
889
+ }
890
+ }
891
+
892
+ export function createQuotaPlugin(
893
+ queryCli: typeof queryAlibabaTokenPlanUsage = queryAlibabaTokenPlanUsage,
894
+ ) {
895
+ const goKeyDiagnostic = createGoKeyDiagnostic()
896
+ return Plugin.define({
897
+ id: 'pantheon.tui.server',
898
+ async setup(context: Context) {
899
+ const resolver = createCredentialResolver(context)
900
+ const shutdownController = new AbortController()
901
+ const adapters = createAdapterExecutor(shutdownController.signal, queryCli)
902
+ const eventController = new AbortController()
903
+ let registration: RpcRegistration<typeof quotaRpc> | undefined
904
+ const eventTask = (async () => {
905
+ try {
906
+ for await (const event of context.event.subscribe({ signal: eventController.signal })) {
907
+ if (isQuotaSourceInvalidationEvent(event.type)) {
908
+ resolver.invalidate()
909
+ adapters.invalidate()
910
+ if (registration) {
911
+ try {
912
+ await registration.events.emit('credentials_changed', {})
913
+ } catch {
914
+ console.warn(
915
+ 'Quota credential-change notification failed; periodic refresh remains active',
916
+ )
917
+ }
918
+ }
919
+ }
920
+ }
921
+ } catch {
922
+ if (!eventController.signal.aborted) {
923
+ resolver.invalidate()
924
+ adapters.invalidate()
925
+ }
926
+ }
927
+ })()
928
+
929
+ try {
930
+ registration = await context.rpc.register(quotaRpc, {
931
+ go_key_diagnostic: async (_input, callContext) =>
932
+ goKeyDiagnostic(
933
+ () => resolver.resolveActiveGoKey(),
934
+ AbortSignal.any([callContext.signal, shutdownController.signal]),
935
+ ),
936
+ status: async (_input, callContext: RpcCallContext<typeof quotaRpc.methods.status>) =>
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
+ },
962
+ })
963
+ } catch (error) {
964
+ console.warn('[pantheon-tui quota] quota RPC registration failed:', error)
965
+ eventController.abort()
966
+ shutdownController.abort()
967
+ resolver.dispose()
968
+ adapters.invalidate()
969
+ await eventTask
970
+ throw error
971
+ }
972
+
973
+ return async () => {
974
+ eventController.abort()
975
+ shutdownController.abort()
976
+ resolver.dispose()
977
+ adapters.invalidate()
978
+ await eventTask
979
+ await registration?.dispose()
980
+ }
981
+ },
982
+ })
983
+ }
984
+
985
+ export default createQuotaPlugin()