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

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 (145) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-gates.mjs +6 -82
  42. package/scripts/release-notes.mjs +30 -7
  43. package/scripts/restore.mjs +22 -10
  44. package/scripts/sync-tui.mjs +3 -3
  45. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  46. package/scripts/versioning.mjs +41 -5
  47. package/src/agents/aphrodite.md +6 -1
  48. package/src/agents/apollo.md +1 -0
  49. package/src/agents/athena.md +1 -0
  50. package/src/agents/demeter.md +1 -1
  51. package/src/agents/gaia.md +1 -0
  52. package/src/agents/hephaestus.md +1 -1
  53. package/src/agents/hermes.md +8 -10
  54. package/src/agents/iris.md +1 -1
  55. package/src/agents/mnemosyne.md +1 -0
  56. package/src/agents/nyx.md +1 -1
  57. package/src/agents/prometheus.md +1 -1
  58. package/src/agents/talos.md +6 -1
  59. package/src/agents/themis.md +1 -1
  60. package/src/agents/zeus.md +52 -62
  61. package/src/mcp/eval_store.py +11 -4
  62. package/src/mcp/mcp_resources.py +11 -9
  63. package/src/mcp/memory_mcp.py +293 -150
  64. package/src/pantheon/cost-command.ts +30 -133
  65. package/src/pantheon/jev-decision-tool.ts +359 -0
  66. package/src/pantheon/jev-decisions.ts +625 -0
  67. package/src/pantheon/local-decision-agents.ts +170 -0
  68. package/src/pantheon/local-decision-budget.ts +1046 -0
  69. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  70. package/src/pantheon/local-decision-prompt.ts +256 -0
  71. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  72. package/src/pantheon/local-decision-router.ts +225 -0
  73. package/src/pantheon/local-decision-skills.ts +281 -0
  74. package/src/pantheon/local-decision-tool.ts +160 -0
  75. package/src/pantheon/local-decision-turn.ts +101 -0
  76. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  77. package/src/pantheon/local-orchestration.ts +322 -0
  78. package/src/pantheon/model-pricing.ts +1 -536
  79. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  80. package/src/pantheon/v2-decision-budget.ts +456 -0
  81. package/src/pantheon/v2-decision-contracts.ts +300 -0
  82. package/src/pantheon/v2-decision-egress.ts +203 -0
  83. package/src/pantheon/v2-decision-events.ts +180 -0
  84. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  85. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  86. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  87. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  88. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  89. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  90. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  91. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  92. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  93. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  94. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  95. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  96. package/src/pantheon/v2-decision-points.ts +242 -0
  97. package/src/pantheon/v2-decision-policy.ts +166 -0
  98. package/src/pantheon/v2-decision-premises.ts +146 -0
  99. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  100. package/src/pantheon/v2-decision-rank.ts +91 -0
  101. package/src/pantheon/v2-decision-registry.ts +391 -0
  102. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  103. package/src/pantheon/v2-decision-shadow.ts +123 -0
  104. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  105. package/src/pantheon/v2-decision-verify.ts +51 -0
  106. package/src/pantheon/v2-hook-engine.ts +307 -0
  107. package/src/pantheon/v2-native-decisions.ts +365 -0
  108. package/src/pantheon/v2-shell-hooks.ts +66 -2
  109. package/src/pantheon/v2-tools.ts +38 -15
  110. package/src/plugin-v2.ts +419 -26
  111. package/src/plugin.ts +4 -0
  112. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  113. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  114. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  115. package/src/plugins/tui/dist/server-v2.js +19 -666
  116. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  117. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  119. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  121. package/src/plugins/tui/dist/tui.js +1 -1
  122. package/src/plugins/tui/package-lock.json +17 -2
  123. package/src/plugins/tui/package.json +4 -2
  124. package/src/plugins/tui/src/cost-data.ts +607 -0
  125. package/src/plugins/tui/src/index-v2.tsx +213 -54
  126. package/src/plugins/tui/src/model-pricing.ts +536 -0
  127. package/src/plugins/tui/src/server-v2.ts +18 -838
  128. package/src/plugins/tui/tsdown.config.ts +28 -6
  129. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  130. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  131. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  132. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  133. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  134. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  135. package/src/plugins/tui/dist/quota-cli.js +0 -184
  136. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  138. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  139. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  140. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  141. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  142. package/src/plugins/tui/src/quota-cli.ts +0 -237
  143. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  144. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  145. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -1,841 +1,21 @@
