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,673 +1,26 @@
1
- import { n as quotaRpc, t as QUOTA_PROVIDER_IDS } from "./quota-rpc-UL2HuFRJ.js";
2
- import { queryAlibabaTokenPlanUsage } from "./quota-cli.js";
3
- import { QUOTA_PROVIDER_CATALOG, isOpenAICodexOAuthMethod, isOpenCodeConsoleOAuthMethod, runQuotaAdapter } from "./quota-adapters.js";
4
- import { Plugin } from "@opencode/plugin";
5
- //#region src/go-key-diagnostic.ts
6
- /** Parse at most 4 KiB; inspect only own top-level error presence, never its value. */
7
- async function errorStructure(body, signal) {
8
- if (!body) return "unavailable";
9
- let reader;
10
- let abort = () => {};
11
- let complete = false;
12
- try {
13
- reader = body.getReader();
14
- const aborted = new Promise((_, reject) => {
15
- abort = () => reject(/* @__PURE__ */ new Error("aborted"));
16
- signal.addEventListener("abort", abort, { once: true });
17
- });
18
- const bytes = /* @__PURE__ */ new Uint8Array(4096);
19
- let length = 0;
20
- while (true) {
21
- signal.throwIfAborted();
22
- const { done, value } = await Promise.race([reader.read(), aborted]);
23
- if (done) {
24
- complete = true;
25
- break;
26
- }
27
- if (value.byteLength > bytes.length - length) return "unavailable";
28
- bytes.set(value, length);
29
- length += value.byteLength;
30
- }
31
- const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length)));
32
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "unavailable";
33
- return Object.hasOwn(parsed, "error") ? "present" : "absent";
34
- } catch {
35
- return "unavailable";
36
- } finally {
37
- signal.removeEventListener("abort", abort);
38
- if (!complete) (reader ? reader.cancel() : body.cancel()).catch(() => {});
39
- reader?.releaseLock();
40
- }
41
- }
42
- /** One explicit invocation per plugin runtime, including failed/no-credential attempts. */
43
- function createGoKeyDiagnostic() {
44
- let attempted = false;
45
- return async (resolveKey, signal) => {
46
- if (attempted) return { category: "already_used" };
47
- attempted = true;
48
- let key;
49
- try {
50
- key = await resolveKey();
51
- } catch {
52
- return { category: "not_run" };
53
- }
54
- if (!key || signal.aborted) return { category: "not_run" };
55
- const timeout = AbortSignal.timeout(5e3);
56
- const requestSignal = AbortSignal.any([signal, timeout]);
57
- try {
58
- const response = await fetch("https://opencode.ai/zen/go/v1/usage", {
59
- method: "GET",
60
- headers: {
61
- Authorization: `Bearer ${key}`,
62
- "x-opencode-session": "pantheon-quota",
63
- "user-agent": "Pantheon-Quota/1.0"
64
- },
65
- redirect: "manual",
66
- signal: requestSignal
67
- });
68
- const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
69
- const contentType = !mediaType ? "missing" : mediaType === "application/json" || mediaType === "text/plain" || mediaType === "text/html" ? mediaType : "other";
70
- let structure;
71
- if (response.status === 401 && contentType === "application/json") structure = await errorStructure(response.body, requestSignal);
72
- else {
73
- response.body?.cancel().catch(() => {});
74
- if (response.status === 401) structure = "unavailable";
75
- }
76
- return {
77
- category: response.status === 401 ? "unauthorized" : response.status >= 300 && response.status < 400 ? "redirect" : response.ok ? "success" : "http_error",
78
- status: response.status,
79
- content_type: contentType,
80
- ...structure ? { error_structure: structure } : {}
81
- };
82
- } catch {
83
- return { category: timeout.aborted ? "timeout" : "network_error" };
84
- }
85
- };
86
- }
87
- //#endregion
88
1
  //#region src/server-v2.ts
