pantheon-opencode 1.6.2-beta.8 → 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 (81) hide show
  1. package/CHANGELOG.md +121 -3
  2. package/README.md +34 -60
  3. package/README.pt-BR.md +10 -12
  4. package/bin/pantheon-init.mjs +30 -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/aphrodite.md +1 -1
  17. package/src/agents/apollo.md +1 -0
  18. package/src/agents/athena.md +1 -0
  19. package/src/agents/demeter.md +1 -1
  20. package/src/agents/gaia.md +1 -0
  21. package/src/agents/hephaestus.md +1 -1
  22. package/src/agents/hermes.md +1 -1
  23. package/src/agents/iris.md +1 -1
  24. package/src/agents/mnemosyne.md +1 -0
  25. package/src/agents/nyx.md +1 -1
  26. package/src/agents/prometheus.md +1 -1
  27. package/src/agents/talos.md +1 -1
  28. package/src/agents/themis.md +1 -1
  29. package/src/agents/zeus.md +5 -2
  30. package/src/pantheon/jev-decision-tool.ts +366 -114
  31. package/src/pantheon/jev-decisions.ts +11 -13
  32. package/src/pantheon/jev-escalation.ts +639 -0
  33. package/src/pantheon/jev-quality-score.ts +432 -0
  34. package/src/pantheon/jev-risk-gate.ts +479 -0
  35. package/src/pantheon/local-decision-prompt.ts +12 -18
  36. package/src/pantheon/v2-decision-telemetry.ts +14 -4
  37. package/src/pantheon/v2-native-decisions.ts +1 -1
  38. package/src/plugin-v2.ts +201 -24
  39. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  40. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  41. package/src/plugins/tui/dist/server-v2.js +19 -789
  42. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  43. package/src/plugins/tui/dist/tui-v2.d.ts +12 -331
  44. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  45. package/src/plugins/tui/dist/tui-v2.js +257 -5370
  46. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  47. package/src/plugins/tui/dist/tui.js +1 -1
  48. package/src/plugins/tui/package-lock.json +2 -2
  49. package/src/plugins/tui/package.json +1 -1
  50. package/src/plugins/tui/src/index-v2.tsx +213 -86
  51. package/src/plugins/tui/src/server-v2.ts +18 -982
  52. package/src/plugins/tui/tsconfig.typecheck.json +1 -6
  53. package/src/plugins/tui/tsdown.config.ts +1 -11
  54. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +0 -749
  55. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +0 -1
  56. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  57. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  58. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  59. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  60. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  61. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  62. package/src/plugins/tui/dist/quota-cli.js +0 -184
  63. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  64. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +0 -684
  65. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +0 -1
  66. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +0 -118
  67. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +0 -1
  68. package/src/plugins/tui/dist/usage-history-worker.js +0 -25
  69. package/src/plugins/tui/dist/usage-history-worker.js.map +0 -1
  70. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  71. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  72. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  73. package/src/plugins/tui/src/quota-cli.ts +0 -237
  74. package/src/plugins/tui/src/quota-rpc.ts +0 -373
  75. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  76. package/src/plugins/tui/src/quota-v2.tsx +0 -1238
  77. package/src/plugins/tui/src/usage-history-contract.ts +0 -217
  78. package/src/plugins/tui/src/usage-history-validation.ts +0 -104
  79. package/src/plugins/tui/src/usage-history-view.tsx +0 -236
  80. package/src/plugins/tui/src/usage-history-worker.ts +0 -25
  81. package/src/plugins/tui/src/usage-view-model.ts +0 -272