1
- import { Plugin } from '@opencode/plugin'
2
- import type { Context } from '@opencode/plugin/promise/plugin'
3
- import type { RpcCallContext, RpcRegistration } from '@opencode/plugin/promise/rpc'
4
- import { createGoKeyDiagnostic } from './go-key-diagnostic'
5
- import {
6
- isOpenAICodexOAuthMethod,
7
- isOpenCodeConsoleOAuthMethod,
8
- QUOTA_PROVIDER_CATALOG,
9
- type QuotaAdapterContext,
10
- type QuotaMetric,
11
- runQuotaAdapter,
12
- } from './quota-adapters'
13
- import { queryAlibabaTokenPlanUsage } from './quota-cli'
14
- import {
15
- type OpenCodeGoRouteKind,
16
- QUOTA_PROVIDER_IDS,
17
- type QuotaProviderId,
18
- quotaRpc,
19
- } from './quota-rpc'
20
-
21
- const CREDENTIAL_CACHE_TTL_MS = 30_000
22
- const ADAPTER_CACHE_TTL_MS = 20_000
23
-
24
- type ResolvedCredential = {
25
- readonly method?: 'oauth' | 'key' | 'unsupported'
26
- readonly routeKind?: OpenCodeGoRouteKind
27
- /** Only adapters receive this secret; blocked sources retain only method status. */
28
- readonly secret?: string
29
- /** OpenCode Go's fixed API-key fallback after its Console OAuth request fails. */
30
- readonly fallbackSecret?: string
31
- /** A tiny, non-secret projection of OAuth metadata required by fixed adapters. */
32
- readonly adapterContext?: QuotaAdapterContext
33
- }
34
- type CachedCredential = {
35
- readonly result: ResolvedCredential
36
- readonly expiresAt: number
37
- readonly expiryTimer: ReturnType<typeof setTimeout>
38
- }
39
- type ProviderStatus = {
40
- provider: QuotaProviderId
41
- label: string
42
- scope: 'account' | 'selected_key' | 'team' | 'session'
43
- authentication: 'connected' | 'not_connected' | 'unavailable'
44
- state: 'available' | 'needs_setup' | 'unavailable'
45
- reason:
46
- | 'none'
47
- | 'not_connected'
48
- | 'unsupported'
49
- | 'private_endpoint'
50
- | 'eligibility_unverified'
51
- | 'runtime_accounting_unavailable'
52
- | 'cli_identity_unavailable'
53
- | 'unsupported_credential_method'
54
- | 'provider_error'
55
- | 'not_subscribed'
56
- | 'rate_limited'
57
- | 'unauthorized'
58
- | 'forbidden'
59
- | 'timeout'
60
- | 'network_error'
61
- | 'invalid_response'
62
- retry_after_ms?: number
63
- route_kind?: OpenCodeGoRouteKind
64
- metrics: QuotaMetric[]
65
- }
66
-
67
- const PROVIDER_IDS = QUOTA_PROVIDER_IDS
68
-
69
- function safeMetadataValue(
70
- metadata: Record<string, unknown> | undefined,
71
- names: readonly string[],
72
- ): string | undefined {
73
- if (!metadata) return undefined
74
- for (const name of names) {
75
- const value = metadata[name]
76
- if (typeof value === 'string' && value.length <= 128 && /^[A-Za-z0-9._:-]+$/.test(value)) {
77
- return value
78
- }
79
- }
80
- return undefined
81
- }
82
-
83
- function projectAdapterContext(
84
- provider: QuotaProviderId,
85
- metadata: unknown,
86
- methodID: unknown,
87
- ): QuotaAdapterContext | undefined {
88
- if (provider === 'openai') {
89
- if (isOpenAICodexOAuthMethod(methodID)) return { methodID }
90
- return undefined
91
- }
92
- if (provider === 'opencode-go') {
93
- if (!isOpenCodeConsoleOAuthMethod(methodID)) return undefined
94
- if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) {
95
- return { methodID }
96
- }
97
- const record = metadata as Record<string, unknown>
98
- if (record.orgID === undefined || record.orgID === null) return { methodID }
99
- if (typeof record.orgID !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(record.orgID)) {
100
- return undefined
101
- }
102
- return { methodID, orgId: record.orgID }
103
- }
104
- if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) return undefined
105
- const record = metadata as Record<string, unknown>
106
- const projectId = safeMetadataValue(record, ['projectID', 'projectId', 'quotaProjectId'])
107
- const accountId = safeMetadataValue(record, ['accountID', 'accountId'])
108
- const orgId = safeMetadataValue(record, ['orgID', 'orgId'])
109
- if (!projectId && !accountId && !orgId) return undefined
110
- return {
111
- ...(projectId ? { projectId } : {}),
112
- ...(accountId ? { accountId } : {}),
113
- ...(orgId ? { orgId } : {}),
114
- }
115
- }
116
-
117
1
  /**
118
- * Accept only the official OpenCode Console default and its retired alias.
119
- * The selected Console token is never sent to a credential-supplied host.
2
+ * No-op server stub for the OpenCode V2 plugin loader.
3
+ *
4
+ * The OpenCode plugin host requires every plugin (TUI included) to expose a
5
+ * `server()` entry via `exports["./server"]` (or package.json `main`) — for the
6
+ * V2 copy this root `index-v2.ts` re-export resolves to this compiled entry —
7
+ * and it loads that server half only from a `config.plugins` entry (see
8
+ * `scripts/install/opencode.mjs`). When the entry is missing the host fails to
9
+ * attach the plugin's server half and the TUI runtime never wires the reactive
10
+ * channel — the initial JSX mounts but effects/refresh/events stay dead (the
11
+ * "mudo panel" symptom; same contract as the V1 `server.ts` stub).
12
+ *
13
+ * This stub satisfies the loader contract. The native quota RPC that used to
14
+ * live here was removed in 1.6.2 — provider quota/usage visibility is now the
15
+ * community plugin's job (`@slkiser/opencode-quota`,
16
+ * docs/tui-v2-quota-providers.md) — and pantheon-tui has no other background
17
+ * server work of its own.
120
18
  */