89
- const CREDENTIAL_CACHE_TTL_MS = 3e4;
90
- const ADAPTER_CACHE_TTL_MS = 2e4;
91
- const PROVIDER_IDS = QUOTA_PROVIDER_IDS;
92
- function safeMetadataValue(metadata, names) {
93
- if (!metadata) return void 0;
94
- for (const name of names) {
95
- const value = metadata[name];
96
- if (typeof value === "string" && value.length <= 128 && /^[A-Za-z0-9._:-]+$/.test(value)) return value;
97
- }
98
- }
99
- function projectAdapterContext(provider, metadata, methodID) {
100
- if (provider === "openai") {
101
- if (isOpenAICodexOAuthMethod(methodID)) return { methodID };
102
- return;
103
- }
104
- if (provider === "opencode-go") {
105
- if (!isOpenCodeConsoleOAuthMethod(methodID)) return void 0;
106
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return { methodID };
107
- const record = metadata;
108
- if (record.orgID === void 0 || record.orgID === null) return { methodID };
109
- if (typeof record.orgID !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(record.orgID)) return;
110
- return {
111
- methodID,
112
- orgId: record.orgID
113
- };
114
- }
115
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return void 0;
116
- const record = metadata;
117
- const projectId = safeMetadataValue(record, [
118
- "projectID",
119
- "projectId",
120
- "quotaProjectId"
121
- ]);
122
- const accountId = safeMetadataValue(record, ["accountID", "accountId"]);
123
- const orgId = safeMetadataValue(record, ["orgID", "orgId"]);
124
- if (!projectId && !accountId && !orgId) return void 0;
125
- return {
126
- ...projectId ? { projectId } : {},
127
- ...accountId ? { accountId } : {},
128
- ...orgId ? { orgId } : {}
129
- };
130
- }
131
2
  /**
132
- * Accept only the official OpenCode Console default and its retired alias.
133
- * The selected Console token is never sent to a credential-supplied host.
3
+ * No-op server stub for the OpenCode V2 plugin loader.
4
+ *
5
+ * The OpenCode plugin host requires every plugin (TUI included) to expose a
6
+ * `server()` entry via `exports["./server"]` (or package.json `main`) — for the
7
+ * V2 copy this root `index-v2.ts` re-export resolves to this compiled entry —
8
+ * and it loads that server half only from a `config.plugins` entry (see
9
+ * `scripts/install/opencode.mjs`). When the entry is missing the host fails to
10
+ * attach the plugin's server half and the TUI runtime never wires the reactive
11
+ * channel — the initial JSX mounts but effects/refresh/events stay dead (the
12
+ * "mudo panel" symptom; same contract as the V1 `server.ts` stub).
13
+ *
14
+ * This stub satisfies the loader contract. The native quota RPC that used to
15
+ * live here was removed in 1.6.2 — provider quota/usage visibility is now the
16
+ * community plugin's job (`@slkiser/opencode-quota`,
17
+ * docs/tui-v2-quota-providers.md) — and pantheon-tui has no other background
18
+ * server work of its own.
134
19
  */
