pantheon-opencode 1.6.2-beta.9 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +34 -60
  3. package/README.pt-BR.md +10 -12
  4. package/bin/pantheon-init.mjs +22 -32
  5. package/package.json +3 -3
  6. package/plugin.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/scripts/decision-router.mjs +41 -56
  9. package/scripts/install/decision-router-config.mjs +67 -1
  10. package/scripts/install/npx-cache-sweep.mjs +103 -0
  11. package/scripts/install/opencode.mjs +7 -7
  12. package/scripts/install/plugin.mjs +4 -3
  13. package/scripts/install/strings.mjs +4 -0
  14. package/scripts/release-gates.mjs +6 -82
  15. package/scripts/sync-tui.mjs +3 -3
  16. package/src/agents/zeus.md +4 -2
  17. package/src/pantheon/jev-decision-tool.ts +366 -114
  18. package/src/pantheon/jev-decisions.ts +11 -13
  19. package/src/pantheon/jev-escalation.ts +639 -0
  20. package/src/pantheon/jev-quality-score.ts +432 -0
  21. package/src/pantheon/jev-risk-gate.ts +479 -0
  22. package/src/pantheon/local-decision-prompt.ts +12 -18
  23. package/src/pantheon/v2-decision-telemetry.ts +14 -4
  24. package/src/pantheon/v2-native-decisions.ts +1 -1
  25. package/src/plugin-v2.ts +201 -24
  26. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  27. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  28. package/src/plugins/tui/dist/server-v2.js +19 -789
  29. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  30. package/src/plugins/tui/dist/tui-v2.d.ts +12 -331
  31. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  32. package/src/plugins/tui/dist/tui-v2.js +257 -5370
  33. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  34. package/src/plugins/tui/dist/tui.js +1 -1
  35. package/src/plugins/tui/package-lock.json +2 -2
  36. package/src/plugins/tui/package.json +1 -1
  37. package/src/plugins/tui/src/index-v2.tsx +213 -86
  38. package/src/plugins/tui/src/server-v2.ts +18 -982
  39. package/src/plugins/tui/tsconfig.typecheck.json +1 -6
  40. package/src/plugins/tui/tsdown.config.ts +1 -11
  41. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +0 -749
  42. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +0 -1
  43. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  44. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  45. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  46. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  47. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  48. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  49. package/src/plugins/tui/dist/quota-cli.js +0 -184
  50. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  51. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +0 -684
  52. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +0 -1
  53. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +0 -118
  54. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +0 -1
  55. package/src/plugins/tui/dist/usage-history-worker.js +0 -25
  56. package/src/plugins/tui/dist/usage-history-worker.js.map +0 -1
  57. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  58. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  59. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  60. package/src/plugins/tui/src/quota-cli.ts +0 -237
  61. package/src/plugins/tui/src/quota-rpc.ts +0 -373
  62. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  63. package/src/plugins/tui/src/quota-v2.tsx +0 -1238
  64. package/src/plugins/tui/src/usage-history-contract.ts +0 -217
  65. package/src/plugins/tui/src/usage-history-validation.ts +0 -104
  66. package/src/plugins/tui/src/usage-history-view.tsx +0 -236
  67. package/src/plugins/tui/src/usage-history-worker.ts +0 -25
  68. package/src/plugins/tui/src/usage-view-model.ts +0 -272