121
- function isApprovedOpenCodeConsoleServer(metadata: unknown): boolean {
122
- if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) return true
123
- const record = metadata as Record<string, unknown>
124
- if (!Object.hasOwn(record, 'server')) return true
125
- const server = record.server
126
- if (typeof server !== 'string' || server.length === 0 || server.length > 2_048) return false
127
- if (server.trim() !== server) return false
128
-
129
- let url: URL
130
- try {
131
- url = new URL(server)
132
- } catch {
133
- return false
134
- }
135
- if (
136
- url.protocol !== 'https:' ||
137
- url.username !== '' ||
138
- url.password !== '' ||
139
- url.port !== '' ||
140
- url.search !== '' ||
141
- url.hash !== ''
142
- ) {
143
- return false
144
- }
145
-
146
- const path = url.pathname.replace(/\/$/, '')
147
- if (url.hostname === 'opencode.ai') return path === '/console'
148
- return url.hostname === 'console.opencode.ai' && (path === '' || path === '/console')
149
- }
150
-
151
- function routeKindField(
152
- provider: QuotaProviderId,
153
- credential?: ResolvedCredential,
154
- effectiveRouteKind?: OpenCodeGoRouteKind,
155
- ): { route_kind?: OpenCodeGoRouteKind } {
156
- return provider === 'opencode-go'
157
- ? { route_kind: effectiveRouteKind ?? credential?.routeKind ?? 'none' }
158
- : {}
159
- }
160
-
161
- /**
162
- * Resolve only listed, selected credential connections in the closed provider
163
- * catalog. Only the minimum access-token/key field is retained in memory.
164
- */
165
- function createCredentialResolver(context: Context) {
166
- const cache = new Map<QuotaProviderId, CachedCredential>()
167
- const pending = new Map<QuotaProviderId, Promise<ResolvedCredential>>()
168
- let integrations: Map<string, Set<string>> | undefined
169
- let integrationListPending: Promise<Map<string, Set<string>>> | undefined
170
- let generation = 0
171
- let disposed = false
172
-
173
- function clearCache(): void {
174
- for (const cached of cache.values()) clearTimeout(cached.expiryTimer)
175
- cache.clear()
176
- integrations = undefined
177
- integrationListPending = undefined
178
- }
179
-
180
- async function listCredentialConnections(): Promise<Map<string, Set<string>>> {
181
- if (integrations) return integrations
182
- if (integrationListPending) return integrationListPending
183
- const startedAtGeneration = generation
184
- let request: Promise<Map<string, Set<string>>>
185
- request = context.integration
186
- .list()
187
- .then((value) => {
188
- const connectionsByIntegration = new Map<string, Set<string>>()
189
- for (const integration of value.data) {
190
- const connections = new Set<string>()
191
- if (Array.isArray(integration.connections)) {
192
- for (const connection of integration.connections) {
193
- if (connection.type === 'credential') {
194
- connections.add(`${connection.id}\0${connection.method}`)
195
- }
196
- }
197
- }
198
- connectionsByIntegration.set(integration.id, connections)
199
- }
200
- if (!disposed && generation === startedAtGeneration) integrations = connectionsByIntegration
201
- return connectionsByIntegration
202
- })
203
- .finally(() => {
204
- if (integrationListPending === request) integrationListPending = undefined
205
- })
206
- integrationListPending = request
207
- return request
208
- }
209
-
210
- async function load(provider: QuotaProviderId, goKeyOnly = false): Promise<ResolvedCredential> {
211
- const definition = QUOTA_PROVIDER_CATALOG[provider]
212
- // Quota visibility is tied to a selected OpenCode credential connection;
213
- // local CLI identity is outside that credential context.
214
- if (definition.source === 'local-cli') return {}
215
- try {
216
- const listedConnections = await listCredentialConnections()
217
- if (provider === 'opencode-go') {
218
- const activeListed = async (integrationID: string) => {
219
- const connections = listedConnections.get(integrationID)
220
- if (!connections || connections.size === 0) return undefined
221
- const active = await context.integration.connection.active(integrationID)
222
- if (active?.type !== 'credential' || !connections.has(`${active.id}\0${active.method}`)) {
223
- return undefined
224
- }
225
- return active
226
- }
227
-
228
- let consoleCredential: ResolvedCredential | undefined
229
- let unsupportedConsoleLogin = false
230
- if (!goKeyOnly) {
231
- let activeConsole: Awaited<ReturnType<typeof activeListed>>
232
- try {
233
- activeConsole = await activeListed('opencode')
234
- } catch {
235
- // A Console lookup failure must not prevent using a selected Go API key.
236
- }
237
- if (activeConsole?.method === 'oauth' && activeConsole.status?.status !== 'needs_auth') {
238
- try {
239
- const resolved = await context.integration.connection.resolve(activeConsole)
240
- if (
241
- resolved?.type === 'oauth' &&
242
- resolved.access.trim().length > 0 &&
243
- isOpenCodeConsoleOAuthMethod(resolved.methodID) &&
244
- isApprovedOpenCodeConsoleServer(resolved.metadata)
245
- ) {
246
- const adapterContext = projectAdapterContext(
247
- provider,
248
- resolved.metadata,
249
- resolved.methodID,
250
- )
251
- if (adapterContext) {
252
- consoleCredential = {
253
- method: 'oauth',
254
- secret: resolved.access.trim(),
255
- routeKind: 'console_oauth',
256
- adapterContext,
257
- }
258
- } else {
259
- unsupportedConsoleLogin = true
260
- }
261
- } else if (resolved?.type === 'oauth') {
262
- unsupportedConsoleLogin = true
263
- }
264
- } catch {
265
- // A failed Console sign-in is allowed to fall through to a listed API key.
266
- }
267
- } else if (activeConsole?.method === 'oauth') {
268
- unsupportedConsoleLogin = activeConsole.status?.status !== 'needs_auth'
269
- }
270
- }
271
-
272
- let activePrimary: Awaited<ReturnType<typeof activeListed>>
273
- try {
274
- activePrimary = await activeListed('opencode-go')
275
- } catch {
276
- // An API-key lookup failure must not discard an already resolved Console login.
277
- }
278
- const unsupportedPrimaryLogin =
279
- activePrimary !== undefined && activePrimary.method !== 'key'
280
- let apiKey: string | undefined
281
- for (const integrationID of ['opencode-go', 'opencode']) {
282
- let active: Awaited<ReturnType<typeof activeListed>>
283
- try {
284
- active =
285
- integrationID === 'opencode-go' ? activePrimary : await activeListed(integrationID)
286
- } catch {
287
- // A failed key lookup does not invalidate another selected credential.
288
- continue
289
- }
290
- if (!active) continue
291
- if (goKeyOnly && active.method !== 'key') return {}
292
- if (active.method !== 'key' || active.status?.status === 'needs_auth') continue
293
- try {
294
- const resolved = await context.integration.connection.resolve(active)
295
- if (resolved?.type === 'key' && resolved.key.trim().length > 0) {
296
- apiKey = resolved.key.trim()
297
- break
298
- }
299
- } catch {
300
- // Try the next explicitly selected OpenCode API-key integration.
301
- }
302
- }
303
-
304
- if (consoleCredential) {
305
- return {
306
- ...consoleCredential,
307
- ...(apiKey ? { fallbackSecret: apiKey } : {}),
308
- }
309
- }
310
- if (apiKey) return { method: 'key', secret: apiKey, routeKind: 'api_key' }
311
- if (unsupportedConsoleLogin || unsupportedPrimaryLogin) {
312
- return { method: 'unsupported', routeKind: 'unsupported' }
313
- }
314
- return {}
315
- }
316
-
317
- const integrationIDs = [
318
- definition.integrationID,
319
- ...(definition.fallbackIntegrationIDs ?? []),
320
- ]
321
- for (const integrationID of integrationIDs) {
322
- const integrationConnections = listedConnections.get(integrationID)
323
- if (!integrationConnections || integrationConnections.size === 0) continue
324
-
325
- const active = await context.integration.connection.active(integrationID)
326
- if (active?.type !== 'credential') continue
327
- const isListedActiveConnection = integrationConnections.has(
328
- `${active.id}\0${active.method}`,
329
- )
330
- if (!isListedActiveConnection) continue
331
- // The manual diagnostic must not even resolve an OAuth connection.
332
- if (goKeyOnly && active.method !== 'key') return {}
333
- if (active.status?.status === 'needs_auth') continue
334
-
335
- if (active.method !== 'oauth' && active.method !== 'key') {
336
- continue
337
- }
338
- if (!definition.methods.includes(active.method)) continue
339
-
340
- const resolved = await context.integration.connection.resolve(active)
341
- if (
342
- active.method === 'oauth' &&
343
- resolved?.type === 'oauth' &&
344
- resolved.access.trim().length > 0
345
- ) {
346
- const accessToken = resolved.access
347
- if (!accessToken) return {}
348
- if (provider === 'opencode-zen' && !isApprovedOpenCodeConsoleServer(resolved.metadata)) {
349
- return { method: 'unsupported' }
350
- }
351
- const adapterContext = projectAdapterContext(
352
- provider,
353
- resolved.metadata,
354
- resolved.methodID,
355
- )
356
- return {
357
- method: 'oauth',
358
- ...(definition.adapter ? { secret: accessToken } : {}),
359
- ...(adapterContext ? { adapterContext } : {}),
360
- }
361
- }
362
- if (active.method === 'key' && resolved?.type === 'key') {
363
- if (resolved.key.trim().length === 0) return {}
364
- if (!definition.adapter) return { method: 'key' }
365
- if (resolved.key.length > 0) return { method: 'key', secret: resolved.key }
366
- }
367
- return {}
368
- }
369
- return {}
370
- } catch (error) {
371
- // Host errors may contain identifiers or provider data; never forward them.
372
- // The sanitized error alone hides the cause, so keep the original in the server log.
373
- console.warn('[pantheon-tui quota] credential resolution failed:', error)
374
- throw new Error('Credential resolution failed')
375
- }
376
- }
377
-
378
- return {
379
- async resolveActiveGoKey(): Promise<string | undefined> {
380
- if (disposed) return undefined
381
- // Fresh resolution avoids a stale selected key and never falls back to Console OAuth.
382
- const startedAtGeneration = generation
383
- const credential = await load('opencode-go', true)
384
- if (disposed || generation !== startedAtGeneration) return undefined
385
- return credential.method === 'key' && credential.routeKind === 'api_key'
386
- ? credential.secret
387
- : undefined
388
- },
389
- async resolve(provider: QuotaProviderId): Promise<ResolvedCredential> {
390
- if (disposed) return {}
391
- const now = Date.now()
392
- const cached = cache.get(provider)
393
- if (cached && cached.expiresAt > now) return cached.result
394
- if (cached) {
395
- clearTimeout(cached.expiryTimer)
396
- cache.delete(provider)
397
- }
398
- const existing = pending.get(provider)
399
- if (existing) return existing
400
-
401
- const startedAtGeneration = generation
402
- let resolution: Promise<ResolvedCredential>
403
- resolution = load(provider)
404
- .then((result) => {
405
- if (disposed || generation !== startedAtGeneration) return {}
406
- const expiresAt = Date.now() + CREDENTIAL_CACHE_TTL_MS
407
- const expiryTimer = setTimeout(() => {
408
- if (cache.get(provider)?.expiryTimer === expiryTimer) cache.delete(provider)
409
- }, CREDENTIAL_CACHE_TTL_MS)
410
- expiryTimer.unref()
411
- cache.set(provider, { result, expiresAt, expiryTimer })
412
- return result
413
- })
414
- .finally(() => {
415
- if (pending.get(provider) === resolution) pending.delete(provider)
416
- })
417
- pending.set(provider, resolution)
418
- return resolution
419
- },
420
- currentGeneration(): number {
421
- return generation
422
- },
423
- isCurrent(version: number): boolean {
424
- return !disposed && generation === version
425
- },
426
- invalidate(): void {
427
- generation += 1
428
- clearCache()
429
- pending.clear()
430
- },
431
- dispose(): void {
432
- disposed = true
433
- generation += 1
434
- clearCache()
435
- pending.clear()
436
- },
437
- }
438
- }
439
-
440
- function isCredentialInvalidationEvent(type: string): boolean {
441
- return (
442
- type === 'credential.updated' ||
443
- type === 'credential.switched' ||
444
- type === 'integration.updated'
445
- )
446
- }
447
-
448
- function createAdapterExecutor(
449
- shutdownSignal: AbortSignal,
450
- queryCli: typeof queryAlibabaTokenPlanUsage,
451
- ) {
452
- const MAX_CONCURRENCY = 3
453
- type AdapterOutcome = Awaited<ReturnType<typeof runQuotaAdapter>>
454
- type PendingAdapter = {
455
- controller: AbortController
456
- callers: Set<symbol>
457
- settled: boolean
458
- promise: Promise<AdapterOutcome>
459
- }
460
- const cache = new Map<QuotaProviderId, { expiresAt: number; result: AdapterOutcome }>()
461
- const pending = new Map<QuotaProviderId, PendingAdapter>()
462
- const cooldown = new Map<QuotaProviderId, number>()
463
- let activeRequests = 0
464
- let generation = 0
465
- const waiters: Array<{
466
- signal: AbortSignal
467
- resolve: (release: (() => void) | undefined) => void
468
- onAbort: () => void
469
- }> = []
470
- let invalidationController = new AbortController()
471
-
472
- function releaseRequest(): () => void {
473
- let released = false
474
- return () => {
475
- if (released) return
476
- released = true
477
- while (waiters.length > 0) {
478
- const waiter = waiters.shift()
479
- if (!waiter) break
480
- waiter.signal.removeEventListener('abort', waiter.onAbort)
481
- if (waiter.signal.aborted) {
482
- waiter.resolve(undefined)
483
- continue
484
- }
485
- waiter.resolve(releaseRequest())
486
- return
487
- }
488
- activeRequests -= 1
489
- }
490
- }
491
-
492
- function acquireRequest(signal: AbortSignal): Promise<(() => void) | undefined> {
493
- if (signal.aborted) return Promise.resolve(undefined)
494
- if (activeRequests < MAX_CONCURRENCY) {
495
- activeRequests += 1
496
- return Promise.resolve(releaseRequest())
497
- }
498
- return new Promise((resolve) => {
499
- const waiter = {
500
- signal,
501
- resolve,
502
- onAbort: () => {
503
- const index = waiters.indexOf(waiter)
504
- if (index >= 0) waiters.splice(index, 1)
505
- resolve(undefined)
506
- },
507
- }
508
- waiters.push(waiter)
509
- signal.addEventListener('abort', waiter.onAbort, { once: true })
510
- })
511
- }
512
-
513
- function subscribe(entry: PendingAdapter, requestSignal: AbortSignal): Promise<AdapterOutcome> {
514
- requestSignal.throwIfAborted()
515
- const caller = Symbol()
516
- entry.callers.add(caller)
517
- return new Promise((resolve, reject) => {
518
- let detached = false
519
- const detach = () => {
520
- if (detached) return
521
- detached = true
522
- requestSignal.removeEventListener('abort', onAbort)
523
- entry.callers.delete(caller)
524
- if (!entry.settled && entry.callers.size === 0) entry.controller.abort()
525
- }
526
- const onAbort = () => {
527
- detach()
528
- reject(requestSignal.reason)
529
- }
530
- requestSignal.addEventListener('abort', onAbort, { once: true })
531
- if (requestSignal.aborted) {
532
- onAbort()
533
- return
534
- }
535
- entry.promise.then(
536
- (result) => {
537
- detach()
538
- resolve(result)
539
- },
540
- (error: unknown) => {
541
- detach()
542
- reject(error)
543
- },
544
- )
545
- })
546
- }
547
-
548
- return {
549
- async run(
550
- provider: QuotaProviderId,
551
- secret: string | undefined,
552
- requestSignal: AbortSignal,
553
- adapterContext?: QuotaAdapterContext,
554
- fallbackSecret?: string,
555
- ) {
556
- requestSignal.throwIfAborted()
557
- const now = Date.now()
558
- const until = cooldown.get(provider)
559
- if (until !== undefined && until > now) {
560
- return { reason: 'rate_limited' as const, retryAfterMs: until - now }
561
- }
562
- const cached = cache.get(provider)
563
- if (cached && cached.expiresAt > now) return cached.result
564
- const existing = pending.get(provider)
565
- if (existing && !existing.controller.signal.aborted) return subscribe(existing, requestSignal)
566
- if (existing) pending.delete(provider)
567
-
568
- const startedAtGeneration = generation
569
- const controller = new AbortController()
570
- const signal = AbortSignal.any([
571
- shutdownSignal,
572
- invalidationController.signal,
573
- controller.signal,
574
- ])
575
- const entry: PendingAdapter = {
576
- controller,
577
- callers: new Set(),
578
- settled: false,
579
- promise: Promise.resolve({ reason: 'provider_error' }),
580
- }
581
- pending.set(provider, entry)
582
- entry.promise = acquireRequest(signal)
583
- .then(async (release) => {
584
- if (!release) return { reason: 'provider_error' as const }
585
- try {
586
- return await runQuotaAdapter(
587
- provider,
588
- secret,
589
- signal,
590
- queryCli,
591
- adapterContext,
592
- fallbackSecret,
593
- )
594
- } finally {
595
- release()
596
- }
597
- })
598
- .then((result) => {
599
- if (generation === startedAtGeneration && !signal.aborted && 'state' in result) {
600
- cache.set(provider, {
601
- expiresAt: Date.now() + ADAPTER_CACHE_TTL_MS,
602
- result,
603
- })
604
- } else if (
605
- generation === startedAtGeneration &&
606
- 'reason' in result &&
607
- result.reason === 'rate_limited' &&
608
- result.retryAfterMs !== undefined
609
- ) {
610
- cooldown.set(provider, Date.now() + result.retryAfterMs)
611
- }
612
- return result
613
- })
614
- .finally(() => {
615
- entry.settled = true
616
- if (pending.get(provider) === entry) pending.delete(provider)
617
- })
618
- return subscribe(entry, requestSignal)
619
- },
620
- invalidate(): void {
621
- generation += 1
622
- invalidationController.abort()
623
- invalidationController = new AbortController()
624
- cache.clear()
625
- pending.clear()
626
- cooldown.clear()
627
- },
628
- }
629
- }
630
-
631
- async function getProviderStatus(
632
- resolver: ReturnType<typeof createCredentialResolver>,
633
- adapters: ReturnType<typeof createAdapterExecutor>,
634
- requestSignal: AbortSignal,
635
- ): Promise<{ providers: ProviderStatus[]; credential_resolution_failed?: true }> {
636
- requestSignal.throwIfAborted()
637
- let credentialResolutionFailed = false
638
- const results = await Promise.all(
639
- PROVIDER_IDS.map(async (provider): Promise<ProviderStatus | undefined> => {
640
- const definition = QUOTA_PROVIDER_CATALOG[provider]
641
- try {
642
- requestSignal.throwIfAborted()
643
- const credentialGeneration = resolver.currentGeneration()
644
- let credential: ResolvedCredential
645
- try {
646
- credential = await resolver.resolve(provider)
647
- } catch {
648
- requestSignal.throwIfAborted()
649
- credentialResolutionFailed = true
650
- return undefined
651
- }
652
- requestSignal.throwIfAborted()
653
- if (!credential.method) return undefined
654
- if (!resolver.isCurrent(credentialGeneration)) {
655
- return {
656
- provider,
657
- label: definition.label,
658
- scope: definition.scope,
659
- authentication: 'unavailable',
660
- state: 'unavailable',
661
- reason: 'provider_error',
662
- ...routeKindField(provider, credential),
663
- metrics: [],
664
- }
665
- }
666
- if (
667
- credential.method === 'unsupported' ||
668
- !definition.methods.includes(credential.method)
669
- ) {
670
- return {
671
- provider,
672
- label: definition.label,
673
- scope: definition.scope,
674
- authentication: 'connected',
675
- state: 'unavailable',
676
- reason: 'unsupported_credential_method',
677
- ...routeKindField(provider, credential),
678
- metrics: [],
679
- }
680
- }
681
- if (!definition.adapter) {
682
- return {
683
- provider,
684
- label: definition.label,
685
- scope: definition.scope,
686
- authentication: 'connected',
687
- state: 'unavailable',
688
- reason: definition.blockedReason ?? 'unsupported',
689
- ...routeKindField(provider, credential),
690
- metrics: [],
691
- }
692
- }
693
- if (!credential.secret) {
694
- return {
695
- provider,
696
- label: definition.label,
697
- scope: definition.scope,
698
- authentication: 'unavailable',
699
- state: 'unavailable',
700
- reason: 'provider_error',
701
- ...routeKindField(provider, credential),
702
- metrics: [],
703
- }
704
- }
705
- const result = await adapters.run(
706
- provider,
707
- credential.secret,
708
- requestSignal,
709
- credential.adapterContext,
710
- credential.fallbackSecret,
711
- )
712
- requestSignal.throwIfAborted()
713
- if (!resolver.isCurrent(credentialGeneration)) {
714
- return {
715
- provider,
716
- label: definition.label,
717
- scope: definition.scope,
718
- authentication: 'unavailable',
719
- state: 'unavailable',
720
- reason: 'provider_error',
721
- ...routeKindField(provider, credential),
722
- metrics: [],
723
- }
724
- }
725
- if ('state' in result) {
726
- return {
727
- provider,
728
- label: definition.label,
729
- scope: definition.scope,
730
- authentication: 'connected',
731
- state: 'available',
732
- reason: 'none',
733
- ...routeKindField(provider, credential, result.routeKind),
734
- metrics: result.metrics,
735
- }
736
- }
737
- return {
738
- provider,
739
- label: definition.label,
740
- scope: definition.scope,
741
- authentication: 'connected',
742
- state: 'unavailable',
743
- reason: result.reason,
744
- ...routeKindField(provider, credential, result.routeKind),
745
- ...(result.retryAfterMs === undefined
746
- ? {}
747
- : { retry_after_ms: Math.ceil(result.retryAfterMs) }),
748
- metrics: [],
749
- }
750
- } catch {
751
- requestSignal.throwIfAborted()
752
- return {
753
- provider,
754
- label: definition.label,
755
- scope: definition.scope,
756
- authentication: 'unavailable',
757
- state: 'unavailable',
758
- reason: 'provider_error',
759
- ...routeKindField(provider),
760
- metrics: [],
761
- }
762
- }
763
- }),
764
- )
765
- const providers = results.filter((provider): provider is ProviderStatus => provider !== undefined)
766
- return {
767
- providers,
768
- ...(credentialResolutionFailed ? { credential_resolution_failed: true as const } : {}),
769
- }
770
- }
771
-
772
- export function createQuotaPlugin(
773
- queryCli: typeof queryAlibabaTokenPlanUsage = queryAlibabaTokenPlanUsage,
774
- ) {
775
- const goKeyDiagnostic = createGoKeyDiagnostic()
776
- return Plugin.define({
777
- id: 'pantheon.tui.server',
778
- async setup(context: Context) {
779
- const resolver = createCredentialResolver(context)
780
- const shutdownController = new AbortController()
781
- const adapters = createAdapterExecutor(shutdownController.signal, queryCli)
782
- const eventController = new AbortController()
783
- let registration: RpcRegistration<typeof quotaRpc> | undefined
784
- const eventTask = (async () => {
785
- try {
786
- for await (const event of context.event.subscribe({ signal: eventController.signal })) {
787
- if (isCredentialInvalidationEvent(event.type)) {
788
- resolver.invalidate()
789
- adapters.invalidate()
790
- if (registration) {
791
- try {
792
- await registration.events.emit('credentials_changed', {})
793
- } catch {
794
- console.warn(
795
- 'Quota credential-change notification failed; periodic refresh remains active',
796
- )
797
- }
798
- }
799
- }
800
- }
801
- } catch {
802
- if (!eventController.signal.aborted) {
803
- resolver.invalidate()
804
- adapters.invalidate()
805
- }
806
- }
807
- })()
808
-
809
- try {
810
- registration = await context.rpc.register(quotaRpc, {
811
- go_key_diagnostic: async (_input, callContext) =>
812
- goKeyDiagnostic(
813
- () => resolver.resolveActiveGoKey(),
814
- AbortSignal.any([callContext.signal, shutdownController.signal]),
815
- ),
816
- status: async (_input, callContext: RpcCallContext<typeof quotaRpc.methods.status>) =>
817
- getProviderStatus(resolver, adapters, callContext.signal),
818
- })
819
- } catch (error) {
820
- console.warn('[pantheon-tui quota] quota RPC registration failed:', error)
821
- eventController.abort()
822
- shutdownController.abort()
823
- resolver.dispose()
824
- adapters.invalidate()
825
- await eventTask
826
- throw error
827
- }
828
-
829
- return async () => {
830
- eventController.abort()
831
- shutdownController.abort()
832
- resolver.dispose()
833
- adapters.invalidate()
834
- await eventTask
835
- await registration?.dispose()
836
- }
837
- },
838
- })
19
+ export default function server() {
20
+ return {}
839
21
  }
840
-
841
- export default createQuotaPlugin()