135
- function isApprovedOpenCodeConsoleServer(metadata) {
136
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return true;
137
- const record = metadata;
138
- if (!Object.hasOwn(record, "server")) return true;
139
- const server = record.server;
140
- if (typeof server !== "string" || server.length === 0 || server.length > 2048) return false;
141
- if (server.trim() !== server) return false;
142
- let url;
143
- try {
144
- url = new URL(server);
145
- } catch {
146
- return false;
147
- }
148
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.port !== "" || url.search !== "" || url.hash !== "") return false;
149
- const path = url.pathname.replace(/\/$/, "");
150
- if (url.hostname === "opencode.ai") return path === "/console";
151
- return url.hostname === "console.opencode.ai" && (path === "" || path === "/console");
152
- }
153
- function routeKindField(provider, credential, effectiveRouteKind) {
154
- return provider === "opencode-go" ? { route_kind: effectiveRouteKind ?? credential?.routeKind ?? "none" } : {};
155
- }
156
- /**
157
- * Resolve only listed, selected credential connections in the closed provider
158
- * catalog. Only the minimum access-token/key field is retained in memory.
159
- */
160
- function createCredentialResolver(context) {
161
- const cache = /* @__PURE__ */ new Map();
162
- const pending = /* @__PURE__ */ new Map();
163
- let integrations;
164
- let integrationListPending;
165
- let generation = 0;
166
- let disposed = false;
167
- function clearCache() {
168
- for (const cached of cache.values()) clearTimeout(cached.expiryTimer);
169
- cache.clear();
170
- integrations = void 0;
171
- integrationListPending = void 0;
172
- }
173
- async function listCredentialConnections() {
174
- if (integrations) return integrations;
175
- if (integrationListPending) return integrationListPending;
176
- const startedAtGeneration = generation;
177
- let request;
178
- request = context.integration.list().then((value) => {
179
- const connectionsByIntegration = /* @__PURE__ */ new Map();
180
- for (const integration of value.data) {
181
- const connections = /* @__PURE__ */ new Set();
182
- if (Array.isArray(integration.connections)) {
183
- for (const connection of integration.connections) if (connection.type === "credential") connections.add(`${connection.id}\0${connection.method}`);
184
- }
185
- connectionsByIntegration.set(integration.id, connections);
186
- }
187
- if (!disposed && generation === startedAtGeneration) integrations = connectionsByIntegration;
188
- return connectionsByIntegration;
189
- }).finally(() => {
190
- if (integrationListPending === request) integrationListPending = void 0;
191
- });
192
- integrationListPending = request;
193
- return request;
194
- }
195
- async function load(provider, goKeyOnly = false) {
196
- const definition = QUOTA_PROVIDER_CATALOG[provider];
197
- if (definition.source === "local-cli") return {};
198
- try {
199
- const listedConnections = await listCredentialConnections();
200
- if (provider === "opencode-go") {
201
- const activeListed = async (integrationID) => {
202
- const connections = listedConnections.get(integrationID);
203
- if (!connections || connections.size === 0) return void 0;
204
- const active = await context.integration.connection.active(integrationID);
205
- if (active?.type !== "credential" || !connections.has(`${active.id}\0${active.method}`)) return;
206
- return active;
207
- };
208
- let consoleCredential;
209
- let unsupportedConsoleLogin = false;
210
- if (!goKeyOnly) {
211
- let activeConsole;
212
- try {
213
- activeConsole = await activeListed("opencode");
214
- } catch {}
215
- if (activeConsole?.method === "oauth" && activeConsole.status?.status !== "needs_auth") try {
216
- const resolved = await context.integration.connection.resolve(activeConsole);
217
- if (resolved?.type === "oauth" && resolved.access.trim().length > 0 && isOpenCodeConsoleOAuthMethod(resolved.methodID) && isApprovedOpenCodeConsoleServer(resolved.metadata)) {
218
- const adapterContext = projectAdapterContext(provider, resolved.metadata, resolved.methodID);
219
- if (adapterContext) consoleCredential = {
220
- method: "oauth",
221
- secret: resolved.access.trim(),
222
- routeKind: "console_oauth",
223
- adapterContext
224
- };
225
- else unsupportedConsoleLogin = true;
226
- } else if (resolved?.type === "oauth") unsupportedConsoleLogin = true;
227
- } catch {}
228
- else if (activeConsole?.method === "oauth") unsupportedConsoleLogin = activeConsole.status?.status !== "needs_auth";
229
- }
230
- let activePrimary;
231
- try {
232
- activePrimary = await activeListed("opencode-go");
233
- } catch {}
234
- const unsupportedPrimaryLogin = activePrimary !== void 0 && activePrimary.method !== "key";
235
- let apiKey;
236
- for (const integrationID of ["opencode-go", "opencode"]) {
237
- let active;
238
- try {
239
- active = integrationID === "opencode-go" ? activePrimary : await activeListed(integrationID);
240
- } catch {
241
- continue;
242
- }
243
- if (!active) continue;
244
- if (goKeyOnly && active.method !== "key") return {};
245
- if (active.method !== "key" || active.status?.status === "needs_auth") continue;
246
- try {
247
- const resolved = await context.integration.connection.resolve(active);
248
- if (resolved?.type === "key" && resolved.key.trim().length > 0) {
249
- apiKey = resolved.key.trim();
250
- break;
251
- }
252
- } catch {}
253
- }
254
- if (consoleCredential) return {
255
- ...consoleCredential,
256
- ...apiKey ? { fallbackSecret: apiKey } : {}
257
- };
258
- if (apiKey) return {
259
- method: "key",
260
- secret: apiKey,
261
- routeKind: "api_key"
262
- };
263
- if (unsupportedConsoleLogin || unsupportedPrimaryLogin) return {
264
- method: "unsupported",
265
- routeKind: "unsupported"
266
- };
267
- return {};
268
- }
269
- const integrationIDs = [definition.integrationID, ...definition.fallbackIntegrationIDs ?? []];
270
- for (const integrationID of integrationIDs) {
271
- const integrationConnections = listedConnections.get(integrationID);
272
- if (!integrationConnections || integrationConnections.size === 0) continue;
273
- const active = await context.integration.connection.active(integrationID);
274
- if (active?.type !== "credential") continue;
275
- if (!integrationConnections.has(`${active.id}\0${active.method}`)) continue;
276
- if (goKeyOnly && active.method !== "key") return {};
277
- if (active.status?.status === "needs_auth") continue;
278
- if (active.method !== "oauth" && active.method !== "key") continue;
279
- if (!definition.methods.includes(active.method)) continue;
280
- const resolved = await context.integration.connection.resolve(active);
281
- if (active.method === "oauth" && resolved?.type === "oauth" && resolved.access.trim().length > 0) {
282
- const accessToken = resolved.access;
283
- if (!accessToken) return {};
284
- if (provider === "opencode-zen" && !isApprovedOpenCodeConsoleServer(resolved.metadata)) return { method: "unsupported" };
285
- const adapterContext = projectAdapterContext(provider, resolved.metadata, resolved.methodID);
286
- return {
287
- method: "oauth",
288
- ...definition.adapter ? { secret: accessToken } : {},
289
- ...adapterContext ? { adapterContext } : {}
290
- };
291
- }
292
- if (active.method === "key" && resolved?.type === "key") {
293
- if (resolved.key.trim().length === 0) return {};
294
- if (!definition.adapter) return { method: "key" };
295
- if (resolved.key.length > 0) return {
296
- method: "key",
297
- secret: resolved.key
298
- };
299
- }
300
- return {};
301
- }
302
- return {};
303
- } catch (error) {
304
- console.warn("[pantheon-tui quota] credential resolution failed:", error);
305
- throw new Error("Credential resolution failed");
306
- }
307
- }
308
- return {
309
- async resolveActiveGoKey() {
310
- if (disposed) return void 0;
311
- const startedAtGeneration = generation;
312
- const credential = await load("opencode-go", true);
313
- if (disposed || generation !== startedAtGeneration) return void 0;
314
- return credential.method === "key" && credential.routeKind === "api_key" ? credential.secret : void 0;
315
- },
316
- async resolve(provider) {
317
- if (disposed) return {};
318
- const now = Date.now();
319
- const cached = cache.get(provider);
320
- if (cached && cached.expiresAt > now) return cached.result;
321
- if (cached) {
322
- clearTimeout(cached.expiryTimer);
323
- cache.delete(provider);
324
- }
325
- const existing = pending.get(provider);
326
- if (existing) return existing;
327
- const startedAtGeneration = generation;
328
- let resolution;
329
- resolution = load(provider).then((result) => {
330
- if (disposed || generation !== startedAtGeneration) return {};
331
- const expiresAt = Date.now() + CREDENTIAL_CACHE_TTL_MS;
332
- const expiryTimer = setTimeout(() => {
333
- if (cache.get(provider)?.expiryTimer === expiryTimer) cache.delete(provider);
334
- }, CREDENTIAL_CACHE_TTL_MS);
335
- expiryTimer.unref();
336
- cache.set(provider, {
337
- result,
338
- expiresAt,
339
- expiryTimer
340
- });
341
- return result;
342
- }).finally(() => {
343
- if (pending.get(provider) === resolution) pending.delete(provider);
344
- });
345
- pending.set(provider, resolution);
346
- return resolution;
347
- },
348
- currentGeneration() {
349
- return generation;
350
- },
351
- isCurrent(version) {
352
- return !disposed && generation === version;
353
- },
354
- invalidate() {
355
- generation += 1;
356
- clearCache();
357
- pending.clear();
358
- },
359
- dispose() {
360
- disposed = true;
361
- generation += 1;
362
- clearCache();
363
- pending.clear();
364
- }
365
- };
366
- }
367
- function isCredentialInvalidationEvent(type) {
368
- return type === "credential.updated" || type === "credential.switched" || type === "integration.updated";
369
- }
370
- function createAdapterExecutor(shutdownSignal, queryCli) {
371
- const MAX_CONCURRENCY = 3;
372
- const cache = /* @__PURE__ */ new Map();
373
- const pending = /* @__PURE__ */ new Map();
374
- const cooldown = /* @__PURE__ */ new Map();
375
- let activeRequests = 0;
376
- let generation = 0;
377
- const waiters = [];
378
- let invalidationController = new AbortController();
379
- function releaseRequest() {
380
- let released = false;
381
- return () => {
382
- if (released) return;
383
- released = true;
384
- while (waiters.length > 0) {
385
- const waiter = waiters.shift();
386
- if (!waiter) break;
387
- waiter.signal.removeEventListener("abort", waiter.onAbort);
388
- if (waiter.signal.aborted) {
389
- waiter.resolve(void 0);
390
- continue;
391
- }
392
- waiter.resolve(releaseRequest());
393
- return;
394
- }
395
- activeRequests -= 1;
396
- };
397
- }
398
- function acquireRequest(signal) {
399
- if (signal.aborted) return Promise.resolve(void 0);
400
- if (activeRequests < MAX_CONCURRENCY) {
401
- activeRequests += 1;
402
- return Promise.resolve(releaseRequest());
403
- }
404
- return new Promise((resolve) => {
405
- const waiter = {
406
- signal,
407
- resolve,
408
- onAbort: () => {
409
- const index = waiters.indexOf(waiter);
410
- if (index >= 0) waiters.splice(index, 1);
411
- resolve(void 0);
412
- }
413
- };
414
- waiters.push(waiter);
415
- signal.addEventListener("abort", waiter.onAbort, { once: true });
416
- });
417
- }
418
- function subscribe(entry, requestSignal) {
419
- requestSignal.throwIfAborted();
420
- const caller = Symbol();
421
- entry.callers.add(caller);
422
- return new Promise((resolve, reject) => {
423
- let detached = false;
424
- const detach = () => {
425
- if (detached) return;
426
- detached = true;
427
- requestSignal.removeEventListener("abort", onAbort);
428
- entry.callers.delete(caller);
429
- if (!entry.settled && entry.callers.size === 0) entry.controller.abort();
430
- };
431
- const onAbort = () => {
432
- detach();
433
- reject(requestSignal.reason);
434
- };
435
- requestSignal.addEventListener("abort", onAbort, { once: true });
436
- if (requestSignal.aborted) {
437
- onAbort();
438
- return;
439
- }
440
- entry.promise.then((result) => {
441
- detach();
442
- resolve(result);
443
- }, (error) => {
444
- detach();
445
- reject(error);
446
- });
447
- });
448
- }
449
- return {
450
- async run(provider, secret, requestSignal, adapterContext, fallbackSecret) {
451
- requestSignal.throwIfAborted();
452
- const now = Date.now();
453
- const until = cooldown.get(provider);
454
- if (until !== void 0 && until > now) return {
455
- reason: "rate_limited",
456
- retryAfterMs: until - now
457
- };
458
- const cached = cache.get(provider);
459
- if (cached && cached.expiresAt > now) return cached.result;
460
- const existing = pending.get(provider);
461
- if (existing && !existing.controller.signal.aborted) return subscribe(existing, requestSignal);
462
- if (existing) pending.delete(provider);
463
- const startedAtGeneration = generation;
464
- const controller = new AbortController();
465
- const signal = AbortSignal.any([
466
- shutdownSignal,
467
- invalidationController.signal,
468
- controller.signal
469
- ]);
470
- const entry = {
471
- controller,
472
- callers: /* @__PURE__ */ new Set(),
473
- settled: false,
474
- promise: Promise.resolve({ reason: "provider_error" })
475
- };
476
- pending.set(provider, entry);
477
- entry.promise = acquireRequest(signal).then(async (release) => {
478
- if (!release) return { reason: "provider_error" };
479
- try {
480
- return await runQuotaAdapter(provider, secret, signal, queryCli, adapterContext, fallbackSecret);
481
- } finally {
482
- release();
483
- }
484
- }).then((result) => {
485
- if (generation === startedAtGeneration && !signal.aborted && "state" in result) cache.set(provider, {
486
- expiresAt: Date.now() + ADAPTER_CACHE_TTL_MS,
487
- result
488
- });
489
- else if (generation === startedAtGeneration && "reason" in result && result.reason === "rate_limited" && result.retryAfterMs !== void 0) cooldown.set(provider, Date.now() + result.retryAfterMs);
490
- return result;
491
- }).finally(() => {
492
- entry.settled = true;
493
- if (pending.get(provider) === entry) pending.delete(provider);
494
- });
495
- return subscribe(entry, requestSignal);
496
- },
497
- invalidate() {
498
- generation += 1;
499
- invalidationController.abort();
500
- invalidationController = new AbortController();
501
- cache.clear();
502
- pending.clear();
503
- cooldown.clear();
504
- }
505
- };
506
- }
507
- async function getProviderStatus(resolver, adapters, requestSignal) {
508
- requestSignal.throwIfAborted();
509
- let credentialResolutionFailed = false;
510
- return {
511
- providers: (await Promise.all(PROVIDER_IDS.map(async (provider) => {
512
- const definition = QUOTA_PROVIDER_CATALOG[provider];
513
- try {
514
- requestSignal.throwIfAborted();
515
- const credentialGeneration = resolver.currentGeneration();
516
- let credential;
517
- try {
518
- credential = await resolver.resolve(provider);
519
- } catch {
520
- requestSignal.throwIfAborted();
521
- credentialResolutionFailed = true;
522
- return;
523
- }
524
- requestSignal.throwIfAborted();
525
- if (!credential.method) return void 0;
526
- if (!resolver.isCurrent(credentialGeneration)) return {
527
- provider,
528
- label: definition.label,
529
- scope: definition.scope,
530
- authentication: "unavailable",
531
- state: "unavailable",
532
- reason: "provider_error",
533
- ...routeKindField(provider, credential),
534
- metrics: []
535
- };
536
- if (credential.method === "unsupported" || !definition.methods.includes(credential.method)) return {
537
- provider,
538
- label: definition.label,
539
- scope: definition.scope,
540
- authentication: "connected",
541
- state: "unavailable",
542
- reason: "unsupported_credential_method",
543
- ...routeKindField(provider, credential),
544
- metrics: []
545
- };
546
- if (!definition.adapter) return {
547
- provider,
548
- label: definition.label,
549
- scope: definition.scope,
550
- authentication: "connected",
551
- state: "unavailable",
552
- reason: definition.blockedReason ?? "unsupported",
553
- ...routeKindField(provider, credential),
554
- metrics: []
555
- };
556
- if (!credential.secret) return {
557
- provider,
558
- label: definition.label,
559
- scope: definition.scope,
560
- authentication: "unavailable",
561
- state: "unavailable",
562
- reason: "provider_error",
563
- ...routeKindField(provider, credential),
564
- metrics: []
565
- };
566
- const result = await adapters.run(provider, credential.secret, requestSignal, credential.adapterContext, credential.fallbackSecret);
567
- requestSignal.throwIfAborted();
568
- if (!resolver.isCurrent(credentialGeneration)) return {
569
- provider,
570
- label: definition.label,
571
- scope: definition.scope,
572
- authentication: "unavailable",
573
- state: "unavailable",
574
- reason: "provider_error",
575
- ...routeKindField(provider, credential),
576
- metrics: []
577
- };
578
- if ("state" in result) return {
579
- provider,
580
- label: definition.label,
581
- scope: definition.scope,
582
- authentication: "connected",
583
- state: "available",
584
- reason: "none",
585
- ...routeKindField(provider, credential, result.routeKind),
586
- metrics: result.metrics
587
- };
588
- return {
589
- provider,
590
- label: definition.label,
591
- scope: definition.scope,
592
- authentication: "connected",
593
- state: "unavailable",
594
- reason: result.reason,
595
- ...routeKindField(provider, credential, result.routeKind),
596
- ...result.retryAfterMs === void 0 ? {} : { retry_after_ms: Math.ceil(result.retryAfterMs) },
597
- metrics: []
598
- };
599
- } catch {
600
- requestSignal.throwIfAborted();
601
- return {
602
- provider,
603
- label: definition.label,
604
- scope: definition.scope,
605
- authentication: "unavailable",
606
- state: "unavailable",
607
- reason: "provider_error",
608
- ...routeKindField(provider),
609
- metrics: []
610
- };
611
- }
612
- }))).filter((provider) => provider !== void 0),
613
- ...credentialResolutionFailed ? { credential_resolution_failed: true } : {}
614
- };
615
- }
616
- function createQuotaPlugin(queryCli = queryAlibabaTokenPlanUsage) {
617
- const goKeyDiagnostic = createGoKeyDiagnostic();
618
- return Plugin.define({
619
- id: "pantheon.tui.server",
620
- async setup(context) {
621
- const resolver = createCredentialResolver(context);
622
- const shutdownController = new AbortController();
623
- const adapters = createAdapterExecutor(shutdownController.signal, queryCli);
624
- const eventController = new AbortController();
625
- let registration;
626
- const eventTask = (async () => {
627
- try {
628
- for await (const event of context.event.subscribe({ signal: eventController.signal })) if (isCredentialInvalidationEvent(event.type)) {
629
- resolver.invalidate();
630
- adapters.invalidate();
631
- if (registration) try {
632
- await registration.events.emit("credentials_changed", {});
633
- } catch {
634
- console.warn("Quota credential-change notification failed; periodic refresh remains active");
635
- }
636
- }
637
- } catch {
638
- if (!eventController.signal.aborted) {
639
- resolver.invalidate();
640
- adapters.invalidate();
641
- }
642
- }
643
- })();
644
- try {
645
- registration = await context.rpc.register(quotaRpc, {
646
- go_key_diagnostic: async (_input, callContext) => goKeyDiagnostic(() => resolver.resolveActiveGoKey(), AbortSignal.any([callContext.signal, shutdownController.signal])),
647
- status: async (_input, callContext) => getProviderStatus(resolver, adapters, callContext.signal)
648
- });
649
- } catch (error) {
650
- console.warn("[pantheon-tui quota] quota RPC registration failed:", error);
651
- eventController.abort();
652
- shutdownController.abort();
653
- resolver.dispose();
654
- adapters.invalidate();
655
- await eventTask;
656
- throw error;
657
- }
658
- return async () => {
659
- eventController.abort();
660
- shutdownController.abort();
661
- resolver.dispose();
662
- adapters.invalidate();
663
- await eventTask;
664
- await registration?.dispose();
665
- };
666
- }
667
- });
20
+ function server() {
21
+ return {};
668
22
  }
669
- var server_v2_default = createQuotaPlugin();
670
23
  //#endregion
671
- export { createQuotaPlugin, server_v2_default as default };
24
+ export { server as default };
672
25
 
673
26
  //# sourceMappingURL=server-v2.js.map