@@ -1,796 +1,26 @@
1
- import { r as isUsageHistoryPeriod, t as MAX_HISTORY_QUERY_MS } from "./usage-history-contract-nt1rnBPE.js";
2
- import { n as quotaRpc, t as QUOTA_PROVIDER_IDS } from "./quota-rpc-DMmXBhBe.js";
3
- import { t as estimateActiveContextCost } from "./cost-data-CCZUs1aJ.js";
4
- import { queryAlibabaTokenPlanUsage } from "./quota-cli.js";
5
- import { QUOTA_PROVIDER_CATALOG, isOpenAICodexOAuthMethod, isOpenCodeConsoleOAuthMethod, runQuotaAdapter } from "./quota-adapters.js";
6
- import { Worker } from "node:worker_threads";
7
- import { Plugin } from "@opencode/plugin";
8
- //#region src/go-key-diagnostic.ts
9
- /** Parse at most 4 KiB; inspect only own top-level error presence, never its value. */
10
- async function errorStructure(body, signal) {
11
- if (!body) return "unavailable";
12
- let reader;
13
- let abort = () => {};
14
- let complete = false;
15
- try {
16
- reader = body.getReader();
17
- const aborted = new Promise((_, reject) => {
18
- abort = () => reject(/* @__PURE__ */ new Error("aborted"));
19
- signal.addEventListener("abort", abort, { once: true });
20
- });
21
- const bytes = /* @__PURE__ */ new Uint8Array(4096);
22
- let length = 0;
23
- while (true) {
24
- signal.throwIfAborted();
25
- const { done, value } = await Promise.race([reader.read(), aborted]);
26
- if (done) {
27
- complete = true;
28
- break;
29
- }
30
- if (value.byteLength > bytes.length - length) return "unavailable";
31
- bytes.set(value, length);
32
- length += value.byteLength;
33
- }
34
- const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length)));
35
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "unavailable";
36
- return Object.hasOwn(parsed, "error") ? "present" : "absent";
37
- } catch {
38
- return "unavailable";
39
- } finally {
40
- signal.removeEventListener("abort", abort);
41
- if (!complete) (reader ? reader.cancel() : body.cancel()).catch(() => {});
42
- reader?.releaseLock();
43
- }
44
- }
45
- /** One explicit invocation per plugin runtime, including failed/no-credential attempts. */
46
- function createGoKeyDiagnostic() {
47
- let attempted = false;
48
- return async (resolveKey, signal) => {
49
- if (attempted) return { category: "already_used" };
50
- attempted = true;
51
- let key;
52
- try {
53
- key = await resolveKey();
54
- } catch {
55
- return { category: "not_run" };
56
- }
57
- if (!key || signal.aborted) return { category: "not_run" };
58
- const timeout = AbortSignal.timeout(5e3);
59
- const requestSignal = AbortSignal.any([signal, timeout]);
60
- try {
61
- const response = await fetch("https://opencode.ai/zen/go/v1/usage", {
62
- method: "GET",
63
- headers: {
64
- Authorization: `Bearer ${key}`,
65
- "x-opencode-session": "pantheon-quota",
66
- "user-agent": "Pantheon-Quota/1.0"
67
- },
68
- redirect: "manual",
69
- signal: requestSignal
70
- });
71
- const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
72
- const contentType = !mediaType ? "missing" : mediaType === "application/json" || mediaType === "text/plain" || mediaType === "text/html" ? mediaType : "other";
73
- let structure;
74
- if (response.status === 401 && contentType === "application/json") structure = await errorStructure(response.body, requestSignal);
75
- else {
76
- response.body?.cancel().catch(() => {});
77
- if (response.status === 401) structure = "unavailable";
78
- }
79
- return {
80
- category: response.status === 401 ? "unauthorized" : response.status >= 300 && response.status < 400 ? "redirect" : response.ok ? "success" : "http_error",
81
- status: response.status,
82
- content_type: contentType,
83
- ...structure ? { error_structure: structure } : {}
84
- };
85
- } catch {
86
- return { category: timeout.aborted ? "timeout" : "network_error" };
87
- }
88
- };
89
- }
90
- //#endregion
91
1
  //#region src/server-v2.ts