@@ -1 +0,0 @@
1
- {"version":3,"file":"cost-data-CCZUs1aJ.js","names":["table"],"sources":["../src/model-pricing.ts","../src/cost-data.ts"],"sourcesContent":["/**\n * Model pricing — money for `pantheon_cost`.\n *\n * Prices come from the public catalog the OpenCode ecosystem already uses,\n * `https://models.dev/api.json` (USD per 1M tokens). The rule that shapes this\n * module is that a tool call must NEVER block on the network:\n *\n * - every call reads a normalized on-disk cache synchronously;\n * - an explicit `refreshPricing` is the only AWAITED fetch (bounded timeout);\n * - a missing or stale cache is refreshed in the BACKGROUND, with a short\n * timeout, so the next call benefits without this one waiting;\n * - every network/parse failure degrades to \"pricing unavailable\" and the\n * token report keeps working.\n *\n * An unknown model is never priced at zero. `0` is a real catalog price (a free\n * model), and conflating it with \"no price\" would report free usage for every\n * model the catalog has never heard of — which is precisely the number a tier\n * decision would be made on.\n *\n * Cache location follows the repository's existing config-dir convention\n * (`PANTHEON_HOME` → `$XDG_CONFIG_HOME/opencode` → `~/.config/opencode`), so no\n * new root is invented: `<configDir>/cache/models-dev.json`.\n *\n * @module model-pricing\n */\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\n\n/** The catalog URL every OpenCode-adjacent tool prices against. */\nconst MODELS_DEV_URL = 'https://models.dev/api.json'\n\n/** Cache payload version; a mismatch is treated as \"no cache\". */\nconst PRICING_CACHE_VERSION = 1\n\n/** Cached prices are considered fresh for one day. */\nconst PRICING_TTL_MS = 24 * 60 * 60 * 1000\n\n/** Upper bound for any catalog fetch, so no request can outlive a tool call. */\nconst PRICING_TIMEOUT_MS = 3000\n\n/** One model's list price, in USD per 1M tokens. */\nexport interface ModelPrice {\n inputPerMTok: number\n outputPerMTok: number\n /**\n * Absent when the catalog publishes no cache-read price. Kept distinct from\n * `0` so cache tokens can never be priced as free by accident.\n */\n cacheReadPerMTok?: number\n cacheWritePerMTok?: number\n}\n\n/** Token counts a cost is computed from. */\nexport interface TokenAmounts {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n}\n\n/** Why a row could not be priced. */\nexport type UnpricedReason =\n | 'no-pricing'\n | 'unknown-model'\n | 'ambiguous-model'\n | 'missing-cache-price'\n\n/** Resolved prices, ready for lookup. */\nexport interface PricingSnapshot {\n /** `${providerId}/${modelId}`, lowercased. */\n index: ReadonlyMap<string, ModelPrice>\n /** Model id → every provider's price for it, for provider-less lookups. */\n modelIndex: ReadonlyMap<string, readonly ModelPrice[]>\n /** True when the cache is older than the TTL. */\n stale: boolean\n /** True when a background refresh is in flight. */\n refreshing: boolean\n /** Epoch ms of the cached catalog. */\n fetchedAt?: number\n /** Set when pricing cannot be used at all, or when a refresh failed. */\n unavailableReason?: string\n /**\n * Set when a refresh was REFUSED rather than attempted (offline mode).\n * Distinguished from a failed fetch so the report can say \"no request was\n * made\" instead of implying the network was tried.\n */\n refused?: boolean\n /** True when offline mode was in effect for this snapshot. */\n offline?: boolean\n}\n\n/** Minimal fetch boundary, so tests never touch the network. */\nexport type FetchLike = (\n url: string,\n init: { signal?: AbortSignal; headers?: Record<string, string> },\n) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>\n\n/** Injectable knobs (tests, air-gapped hosts, unusual installs). */\nexport interface PricingOptions {\n /** Cache file. Default: `<configDir>/cache/models-dev.json`. */\n cachePath?: string\n /** Fetch boundary. Default: global `fetch`. */\n fetchImpl?: FetchLike\n /** Clock. Default: `Date.now`. */\n now?: () => number\n /** Freshness window. Default: {@link PRICING_TTL_MS}. */\n ttlMs?: number\n /** Environment used for cache-path resolution. Default: `process.env`. */\n env?: NodeJS.ProcessEnv\n /** Disable every network attempt (tests / air-gapped hosts). */\n offline?: boolean\n}\n\ninterface CachedCatalog {\n version: number\n fetchedAt: number\n providers: Record<string, Record<string, ModelPrice>>\n}\n\ntype ProviderPrices = Record<string, Record<string, ModelPrice>>\n\n/** Resolve the OpenCode config dir, mirroring `_pantheon_paths.py`. */\nfunction resolvePricingCacheDir(env: NodeJS.ProcessEnv = process.env): string {\n const explicit = env.PANTHEON_HOME?.trim()\n if (explicit !== undefined && explicit !== '') return explicit\n const xdg = env.XDG_CONFIG_HOME?.trim()\n const base = xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.config')\n return join(base, 'opencode')\n}\n\n/** Cache file for the normalized catalog. */\nfunction resolvePricingCachePath(env: NodeJS.ProcessEnv = process.env): string {\n return join(resolvePricingCacheDir(env), 'cache', 'models-dev.json')\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\n/** Reject nonsense prices rather than reporting a $2B session. */\nconst MAX_SANE_PER_MTOK = 100_000\n\nfunction nonNegativePrice(value: unknown): number | undefined {\n const parsed = finiteNumber(value)\n if (parsed === undefined || parsed < 0 || parsed > MAX_SANE_PER_MTOK) return undefined\n return parsed\n}\n\n/** Validate one already-normalized price from the cache file. */\nfunction buildPrice(\n input: number | undefined,\n output: number | undefined,\n cacheRead: number | undefined,\n cacheWrite: number | undefined,\n): ModelPrice | undefined {\n if (input === undefined || output === undefined) return undefined\n return {\n inputPerMTok: input,\n outputPerMTok: output,\n ...(cacheRead === undefined ? {} : { cacheReadPerMTok: cacheRead }),\n ...(cacheWrite === undefined ? {} : { cacheWritePerMTok: cacheWrite }),\n }\n}\n\nfunction parseNormalizedPrice(value: unknown): ModelPrice | undefined {\n if (!isRecord(value)) return undefined\n return buildPrice(\n nonNegativePrice(value.inputPerMTok),\n nonNegativePrice(value.outputPerMTok),\n nonNegativePrice(value.cacheReadPerMTok),\n nonNegativePrice(value.cacheWritePerMTok),\n )\n}\n\n/**\n * Validate the normalized `provider → model → price` shape.\n *\n * The cache stores the RESULT of {@link parseCatalogPayload}, not the raw\n * models.dev payload, so it must not be re-parsed as one: a normalized entry has\n * no `models` key, and treating it as a payload would silently read a valid\n * cache as empty.\n */\nfunction parseNormalizedProviders(value: unknown): ProviderPrices | undefined {\n if (!isRecord(value)) return undefined\n const providers: ProviderPrices = {}\n for (const [providerId, models] of Object.entries(value)) {\n if (!isRecord(models)) continue\n const priced: Record<string, ModelPrice> = {}\n for (const [modelId, price] of Object.entries(models)) {\n const parsed = parseNormalizedPrice(price)\n if (parsed !== undefined) priced[modelId.toLowerCase()] = parsed\n }\n if (Object.keys(priced).length > 0) providers[providerId.toLowerCase()] = priced\n }\n return Object.keys(providers).length === 0 ? undefined : providers\n}\n\n/** Parse one catalog model entry. Missing input/output cost ⇒ unpriced. */\nfunction parseModelPrice(model: unknown): ModelPrice | undefined {\n if (!isRecord(model)) return undefined\n const cost = model.cost\n if (!isRecord(cost)) return undefined\n return buildPrice(\n nonNegativePrice(cost.input),\n nonNegativePrice(cost.output),\n nonNegativePrice(cost.cache_read),\n nonNegativePrice(cost.cache_write),\n )\n}\n\n/**\n * Normalize a models.dev payload into `provider → model → price`.\n *\n * Provider and model ids are lowercased because the ledger stores whatever the\n * host wrote (`opencode-go`) and the catalog keys are not case-normalized.\n */\nexport function parseCatalogPayload(payload: unknown): ProviderPrices | undefined {\n if (!isRecord(payload)) return undefined\n const providers: ProviderPrices = {}\n for (const [providerId, provider] of Object.entries(payload)) {\n if (!isRecord(provider)) continue\n const models = provider.models\n if (!isRecord(models)) continue\n const priced: Record<string, ModelPrice> = {}\n for (const [modelId, model] of Object.entries(models)) {\n const price = parseModelPrice(model)\n if (price !== undefined) priced[modelId.toLowerCase()] = price\n }\n if (Object.keys(priced).length > 0) providers[providerId.toLowerCase()] = priced\n }\n return Object.keys(providers).length === 0 ? undefined : providers\n}\n\nfunction priceKey(price: ModelPrice): string {\n return [\n price.inputPerMTok,\n price.outputPerMTok,\n price.cacheReadPerMTok ?? '-',\n price.cacheWritePerMTok ?? '-',\n ].join('/')\n}\n\nfunction indexCatalog(providers: ProviderPrices): {\n index: Map<string, ModelPrice>\n modelIndex: Map<string, readonly ModelPrice[]>\n} {\n const index = new Map<string, ModelPrice>()\n const modelIndex = new Map<string, ModelPrice[]>()\n const seen = new Map<string, Set<string>>()\n for (const [providerId, models] of Object.entries(providers)) {\n for (const [modelId, price] of Object.entries(models)) {\n index.set(`${providerId}/${modelId}`, price)\n const bucket = modelIndex.get(modelId) ?? []\n const keys = seen.get(modelId) ?? new Set<string>()\n const key = priceKey(price)\n if (!keys.has(key)) {\n keys.add(key)\n bucket.push(price)\n seen.set(modelId, keys)\n modelIndex.set(modelId, bucket)\n }\n }\n }\n return { index, modelIndex }\n}\n\nfunction snapshotFromCatalog(\n catalog: CachedCatalog,\n now: number,\n ttlMs: number,\n refreshing: boolean,\n): PricingSnapshot {\n const { index, modelIndex } = indexCatalog(catalog.providers)\n return {\n index,\n modelIndex,\n fetchedAt: catalog.fetchedAt,\n stale: Math.max(0, now - catalog.fetchedAt) > ttlMs,\n refreshing,\n }\n}\n\nfunction unavailableSnapshot(reason: string): PricingSnapshot {\n return {\n index: new Map(),\n modelIndex: new Map(),\n stale: false,\n refreshing: false,\n unavailableReason: reason,\n }\n}\n\nfunction parseCachedCatalog(raw: unknown): CachedCatalog | undefined {\n if (!isRecord(raw)) return undefined\n if (raw.version !== PRICING_CACHE_VERSION) return undefined\n const fetchedAt = finiteNumber(raw.fetchedAt)\n if (fetchedAt === undefined) return undefined\n const providers = parseNormalizedProviders(raw.providers)\n if (providers === undefined) return undefined\n return { version: PRICING_CACHE_VERSION, fetchedAt, providers }\n}\n\n/** Read the normalized cache. Any problem reads as \"no cache\", never as zero. */\nfunction readPricingCache(cachePath: string): CachedCatalog | undefined {\n try {\n if (!existsSync(cachePath)) return undefined\n return parseCachedCatalog(JSON.parse(readFileSync(cachePath, 'utf8')))\n } catch {\n return undefined\n }\n}\n\n/** Write atomically; a cache that cannot be written must not break a report. */\nfunction writePricingCache(cachePath: string, catalog: CachedCatalog): boolean {\n const temp = `${cachePath}.tmp-${process.pid}`\n try {\n mkdirSync(dirname(cachePath), { recursive: true })\n writeFileSync(temp, `${JSON.stringify(catalog)}\\n`, 'utf8')\n renameSync(temp, cachePath)\n return true\n } catch {\n return false\n }\n}\n\nconst inFlight = new Map<string, Promise<PricingSnapshot>>()\n\n/**\n * Offline is a HOST-wide guarantee, not a hint.\n *\n * Both switches are honoured on every path that could open a socket, so the\n * env var cannot be defeated by a caller that passes `refreshPricing` (or by a\n * future code path that forgets to check). The reason names both switches,\n * because a user reading the report needs to know which one to change.\n */\nconst OFFLINE_REFUSAL =\n 'refreshPricing cannot run: PANTHEON_COST_OFFLINE=1 (or the offline option) forbids every network request'\n\nfunction isPricingOffline(options?: PricingOptions): boolean {\n const env = options?.env ?? process.env\n return options?.offline === true || env.PANTHEON_COST_OFFLINE === '1'\n}\n\n/**\n * Fetch the catalog once per cache path at a time, bounded by a timeout.\n *\n * Failures are values, not throws: the caller reports \"pricing unavailable\" and\n * keeps the token ledger it already read.\n */\nfunction refreshPricingCatalog(options?: PricingOptions): Promise<PricingSnapshot> {\n // The gate sits on the fetch itself, so no caller — background, forced, or a\n // future one — can open a socket while offline.\n if (isPricingOffline(options)) {\n return Promise.resolve({\n ...unavailableSnapshot(OFFLINE_REFUSAL),\n refused: true,\n offline: true,\n })\n }\n const env = options?.env ?? process.env\n const cachePath = options?.cachePath ?? resolvePricingCachePath(env)\n const existing = inFlight.get(cachePath)\n if (existing !== undefined) return existing\n\n const now = (options?.now ?? Date.now)()\n const ttlMs = options?.ttlMs ?? PRICING_TTL_MS\n const doFetch: FetchLike =\n options?.fetchImpl ??\n ((url, init) =>\n fetch(url, {\n ...(init.signal === undefined ? {} : { signal: init.signal }),\n ...(init.headers === undefined ? {} : { headers: init.headers }),\n }))\n\n const task = (async (): Promise<PricingSnapshot> => {\n try {\n const response = await doFetch(MODELS_DEV_URL, {\n signal: AbortSignal.timeout(PRICING_TIMEOUT_MS),\n headers: { accept: 'application/json' },\n })\n if (!response.ok) {\n return unavailableSnapshot(`models.dev returned HTTP ${response.status}`)\n }\n const providers = parseCatalogPayload(await response.json())\n if (providers === undefined) {\n return unavailableSnapshot('models.dev payload carried no usable prices')\n }\n const catalog: CachedCatalog = { version: PRICING_CACHE_VERSION, fetchedAt: now, providers }\n const cached = writePricingCache(cachePath, catalog)\n const snapshot = snapshotFromCatalog(catalog, now, ttlMs, false)\n return cached ? snapshot : { ...snapshot, unavailableReason: 'price cache is not writable' }\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n return unavailableSnapshot(`models.dev fetch failed: ${detail}`)\n } finally {\n inFlight.delete(cachePath)\n }\n })()\n\n inFlight.set(cachePath, task)\n return task\n}\n\n/**\n * Load prices without blocking on the network.\n *\n * A stale cache is served immediately and refreshed in the background; with no\n * cache there is nothing to serve, so the snapshot is explicitly unavailable\n * and `pending` carries the opportunistic refresh for callers that want it.\n */\nexport function loadPricing(options?: PricingOptions): {\n snapshot: PricingSnapshot\n pending?: Promise<void>\n} {\n const env = options?.env ?? process.env\n const cachePath = options?.cachePath ?? resolvePricingCachePath(env)\n const now = (options?.now ?? Date.now)()\n const ttlMs = options?.ttlMs ?? PRICING_TTL_MS\n const catalog = readPricingCache(cachePath)\n const offline = isPricingOffline(options)\n\n if (catalog === undefined) {\n if (offline) {\n return {\n snapshot: {\n ...unavailableSnapshot(\n 'no price cache, and pricing is offline (PANTHEON_COST_OFFLINE=1 or the offline option)',\n ),\n offline: true,\n },\n }\n }\n const pending = refreshPricingCatalog(options)\n return {\n snapshot: unavailableSnapshot(\n 'no cached models.dev catalog yet; fetching one in the background',\n ),\n pending: pending.then(() => undefined),\n }\n }\n\n const snapshot = snapshotFromCatalog(catalog, now, ttlMs, false)\n if (!snapshot.stale || offline) {\n return { snapshot: offline ? { ...snapshot, offline: true } : snapshot }\n }\n // Stale prices are better than none: serve them and refresh behind the call.\n const pending = refreshPricingCatalog(options)\n return {\n snapshot: { ...snapshot, refreshing: true },\n pending: pending.then(() => undefined),\n }\n}\n\n/**\n * Await a refresh — only for an explicit `refreshPricing: true`.\n *\n * On failure the previously cached prices are still returned (marked stale), so\n * a failed refresh does not erase the only prices the host has.\n */\nexport async function forceRefreshPricing(options?: PricingOptions): Promise<PricingSnapshot> {\n const refreshed = await refreshPricingCatalog(options)\n if (refreshed.unavailableReason === undefined) return refreshed\n const env = options?.env ?? process.env\n const cachePath = options?.cachePath ?? resolvePricingCachePath(env)\n const catalog = readPricingCache(cachePath)\n if (catalog === undefined) return refreshed\n const now = (options?.now ?? Date.now)()\n const cached = snapshotFromCatalog(catalog, now, options?.ttlMs ?? PRICING_TTL_MS, false)\n return {\n ...cached,\n unavailableReason: refreshed.unavailableReason,\n ...(refreshed.refused === true ? { refused: true } : {}),\n ...(refreshed.offline === true ? { offline: true } : {}),\n }\n}\n\n/** Result of a price lookup. */\nexport type PriceLookup = { ok: true; price: ModelPrice } | { ok: false; reason: UnpricedReason }\n\n/**\n * Resolve a price for one ledger model.\n *\n * Exact `provider/model` wins. A model that exists under exactly one provider\n * price is accepted when the ledger's provider id is unknown to the catalog\n * (real hosts name their own gateways, e.g. `opencode-go` serving a model the\n * catalog lists under `opencode`). Two DIFFERENT prices for the same model id\n * are ambiguous and stay unpriced rather than guessing a provider.\n */\nexport function lookupModelPrice(\n snapshot: PricingSnapshot,\n providerId: string | undefined,\n modelId: string | undefined,\n): PriceLookup {\n if (snapshot.index.size === 0) return { ok: false, reason: 'no-pricing' }\n const model = (modelId ?? '').trim().toLowerCase()\n if (model === '') return { ok: false, reason: 'unknown-model' }\n const provider = (providerId ?? '').trim().toLowerCase()\n if (provider !== '') {\n const exact = snapshot.index.get(`${provider}/${model}`)\n if (exact !== undefined) return { ok: true, price: exact }\n }\n const candidates = snapshot.modelIndex.get(model) ?? []\n const only = candidates.length === 1 ? candidates[0] : undefined\n if (only !== undefined) return { ok: true, price: only }\n if (candidates.length === 0) return { ok: false, reason: 'unknown-model' }\n return { ok: false, reason: 'ambiguous-model' }\n}\n\n/** Result of the cost math. */\nexport type CostResult = { ok: true; usd: number } | { ok: false; reason: 'missing-cache-price' }\n\n/**\n * Cost of one model's token counts.\n *\n * Cache tokens are billed at their own rate; when the catalog has no cache rate\n * the row is unpriced instead of being charged at the input rate or at zero.\n */\nexport function computeModelCost(price: ModelPrice, tokens: TokenAmounts): CostResult {\n let usd = (tokens.input * price.inputPerMTok + tokens.output * price.outputPerMTok) / 1_000_000\n if (tokens.cacheRead > 0) {\n const rate = price.cacheReadPerMTok\n if (rate === undefined) return { ok: false, reason: 'missing-cache-price' }\n usd += (tokens.cacheRead * rate) / 1_000_000\n }\n if (tokens.cacheWrite > 0) {\n const rate = price.cacheWritePerMTok\n if (rate === undefined) return { ok: false, reason: 'missing-cache-price' }\n usd += (tokens.cacheWrite * rate) / 1_000_000\n }\n return { ok: true, usd }\n}\n","/**\n * Read-only cost and usage data shared by the CLI and the TUI package.\n *\n * This module lives inside the TUI package so its worker and bundled server do\n * not import source files outside the package boundary. The CLI imports these\n * same helpers, preserving a single implementation.\n */\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport {\n computeModelCost,\n loadPricing,\n lookupModelPrice,\n type PricingOptions,\n type PricingSnapshot,\n type UnpricedReason,\n} from './model-pricing.ts'\n\nexport interface SqliteDatabase {\n prepare(sql: string): {\n get(...args: unknown[]): unknown\n all(...args: unknown[]): unknown[]\n }\n close(): void\n}\n\nexport interface SqliteModule {\n DatabaseSync: new (path: string, options: { readOnly: boolean }) => SqliteDatabase\n}\n\nexport type OpenCodeVersion = 'v1' | 'v2'\n\n/**\n * Host table families that can carry a token ledger. A migrated database\n * carries both at once.\n */\nexport type CostSource = 'message' | 'session_message'\n\nconst COST_SOURCES: readonly CostSource[] = ['message', 'session_message']\n\n/**\n * Which table family each host generation stores its ledger in.\n *\n * Spelled out rather than comparing the literals: `'message' === 'v1'` is\n * false, so a filter written as `source === requested` narrows to nothing and\n * every version-pinned read fails.\n */\nconst VERSION_SOURCES: Record<OpenCodeVersion, CostSource> = {\n v1: 'message',\n v2: 'session_message',\n}\n\n/** The XDG state directory every real host installation writes its ledger to. */\nfunction defaultDbPath(): string {\n const xdg = process.env.XDG_DATA_HOME\n const dataHome = xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.local', 'share')\n return join(dataHome, 'opencode', 'opencode.db')\n}\n\n/** Read and validate the optional host-generation selector. */\nexport function requestedVersion(): OpenCodeVersion | undefined {\n const configured = process.env.PANTHEON_OPENCODE_VERSION\n if (configured === undefined) return undefined\n if (configured !== 'v1' && configured !== 'v2') {\n throw new Error(`invalid PANTHEON_OPENCODE_VERSION \"${configured}\"; expected \"v1\" or \"v2\"`)\n }\n return configured\n}\n\n/**\n * Resolve the database.\n *\n * Precedence: explicit option → PANTHEON_COST_DB → OPENCODE_DB → the XDG\n * default `opencode.db`. An invalid PANTHEON_OPENCODE_VERSION fails fast rather\n * than being silently ignored.\n *\n * There is deliberately NO per-version filename. Deriving one from the host\n * generation pointed the V2 report at `opencode-v2.db`, which exists only\n * because a sandbox sets OPENCODE_DB — hence OPENCODE_DB's place in this chain.\n */\nexport function resolveCostDbPath(options?: { dbPath?: string }): string {\n const explicit = options?.dbPath || process.env.PANTHEON_COST_DB || process.env.OPENCODE_DB\n if (explicit) return explicit\n requestedVersion()\n return defaultDbPath()\n}\n\n/**\n * Detect the ledger families by TABLE PRESENCE.\n *\n * Presence is the only reliable discriminator: a migrated database carries both\n * families, so pinning a schema-version constant would break whichever\n * population it excluded, and no manifest declares a supported host range.\n * PANTHEON_OPENCODE_VERSION only NARROWS an already-detected set — it never\n * chooses a file and never invents a family that is not there.\n */\nexport function resolveSources(\n db: SqliteDatabase,\n requested: OpenCodeVersion | undefined,\n): CostSource[] {\n const present = new Set(\n (\n db\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('message', 'session_message')\",\n )\n .all() as Array<{ name?: unknown }>\n ).map((row) => String(row.name)),\n )\n const detected = COST_SOURCES.filter((source) => present.has(source))\n if (detected.length === 0) {\n throw new Error(\n 'incompatible opencode.db schema: neither the \"message\" nor the \"session_message\" table exists, so there is no token ledger to read',\n )\n }\n if (requested === undefined) return detected\n const wanted = VERSION_SOURCES[requested]\n const narrowed = detected.filter((source) => source === wanted)\n if (narrowed.length === 0) {\n throw new Error(\n `incompatible opencode.db schema: PANTHEON_OPENCODE_VERSION=${requested} selected no table family, but this database contains ${detected.join(' and ')}`,\n )\n }\n return narrowed\n}\n\n/**\n * UTC day + provider/model aggregation used by the TUI charts.\n *\n * The only interpolated fragments are fixed module constants (family table,\n * discriminator, and time predicates). JSON is validated in the CTE before\n * extraction, and all time bounds remain bound SQL parameters.\n */\nfunction assistantLedgerPredicate(source: CostSource): string {\n return source === 'message'\n ? \"CASE WHEN json_valid(data) THEN json_extract(data, '$.role') = 'assistant' ELSE 0 END\"\n : \"type = 'assistant'\"\n}\n\nfunction usageHistorySql(source: CostSource, rolling: boolean): string {\n const table = source\n const assistantPredicate = assistantLedgerPredicate(source)\n const timeRange = rolling\n ? 'AND time_created >= ? AND time_created <= ?'\n : 'AND time_created <= ?'\n return `\n WITH valid AS (\n SELECT strftime('%Y-%m-%d', time_created / 1000, 'unixepoch') AS day,\n COALESCE(NULLIF(TRIM(json_extract(data, '$.model.providerID')), ''),\n NULLIF(TRIM(json_extract(data, '$.providerID')), '')) AS provider,\n COALESCE(NULLIF(TRIM(json_extract(data, '$.model.id')), ''),\n NULLIF(TRIM(json_extract(data, '$.modelID')), '')) AS model,\n CASE WHEN json_type(data, '$.agent') IS NULL\n OR json_extract(data, '$.agent') IS NULL\n OR TRIM(json_extract(data, '$.agent')) = ''\n THEN 1 ELSE 0 END AS agentless,\n CASE WHEN json_type(data, '$.tokens.input') IN ('integer', 'real')\n AND json_extract(data, '$.tokens.input') >= 0\n THEN CAST(json_extract(data, '$.tokens.input') AS INTEGER) ELSE 0 END AS inTok,\n CASE WHEN json_type(data, '$.tokens.output') IN ('integer', 'real')\n AND json_extract(data, '$.tokens.output') >= 0\n THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END AS outTok,\n CASE WHEN json_type(data, '$.tokens.cache.read') IN ('integer', 'real')\n AND json_extract(data, '$.tokens.cache.read') >= 0\n THEN CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) ELSE 0 END AS cacheReadTok,\n CASE WHEN json_type(data, '$.tokens.cache.write') IN ('integer', 'real')\n AND json_extract(data, '$.tokens.cache.write') >= 0\n THEN CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) ELSE 0 END AS cacheWriteTok\n FROM ${table}\n WHERE json_valid(data) AND ${assistantPredicate} ${timeRange}\n )\n SELECT day,\n provider,\n model,\n COUNT(*) AS rows,\n SUM(agentless) AS agentlessRows,\n COALESCE(SUM(inTok), 0) AS tokensInput,\n COALESCE(SUM(outTok), 0) AS tokensOutput,\n COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,\n COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite\n FROM valid\n GROUP BY day, provider, model\n ORDER BY day, provider, model`\n}\n\nfunction usageCoverageSql(source: CostSource): string {\n const table = source\n const assistantPredicate = assistantLedgerPredicate(source)\n return `SELECT MIN(time_created) AS coverageStartAt\n FROM ${table}\n WHERE json_valid(data) AND ${assistantPredicate} AND time_created <= ?`\n}\n\nexport function numberOf(value: unknown): number | undefined {\n if (value === null || value === undefined) return undefined\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/** A ledger label the catalog cannot know; never an empty string. */\nexport function ledgerLabel(value: unknown): string {\n if (value === undefined || value === null) return 'unknown'\n const text = String(value).trim()\n return text === '' ? 'unknown' : text\n}\n\n/** Price one group, or explain why it cannot be priced. */\nexport function priceTokens(\n pricing: PricingSnapshot | undefined,\n provider: string,\n model: string,\n tokens: { input: number; output: number; cacheRead: number; cacheWrite: number },\n): { usd: number } | { reason: UnpricedReason } {\n if (pricing === undefined) return { reason: 'no-pricing' }\n const lookup = lookupModelPrice(pricing, provider, model)\n if (!lookup.ok) return { reason: lookup.reason }\n const cost = computeModelCost(lookup.price, tokens)\n if (!cost.ok) return { reason: cost.reason }\n return { usd: cost.usd }\n}\n\n/** Available chart windows. Rolling windows are exact 24-hour ranges ending now. */\nexport type UsageHistoryPeriod = '7d' | '15d' | '30d' | 'total'\n\n/** Token quantities; `total` follows the cost report convention: input + output. */\nexport interface UsageTokenTotals {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n total: number\n}\n\n/** One UTC calendar-day bucket, with catalog estimate omitted when unpriceable. */\nexport interface UsageHistoryBucket extends UsageTokenTotals {\n date: string\n estimatedUsd?: number\n pricingComplete: boolean\n}\n\n/** One provider/model's date series and totals. */\nexport interface UsageHistoryModel {\n providerID: string\n modelID: string\n rows: number\n agentlessRows: number\n buckets: UsageHistoryBucket[]\n totals: UsageTokenTotals\n estimatedUsd?: number\n pricingComplete: boolean\n unpricedReason?: UnpricedReason\n}\n\nexport type UsagePricingStatus = 'empty' | 'unavailable' | 'partial' | 'complete'\n\n/** Catalog-derived USD is an estimate, not a provider invoice. */\nexport interface UsageHistoryPricing {\n status: UsagePricingStatus\n complete: boolean\n estimatedUsd?: number\n unpricedModels: number\n}\n\n/** Read-only chart data for the rows present in the current opencode.db. */\nexport interface UsageHistoryResult {\n period: UsageHistoryPeriod\n /** Earliest ledger record actually present in the database, as UTC date. */\n coverageStart: string | null\n /** Exact epoch-ms start of the earliest ledger record. */\n coverageStartAt: number | null\n /** True only when a rolling window begins before this database's earliest ledger record. */\n partial: boolean\n rows: number\n buckets: UsageHistoryBucket[]\n totals: UsageTokenTotals\n models: UsageHistoryModel[]\n pricing: UsageHistoryPricing\n}\n\nexport interface UsageHistoryOptions {\n /** Injectable clock for deterministic rolling-window boundaries. */\n now?: number\n /** Explicit price snapshot; otherwise only the on-disk cache is read. */\n pricing?: PricingSnapshot\n /** Cache path/environment injection; all network refreshes are disabled. */\n pricingOptions?: PricingOptions\n}\n\n/** Current context estimate input; cache metrics are intentionally not accepted. */\nexport interface ActiveContextCostInput {\n providerID: string | null\n modelID: string | null\n contextTokens: number | null\n}\n\nexport interface ActiveContextCostEstimate {\n status: 'estimated' | 'unavailable'\n /** Catalog estimate from context tokens × input price; never a billed amount. */\n estimatedUsd?: number\n billed: false\n basis: 'pre-cache-context-tokens-times-input-price'\n cacheDiscountApplied: false\n reason?: 'invalid-context-token-count' | 'missing-model-identity' | UnpricedReason\n}\n\ninterface UsageHistoryLedgerGroup {\n day?: unknown\n provider?: unknown\n model?: unknown\n rows?: unknown\n agentlessRows?: unknown\n tokensInput?: unknown\n tokensOutput?: unknown\n tokensCacheRead?: unknown\n tokensCacheWrite?: unknown\n}\n\ninterface MutableUsageTokens {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n}\n\ninterface MutableUsageDay {\n tokens: MutableUsageTokens\n rows: number\n agentlessRows: number\n}\n\ninterface MutableUsageModel {\n providerID: string\n modelID: string\n tokens: MutableUsageTokens\n rows: number\n agentlessRows: number\n days: Map<string, MutableUsageDay>\n}\n\nfunction emptyUsageTokens(): MutableUsageTokens {\n return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }\n}\n\nfunction addUsageTokens(target: MutableUsageTokens, source: MutableUsageTokens): void {\n target.input += source.input\n target.output += source.output\n target.cacheRead += source.cacheRead\n target.cacheWrite += source.cacheWrite\n}\n\nfunction toUsageTokenTotals(tokens: MutableUsageTokens): UsageTokenTotals {\n return {\n input: tokens.input,\n output: tokens.output,\n cacheRead: tokens.cacheRead,\n cacheWrite: tokens.cacheWrite,\n // Cache channels are shown independently and are not folded into total.\n total: tokens.input + tokens.output,\n }\n}\n\nfunction offlinePricing(options?: UsageHistoryOptions): PricingSnapshot {\n return options?.pricing ?? loadPricing({ ...options?.pricingOptions, offline: true }).snapshot\n}\n\n/**\n * Read daily token history for the Usage charts.\n *\n * Rolling periods are exact N×24-hour windows ending at `now`; daily buckets\n * are UTC dates. Future-dated rows are excluded from every period, including\n * `total`, while `total` has no lower age cap. Both V1 and V2 tables are read\n * when a migrated database contains both. The database is opened read-only and\n * model pricing comes only from a cached snapshot: this path never fetches pricing.\n */\nexport async function queryUsageHistory(\n dbPath: string,\n period: UsageHistoryPeriod,\n options?: UsageHistoryOptions,\n): Promise<UsageHistoryResult> {\n const dayCounts: Record<Exclude<UsageHistoryPeriod, 'total'>, number> = {\n '7d': 7,\n '15d': 15,\n '30d': 30,\n }\n if (period !== 'total' && !Object.hasOwn(dayCounts, period)) {\n throw new Error(`unsupported usage history period: ${String(period)}`)\n }\n const now = options?.now ?? Date.now()\n if (!Number.isFinite(now)) throw new Error('usage history clock must be finite')\n const rolling = period !== 'total'\n const since = rolling ? now - dayCounts[period] * 86_400_000 : undefined\n const sqlite = (await import('node:sqlite')) as SqliteModule\n const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })\n try {\n // Historical charts always mean all known ledger families in this file.\n // The host-version override is a diagnostic narrowing for pantheon_cost,\n // not a reason to hide rows from a database-wide history view.\n const sources = resolveSources(db, undefined)\n const models = new Map<string, MutableUsageModel>()\n let rows = 0\n let coverageStartAt: number | null = null\n\n for (const source of sources) {\n const coverage = db.prepare(usageCoverageSql(source)).get(now) as {\n coverageStartAt?: unknown\n }\n const sourceStart = numberOf(coverage?.coverageStartAt)\n if (sourceStart !== undefined) {\n coverageStartAt =\n coverageStartAt === null ? sourceStart : Math.min(coverageStartAt, sourceStart)\n }\n\n const groups = db\n .prepare(usageHistorySql(source, rolling))\n .all(...(since === undefined ? [now] : [since, now])) as UsageHistoryLedgerGroup[]\n for (const group of groups) {\n if (typeof group.day !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}$/.test(group.day)) continue\n const providerID = ledgerLabel(group.provider)\n const modelID = ledgerLabel(group.model)\n const key = `${providerID}\\u0000${modelID}`\n const model = models.get(key) ?? {\n providerID,\n modelID,\n tokens: emptyUsageTokens(),\n rows: 0,\n agentlessRows: 0,\n days: new Map<string, MutableUsageDay>(),\n }\n const tokens: MutableUsageTokens = {\n input: numberOf(group.tokensInput) ?? 0,\n output: numberOf(group.tokensOutput) ?? 0,\n cacheRead: numberOf(group.tokensCacheRead) ?? 0,\n cacheWrite: numberOf(group.tokensCacheWrite) ?? 0,\n }\n const groupRows = numberOf(group.rows) ?? 0\n const agentlessRows = numberOf(group.agentlessRows) ?? 0\n rows += groupRows\n addUsageTokens(model.tokens, tokens)\n model.rows += groupRows\n model.agentlessRows += agentlessRows\n const day = model.days.get(group.day) ?? {\n tokens: emptyUsageTokens(),\n rows: 0,\n agentlessRows: 0,\n }\n addUsageTokens(day.tokens, tokens)\n day.rows += groupRows\n day.agentlessRows += agentlessRows\n model.days.set(group.day, day)\n models.set(key, model)\n }\n }\n\n const priceSnapshot = offlinePricing(options)\n const daily = new Map<\n string,\n { tokens: MutableUsageTokens; usd: number; pricedModels: number; unpricedModels: number }\n >()\n let pricedModels = 0\n let unpricedModels = 0\n let estimatedUsd = 0\n const modelRows: UsageHistoryModel[] = []\n\n for (const model of models.values()) {\n const totalsPrice = priceTokens(priceSnapshot, model.providerID, model.modelID, {\n input: model.tokens.input,\n output: model.tokens.output,\n cacheRead: model.tokens.cacheRead,\n cacheWrite: model.tokens.cacheWrite,\n })\n const modelPriced = 'usd' in totalsPrice\n if ('usd' in totalsPrice) {\n pricedModels += 1\n estimatedUsd += totalsPrice.usd\n } else {\n unpricedModels += 1\n }\n\n const buckets: UsageHistoryBucket[] = [...model.days.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([date, value]) => {\n const bucketPrice = priceTokens(priceSnapshot, model.providerID, model.modelID, {\n input: value.tokens.input,\n output: value.tokens.output,\n cacheRead: value.tokens.cacheRead,\n cacheWrite: value.tokens.cacheWrite,\n })\n const dailyTotal = daily.get(date) ?? {\n tokens: emptyUsageTokens(),\n usd: 0,\n pricedModels: 0,\n unpricedModels: 0,\n }\n addUsageTokens(dailyTotal.tokens, value.tokens)\n if ('usd' in bucketPrice) {\n dailyTotal.usd += bucketPrice.usd\n dailyTotal.pricedModels += 1\n } else {\n dailyTotal.unpricedModels += 1\n }\n daily.set(date, dailyTotal)\n return {\n date,\n ...toUsageTokenTotals(value.tokens),\n ...('usd' in bucketPrice ? { estimatedUsd: bucketPrice.usd } : {}),\n pricingComplete: 'usd' in bucketPrice,\n }\n })\n\n modelRows.push({\n providerID: model.providerID,\n modelID: model.modelID,\n rows: model.rows,\n agentlessRows: model.agentlessRows,\n buckets,\n totals: toUsageTokenTotals(model.tokens),\n ...('usd' in totalsPrice ? { estimatedUsd: totalsPrice.usd } : {}),\n pricingComplete: modelPriced,\n ...(!modelPriced && 'reason' in totalsPrice ? { unpricedReason: totalsPrice.reason } : {}),\n })\n }\n\n modelRows.sort(\n (left, right) =>\n left.providerID.localeCompare(right.providerID) ||\n left.modelID.localeCompare(right.modelID),\n )\n const buckets: UsageHistoryBucket[] = [...daily.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([date, value]) => ({\n date,\n ...toUsageTokenTotals(value.tokens),\n ...(value.pricedModels > 0 ? { estimatedUsd: value.usd } : {}),\n pricingComplete: value.unpricedModels === 0,\n }))\n\n const empty = rows === 0\n const pricingStatus: UsagePricingStatus = empty\n ? 'empty'\n : pricedModels === 0\n ? 'unavailable'\n : unpricedModels > 0\n ? 'partial'\n : 'complete'\n const totals = emptyUsageTokens()\n for (const model of models.values()) addUsageTokens(totals, model.tokens)\n const requestedStart = since\n return {\n period,\n coverageStart:\n coverageStartAt === null ? null : new Date(coverageStartAt).toISOString().slice(0, 10),\n coverageStartAt,\n partial:\n requestedStart !== undefined &&\n coverageStartAt !== null &&\n coverageStartAt > requestedStart,\n rows,\n buckets,\n totals: toUsageTokenTotals(totals),\n models: modelRows,\n pricing: {\n status: pricingStatus,\n complete: pricingStatus === 'complete',\n ...(pricedModels > 0 ? { estimatedUsd } : {}),\n unpricedModels,\n },\n }\n } finally {\n db.close()\n }\n}\n\n/**\n * Estimate current context cost using only its token count and cached input rate.\n * This is a pre-cache estimate, applies no cache discount, and is not billed or\n * used to alter host-reported session spend.\n */\nexport function estimateActiveContextCost(\n input: ActiveContextCostInput,\n options?: UsageHistoryOptions,\n): ActiveContextCostEstimate {\n const metadata = {\n billed: false as const,\n basis: 'pre-cache-context-tokens-times-input-price' as const,\n cacheDiscountApplied: false as const,\n }\n if (\n typeof input.contextTokens !== 'number' ||\n !Number.isSafeInteger(input.contextTokens) ||\n input.contextTokens < 0\n ) {\n return { status: 'unavailable', ...metadata, reason: 'invalid-context-token-count' }\n }\n if (!input.providerID?.trim() || !input.modelID?.trim()) {\n return { status: 'unavailable', ...metadata, reason: 'missing-model-identity' }\n }\n const pricing = offlinePricing(options)\n const lookup = lookupModelPrice(pricing, input.providerID, input.modelID)\n if (!lookup.ok) {\n return { status: 'unavailable', ...metadata, reason: lookup.reason }\n }\n return {\n status: 'estimated',\n ...metadata,\n estimatedUsd: (input.contextTokens / 1_000_000) * lookup.price.inputPerMTok,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,iBAAiB;;AAGvB,MAAM,wBAAwB;;AAG9B,MAAM,iBAAiB;;AAGvB,MAAM,qBAAqB;;AAoF3B,SAAS,uBAAuB,MAAyB,QAAQ,KAAa;CAC5E,MAAM,WAAW,IAAI,eAAe,KAAK;CACzC,IAAI,aAAa,KAAA,KAAa,aAAa,IAAI,OAAO;CACtD,MAAM,MAAM,IAAI,iBAAiB,KAAK;CACtC,MAAM,OAAO,QAAQ,KAAA,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AAM;GACjC,QAAQ;GACR,SAAS;IACP,QAAQ;IACR,UAAU,kBAAkB;IAC5B,GAAI,eAAe,IAAI,EAAE,aAAa,IAAI,CAAC;IAC3C;GACF;EACF;CACF,UAAU;EACR,GAAG,MAAM;CACX;AACF;;;;;;AAOA,SAAgB,0BACd,OACA,SAC2B;CAC3B,MAAM,WAAW;EACf,QAAQ;EACR,OAAO;EACP,sBAAsB;CACxB;CACA,IACE,OAAO,MAAM,kBAAkB,YAC/B,CAAC,OAAO,cAAc,MAAM,aAAa,KACzC,MAAM,gBAAgB,GAEtB,OAAO;EAAE,QAAQ;EAAe,GAAG;EAAU,QAAQ;CAA8B;CAErF,IAAI,CAAC,MAAM,YAAY,KAAK,KAAK,CAAC,MAAM,SAAS,KAAK,GACpD,OAAO;EAAE,QAAQ;EAAe,GAAG;EAAU,QAAQ;CAAyB;CAGhF,MAAM,SAAS,iBADC,eAAe,OACC,GAAS,MAAM,YAAY,MAAM,OAAO;CACxE,IAAI,CAAC,OAAO,IACV,OAAO;EAAE,QAAQ;EAAe,GAAG;EAAU,QAAQ,OAAO;CAAO;CAErE,OAAO;EACL,QAAQ;EACR,GAAG;EACH,cAAe,MAAM,gBAAgB,MAAa,OAAO,MAAM;CACjE;AACF"}
@@ -1,89 +0,0 @@
1
- import { queryAlibabaTokenPlanUsage } from "./quota-cli.js";
2
- //#region src/quota-rpc.d.ts
3
- /** Full provider matrix approved for the V2 quota surface. */
4
- declare const QUOTA_PROVIDER_IDS: readonly ['anthropic', 'chutes', 'cursor', 'github-copilot', 'google-agy', 'kilo-gateway', 'nanogpt', 'ollama-cloud', 'openai', 'opencode-go', 'opencode-zen', 'openrouter', 'synthetic', 'xai-supergrok', 'gemini-cli', 'alibaba-coding-plan', 'alibaba-token-plan', 'deepseek', 'kimi-code-global', 'kimi-code-cn', 'minimax-plan-global', 'minimax-plan-cn', 'xiaomi-mimo', 'zai-coding-plan', 'zhipu-coding-plan'];
5
- type QuotaProviderId = (typeof QUOTA_PROVIDER_IDS)[number];
6
- //#endregion
7
- //#region src/quota-adapters.d.ts
8
- export declare const OPENAI_CODEX_OAUTH_METHOD_IDS: readonly ['chatgpt-browser', 'chatgpt-headless'];
9
- type OpenAICodexOAuthMethodID = (typeof OPENAI_CODEX_OAUTH_METHOD_IDS)[number];
10
- export declare function isOpenAICodexOAuthMethod(value: unknown): value is OpenAICodexOAuthMethodID;
11
- export declare const OPENCODE_CONSOLE_OAUTH_METHOD_IDS: readonly ['device'];
12
- type OpenCodeConsoleOAuthMethodID = (typeof OPENCODE_CONSOLE_OAUTH_METHOD_IDS)[number];
13
- export declare function isOpenCodeConsoleOAuthMethod(value: unknown): value is OpenCodeConsoleOAuthMethodID;
14
- type OAuthMethodID = OpenAICodexOAuthMethodID | OpenCodeConsoleOAuthMethodID;
15
- export type QuotaAdapterContext = {
16
- readonly projectId?: string;
17
- readonly accountId?: string;
18
- readonly orgId?: string;
19
- readonly methodID?: OAuthMethodID;
20
- };
21
- export type QuotaAudience = 'us_personal' | 'us_business' | 'china_personal' | 'china_business';
22
- export type QuotaMetric = {
23
- kind: 'provider_quota';
24
- used: number;
25
- remaining: number;
26
- unit: string;
27
- label: string;
28
- period?: string;
29
- resetsAt?: number;
30
- } | {
31
- kind: 'balance';
32
- amount: number;
33
- currency: 'USD' | 'CNY';
34
- label: string;
35
- status?: 'available' | 'unavailable' | 'active' | 'inactive';
36
- } | {
37
- kind: 'estimate';
38
- amount: number;
39
- unit: string;
40
- label: string;
41
- } | {
42
- kind: 'provider_status';
43
- status: 'available' | 'unavailable' | 'active' | 'inactive';
44
- label: string;
45
- } | {
46
- kind: 'key_usage';
47
- amount: number;
48
- currency: 'USD' | 'CNY';
49
- label: string;
50
- period?: string;
51
- } | {
52
- kind: 'session_usage';
53
- amount: number;
54
- unit: string;
55
- label: string;
56
- };
57
- export type AdapterFailureReason = 'provider_error' | 'not_subscribed' | 'rate_limited' | 'unauthorized' | 'forbidden' | 'timeout' | 'network_error' | 'invalid_response' | 'cli_identity_unavailable' | 'eligibility_unverified';
58
- export type AdapterFailure = {
59
- readonly reason: AdapterFailureReason;
60
- readonly retryAfterMs?: number;
61
- };
62
- type ProviderDefinition = {
63
- readonly label: string;
64
- readonly integrationID: string;
65
- readonly fallbackIntegrationIDs?: readonly string[];
66
- readonly audiences: readonly QuotaAudience[];
67
- readonly scope: 'account' | 'selected_key' | 'team' | 'session';
68
- readonly methods: readonly ('key' | 'oauth' | 'cli')[];
69
- readonly source?: 'integration' | 'local-cli';
70
- readonly adapter?: 'anthropic' | 'chutes' | 'copilot' | 'deepseek' | 'google-agy' | 'alibaba-token-plan-cli' | 'kilo-gateway' | 'kimi-global' | 'kimi-cn' | 'minimax-global' | 'minimax-cn' | 'nanogpt' | 'ollama-cloud' | 'openai' | 'openrouter' | 'opencode-go' | 'opencode-zen' | 'synthetic' | 'xai-supergrok' | 'zai' | 'zhipu';
71
- readonly blockedReason?: 'unsupported' | 'private_endpoint' | 'eligibility_unverified' | 'runtime_accounting_unavailable' | 'cli_identity_unavailable';
72
- };
73
- /**
74
- * Closed provider/integration/method allowlist. Only rows with a reviewed
75
- * adapter may make a network request; remaining rows are explicitly blocked.
76
- * Audience lists describe the approved matrix and do not claim that account
77
- * type was inferred from credentials.
78
- */
79
- export declare const QUOTA_PROVIDER_CATALOG: Record<QuotaProviderId, ProviderDefinition>;
80
- export type AdapterResult = {
81
- readonly state: 'available';
82
- readonly metrics: QuotaMetric[];
83
- readonly routeKind?: 'api_key' | 'console_oauth';
84
- } | (AdapterFailure & {
85
- readonly routeKind?: 'api_key' | 'console_oauth';
86
- });
87
- export declare function runQuotaAdapter(provider: QuotaProviderId, secret: string | undefined, shutdownSignal: AbortSignal, queryCli?: typeof queryAlibabaTokenPlanUsage, adapterContext?: QuotaAdapterContext, fallbackSecret?: string): Promise<AdapterResult>;
88
- //#endregion
89
- //# sourceMappingURL=quota-adapters.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"quota-adapters.d.ts","names":[],"sources":["../src/quota-rpc.ts","../src/quota-adapters.ts"],"mappings":";;;cAQa;KA4BD,0BAA0B;;;qBC/BzB;KACR,mCAAmC;wBAExB,yBAAyB,iBAAiB,SAAS;qBAQtD;KACR,uCAAuC;wBAE5B,6BACd,iBACC,SAAS;KAOP,gBAAgB,2BAA2B;YAEpC;WACD;WACA;WACA;WACA,WAAW;;YAGV;YACA;EAEN;EACA;EACA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;;EAEA;EAAkB;EAAgB;EAAc;;EAEhD;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;;EAEA;EAAuB;EAAgB;EAAc;;YAE/C;YAWA;WACD,QAAQ;WACR;;KAGN;WACM;WACA;WACA;WACA,oBAAoB;WACpB;WACA;WACA;WACA;WAsBA;;;;;;;;qBAsBE,wBAAwB,OAAO,iBAAiB;YAqNjD;WAEG;WACA,SAAS;WACT;KAEV;WAA4B;;wBA2/BX,gBACpB,UAAU,iBACV,4BACA,gBAAgB,aAChB,kBAAiB,4BACjB,iBAAgB,qBAChB,0BACC,QAAQ"}