92
- const CREDENTIAL_CACHE_TTL_MS = 3e4;
93
- const ADAPTER_CACHE_TTL_MS = 2e4;
94
- function queryUsageHistoryInWorker(period, signal) {
95
- if (!isUsageHistoryPeriod(period)) return Promise.resolve({
96
- status: "unavailable",
97
- reason: "invalid_period"
98
- });
99
- return new Promise((resolve, reject) => {
100
- let settled = false;
101
- let worker;
102
- try {
103
- worker = new Worker(new URL("./usage-history-worker.js", import.meta.url), {
104
- workerData: { period },
105
- resourceLimits: {
106
- maxOldGenerationSizeMb: 64,
107
- stackSizeMb: 2
108
- }
109
- });
110
- } catch {
111
- resolve({
112
- status: "unavailable",
113
- reason: "history_unavailable"
114
- });
115
- return;
116
- }
117
- let timer;
118
- const onAbort = () => {
119
- if (settled) return;
120
- settled = true;
121
- clearTimeout(timer);
122
- signal.removeEventListener("abort", onAbort);
123
- worker.terminate();
124
- reject(new DOMException("Usage history request aborted", "AbortError"));
125
- };
126
- const finish = (result) => {
127
- if (settled) return;
128
- settled = true;
129
- clearTimeout(timer);
130
- signal.removeEventListener("abort", onAbort);
131
- worker.terminate();
132
- resolve(result);
133
- };
134
- timer = setTimeout(() => {
135
- finish({
136
- status: "unavailable",
137
- reason: "history_timeout"
138
- });
139
- }, MAX_HISTORY_QUERY_MS);
140
- signal.addEventListener("abort", onAbort, { once: true });
141
- worker.once("message", (message) => {
142
- if (typeof message === "object" && message !== null && "ok" in message && message.ok === true && "result" in message && typeof message.result === "object" && message.result !== null) {
143
- finish(message.result);
144
- return;
145
- }
146
- finish({
147
- status: "unavailable",
148
- reason: "history_unavailable"
149
- });
150
- });
151
- worker.once("error", () => finish({
152
- status: "unavailable",
153
- reason: "history_unavailable"
154
- }));
155
- worker.once("exit", () => {
156
- if (!settled) finish({
157
- status: "unavailable",
158
- reason: "history_unavailable"
159
- });
160
- });
161
- if (signal.aborted) onAbort();
162
- });
163
- }
164
- const PROVIDER_IDS = QUOTA_PROVIDER_IDS;
165
- function safeMetadataValue(metadata, names) {
166
- if (!metadata) return void 0;
167
- for (const name of names) {
168
- const value = metadata[name];
169
- if (typeof value === "string" && value.length <= 128 && /^[A-Za-z0-9._:-]+$/.test(value)) return value;
170
- }
171
- }
172
- function projectAdapterContext(provider, metadata, methodID) {
173
- if (provider === "openai") {
174
- if (isOpenAICodexOAuthMethod(methodID)) return { methodID };
175
- return;
176
- }
177
- if (provider === "opencode-go") {
178
- if (!isOpenCodeConsoleOAuthMethod(methodID)) return void 0;
179
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return { methodID };
180
- const record = metadata;
181
- if (record.orgID === void 0 || record.orgID === null) return { methodID };
182
- if (typeof record.orgID !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(record.orgID)) return;
183
- return {
184
- methodID,
185
- orgId: record.orgID
186
- };
187
- }
188
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return void 0;
189
- const record = metadata;
190
- const projectId = safeMetadataValue(record, [
191
- "projectID",
192
- "projectId",
193
- "quotaProjectId"
194
- ]);
195
- const accountId = safeMetadataValue(record, ["accountID", "accountId"]);
196
- const orgId = safeMetadataValue(record, ["orgID", "orgId"]);
197
- if (!projectId && !accountId && !orgId) return void 0;
198
- return {
199
- ...projectId ? { projectId } : {},
200
- ...accountId ? { accountId } : {},
201
- ...orgId ? { orgId } : {}
202
- };
203
- }
204
2
  /**
205
- * Accept only the official OpenCode Console default and its retired alias.
206
- * 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.
207
19
  */
208
- function isApprovedOpenCodeConsoleServer(metadata) {
209
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return true;
210
- const record = metadata;
211
- if (!Object.hasOwn(record, "server")) return true;
212
- const server = record.server;
213
- if (typeof server !== "string" || server.length === 0 || server.length > 2048) return false;
214
- if (server.trim() !== server) return false;
215
- let url;
216
- try {
217
- url = new URL(server);
218
- } catch {
219
- return false;
220
- }
221
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.port !== "" || url.search !== "" || url.hash !== "") return false;
222
- const path = url.pathname.replace(/\/$/, "");
223
- if (url.hostname === "opencode.ai") return path === "/console";
224
- return url.hostname === "console.opencode.ai" && (path === "" || path === "/console");
225
- }
226
- function routeKindField(provider, credential, effectiveRouteKind) {
227
- return provider === "opencode-go" ? { route_kind: effectiveRouteKind ?? credential?.routeKind ?? "none" } : {};
228
- }
229
- /**
230
- * OpenCode Go follows the upstream quota plugin's key order: process environment, the
231
- * effective OpenCode provider settings, then a selected OpenCode API-key connection.
232
- * Provider settings are read through the host API; Pantheon never parses OpenCode files.
233
- */
234
- async function configuredOpenCodeGoApiKey(context) {
235
- const environmentKey = process.env.OPENCODE_API_KEY?.trim();
236
- if (environmentKey) return environmentKey;
237
- for (const providerID of ["opencode-go", "opencode"]) {
238
- let value;
239
- try {
240
- value = (await context.provider.get({ providerID })).data.settings?.apiKey;
241
- } catch {
242
- continue;
243
- }
244
- if (typeof value !== "string") continue;
245
- const configured = value.trim();
246
- if (!configured) continue;
247
- const environmentTemplate = configured.match(/^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/);
248
- if (environmentTemplate) {
249
- if (environmentTemplate[1] !== "OPENCODE_API_KEY") continue;
250
- const resolved = process.env.OPENCODE_API_KEY?.trim();
251
- if (resolved) return resolved;
252
- continue;
253
- }
254
- if (configured.startsWith("{env:")) continue;
255
- return configured;
256
- }
257
- }
258
- /**
259
- * Resolve only listed, selected credential connections in the closed provider
260
- * catalog. Only the minimum access-token/key field is retained in memory.
261
- */
262
- function createCredentialResolver(context) {
263
- const cache = /* @__PURE__ */ new Map();
264
- const pending = /* @__PURE__ */ new Map();
265
- let integrations;
266
- let integrationListPending;
267
- let generation = 0;
268
- let disposed = false;
269
- function clearCache() {
270
- for (const cached of cache.values()) clearTimeout(cached.expiryTimer);
271
- cache.clear();
272
- integrations = void 0;
273
- integrationListPending = void 0;
274
- }
275
- async function listCredentialConnections() {
276
- if (integrations) return integrations;
277
- if (integrationListPending) return integrationListPending;
278
- const startedAtGeneration = generation;
279
- let request;
280
- request = context.integration.list().then((value) => {
281
- const connectionsByIntegration = /* @__PURE__ */ new Map();
282
- for (const integration of value.data) {
283
- const connections = /* @__PURE__ */ new Set();
284
- if (Array.isArray(integration.connections)) {
285
- for (const connection of integration.connections) if (connection.type === "credential") connections.add(`${connection.id}\0${connection.method}`);
286
- }
287
- connectionsByIntegration.set(integration.id, connections);
288
- }
289
- if (!disposed && generation === startedAtGeneration) integrations = connectionsByIntegration;
290
- return connectionsByIntegration;
291
- }).finally(() => {
292
- if (integrationListPending === request) integrationListPending = void 0;
293
- });
294
- integrationListPending = request;
295
- return request;
296
- }
297
- async function load(provider, goKeyOnly = false) {
298
- const definition = QUOTA_PROVIDER_CATALOG[provider];
299
- if (definition.source === "local-cli") return {};
300
- const configuredGoKey = provider === "opencode-go" ? await configuredOpenCodeGoApiKey(context) : void 0;
301
- if (goKeyOnly && configuredGoKey) return {
302
- method: "key",
303
- secret: configuredGoKey,
304
- routeKind: "api_key"
305
- };
306
- try {
307
- let listedConnections;
308
- try {
309
- listedConnections = await listCredentialConnections();
310
- } catch (error) {
311
- if (provider !== "opencode-go" || !configuredGoKey) throw error;
312
- listedConnections = /* @__PURE__ */ new Map();
313
- }
314
- if (provider === "opencode-go") {
315
- const activeListed = async (integrationID) => {
316
- const connections = listedConnections.get(integrationID);
317
- if (!connections || connections.size === 0) return void 0;
318
- const active = await context.integration.connection.active(integrationID);
319
- if (active?.type !== "credential" || !connections.has(`${active.id}\0${active.method}`)) return;
320
- return active;
321
- };
322
- let consoleCredential;
323
- let unsupportedConsoleLogin = false;
324
- if (!goKeyOnly) {
325
- let activeConsole;
326
- try {
327
- activeConsole = await activeListed("opencode");
328
- } catch {}
329
- if (activeConsole?.method === "oauth" && activeConsole.status?.status !== "needs_auth") try {
330
- const resolved = await context.integration.connection.resolve(activeConsole);
331
- if (resolved?.type === "oauth" && resolved.access.trim().length > 0 && isOpenCodeConsoleOAuthMethod(resolved.methodID) && isApprovedOpenCodeConsoleServer(resolved.metadata)) {
332
- const adapterContext = projectAdapterContext(provider, resolved.metadata, resolved.methodID);
333
- if (adapterContext) consoleCredential = {
334
- method: "oauth",
335
- secret: resolved.access.trim(),
336
- routeKind: "console_oauth",
337
- adapterContext
338
- };
339
- else unsupportedConsoleLogin = true;
340
- } else if (resolved?.type === "oauth") unsupportedConsoleLogin = true;
341
- } catch {}
342
- else if (activeConsole?.method === "oauth") unsupportedConsoleLogin = activeConsole.status?.status !== "needs_auth";
343
- }
344
- let activePrimary;
345
- if (!configuredGoKey) try {
346
- activePrimary = await activeListed("opencode-go");
347
- } catch {}
348
- const unsupportedPrimaryLogin = !configuredGoKey && activePrimary !== void 0 && activePrimary.method !== "key";
349
- let apiKey = configuredGoKey;
350
- for (const integrationID of configuredGoKey ? [] : ["opencode-go", "opencode"]) {
351
- let active;
352
- try {
353
- active = integrationID === "opencode-go" ? activePrimary : await activeListed(integrationID);
354
- } catch {
355
- continue;
356
- }
357
- if (!active) continue;
358
- if (goKeyOnly && active.method !== "key") return {};
359
- if (active.method !== "key" || active.status?.status === "needs_auth") continue;
360
- try {
361
- const resolved = await context.integration.connection.resolve(active);
362
- if (resolved?.type === "key" && resolved.key.trim().length > 0) {
363
- apiKey = resolved.key.trim();
364
- break;
365
- }
366
- } catch {}
367
- }
368
- if (consoleCredential) return {
369
- ...consoleCredential,
370
- ...apiKey ? { fallbackSecret: apiKey } : {}
371
- };
372
- if (apiKey) return {
373
- method: "key",
374
- secret: apiKey,
375
- routeKind: "api_key"
376
- };
377
- if (unsupportedConsoleLogin || unsupportedPrimaryLogin) return {
378
- method: "unsupported",
379
- routeKind: "unsupported"
380
- };
381
- return {};
382
- }
383
- const integrationIDs = [definition.integrationID, ...definition.fallbackIntegrationIDs ?? []];
384
- for (const integrationID of integrationIDs) {
385
- const integrationConnections = listedConnections.get(integrationID);
386
- if (!integrationConnections || integrationConnections.size === 0) continue;
387
- const active = await context.integration.connection.active(integrationID);
388
- if (active?.type !== "credential") continue;
389
- if (!integrationConnections.has(`${active.id}\0${active.method}`)) continue;
390
- if (goKeyOnly && active.method !== "key") return {};
391
- if (active.status?.status === "needs_auth") continue;
392
- if (active.method !== "oauth" && active.method !== "key") continue;
393
- if (!definition.methods.includes(active.method)) continue;
394
- const resolved = await context.integration.connection.resolve(active);
395
- if (active.method === "oauth" && resolved?.type === "oauth" && resolved.access.trim().length > 0) {
396
- const accessToken = resolved.access;
397
- if (!accessToken) return {};
398
- if (provider === "opencode-zen" && !isApprovedOpenCodeConsoleServer(resolved.metadata)) return { method: "unsupported" };
399
- const adapterContext = projectAdapterContext(provider, resolved.metadata, resolved.methodID);
400
- return {
401
- method: "oauth",
402
- ...definition.adapter ? { secret: accessToken } : {},
403
- ...adapterContext ? { adapterContext } : {}
404
- };
405
- }
406
- if (active.method === "key" && resolved?.type === "key") {
407
- if (resolved.key.trim().length === 0) return {};
408
- if (!definition.adapter) return { method: "key" };
409
- if (resolved.key.length > 0) return {
410
- method: "key",
411
- secret: resolved.key
412
- };
413
- }
414
- return {};
415
- }
416
- return {};
417
- } catch {
418
- console.warn("[pantheon-tui quota] credential resolution failed (exception)");
419
- throw new Error("Credential resolution failed");
420
- }
421
- }
422
- return {
423
- async resolveActiveGoKey() {
424
- if (disposed) return void 0;
425
- const startedAtGeneration = generation;
426
- const credential = await load("opencode-go", true);
427
- if (disposed || generation !== startedAtGeneration) return void 0;
428
- return credential.method === "key" && credential.routeKind === "api_key" ? credential.secret : void 0;
429
- },
430
- async resolve(provider) {
431
- if (disposed) return {};
432
- const now = Date.now();
433
- const cached = cache.get(provider);
434
- if (cached && cached.expiresAt > now) return cached.result;
435
- if (cached) {
436
- clearTimeout(cached.expiryTimer);
437
- cache.delete(provider);
438
- }
439
- const existing = pending.get(provider);
440
- if (existing) return existing;
441
- const startedAtGeneration = generation;
442
- let resolution;
443
- resolution = load(provider).then((result) => {
444
- if (disposed || generation !== startedAtGeneration) return {};
445
- const expiresAt = Date.now() + CREDENTIAL_CACHE_TTL_MS;
446
- const expiryTimer = setTimeout(() => {
447
- if (cache.get(provider)?.expiryTimer === expiryTimer) cache.delete(provider);
448
- }, CREDENTIAL_CACHE_TTL_MS);
449
- expiryTimer.unref();
450
- cache.set(provider, {
451
- result,
452
- expiresAt,
453
- expiryTimer
454
- });
455
- return result;
456
- }).finally(() => {
457
- if (pending.get(provider) === resolution) pending.delete(provider);
458
- });
459
- pending.set(provider, resolution);
460
- return resolution;
461
- },
462
- currentGeneration() {
463
- return generation;
464
- },
465
- isCurrent(version) {
466
- return !disposed && generation === version;
467
- },
468
- invalidate() {
469
- generation += 1;
470
- clearCache();
471
- pending.clear();
472
- },
473
- dispose() {
474
- disposed = true;
475
- generation += 1;
476
- clearCache();
477
- pending.clear();
478
- }
479
- };
480
- }
481
- function isQuotaSourceInvalidationEvent(type) {
482
- return type === "credential.updated" || type === "credential.switched" || type === "integration.updated" || type === "provider.updated";
483
- }
484
- function createAdapterExecutor(shutdownSignal, queryCli) {
485
- const MAX_CONCURRENCY = 3;
486
- const cache = /* @__PURE__ */ new Map();
487
- const pending = /* @__PURE__ */ new Map();
488
- const cooldown = /* @__PURE__ */ new Map();
489
- let activeRequests = 0;
490
- let generation = 0;
491
- const waiters = [];
492
- let invalidationController = new AbortController();
493
- function releaseRequest() {
494
- let released = false;
495
- return () => {
496
- if (released) return;
497
- released = true;
498
- while (waiters.length > 0) {
499
- const waiter = waiters.shift();
500
- if (!waiter) break;
501
- waiter.signal.removeEventListener("abort", waiter.onAbort);
502
- if (waiter.signal.aborted) {
503
- waiter.resolve(void 0);
504
- continue;
505
- }
506
- waiter.resolve(releaseRequest());
507
- return;
508
- }
509
- activeRequests -= 1;
510
- };
511
- }
512
- function acquireRequest(signal) {
513
- if (signal.aborted) return Promise.resolve(void 0);
514
- if (activeRequests < MAX_CONCURRENCY) {
515
- activeRequests += 1;
516
- return Promise.resolve(releaseRequest());
517
- }
518
- return new Promise((resolve) => {
519
- const waiter = {
520
- signal,
521
- resolve,
522
- onAbort: () => {
523
- const index = waiters.indexOf(waiter);
524
- if (index >= 0) waiters.splice(index, 1);
525
- resolve(void 0);
526
- }
527
- };
528
- waiters.push(waiter);
529
- signal.addEventListener("abort", waiter.onAbort, { once: true });
530
- });
531
- }
532
- function subscribe(entry, requestSignal) {
533
- requestSignal.throwIfAborted();
534
- const caller = Symbol();
535
- entry.callers.add(caller);
536
- return new Promise((resolve, reject) => {
537
- let detached = false;
538
- const detach = () => {
539
- if (detached) return;
540
- detached = true;
541
- requestSignal.removeEventListener("abort", onAbort);
542
- entry.callers.delete(caller);
543
- if (!entry.settled && entry.callers.size === 0) entry.controller.abort();
544
- };
545
- const onAbort = () => {
546
- detach();
547
- reject(requestSignal.reason);
548
- };
549
- requestSignal.addEventListener("abort", onAbort, { once: true });
550
- if (requestSignal.aborted) {
551
- onAbort();
552
- return;
553
- }
554
- entry.promise.then((result) => {
555
- detach();
556
- resolve(result);
557
- }, (error) => {
558
- detach();
559
- reject(error);
560
- });
561
- });
562
- }
563
- return {
564
- async run(provider, secret, requestSignal, adapterContext, fallbackSecret) {
565
- requestSignal.throwIfAborted();
566
- const now = Date.now();
567
- const until = cooldown.get(provider);
568
- if (until !== void 0 && until > now) return {
569
- reason: "rate_limited",
570
- retryAfterMs: until - now
571
- };
572
- const cached = cache.get(provider);
573
- if (cached && cached.expiresAt > now) return cached.result;
574
- const existing = pending.get(provider);
575
- if (existing && !existing.controller.signal.aborted) return subscribe(existing, requestSignal);
576
- if (existing) pending.delete(provider);
577
- const startedAtGeneration = generation;
578
- const controller = new AbortController();
579
- const signal = AbortSignal.any([
580
- shutdownSignal,
581
- invalidationController.signal,
582
- controller.signal
583
- ]);
584
- const entry = {
585
- controller,
586
- callers: /* @__PURE__ */ new Set(),
587
- settled: false,
588
- promise: Promise.resolve({ reason: "provider_error" })
589
- };
590
- pending.set(provider, entry);
591
- entry.promise = acquireRequest(signal).then(async (release) => {
592
- if (!release) return { reason: "provider_error" };
593
- try {
594
- return await runQuotaAdapter(provider, secret, signal, queryCli, adapterContext, fallbackSecret);
595
- } finally {
596
- release();
597
- }
598
- }).then((result) => {
599
- if (generation === startedAtGeneration && !signal.aborted && "state" in result) cache.set(provider, {
600
- expiresAt: Date.now() + ADAPTER_CACHE_TTL_MS,
601
- result
602
- });
603
- else if (generation === startedAtGeneration && "reason" in result && result.reason === "rate_limited" && result.retryAfterMs !== void 0) cooldown.set(provider, Date.now() + result.retryAfterMs);
604
- return result;
605
- }).finally(() => {
606
- entry.settled = true;
607
- if (pending.get(provider) === entry) pending.delete(provider);
608
- });
609
- return subscribe(entry, requestSignal);
610
- },
611
- invalidate() {
612
- generation += 1;
613
- invalidationController.abort();
614
- invalidationController = new AbortController();
615
- cache.clear();
616
- pending.clear();
617
- cooldown.clear();
618
- }
619
- };
620
- }
621
- async function getProviderStatus(resolver, adapters, requestSignal) {
622
- requestSignal.throwIfAborted();
623
- let credentialResolutionFailed = false;
624
- return {
625
- providers: (await Promise.all(PROVIDER_IDS.map(async (provider) => {
626
- const definition = QUOTA_PROVIDER_CATALOG[provider];
627
- try {
628
- requestSignal.throwIfAborted();
629
- const credentialGeneration = resolver.currentGeneration();
630
- let credential;
631
- try {
632
- credential = await resolver.resolve(provider);
633
- } catch {
634
- requestSignal.throwIfAborted();
635
- credentialResolutionFailed = true;
636
- return;
637
- }
638
- requestSignal.throwIfAborted();
639
- if (!credential.method) return void 0;
640
- if (!resolver.isCurrent(credentialGeneration)) return {
641
- provider,
642
- label: definition.label,
643
- scope: definition.scope,
644
- authentication: "unavailable",
645
- state: "unavailable",
646
- reason: "provider_error",
647
- ...routeKindField(provider, credential),
648
- metrics: []
649
- };
650
- if (credential.method === "unsupported" || !definition.methods.includes(credential.method)) return {
651
- provider,
652
- label: definition.label,
653
- scope: definition.scope,
654
- authentication: "connected",
655
- state: "unavailable",
656
- reason: "unsupported_credential_method",
657
- ...routeKindField(provider, credential),
658
- metrics: []
659
- };
660
- if (!definition.adapter) return {
661
- provider,
662
- label: definition.label,
663
- scope: definition.scope,
664
- authentication: "connected",
665
- state: "unavailable",
666
- reason: definition.blockedReason ?? "unsupported",
667
- ...routeKindField(provider, credential),
668
- metrics: []
669
- };
670
- if (!credential.secret) return {
671
- provider,
672
- label: definition.label,
673
- scope: definition.scope,
674
- authentication: "unavailable",
675
- state: "unavailable",
676
- reason: "provider_error",
677
- ...routeKindField(provider, credential),
678
- metrics: []
679
- };
680
- const result = await adapters.run(provider, credential.secret, requestSignal, credential.adapterContext, credential.fallbackSecret);
681
- requestSignal.throwIfAborted();
682
- if (!resolver.isCurrent(credentialGeneration)) return {
683
- provider,
684
- label: definition.label,
685
- scope: definition.scope,
686
- authentication: "unavailable",
687
- state: "unavailable",
688
- reason: "provider_error",
689
- ...routeKindField(provider, credential),
690
- metrics: []
691
- };
692
- if ("state" in result) return {
693
- provider,
694
- label: definition.label,
695
- scope: definition.scope,
696
- authentication: "connected",
697
- state: "available",
698
- reason: "none",
699
- ...routeKindField(provider, credential, result.routeKind),
700
- metrics: result.metrics
701
- };
702
- return {
703
- provider,
704
- label: definition.label,
705
- scope: definition.scope,
706
- authentication: "connected",
707
- state: "unavailable",
708
- reason: result.reason,
709
- ...routeKindField(provider, credential, result.routeKind),
710
- ...result.retryAfterMs === void 0 ? {} : { retry_after_ms: Math.ceil(result.retryAfterMs) },
711
- metrics: []
712
- };
713
- } catch {
714
- requestSignal.throwIfAborted();
715
- return {
716
- provider,
717
- label: definition.label,
718
- scope: definition.scope,
719
- authentication: "unavailable",
720
- state: "unavailable",
721
- reason: "provider_error",
722
- ...routeKindField(provider),
723
- metrics: []
724
- };
725
- }
726
- }))).filter((provider) => provider !== void 0),
727
- ...credentialResolutionFailed ? { credential_resolution_failed: true } : {}
728
- };
729
- }
730
- function createQuotaPlugin(queryCli = queryAlibabaTokenPlanUsage) {
731
- const goKeyDiagnostic = createGoKeyDiagnostic();
732
- return Plugin.define({
733
- id: "pantheon.tui.server",
734
- async setup(context) {
735
- const resolver = createCredentialResolver(context);
736
- const shutdownController = new AbortController();
737
- const adapters = createAdapterExecutor(shutdownController.signal, queryCli);
738
- const eventController = new AbortController();
739
- let registration;
740
- const eventTask = (async () => {
741
- try {
742
- for await (const event of context.event.subscribe({ signal: eventController.signal })) if (isQuotaSourceInvalidationEvent(event.type)) {
743
- resolver.invalidate();
744
- adapters.invalidate();
745
- if (registration) try {
746
- await registration.events.emit("credentials_changed", {});
747
- } catch {
748
- console.warn("Quota credential-change notification failed; periodic refresh remains active");
749
- }
750
- }
751
- } catch {
752
- if (!eventController.signal.aborted) {
753
- resolver.invalidate();
754
- adapters.invalidate();
755
- }
756
- }
757
- })();
758
- try {
759
- registration = await context.rpc.register(quotaRpc, {
760
- go_key_diagnostic: async (_input, callContext) => goKeyDiagnostic(() => resolver.resolveActiveGoKey(), AbortSignal.any([callContext.signal, shutdownController.signal])),
761
- status: async (_input, callContext) => getProviderStatus(resolver, adapters, callContext.signal),
762
- usage_history: async (input, callContext) => {
763
- callContext.signal.throwIfAborted();
764
- const period = input.period;
765
- return queryUsageHistoryInWorker(period, AbortSignal.any([callContext.signal, shutdownController.signal]));
766
- },
767
- active_context_cost: async (input, callContext) => {
768
- callContext.signal.throwIfAborted();
769
- return estimateActiveContextCost(input);
770
- }
771
- });
772
- } catch (error) {
773
- console.warn("[pantheon-tui quota] quota RPC registration failed:", error);
774
- eventController.abort();
775
- shutdownController.abort();
776
- resolver.dispose();
777
- adapters.invalidate();
778
- await eventTask;
779
- throw error;
780
- }
781
- return async () => {
782
- eventController.abort();
783
- shutdownController.abort();
784
- resolver.dispose();
785
- adapters.invalidate();
786
- await eventTask;
787
- await registration?.dispose();
788
- };
789
- }
790
- });
20
+ function server() {
21
+ return {};
791
22
  }
792
- var server_v2_default = createQuotaPlugin();
793
23
  //#endregion
794
- export { createQuotaPlugin, server_v2_default as default };
24
+ export { server as default };
795
25
 
796
26
  //# sourceMappingURL=server-v2.js.map