open-multi-agent-kit 0.98.0 → 0.98.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 (63) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/README.md +2 -2
  3. package/dist/cli/mcp-attach.d.ts +15 -0
  4. package/dist/cli/mcp-attach.d.ts.map +1 -0
  5. package/dist/cli/mcp-attach.js +14 -0
  6. package/dist/cli/mcp-attach.js.map +1 -0
  7. package/dist/core/agent-session.d.ts +7 -0
  8. package/dist/core/agent-session.d.ts.map +1 -1
  9. package/dist/core/agent-session.js +66 -14
  10. package/dist/core/agent-session.js.map +1 -1
  11. package/dist/core/auth-storage.d.ts +19 -2
  12. package/dist/core/auth-storage.d.ts.map +1 -1
  13. package/dist/core/auth-storage.js +57 -6
  14. package/dist/core/auth-storage.js.map +1 -1
  15. package/dist/core/compaction/oauth-recovery.d.ts +29 -0
  16. package/dist/core/compaction/oauth-recovery.d.ts.map +1 -0
  17. package/dist/core/compaction/oauth-recovery.js +40 -0
  18. package/dist/core/compaction/oauth-recovery.js.map +1 -0
  19. package/dist/core/model-registry.d.ts +10 -1
  20. package/dist/core/model-registry.d.ts.map +1 -1
  21. package/dist/core/model-registry.js +16 -2
  22. package/dist/core/model-registry.js.map +1 -1
  23. package/dist/core/provider-resilience.d.ts +8 -0
  24. package/dist/core/provider-resilience.d.ts.map +1 -1
  25. package/dist/core/provider-resilience.js +17 -0
  26. package/dist/core/provider-resilience.js.map +1 -1
  27. package/dist/core/provider-usage.d.ts +1 -1
  28. package/dist/core/provider-usage.d.ts.map +1 -1
  29. package/dist/core/provider-usage.js +3 -2
  30. package/dist/core/provider-usage.js.map +1 -1
  31. package/dist/core/session-failure-cause.d.ts.map +1 -1
  32. package/dist/core/session-failure-cause.js +7 -1
  33. package/dist/core/session-failure-cause.js.map +1 -1
  34. package/dist/core/session-termination.d.ts.map +1 -1
  35. package/dist/core/session-termination.js +3 -1
  36. package/dist/core/session-termination.js.map +1 -1
  37. package/dist/core/verified-bash-runtime.d.ts.map +1 -1
  38. package/dist/core/verified-bash-runtime.js +6 -4
  39. package/dist/core/verified-bash-runtime.js.map +1 -1
  40. package/dist/guardrails/workspace-fingerprint.d.ts +2 -0
  41. package/dist/guardrails/workspace-fingerprint.d.ts.map +1 -1
  42. package/dist/guardrails/workspace-fingerprint.js +12 -10
  43. package/dist/guardrails/workspace-fingerprint.js.map +1 -1
  44. package/dist/main.d.ts.map +1 -1
  45. package/dist/main.js +7 -0
  46. package/dist/main.js.map +1 -1
  47. package/docs/book-to-skill.md +17 -0
  48. package/docs/docs.json +4 -0
  49. package/docs/index.md +2 -0
  50. package/docs/mcp.md +10 -2
  51. package/docs/security.md +4 -9
  52. package/examples/extensions/custom-provider-anthropic/index.ts +4 -1
  53. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  54. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  55. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  56. package/examples/extensions/gondolin/package-lock.json +2 -2
  57. package/examples/extensions/gondolin/package.json +1 -1
  58. package/examples/extensions/sandbox/package-lock.json +2 -2
  59. package/examples/extensions/sandbox/package.json +1 -1
  60. package/examples/extensions/with-deps/package-lock.json +2 -2
  61. package/examples/extensions/with-deps/package.json +1 -1
  62. package/npm-shrinkwrap.json +18 -18
  63. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"provider-usage.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage.ts"],"names":[],"mappings":"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","sourcesContent":["import { execFile } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport type { ProviderRateLimitSnapshot, ProviderRateLimitWindow } from \"omk-ai\";\nimport type { AgentSession } from \"./agent-session.ts\";\n\nconst FIVE_HOUR_SECONDS = 5 * 60 * 60;\nconst SEVEN_DAY_SECONDS = 7 * 24 * 60 * 60;\nconst WINDOW_TOLERANCE_SECONDS = 120;\nconst CODEX_USAGE_URL = \"https://chatgpt.com/backend-api/wham/usage\";\nconst CLAUDE_USAGE_URL = \"https://api.anthropic.com/api/oauth/usage\";\nconst CLAUDE_MESSAGES_URL = \"https://api.anthropic.com/v1/messages\";\nconst KIMI_USAGE_URL = \"https://api.kimi.com/coding/v1/usages\";\nconst GROK_BILLING_URL = \"https://cli-chat-proxy.grok.com/v1/billing?format=credits\";\nconst OPENAI_AUTH_CLAIM = \"https://api.openai.com/auth\";\nconst MAX_USAGE_RESPONSE_BYTES = 1024 * 1024;\nconst MAX_USAGE_LIMITS = 64;\nconst MAX_PASSIVE_ACCOUNTS = 64;\nconst PASSIVE_USAGE_TTL_MS = 6 * 60 * 60 * 1000;\nconst CLAUDE_QUOTA_PROBE_COOLDOWN_MS = 60 * 60 * 1000;\nconst CLAUDE_QUOTA_PROBE_TIMEOUT_MS = 10_000;\nconst QWEN_CLI_TIMEOUT_MS = 15_000;\nconst QWEN_CLI_ARGS = [\"usage\", \"summary\", \"--format\", \"json\"] as const;\nconst qwenBillingArgs = (month: string): readonly string[] =>\n\t[\"billing\", \"breakdown\", \"--from\", month, \"--to\", month, \"--group-by\", \"model\", \"--format\", \"json\"] as const;\nconst QWEN_CONNECT_HINT = \"connect: npm i -g @qwencloud/qwencloud-cli && qwencloud auth login\";\nconst QWEN_CLI_ENV_KEYS = [\n\t\"PATH\",\n\t\"Path\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"HOMEDRIVE\",\n\t\"HOMEPATH\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"XDG_CONFIG_HOME\",\n\t\"XDG_DATA_HOME\",\n\t\"XDG_CACHE_HOME\",\n\t\"TMPDIR\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"SystemRoot\",\n\t\"WINDIR\",\n\t\"ComSpec\",\n\t\"PATHEXT\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"LC_CTYPE\",\n\t\"TERM\",\n\t\"SSL_CERT_FILE\",\n\t\"SSL_CERT_DIR\",\n] as const;\n\nexport type SubscriptionUsageWindow = {\n\treadonly label: string;\n\treadonly usedPercent: number;\n\treadonly resetsAt?: number;\n};\n\nexport type SubscriptionUsageSnapshot = {\n\treadonly label: string;\n\treadonly windows: readonly SubscriptionUsageWindow[];\n\treadonly message?: string;\n};\n\ntype CodexUsageWindow = { readonly usedPercent: number; readonly resetsAt?: number };\nexport type CodexUsageSnapshot = {\n\treadonly fiveHour?: CodexUsageWindow;\n\treadonly sevenDay?: CodexUsageWindow;\n};\n\ntype ParsedCodexWindow = CodexUsageWindow & { readonly windowSeconds?: number };\ntype ObservedCodexWindow = { readonly window: ParsedCodexWindow; readonly observedAt: number };\ntype PassiveUsageEntry = { readonly primary?: ObservedCodexWindow; readonly secondary?: ObservedCodexWindow };\ntype UsageKind = \"codex\" | \"claude\" | \"kimi\" | \"zai\" | \"grok\" | \"qwen-token-plan\" | \"unavailable\";\ntype CredentialCandidate = { readonly provider: string; readonly oauthOnly: boolean };\n\nexport type SubscriptionUsageSource = {\n\treadonly label: string;\n\treadonly kind: UsageKind;\n\treadonly credentials: readonly CredentialCandidate[];\n\treadonly ttlMs: number;\n\treadonly unavailableMessage?: string;\n};\n\ntype UsageSession = Pick<AgentSession, \"state\" | \"modelRegistry\">;\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\ntype FetchJsonResult = { readonly status: number; readonly payload?: unknown };\n\nconst passiveCodexUsage = new Map<string, PassiveUsageEntry>();\nconst passiveClaudeUsage = new Map<string, PassiveUsageEntry>();\nconst claudeQuotaProbeAttempts = new Map<string, number>();\nconst claudeQuotaProbesInFlight = new Map<string, Promise<void>>();\nconst subscriptionUsageRevisions = new Map<string, number>();\nconst MINUTE_TTL_MS = 60_000;\nconst VISIBLE_USAGE_PROVIDERS = [\n\t\"openai-codex\",\n\t\"anthropic\",\n\t\"kimi-coding\",\n\t\"zai\",\n\t\"modelstudio-maas\",\n\t\"qwen-oauth\",\n\t\"xai\",\n] as const;\nconst SOURCES: Readonly<Record<string, SubscriptionUsageSource>> = {\n\t\"openai-codex\": source(\"CODEX\", \"codex\", [{ provider: \"openai-codex\", oauthOnly: true }]),\n\tanthropic: source(\"CLAUDE\", \"claude\", [{ provider: \"anthropic\", oauthOnly: true }], 5 * MINUTE_TTL_MS),\n\t\"qwen-oauth\": source(\"QWEN\", \"unavailable\", [{ provider: \"qwen-oauth\", oauthOnly: true }]),\n\t// Model Studio exposes no API-key quota endpoint (console gateway is\n\t// session-only), so the token-plan quota rides the official QwenCloud\n\t// management CLI, which holds its own OAuth credential.\n\t\"modelstudio-maas\": source(\n\t\t\"QWEN TOKEN PLAN\",\n\t\t\"qwen-token-plan\",\n\t\t[{ provider: \"modelstudio-maas\", oauthOnly: false }],\n\t\t5 * MINUTE_TTL_MS,\n\t),\n\t\"kimi-code\": source(\"KIMI\", \"kimi\", [\n\t\t{ provider: \"kimi-code\", oauthOnly: true },\n\t\t{ provider: \"kimi-coding\", oauthOnly: false },\n\t]),\n\t\"kimi-coding\": source(\"KIMI\", \"kimi\", [\n\t\t{ provider: \"kimi-code\", oauthOnly: true },\n\t\t{ provider: \"kimi-coding\", oauthOnly: false },\n\t]),\n\t\"zhipu-coding-plan\": source(\"GLM\", \"zai\", [{ provider: \"zhipu-coding-plan\", oauthOnly: true }]),\n\tzai: source(\"GLM\", \"zai\", [\n\t\t{ provider: \"zai\", oauthOnly: false },\n\t\t{ provider: \"zai-coding-cn\", oauthOnly: false },\n\t\t{ provider: \"zhipu-coding-plan\", oauthOnly: true },\n\t]),\n\t\"zai-coding-cn\": source(\"GLM\", \"zai\", [\n\t\t{ provider: \"zai-coding-cn\", oauthOnly: false },\n\t\t{ provider: \"zhipu-coding-plan\", oauthOnly: true },\n\t]),\n\txai: source(\"GROK\", \"grok\", [{ provider: \"xai\", oauthOnly: true }]),\n};\n\nfunction source(\n\tlabel: string,\n\tkind: UsageKind,\n\tcredentials: readonly CredentialCandidate[],\n\tttlMs = MINUTE_TTL_MS,\n\tunavailableMessage?: string,\n): SubscriptionUsageSource {\n\treturn { label, kind, credentials, ttlMs, unavailableMessage };\n}\n\nexport function getSubscriptionUsageSource(provider: string | undefined): SubscriptionUsageSource | undefined {\n\tif (!provider) return undefined;\n\tconst configured = SOURCES[provider];\n\tif (configured) return configured;\n\tif (/^openai-codex-\\d+$/.test(provider)) {\n\t\treturn source(\"CODEX\", \"codex\", [\n\t\t\t{ provider, oauthOnly: true },\n\t\t\t{ provider: \"openai-codex\", oauthOnly: true },\n\t\t]);\n\t}\n\treturn undefined;\n}\n\nfunction usageRevisionKey(provider: string): string {\n\tconst kind = getSubscriptionUsageSource(provider)?.kind;\n\tif (kind === \"codex\") return \"codex\";\n\tif (kind === \"claude\") return \"claude\";\n\treturn provider;\n}\n\nexport function getSubscriptionUsageRevision(provider: string): number {\n\treturn subscriptionUsageRevisions.get(usageRevisionKey(provider)) ?? 0;\n}\n\nfunction bumpSubscriptionUsageRevision(provider: string): void {\n\tconst key = usageRevisionKey(provider);\n\tsubscriptionUsageRevisions.set(key, (subscriptionUsageRevisions.get(key) ?? 0) + 1);\n}\n\nexport function supportsSubscriptionUsage(session: UsageSession, provider = session.state.model?.provider): boolean {\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\treturn usageSource?.credentials.some((candidate) => credentialConfigured(session, candidate)) ?? false;\n}\n\n/** Configured quota groups shown in the rail, with the active group first. */\nexport function getConfiguredSubscriptionUsageProviders(session: UsageSession): readonly string[] {\n\tconst activeProvider = session.state.model?.provider;\n\tconst activeSource = getSubscriptionUsageSource(activeProvider);\n\tconst providers = VISIBLE_USAGE_PROVIDERS.filter((provider) => supportsSubscriptionUsage(session, provider));\n\tif (!activeProvider || !activeSource || !supportsSubscriptionUsage(session, activeProvider)) return providers;\n\tconst activeCanonical = providers.find(\n\t\t(provider) => getSubscriptionUsageSource(provider)?.label === activeSource.label,\n\t);\n\tif (!activeCanonical) return [activeProvider, ...providers];\n\treturn [activeCanonical, ...providers.filter((provider) => provider !== activeCanonical)];\n}\n\nexport async function loadSubscriptionUsage(\n\tsession: UsageSession,\n\tfetchImpl: FetchLike = fetch,\n\tprovider = session.state.model?.provider,\n\tqwenCliRunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot | undefined> {\n\tconst model = session.state.model;\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\tif (!model || !usageSource || !supportsSubscriptionUsage(session, provider)) return undefined;\n\tif (usageSource.kind === \"unavailable\") {\n\t\treturn {\n\t\t\tlabel: usageSource.label,\n\t\t\twindows: [],\n\t\t\tmessage: usageSource.unavailableMessage ?? \"quota API unavailable\",\n\t\t};\n\t}\n\tif (offline()) return { label: usageSource.label, windows: [], message: \"offline\" };\n\tif (usageSource.kind === \"qwen-token-plan\") {\n\t\t// The QwenCloud CLI authenticates itself; no OMK-held credential is used.\n\t\treturn await fetchQwenTokenPlanUsage(usageSource.label, qwenCliRunner);\n\t}\n\n\tconst credential = await resolveCredential(session, usageSource);\n\tif (!credential) return { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\n\ttry {\n\t\tswitch (usageSource.kind) {\n\t\t\tcase \"codex\":\n\t\t\t\treturn await fetchCodexUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"claude\":\n\t\t\t\treturn await fetchClaudeUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"kimi\":\n\t\t\t\treturn await fetchKimiUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"zai\":\n\t\t\t\treturn await fetchZaiUsage(usageSource.label, provider ?? model.provider, credential, fetchImpl);\n\t\t\tcase \"grok\":\n\t\t\t\treturn await fetchGrokUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tdefault:\n\t\t\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t\t}\n\t} catch {\n\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t}\n}\n\nexport function parseCodexUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): CodexUsageSnapshot | undefined {\n\tconst rateLimit = record(record(value)?.rate_limit);\n\tconst primary = codexWindow(rateLimit?.primary_window, nowSeconds);\n\tconst secondary = codexWindow(rateLimit?.secondary_window, nowSeconds);\n\tconst windows = [primary, secondary].filter((window): window is ParsedCodexWindow => window !== undefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tconst fallbackFiveHour = fiveHour ?? (primary?.windowSeconds === undefined ? primary : undefined);\n\tconst fallbackSevenDay = sevenDay ?? (secondary?.windowSeconds === undefined ? secondary : undefined);\n\tif (!fallbackFiveHour && !fallbackSevenDay) return undefined;\n\treturn {\n\t\t...(fallbackFiveHour ? { fiveHour: publicCodexWindow(fallbackFiveHour) } : {}),\n\t\t...(fallbackSevenDay ? { sevenDay: publicCodexWindow(fallbackSevenDay) } : {}),\n\t};\n}\n\nexport function parseClaudeUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst entries = Array.isArray(payload.limits)\n\t\t? payload.limits.slice(0, MAX_USAGE_LIMITS).map(record).filter(isDefined)\n\t\t: [];\n\tconst fiveHour = claudeWindow(payload.five_hour) ?? claudeWindow(entries.find((entry) => entry.kind === \"session\"));\n\tconst sevenDay =\n\t\tclaudeWindow(payload.seven_day) ?? claudeWindow(entries.find((entry) => entry.kind === \"weekly_all\"));\n\tconst windows = [\n\t\tfiveHour ? withLabel(\"5H\", fiveHour) : undefined,\n\t\tsevenDay ? withLabel(\"7D\", sevenDay) : undefined,\n\t].filter(isDefined);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function parseKimiUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst windows: SubscriptionUsageWindow[] = [];\n\tconst total = usageRatio(record(payload.usage), nowSeconds);\n\tif (total) windows.push(withLabel(\"TOTAL\", total));\n\tif (Array.isArray(payload.limits)) {\n\t\tfor (const rawLimit of payload.limits.slice(0, MAX_USAGE_LIMITS)) {\n\t\t\tconst limit = record(rawLimit);\n\t\t\tif (!limit) continue;\n\t\t\tconst detail = record(limit.detail) ?? limit;\n\t\t\tconst windowData = record(limit.window);\n\t\t\tconst parsed = usageRatio(detail, nowSeconds);\n\t\t\tif (!parsed) continue;\n\t\t\tconst resetsAt = parseReset(windowData, nowSeconds) ?? parsed.resetsAt;\n\t\t\twindows.push({\n\t\t\t\tlabel: durationLabel(windowData) ?? shortLabel(limit.name ?? limit.title ?? limit.scope, windows.length),\n\t\t\t\tusedPercent: parsed.usedPercent,\n\t\t\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t\t\t});\n\t\t}\n\t}\n\treturn windows.length > 0 ? windows.slice(0, 4) : undefined;\n}\n\n/** Result of one `qwencloud` invocation; `missing` means the CLI is not installed. */\nexport type QwenCliResult =\n\t| { readonly kind: \"missing\" }\n\t| { readonly kind: \"ran\"; readonly exitCode: number; readonly stdout: string };\nexport type QwenCliRunner = (args: readonly string[], timeoutMs: number) => Promise<QwenCliResult>;\n\nexport function buildQwenCliEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n\tconst childEnvironment: NodeJS.ProcessEnv = {};\n\tfor (const key of QWEN_CLI_ENV_KEYS) {\n\t\tconst value = source[key];\n\t\tif (value !== undefined) childEnvironment[key] = value;\n\t}\n\treturn childEnvironment;\n}\n\n/** Parse `qwencloud usage summary --format json` → the token-plan 7-day window. */\nexport function parseQwenTokenPlanUsage(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst tokenPlan = record(record(value)?.token_plan);\n\tif (!tokenPlan || tokenPlan.subscribed === false) return undefined;\n\tconst resetsAt = epochSeconds(tokenPlan.resetDate);\n\tlet usedPercent = finiteNumber(tokenPlan.usedPct) ?? finiteNumber(tokenPlan.used_pct);\n\tif (usedPercent === undefined) {\n\t\tconst total = finiteNumber(tokenPlan.totalCredits);\n\t\tconst remaining = finiteNumber(tokenPlan.remainingCredits);\n\t\tif (total !== undefined && remaining !== undefined && total > 0) {\n\t\t\tusedPercent = ((total - remaining) / total) * 100;\n\t\t}\n\t}\n\tif (usedPercent === undefined) return undefined;\n\treturn [{ label: \"7D\", usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport async function fetchQwenTokenPlanUsage(\n\tlabel: string,\n\trunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst unavailable = (message: string): SubscriptionUsageSnapshot => ({ label, windows: [], message });\n\ttry {\n\t\tconst result = await runner(QWEN_CLI_ARGS, QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind === \"missing\") return unavailable(QWEN_CONNECT_HINT);\n\t\tif (result.exitCode === 2) return unavailable(\"run: qwencloud auth login\");\n\t\tif (result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn unavailable(\"usage unavailable\");\n\t\t}\n\t\tconst payload: unknown = JSON.parse(result.stdout);\n\t\tconst tokenPlan = record(record(payload)?.token_plan);\n\t\tif (tokenPlan?.subscribed === false) {\n\t\t\tconst periodTo = record(record(payload)?.period)?.to;\n\t\t\tconst month = typeof periodTo === \"string\" ? periodTo.slice(0, 7) : new Date().toISOString().slice(0, 7);\n\t\t\treturn unavailable(await billingFallbackMessage(runner, month, payload));\n\t\t}\n\t\tconst windows = parseQwenTokenPlanUsage(payload);\n\t\treturn windows ? { label, windows } : unavailable(\"usage unavailable\");\n\t} catch {\n\t\treturn unavailable(\"usage unavailable\");\n\t}\n}\n\n/** No active token plan: fall back to settled billing — subscription charge + PAYG spend — when the CLI reports it. */\nasync function billingFallbackMessage(runner: QwenCliRunner, month: string, summaryPayload: unknown): Promise<string> {\n\ttry {\n\t\tconst result = await runner(qwenBillingArgs(month), QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind !== \"ran\" || result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn paygFallbackMessage(summaryPayload);\n\t\t}\n\t\tconst billing = parseBillingBreakdown(JSON.parse(result.stdout));\n\t\tconst cur = billing.currency === undefined || billing.currency === \"USD\" ? \"$\" : `${billing.currency} `;\n\t\tconst parts: string[] = [];\n\t\tif (billing.subscription !== undefined && billing.subscription > 0) {\n\t\t\tparts.push(`subscription ${cur}${billing.subscription.toFixed(2)}`);\n\t\t}\n\t\tconst payg = billing.payg ?? paygTotalCost(summaryPayload);\n\t\tif (payg !== undefined && payg > 0) parts.push(`PAYG ${cur}${payg.toFixed(2)}`);\n\t\tif (parts.length === 0) return \"no active token plan\";\n\t\treturn `${parts.join(\" · \")} (${month})`;\n\t} catch {\n\t\treturn paygFallbackMessage(summaryPayload);\n\t}\n}\n\n/** Split settled billing rows into the fixed subscription charge vs per-model PAYG spend. */\nfunction parseBillingBreakdown(payload: unknown): { subscription?: number; payg?: number; currency?: string } {\n\tconst data = record(payload);\n\tconst rows = Array.isArray(data?.rows) ? data.rows : [];\n\tlet subscription: number | undefined;\n\tlet payg = 0;\n\tlet paygSeen = false;\n\tfor (const raw of rows) {\n\t\tconst row = record(raw);\n\t\tconst amount = finiteNumber(row?.amount);\n\t\tif (amount === undefined) continue;\n\t\tconst key = typeof row?.groupKey === \"string\" ? row.groupKey : \"\";\n\t\tif (key === \"__tax__\") continue;\n\t\tif (key === \"DIMENSION_FILTER_NULL_VALUE\") subscription = (subscription ?? 0) + amount;\n\t\telse {\n\t\t\tpayg += amount;\n\t\t\tpaygSeen = true;\n\t\t}\n\t}\n\tconst currency = typeof data?.currency === \"string\" ? data.currency : undefined;\n\treturn { subscription, payg: paygSeen ? payg : undefined, currency };\n}\n\nfunction paygTotalCost(payload: unknown): number | undefined {\n\treturn finiteNumber(record(record(record(payload)?.pay_as_you_go)?.total)?.cost);\n}\n\n/** No active token plan: fall back to the account's pay-as-you-go spend when the CLI reports it. */\nfunction paygFallbackMessage(payload: unknown): string {\n\tconst cost = paygTotalCost(payload);\n\tif (cost === undefined) return \"no active token plan\";\n\tconst currency = \"$\";\n\tconst period = record(record(payload)?.period);\n\tconst from = typeof period?.from === \"string\" ? period.from.slice(0, 7) : undefined;\n\treturn `no token plan · PAYG ${currency}${cost.toFixed(2)}${from ? ` (${from})` : \"\"}`;\n}\n\nfunction runQwenCli(args: readonly string[], timeoutMs: number): Promise<QwenCliResult> {\n\treturn new Promise((resolve) => {\n\t\tconst binary = process.env.QWENCLOUD_CLI ?? \"qwencloud\";\n\t\texecFile(\n\t\t\tbinary,\n\t\t\t[...args],\n\t\t\t{\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tmaxBuffer: MAX_USAGE_RESPONSE_BYTES,\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv: buildQwenCliEnvironment(process.env),\n\t\t\t},\n\t\t\t(error, stdout) => {\n\t\t\t\tif (!error) {\n\t\t\t\t\tresolve({ kind: \"ran\", exitCode: 0, stdout });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst errno = (error as NodeJS.ErrnoException).code;\n\t\t\t\tif (errno === \"ENOENT\") {\n\t\t\t\t\tresolve({ kind: \"missing\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve({ kind: \"ran\", exitCode: typeof errno === \"number\" ? errno : 1, stdout: stdout ?? \"\" });\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport function parseGrokUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst config = record(record(value)?.config);\n\tif (!config) return undefined;\n\tconst period = record(config.currentPeriod);\n\tconst resetsAt = epochSeconds(period?.end) ?? epochSeconds(config.billingPeriodEnd);\n\tconst percent = finiteNumber(config.creditUsagePercent);\n\tconst onDemandUsed = finiteNumber(record(config.onDemandUsed)?.val);\n\tconst onDemandCap = finiteNumber(record(config.onDemandCap)?.val);\n\tlet usedPercent = percent;\n\tif (usedPercent === undefined && onDemandUsed !== undefined && onDemandCap !== undefined && onDemandCap > 0) {\n\t\tusedPercent = (onDemandUsed / onDemandCap) * 100;\n\t}\n\tif (usedPercent === undefined && (period || resetsAt !== undefined)) usedPercent = 0;\n\tif (usedPercent === undefined) return undefined;\n\tconst periodType = typeof period?.type === \"string\" ? period.type : \"\";\n\tconst label = periodType.includes(\"MONTHLY\") ? \"30D\" : \"7D\";\n\treturn [{ label, usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tconst limits = record(payload?.data)?.limits;\n\tif (payload?.success !== true || !Array.isArray(limits)) return undefined;\n\tconst parsed = limits.slice(0, MAX_USAGE_LIMITS).map(zaiWindow).filter(isDefined);\n\tconst requestWindows = parsed.filter((window) => window.type === \"TIME_LIMIT\" && !window.featureOnly);\n\tconst selected =\n\t\trequestWindows.length > 0 ? requestWindows : parsed.filter((window) => window.type === \"TOKENS_LIMIT\");\n\tselected.sort((left, right) => left.durationSeconds - right.durationSeconds);\n\tconst windows = selected\n\t\t.slice(0, 4)\n\t\t.map(({ type: _type, durationSeconds: _duration, featureOnly: _feature, ...window }) => window);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs = Date.now()): void {\n\tconst accountId = codexAccountId(apiKey);\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0 || (limitId && limitId !== \"codex\")) return;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveCodexUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, next);\n\twhile (passiveCodexUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveCodexUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveCodexUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"openai-codex\");\n}\n\nexport function recordClaudePassiveUsage(\n\tapiKey: string,\n\tsnapshot: ProviderRateLimitSnapshot,\n\tnowMs = Date.now(),\n): void {\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (\n\t\t!apiKey ||\n\t\tapiKey.length > 32_768 ||\n\t\t!Number.isFinite(nowMs) ||\n\t\tnowMs < 0 ||\n\t\t(limitId && limitId !== \"anthropic_unified\")\n\t) {\n\t\treturn;\n\t}\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveClaudeUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, next);\n\twhile (passiveClaudeUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveClaudeUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveClaudeUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"anthropic\");\n}\n\nasync function fetchCodexUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId) return { label, windows: [], message: \"usage unavailable\" };\n\tconst passive = passiveCodexSnapshot(apiKey);\n\tlet polled: CodexUsageSnapshot | undefined;\n\ttry {\n\t\tconst payload = await fetchJson(fetchImpl, CODEX_USAGE_URL, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\t\"User-Agent\": \"omk\",\n\t\t\t},\n\t\t});\n\t\tpolled = parseCodexUsageSnapshot(payload);\n\t} catch (error) {\n\t\tif (!passive) throw error;\n\t}\n\tconst merged: CodexUsageSnapshot = {\n\t\tfiveHour: polled?.fiveHour ?? passive?.fiveHour,\n\t\tsevenDay: polled?.sevenDay ?? passive?.sevenDay,\n\t};\n\tif (!merged.fiveHour && !merged.sevenDay) return { label, windows: [], message: \"usage unavailable\" };\n\treturn {\n\t\tlabel,\n\t\twindows: [\n\t\t\tmerged.fiveHour ? withLabel(\"5H\", merged.fiveHour) : undefined,\n\t\t\tmerged.sevenDay ? withLabel(\"7D\", merged.sevenDay) : undefined,\n\t\t].filter(isDefined),\n\t};\n}\n\nasync function fetchClaudeUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tlet passive = passiveClaudeSnapshot(apiKey);\n\tconst response = await fetchJsonResult(fetchImpl, CLAUDE_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\"User-Agent\": \"claude-cli/2.1.177 (external, cli)\",\n\t\t},\n\t});\n\tconst windows = [...(parseClaudeUsageSnapshot(response.payload) ?? [])];\n\tif (response.status === 429 && (!passive?.fiveHour || !passive?.sevenDay)) {\n\t\tawait probeClaudeQuota(apiKey, fetchImpl);\n\t\tpassive = passiveClaudeSnapshot(apiKey);\n\t}\n\tfor (const passiveWindow of [\n\t\tpassive?.fiveHour ? withLabel(\"5H\", passive.fiveHour) : undefined,\n\t\tpassive?.sevenDay ? withLabel(\"7D\", passive.sevenDay) : undefined,\n\t].filter(isDefined)) {\n\t\tif (!windows.some((window) => window.label === passiveWindow.label)) windows.push(passiveWindow);\n\t}\n\treturn windows.length > 0\n\t\t? { label, windows }\n\t\t: { label, windows: [], message: response.status === 429 ? \"rate limited · retry later\" : \"usage unavailable\" };\n}\n\n/**\n * Claude Code 2.1.177 performs the same `quota`/`max_tokens: 1` request during startup.\n * Keep it account-scoped and hourly so a pinned sidebar cannot turn the fallback into polling.\n */\nasync function probeClaudeQuota(apiKey: string, fetchImpl: FetchLike, nowMs = Date.now()): Promise<void> {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return;\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst activeProbe = claudeQuotaProbesInFlight.get(cacheKey);\n\tif (activeProbe) return activeProbe;\n\tconst lastAttempt = claudeQuotaProbeAttempts.get(cacheKey);\n\tif (lastAttempt !== undefined && nowMs - lastAttempt < CLAUDE_QUOTA_PROBE_COOLDOWN_MS) return;\n\tif (claudeQuotaProbesInFlight.size >= MAX_PASSIVE_ACCOUNTS) return;\n\n\tclaudeQuotaProbeAttempts.delete(cacheKey);\n\tclaudeQuotaProbeAttempts.set(cacheKey, nowMs);\n\twhile (claudeQuotaProbeAttempts.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = claudeQuotaProbeAttempts.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tclaudeQuotaProbeAttempts.delete(oldestCacheKey);\n\t}\n\n\tconst probe = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetchImpl(CLAUDE_MESSAGES_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n\t\t\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"User-Agent\": \"claude-cli/2.1.177 (external, cli)\",\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel: \"claude-haiku-4-5\",\n\t\t\t\t\tmax_tokens: 1,\n\t\t\t\t\tmessages: [{ role: \"user\", content: \"quota\" }],\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(CLAUDE_QUOTA_PROBE_TIMEOUT_MS),\n\t\t\t});\n\t\t\tconst snapshot = parseClaudeQuotaProbeHeaders(response.headers, nowMs);\n\t\t\tif (snapshot) recordClaudePassiveUsage(apiKey, snapshot, nowMs);\n\t\t\ttry {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t} catch {\n\t\t\t\t// The quota snapshot lives entirely in response headers.\n\t\t\t}\n\t\t} catch {\n\t\t\t// This mirrors Claude Code's best-effort startup quota check.\n\t\t}\n\t})().finally(() => {\n\t\tclaudeQuotaProbesInFlight.delete(cacheKey);\n\t});\n\tclaudeQuotaProbesInFlight.set(cacheKey, probe);\n\treturn probe;\n}\n\nfunction parseClaudeQuotaProbeHeaders(headers: Headers, nowMs: number): ProviderRateLimitSnapshot | undefined {\n\tconst parseWindow = (prefix: \"5h\" | \"7d\", windowSeconds: number): ProviderRateLimitWindow | undefined => {\n\t\tconst rawUtilization = headers.get(`anthropic-ratelimit-unified-${prefix}-utilization`);\n\t\tconst rawReset = headers.get(`anthropic-ratelimit-unified-${prefix}-reset`);\n\t\tif (rawUtilization === null || rawReset === null) return undefined;\n\t\tconst utilization = Number(rawUtilization);\n\t\tconst resetsAt = Number(rawReset);\n\t\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\t\tif (\n\t\t\t!Number.isFinite(utilization) ||\n\t\t\tutilization < 0 ||\n\t\t\tutilization > 1 ||\n\t\t\t!Number.isSafeInteger(resetsAt) ||\n\t\t\tresetsAt <= 0 ||\n\t\t\tresetsAt > maxResetAt\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { usedPercent: Math.round(utilization * 10_000) / 100, windowSeconds, resetsAt };\n\t};\n\tconst primary = parseWindow(\"5h\", FIVE_HOUR_SECONDS);\n\tconst secondary = parseWindow(\"7d\", SEVEN_DAY_SECONDS);\n\treturn primary || secondary ? { limitId: \"anthropic-unified\", primary, secondary } : undefined;\n}\n\nasync function fetchGrokUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, GROK_BILLING_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"x-xai-token-auth\": \"xai-grok-cli\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseGrokUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchKimiUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, KIMI_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"KimiCLI/1.5\",\n\t\t\t\"X-Msh-Platform\": \"kimi_cli\",\n\t\t\t\"X-Msh-Version\": \"1.5\",\n\t\t},\n\t});\n\tconst windows = parseKimiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchZaiUsage(\n\tlabel: string,\n\tmodelProvider: string,\n\tcredential: { readonly provider: string; readonly apiKey: string },\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst origin =\n\t\tmodelProvider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zhipu-coding-plan\"\n\t\t\t? \"https://open.bigmodel.cn\"\n\t\t\t: \"https://api.z.ai\";\n\tconst payload = await fetchJson(fetchImpl, `${origin}/api/monitor/usage/quota/limit`, {\n\t\theaders: {\n\t\t\tAuthorization: credential.apiKey,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseZaiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchJson(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<unknown> {\n\treturn (await fetchJsonResult(fetchImpl, url, init)).payload;\n}\n\nasync function fetchJsonResult(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<FetchJsonResult> {\n\tconst response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(10_000) });\n\tif (!response.ok) return { status: response.status };\n\tconst declaredBytes = Number(response.headers?.get(\"content-length\"));\n\tif (Number.isFinite(declaredBytes) && declaredBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\treturn { status: response.status };\n\t}\n\tif (!response.body || typeof response.body.getReader !== \"function\") {\n\t\treturn { status: response.status, payload: await response.json() };\n\t}\n\n\tconst reader = response.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet totalBytes = 0;\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\treturn { status: response.status };\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst body = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\ttry {\n\t\treturn { status: response.status, payload: JSON.parse(new TextDecoder().decode(body)) as unknown };\n\t} catch {\n\t\treturn { status: response.status };\n\t}\n}\n\nfunction credentialConfigured(session: UsageSession, candidate: CredentialCandidate): boolean {\n\tif (candidate.oauthOnly) return session.modelRegistry.isUsingOAuthProvider(candidate.provider);\n\tconst status = session.modelRegistry.getProviderAuthStatus(candidate.provider);\n\treturn status.configured || status.source !== undefined;\n}\n\nasync function resolveCredential(\n\tsession: UsageSession,\n\tusageSource: SubscriptionUsageSource,\n): Promise<{ readonly provider: string; readonly apiKey: string } | undefined> {\n\tfor (const candidate of usageSource.credentials) {\n\t\tif (!credentialConfigured(session, candidate)) continue;\n\t\tconst apiKey = await session.modelRegistry.getApiKeyForProvider(candidate.provider);\n\t\tif (apiKey) return { provider: candidate.provider, apiKey };\n\t}\n\treturn undefined;\n}\n\nfunction codexWindow(value: unknown, nowSeconds: number): ParsedCodexWindow | undefined {\n\tconst window = record(value);\n\tconst usedPercent = finiteNumber(window?.used_percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst windowSeconds = finiteNumber(window?.limit_window_seconds);\n\tconst resetAt = finiteNumber(window?.reset_at);\n\tconst resetAfter = finiteNumber(window?.reset_after_seconds);\n\tconst resetsAt = resetAt ?? (resetAfter === undefined ? undefined : nowSeconds + resetAfter);\n\treturn {\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction claudeWindow(value: unknown): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tconst bucket = record(value);\n\tif (!bucket || bucket.is_active === false) return undefined;\n\tconst usedPercent = finiteNumber(bucket.utilization ?? bucket.percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst resetsAt = epochSeconds(bucket.resets_at);\n\treturn { usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) };\n}\n\nfunction usageRatio(\n\tdata: Record<string, unknown> | undefined,\n\tnowSeconds: number,\n): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tif (!data) return undefined;\n\tconst limit = finiteNumber(data.limit);\n\tlet used = finiteNumber(data.used);\n\tconst remaining = finiteNumber(data.remaining);\n\tif (used === undefined && limit !== undefined && remaining !== undefined) used = limit - remaining;\n\tif (used === undefined || limit === undefined || limit <= 0) return undefined;\n\tconst resetsAt = parseReset(data, nowSeconds);\n\treturn {\n\t\tusedPercent: clampPercent((used / limit) * 100),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiWindow(value: unknown):\n\t| (SubscriptionUsageWindow & {\n\t\t\treadonly type: string;\n\t\t\treadonly durationSeconds: number;\n\t\t\treadonly featureOnly: boolean;\n\t })\n\t| undefined {\n\tconst item = record(value);\n\tif (!item || (item.type !== \"TIME_LIMIT\" && item.type !== \"TOKENS_LIMIT\")) return undefined;\n\tconst percentage = finiteNumber(item.percentage);\n\tconst current = finiteNumber(item.currentValue);\n\tconst limit = finiteNumber(item.usage);\n\tconst usedPercent =\n\t\tpercentage ?? (current !== undefined && limit !== undefined && limit > 0 ? (current / limit) * 100 : undefined);\n\tif (usedPercent === undefined) return undefined;\n\tconst duration = zaiDuration(finiteNumber(item.unit), finiteNumber(item.number));\n\tconst resetsAt = epochSeconds(item.nextResetTime);\n\tconst detailCodes = Array.isArray(item.usageDetails)\n\t\t? item.usageDetails\n\t\t\t\t.map((detail) => record(detail)?.modelCode)\n\t\t\t\t.filter((code): code is string => typeof code === \"string\")\n\t\t: [];\n\treturn {\n\t\ttype: item.type,\n\t\tlabel: duration.label,\n\t\tdurationSeconds: duration.seconds,\n\t\tfeatureOnly: [\"search-prime\", \"web-reader\", \"zread\"].every((code) => detailCodes.includes(code)),\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiDuration(unit: number | undefined, countValue: number | undefined): { label: string; seconds: number } {\n\tconst count = countValue && countValue > 0 ? countValue : 1;\n\tif (unit === 3) return { label: `${count}H`, seconds: count * 60 * 60 };\n\tif (unit === 4) return { label: `${count}D`, seconds: count * 24 * 60 * 60 };\n\tif (unit === 5) return { label: count === 1 ? \"30D\" : `${count}MO`, seconds: count * 30 * 24 * 60 * 60 };\n\tif (unit === 6) return { label: \"7D\", seconds: 7 * 24 * 60 * 60 };\n\treturn { label: \"QUOTA\", seconds: Number.POSITIVE_INFINITY };\n}\n\nfunction durationLabel(window: Record<string, unknown> | undefined): string | undefined {\n\tif (!window) return undefined;\n\tconst duration = finiteNumber(window.duration);\n\tconst unit = typeof window.timeUnit === \"string\" ? window.timeUnit.toUpperCase() : \"\";\n\tif (duration === undefined) return undefined;\n\tif (unit.includes(\"MINUTE\")) return duration % 60 === 0 ? `${duration / 60}H` : `${duration}M`;\n\tif (unit.includes(\"HOUR\")) return `${duration}H`;\n\tif (unit.includes(\"DAY\")) return `${duration}D`;\n\tif (unit.includes(\"SECOND\")) return `${duration}S`;\n\treturn undefined;\n}\n\nfunction parseReset(data: Record<string, unknown> | undefined, nowSeconds: number): number | undefined {\n\tif (!data) return undefined;\n\tfor (const key of [\"reset_at\", \"resetAt\", \"reset_time\", \"resetTime\"] as const) {\n\t\tconst parsed = epochSeconds(data[key]);\n\t\tif (parsed !== undefined) return parsed;\n\t}\n\tfor (const key of [\"reset_in\", \"resetIn\", \"ttl\"] as const) {\n\t\tconst seconds = finiteNumber(data[key]);\n\t\tif (seconds !== undefined) return nowSeconds + seconds;\n\t}\n\treturn undefined;\n}\n\nfunction epochSeconds(value: unknown): number | undefined {\n\tconst numeric = finiteNumber(value);\n\tif (numeric !== undefined) return numeric > 1_000_000_000_000 ? numeric / 1000 : numeric;\n\tif (typeof value !== \"string\" || !value.trim()) return undefined;\n\tconst parsed = Date.parse(value);\n\treturn Number.isFinite(parsed) ? parsed / 1000 : undefined;\n}\n\nfunction normalizePassiveCodexWindow(\n\twindow: ProviderRateLimitWindow | undefined,\n\tnowMs: number,\n): ParsedCodexWindow | undefined {\n\tif (!window || !Number.isFinite(window.usedPercent)) return undefined;\n\tconst windowSeconds =\n\t\twindow.windowSeconds !== undefined &&\n\t\tNumber.isFinite(window.windowSeconds) &&\n\t\twindow.windowSeconds > 0 &&\n\t\twindow.windowSeconds <= Number.MAX_SAFE_INTEGER\n\t\t\t? Math.round(window.windowSeconds)\n\t\t\t: undefined;\n\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\tconst resetsAtValue = window.resetsAt === undefined ? undefined : Math.floor(window.resetsAt);\n\tconst resetsAt =\n\t\tresetsAtValue !== undefined &&\n\t\tNumber.isSafeInteger(resetsAtValue) &&\n\t\tresetsAtValue > 0 &&\n\t\tresetsAtValue <= maxResetAt\n\t\t\t? resetsAtValue\n\t\t\t: undefined;\n\treturn {\n\t\tusedPercent: clampPercent(window.usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction passiveCredentialCacheKey(identifier: string): string {\n\treturn createHash(\"sha256\").update(identifier).digest(\"base64url\");\n}\n\nfunction freshObservedCodexWindow(\n\tobserved: ObservedCodexWindow | undefined,\n\tnowMs: number,\n): ObservedCodexWindow | undefined {\n\tif (!observed || nowMs - observed.observedAt > PASSIVE_USAGE_TTL_MS) return undefined;\n\tif (observed.window.resetsAt !== undefined && observed.window.resetsAt <= nowMs / 1000) return undefined;\n\treturn observed;\n}\n\nfunction prunePassiveCodexUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveCodexUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveCodexUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction prunePassiveClaudeUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveClaudeUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction passiveCodexSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst entry = passiveCodexUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveCodexUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tconst freshEntry = { primary, secondary };\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, freshEntry);\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction passiveClaudeSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst entry = passiveClaudeUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, { primary, secondary });\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction codexAccountId(token: string): string | undefined {\n\ttry {\n\t\tconst payload = token.split(\".\")[1];\n\t\tif (!payload) return undefined;\n\t\tconst claims = record(JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\")));\n\t\tconst auth = record(claims?.[OPENAI_AUTH_CLAIM]);\n\t\tconst accountId = typeof auth?.chatgpt_account_id === \"string\" ? auth.chatgpt_account_id.trim() : \"\";\n\t\treturn accountId && accountId.length <= 256 ? accountId : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction publicCodexWindow(window: ParsedCodexWindow): CodexUsageWindow {\n\treturn { usedPercent: window.usedPercent, ...(window.resetsAt === undefined ? {} : { resetsAt: window.resetsAt }) };\n}\n\nfunction withLabel(label: string, window: Omit<SubscriptionUsageWindow, \"label\">): SubscriptionUsageWindow {\n\treturn { label, ...window };\n}\n\nfunction shortLabel(value: unknown, index: number): string {\n\tif (typeof value !== \"string\") return `LIMIT${index + 1}`;\n\tconst safe = value\n\t\t.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u206f]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn safe ? safe.toUpperCase().slice(0, 8) : `LIMIT${index + 1}`;\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n\tconst number =\n\t\ttypeof value === \"number\" ? value : typeof value === \"string\" && value.trim() ? Number(value) : Number.NaN;\n\treturn Number.isFinite(number) ? number : undefined;\n}\n\nfunction clampPercent(value: number): number {\n\treturn Number(Math.max(0, Math.min(100, value)).toFixed(2));\n}\n\nfunction near(actual: number | undefined, expected: number): boolean {\n\treturn actual !== undefined && Math.abs(actual - expected) <= WINDOW_TOLERANCE_SECONDS;\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isDefined<T>(value: T | undefined): value is T {\n\treturn value !== undefined;\n}\n\nfunction offline(): boolean {\n\tconst value = process.env.OMK_OFFLINE?.toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n"]}
1
+ {"version":3,"file":"provider-usage.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage.ts"],"names":[],"mappings":"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","sourcesContent":["import { execFile } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { CLAUDE_CODE_EXTERNAL_USER_AGENT, type ProviderRateLimitSnapshot, type ProviderRateLimitWindow } from \"omk-ai\";\nimport type { AgentSession } from \"./agent-session.ts\";\n\nconst FIVE_HOUR_SECONDS = 5 * 60 * 60;\nconst SEVEN_DAY_SECONDS = 7 * 24 * 60 * 60;\nconst WINDOW_TOLERANCE_SECONDS = 120;\nconst CODEX_USAGE_URL = \"https://chatgpt.com/backend-api/wham/usage\";\nconst CLAUDE_USAGE_URL = \"https://api.anthropic.com/api/oauth/usage\";\nconst CLAUDE_MESSAGES_URL = \"https://api.anthropic.com/v1/messages\";\nconst KIMI_USAGE_URL = \"https://api.kimi.com/coding/v1/usages\";\nconst GROK_BILLING_URL = \"https://cli-chat-proxy.grok.com/v1/billing?format=credits\";\nconst OPENAI_AUTH_CLAIM = \"https://api.openai.com/auth\";\nconst MAX_USAGE_RESPONSE_BYTES = 1024 * 1024;\nconst MAX_USAGE_LIMITS = 64;\nconst MAX_PASSIVE_ACCOUNTS = 64;\nconst PASSIVE_USAGE_TTL_MS = 6 * 60 * 60 * 1000;\nconst CLAUDE_QUOTA_PROBE_COOLDOWN_MS = 60 * 60 * 1000;\nconst CLAUDE_QUOTA_PROBE_TIMEOUT_MS = 10_000;\nconst QWEN_CLI_TIMEOUT_MS = 15_000;\nconst QWEN_CLI_ARGS = [\"usage\", \"summary\", \"--format\", \"json\"] as const;\nconst qwenBillingArgs = (month: string): readonly string[] =>\n\t[\"billing\", \"breakdown\", \"--from\", month, \"--to\", month, \"--group-by\", \"model\", \"--format\", \"json\"] as const;\nconst QWEN_CONNECT_HINT = \"connect: npm i -g @qwencloud/qwencloud-cli && qwencloud auth login\";\nconst QWEN_CLI_ENV_KEYS = [\n\t\"PATH\",\n\t\"Path\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"HOMEDRIVE\",\n\t\"HOMEPATH\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"XDG_CONFIG_HOME\",\n\t\"XDG_DATA_HOME\",\n\t\"XDG_CACHE_HOME\",\n\t\"TMPDIR\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"SystemRoot\",\n\t\"WINDIR\",\n\t\"ComSpec\",\n\t\"PATHEXT\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"LC_CTYPE\",\n\t\"TERM\",\n\t\"SSL_CERT_FILE\",\n\t\"SSL_CERT_DIR\",\n] as const;\n\nexport type SubscriptionUsageWindow = {\n\treadonly label: string;\n\treadonly usedPercent: number;\n\treadonly resetsAt?: number;\n};\n\nexport type SubscriptionUsageSnapshot = {\n\treadonly label: string;\n\treadonly windows: readonly SubscriptionUsageWindow[];\n\treadonly message?: string;\n};\n\ntype CodexUsageWindow = { readonly usedPercent: number; readonly resetsAt?: number };\nexport type CodexUsageSnapshot = {\n\treadonly fiveHour?: CodexUsageWindow;\n\treadonly sevenDay?: CodexUsageWindow;\n};\n\ntype ParsedCodexWindow = CodexUsageWindow & { readonly windowSeconds?: number };\ntype ObservedCodexWindow = { readonly window: ParsedCodexWindow; readonly observedAt: number };\ntype PassiveUsageEntry = { readonly primary?: ObservedCodexWindow; readonly secondary?: ObservedCodexWindow };\ntype UsageKind = \"codex\" | \"claude\" | \"kimi\" | \"zai\" | \"grok\" | \"qwen-token-plan\" | \"unavailable\";\ntype CredentialCandidate = { readonly provider: string; readonly oauthOnly: boolean };\n\nexport type SubscriptionUsageSource = {\n\treadonly label: string;\n\treadonly kind: UsageKind;\n\treadonly credentials: readonly CredentialCandidate[];\n\treadonly ttlMs: number;\n\treadonly unavailableMessage?: string;\n};\n\ntype UsageSession = Pick<AgentSession, \"state\" | \"modelRegistry\">;\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\ntype FetchJsonResult = { readonly status: number; readonly payload?: unknown };\n\nconst passiveCodexUsage = new Map<string, PassiveUsageEntry>();\nconst passiveClaudeUsage = new Map<string, PassiveUsageEntry>();\nconst claudeQuotaProbeAttempts = new Map<string, number>();\nconst claudeQuotaProbesInFlight = new Map<string, Promise<void>>();\nconst subscriptionUsageRevisions = new Map<string, number>();\nconst MINUTE_TTL_MS = 60_000;\nconst VISIBLE_USAGE_PROVIDERS = [\n\t\"openai-codex\",\n\t\"anthropic\",\n\t\"kimi-coding\",\n\t\"zai\",\n\t\"modelstudio-maas\",\n\t\"qwen-oauth\",\n\t\"xai\",\n] as const;\nconst SOURCES: Readonly<Record<string, SubscriptionUsageSource>> = {\n\t\"openai-codex\": source(\"CODEX\", \"codex\", [{ provider: \"openai-codex\", oauthOnly: true }]),\n\tanthropic: source(\"CLAUDE\", \"claude\", [{ provider: \"anthropic\", oauthOnly: true }], 5 * MINUTE_TTL_MS),\n\t\"qwen-oauth\": source(\"QWEN\", \"unavailable\", [{ provider: \"qwen-oauth\", oauthOnly: true }]),\n\t// Model Studio exposes no API-key quota endpoint (console gateway is\n\t// session-only), so the token-plan quota rides the official QwenCloud\n\t// management CLI, which holds its own OAuth credential.\n\t\"modelstudio-maas\": source(\n\t\t\"QWEN TOKEN PLAN\",\n\t\t\"qwen-token-plan\",\n\t\t[{ provider: \"modelstudio-maas\", oauthOnly: false }],\n\t\t5 * MINUTE_TTL_MS,\n\t),\n\t\"kimi-code\": source(\"KIMI\", \"kimi\", [\n\t\t{ provider: \"kimi-code\", oauthOnly: true },\n\t\t{ provider: \"kimi-coding\", oauthOnly: false },\n\t]),\n\t\"kimi-coding\": source(\"KIMI\", \"kimi\", [\n\t\t{ provider: \"kimi-code\", oauthOnly: true },\n\t\t{ provider: \"kimi-coding\", oauthOnly: false },\n\t]),\n\t\"zhipu-coding-plan\": source(\"GLM\", \"zai\", [{ provider: \"zhipu-coding-plan\", oauthOnly: true }]),\n\tzai: source(\"GLM\", \"zai\", [\n\t\t{ provider: \"zai\", oauthOnly: false },\n\t\t{ provider: \"zai-coding-cn\", oauthOnly: false },\n\t\t{ provider: \"zhipu-coding-plan\", oauthOnly: true },\n\t]),\n\t\"zai-coding-cn\": source(\"GLM\", \"zai\", [\n\t\t{ provider: \"zai-coding-cn\", oauthOnly: false },\n\t\t{ provider: \"zhipu-coding-plan\", oauthOnly: true },\n\t]),\n\txai: source(\"GROK\", \"grok\", [{ provider: \"xai\", oauthOnly: true }]),\n};\n\nfunction source(\n\tlabel: string,\n\tkind: UsageKind,\n\tcredentials: readonly CredentialCandidate[],\n\tttlMs = MINUTE_TTL_MS,\n\tunavailableMessage?: string,\n): SubscriptionUsageSource {\n\treturn { label, kind, credentials, ttlMs, unavailableMessage };\n}\n\nexport function getSubscriptionUsageSource(provider: string | undefined): SubscriptionUsageSource | undefined {\n\tif (!provider) return undefined;\n\tconst configured = SOURCES[provider];\n\tif (configured) return configured;\n\tif (/^openai-codex-\\d+$/.test(provider)) {\n\t\treturn source(\"CODEX\", \"codex\", [\n\t\t\t{ provider, oauthOnly: true },\n\t\t\t{ provider: \"openai-codex\", oauthOnly: true },\n\t\t]);\n\t}\n\treturn undefined;\n}\n\nfunction usageRevisionKey(provider: string): string {\n\tconst kind = getSubscriptionUsageSource(provider)?.kind;\n\tif (kind === \"codex\") return \"codex\";\n\tif (kind === \"claude\") return \"claude\";\n\treturn provider;\n}\n\nexport function getSubscriptionUsageRevision(provider: string): number {\n\treturn subscriptionUsageRevisions.get(usageRevisionKey(provider)) ?? 0;\n}\n\nfunction bumpSubscriptionUsageRevision(provider: string): void {\n\tconst key = usageRevisionKey(provider);\n\tsubscriptionUsageRevisions.set(key, (subscriptionUsageRevisions.get(key) ?? 0) + 1);\n}\n\nexport function supportsSubscriptionUsage(session: UsageSession, provider = session.state.model?.provider): boolean {\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\treturn usageSource?.credentials.some((candidate) => credentialConfigured(session, candidate)) ?? false;\n}\n\n/** Configured quota groups shown in the rail, with the active group first. */\nexport function getConfiguredSubscriptionUsageProviders(session: UsageSession): readonly string[] {\n\tconst activeProvider = session.state.model?.provider;\n\tconst activeSource = getSubscriptionUsageSource(activeProvider);\n\tconst providers = VISIBLE_USAGE_PROVIDERS.filter((provider) => supportsSubscriptionUsage(session, provider));\n\tif (!activeProvider || !activeSource || !supportsSubscriptionUsage(session, activeProvider)) return providers;\n\tconst activeCanonical = providers.find(\n\t\t(provider) => getSubscriptionUsageSource(provider)?.label === activeSource.label,\n\t);\n\tif (!activeCanonical) return [activeProvider, ...providers];\n\treturn [activeCanonical, ...providers.filter((provider) => provider !== activeCanonical)];\n}\n\nexport async function loadSubscriptionUsage(\n\tsession: UsageSession,\n\tfetchImpl: FetchLike = fetch,\n\tprovider = session.state.model?.provider,\n\tqwenCliRunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot | undefined> {\n\tconst model = session.state.model;\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\tif (!model || !usageSource || !supportsSubscriptionUsage(session, provider)) return undefined;\n\tif (usageSource.kind === \"unavailable\") {\n\t\treturn {\n\t\t\tlabel: usageSource.label,\n\t\t\twindows: [],\n\t\t\tmessage: usageSource.unavailableMessage ?? \"quota API unavailable\",\n\t\t};\n\t}\n\tif (offline()) return { label: usageSource.label, windows: [], message: \"offline\" };\n\tif (usageSource.kind === \"qwen-token-plan\") {\n\t\t// The QwenCloud CLI authenticates itself; no OMK-held credential is used.\n\t\treturn await fetchQwenTokenPlanUsage(usageSource.label, qwenCliRunner);\n\t}\n\n\tconst credential = await resolveCredential(session, usageSource);\n\tif (!credential) return { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\n\ttry {\n\t\tswitch (usageSource.kind) {\n\t\t\tcase \"codex\":\n\t\t\t\treturn await fetchCodexUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"claude\":\n\t\t\t\treturn await fetchClaudeUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"kimi\":\n\t\t\t\treturn await fetchKimiUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"zai\":\n\t\t\t\treturn await fetchZaiUsage(usageSource.label, provider ?? model.provider, credential, fetchImpl);\n\t\t\tcase \"grok\":\n\t\t\t\treturn await fetchGrokUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tdefault:\n\t\t\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t\t}\n\t} catch {\n\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t}\n}\n\nexport function parseCodexUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): CodexUsageSnapshot | undefined {\n\tconst rateLimit = record(record(value)?.rate_limit);\n\tconst primary = codexWindow(rateLimit?.primary_window, nowSeconds);\n\tconst secondary = codexWindow(rateLimit?.secondary_window, nowSeconds);\n\tconst windows = [primary, secondary].filter((window): window is ParsedCodexWindow => window !== undefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tconst fallbackFiveHour = fiveHour ?? (primary?.windowSeconds === undefined ? primary : undefined);\n\tconst fallbackSevenDay = sevenDay ?? (secondary?.windowSeconds === undefined ? secondary : undefined);\n\tif (!fallbackFiveHour && !fallbackSevenDay) return undefined;\n\treturn {\n\t\t...(fallbackFiveHour ? { fiveHour: publicCodexWindow(fallbackFiveHour) } : {}),\n\t\t...(fallbackSevenDay ? { sevenDay: publicCodexWindow(fallbackSevenDay) } : {}),\n\t};\n}\n\nexport function parseClaudeUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst entries = Array.isArray(payload.limits)\n\t\t? payload.limits.slice(0, MAX_USAGE_LIMITS).map(record).filter(isDefined)\n\t\t: [];\n\tconst fiveHour = claudeWindow(payload.five_hour) ?? claudeWindow(entries.find((entry) => entry.kind === \"session\"));\n\tconst sevenDay =\n\t\tclaudeWindow(payload.seven_day) ?? claudeWindow(entries.find((entry) => entry.kind === \"weekly_all\"));\n\tconst windows = [\n\t\tfiveHour ? withLabel(\"5H\", fiveHour) : undefined,\n\t\tsevenDay ? withLabel(\"7D\", sevenDay) : undefined,\n\t].filter(isDefined);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function parseKimiUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst windows: SubscriptionUsageWindow[] = [];\n\tconst total = usageRatio(record(payload.usage), nowSeconds);\n\tif (total) windows.push(withLabel(\"TOTAL\", total));\n\tif (Array.isArray(payload.limits)) {\n\t\tfor (const rawLimit of payload.limits.slice(0, MAX_USAGE_LIMITS)) {\n\t\t\tconst limit = record(rawLimit);\n\t\t\tif (!limit) continue;\n\t\t\tconst detail = record(limit.detail) ?? limit;\n\t\t\tconst windowData = record(limit.window);\n\t\t\tconst parsed = usageRatio(detail, nowSeconds);\n\t\t\tif (!parsed) continue;\n\t\t\tconst resetsAt = parseReset(windowData, nowSeconds) ?? parsed.resetsAt;\n\t\t\twindows.push({\n\t\t\t\tlabel: durationLabel(windowData) ?? shortLabel(limit.name ?? limit.title ?? limit.scope, windows.length),\n\t\t\t\tusedPercent: parsed.usedPercent,\n\t\t\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t\t\t});\n\t\t}\n\t}\n\treturn windows.length > 0 ? windows.slice(0, 4) : undefined;\n}\n\n/** Result of one `qwencloud` invocation; `missing` means the CLI is not installed. */\nexport type QwenCliResult =\n\t| { readonly kind: \"missing\" }\n\t| { readonly kind: \"ran\"; readonly exitCode: number; readonly stdout: string };\nexport type QwenCliRunner = (args: readonly string[], timeoutMs: number) => Promise<QwenCliResult>;\n\nexport function buildQwenCliEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n\tconst childEnvironment: NodeJS.ProcessEnv = {};\n\tfor (const key of QWEN_CLI_ENV_KEYS) {\n\t\tconst value = source[key];\n\t\tif (value !== undefined) childEnvironment[key] = value;\n\t}\n\treturn childEnvironment;\n}\n\n/** Parse `qwencloud usage summary --format json` → the token-plan 7-day window. */\nexport function parseQwenTokenPlanUsage(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst tokenPlan = record(record(value)?.token_plan);\n\tif (!tokenPlan || tokenPlan.subscribed === false) return undefined;\n\tconst resetsAt = epochSeconds(tokenPlan.resetDate);\n\tlet usedPercent = finiteNumber(tokenPlan.usedPct) ?? finiteNumber(tokenPlan.used_pct);\n\tif (usedPercent === undefined) {\n\t\tconst total = finiteNumber(tokenPlan.totalCredits);\n\t\tconst remaining = finiteNumber(tokenPlan.remainingCredits);\n\t\tif (total !== undefined && remaining !== undefined && total > 0) {\n\t\t\tusedPercent = ((total - remaining) / total) * 100;\n\t\t}\n\t}\n\tif (usedPercent === undefined) return undefined;\n\treturn [{ label: \"7D\", usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport async function fetchQwenTokenPlanUsage(\n\tlabel: string,\n\trunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst unavailable = (message: string): SubscriptionUsageSnapshot => ({ label, windows: [], message });\n\ttry {\n\t\tconst result = await runner(QWEN_CLI_ARGS, QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind === \"missing\") return unavailable(QWEN_CONNECT_HINT);\n\t\tif (result.exitCode === 2) return unavailable(\"run: qwencloud auth login\");\n\t\tif (result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn unavailable(\"usage unavailable\");\n\t\t}\n\t\tconst payload: unknown = JSON.parse(result.stdout);\n\t\tconst tokenPlan = record(record(payload)?.token_plan);\n\t\tif (tokenPlan?.subscribed === false) {\n\t\t\tconst periodTo = record(record(payload)?.period)?.to;\n\t\t\tconst month = typeof periodTo === \"string\" ? periodTo.slice(0, 7) : new Date().toISOString().slice(0, 7);\n\t\t\treturn unavailable(await billingFallbackMessage(runner, month, payload));\n\t\t}\n\t\tconst windows = parseQwenTokenPlanUsage(payload);\n\t\treturn windows ? { label, windows } : unavailable(\"usage unavailable\");\n\t} catch {\n\t\treturn unavailable(\"usage unavailable\");\n\t}\n}\n\n/** No active token plan: fall back to settled billing — subscription charge + PAYG spend — when the CLI reports it. */\nasync function billingFallbackMessage(runner: QwenCliRunner, month: string, summaryPayload: unknown): Promise<string> {\n\ttry {\n\t\tconst result = await runner(qwenBillingArgs(month), QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind !== \"ran\" || result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn paygFallbackMessage(summaryPayload);\n\t\t}\n\t\tconst billing = parseBillingBreakdown(JSON.parse(result.stdout));\n\t\tconst cur = billing.currency === undefined || billing.currency === \"USD\" ? \"$\" : `${billing.currency} `;\n\t\tconst parts: string[] = [];\n\t\tif (billing.subscription !== undefined && billing.subscription > 0) {\n\t\t\tparts.push(`subscription ${cur}${billing.subscription.toFixed(2)}`);\n\t\t}\n\t\tconst payg = billing.payg ?? paygTotalCost(summaryPayload);\n\t\tif (payg !== undefined && payg > 0) parts.push(`PAYG ${cur}${payg.toFixed(2)}`);\n\t\tif (parts.length === 0) return \"no active token plan\";\n\t\treturn `${parts.join(\" · \")} (${month})`;\n\t} catch {\n\t\treturn paygFallbackMessage(summaryPayload);\n\t}\n}\n\n/** Split settled billing rows into the fixed subscription charge vs per-model PAYG spend. */\nfunction parseBillingBreakdown(payload: unknown): { subscription?: number; payg?: number; currency?: string } {\n\tconst data = record(payload);\n\tconst rows = Array.isArray(data?.rows) ? data.rows : [];\n\tlet subscription: number | undefined;\n\tlet payg = 0;\n\tlet paygSeen = false;\n\tfor (const raw of rows) {\n\t\tconst row = record(raw);\n\t\tconst amount = finiteNumber(row?.amount);\n\t\tif (amount === undefined) continue;\n\t\tconst key = typeof row?.groupKey === \"string\" ? row.groupKey : \"\";\n\t\tif (key === \"__tax__\") continue;\n\t\tif (key === \"DIMENSION_FILTER_NULL_VALUE\") subscription = (subscription ?? 0) + amount;\n\t\telse {\n\t\t\tpayg += amount;\n\t\t\tpaygSeen = true;\n\t\t}\n\t}\n\tconst currency = typeof data?.currency === \"string\" ? data.currency : undefined;\n\treturn { subscription, payg: paygSeen ? payg : undefined, currency };\n}\n\nfunction paygTotalCost(payload: unknown): number | undefined {\n\treturn finiteNumber(record(record(record(payload)?.pay_as_you_go)?.total)?.cost);\n}\n\n/** No active token plan: fall back to the account's pay-as-you-go spend when the CLI reports it. */\nfunction paygFallbackMessage(payload: unknown): string {\n\tconst cost = paygTotalCost(payload);\n\tif (cost === undefined) return \"no active token plan\";\n\tconst currency = \"$\";\n\tconst period = record(record(payload)?.period);\n\tconst from = typeof period?.from === \"string\" ? period.from.slice(0, 7) : undefined;\n\treturn `no token plan · PAYG ${currency}${cost.toFixed(2)}${from ? ` (${from})` : \"\"}`;\n}\n\nfunction runQwenCli(args: readonly string[], timeoutMs: number): Promise<QwenCliResult> {\n\treturn new Promise((resolve) => {\n\t\tconst binary = process.env.QWENCLOUD_CLI ?? \"qwencloud\";\n\t\texecFile(\n\t\t\tbinary,\n\t\t\t[...args],\n\t\t\t{\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tmaxBuffer: MAX_USAGE_RESPONSE_BYTES,\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv: buildQwenCliEnvironment(process.env),\n\t\t\t},\n\t\t\t(error, stdout) => {\n\t\t\t\tif (!error) {\n\t\t\t\t\tresolve({ kind: \"ran\", exitCode: 0, stdout });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst errno = (error as NodeJS.ErrnoException).code;\n\t\t\t\tif (errno === \"ENOENT\") {\n\t\t\t\t\tresolve({ kind: \"missing\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve({ kind: \"ran\", exitCode: typeof errno === \"number\" ? errno : 1, stdout: stdout ?? \"\" });\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport function parseGrokUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst config = record(record(value)?.config);\n\tif (!config) return undefined;\n\tconst period = record(config.currentPeriod);\n\tconst resetsAt = epochSeconds(period?.end) ?? epochSeconds(config.billingPeriodEnd);\n\tconst percent = finiteNumber(config.creditUsagePercent);\n\tconst onDemandUsed = finiteNumber(record(config.onDemandUsed)?.val);\n\tconst onDemandCap = finiteNumber(record(config.onDemandCap)?.val);\n\tlet usedPercent = percent;\n\tif (usedPercent === undefined && onDemandUsed !== undefined && onDemandCap !== undefined && onDemandCap > 0) {\n\t\tusedPercent = (onDemandUsed / onDemandCap) * 100;\n\t}\n\tif (usedPercent === undefined && (period || resetsAt !== undefined)) usedPercent = 0;\n\tif (usedPercent === undefined) return undefined;\n\tconst periodType = typeof period?.type === \"string\" ? period.type : \"\";\n\tconst label = periodType.includes(\"MONTHLY\") ? \"30D\" : \"7D\";\n\treturn [{ label, usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tconst limits = record(payload?.data)?.limits;\n\tif (payload?.success !== true || !Array.isArray(limits)) return undefined;\n\tconst parsed = limits.slice(0, MAX_USAGE_LIMITS).map(zaiWindow).filter(isDefined);\n\tconst requestWindows = parsed.filter((window) => window.type === \"TIME_LIMIT\" && !window.featureOnly);\n\tconst selected =\n\t\trequestWindows.length > 0 ? requestWindows : parsed.filter((window) => window.type === \"TOKENS_LIMIT\");\n\tselected.sort((left, right) => left.durationSeconds - right.durationSeconds);\n\tconst windows = selected\n\t\t.slice(0, 4)\n\t\t.map(({ type: _type, durationSeconds: _duration, featureOnly: _feature, ...window }) => window);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs = Date.now()): void {\n\tconst accountId = codexAccountId(apiKey);\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0 || (limitId && limitId !== \"codex\")) return;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveCodexUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, next);\n\twhile (passiveCodexUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveCodexUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveCodexUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"openai-codex\");\n}\n\nexport function recordClaudePassiveUsage(\n\tapiKey: string,\n\tsnapshot: ProviderRateLimitSnapshot,\n\tnowMs = Date.now(),\n): void {\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (\n\t\t!apiKey ||\n\t\tapiKey.length > 32_768 ||\n\t\t!Number.isFinite(nowMs) ||\n\t\tnowMs < 0 ||\n\t\t(limitId && limitId !== \"anthropic_unified\")\n\t) {\n\t\treturn;\n\t}\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveClaudeUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, next);\n\twhile (passiveClaudeUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveClaudeUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveClaudeUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"anthropic\");\n}\n\nasync function fetchCodexUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId) return { label, windows: [], message: \"usage unavailable\" };\n\tconst passive = passiveCodexSnapshot(apiKey);\n\tlet polled: CodexUsageSnapshot | undefined;\n\ttry {\n\t\tconst payload = await fetchJson(fetchImpl, CODEX_USAGE_URL, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\t\"User-Agent\": \"omk\",\n\t\t\t},\n\t\t});\n\t\tpolled = parseCodexUsageSnapshot(payload);\n\t} catch (error) {\n\t\tif (!passive) throw error;\n\t}\n\tconst merged: CodexUsageSnapshot = {\n\t\tfiveHour: polled?.fiveHour ?? passive?.fiveHour,\n\t\tsevenDay: polled?.sevenDay ?? passive?.sevenDay,\n\t};\n\tif (!merged.fiveHour && !merged.sevenDay) return { label, windows: [], message: \"usage unavailable\" };\n\treturn {\n\t\tlabel,\n\t\twindows: [\n\t\t\tmerged.fiveHour ? withLabel(\"5H\", merged.fiveHour) : undefined,\n\t\t\tmerged.sevenDay ? withLabel(\"7D\", merged.sevenDay) : undefined,\n\t\t].filter(isDefined),\n\t};\n}\n\nasync function fetchClaudeUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tlet passive = passiveClaudeSnapshot(apiKey);\n\tconst response = await fetchJsonResult(fetchImpl, CLAUDE_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\"User-Agent\": CLAUDE_CODE_EXTERNAL_USER_AGENT,\n\t\t},\n\t});\n\tconst windows = [...(parseClaudeUsageSnapshot(response.payload) ?? [])];\n\tif (response.status === 429 && (!passive?.fiveHour || !passive?.sevenDay)) {\n\t\tawait probeClaudeQuota(apiKey, fetchImpl);\n\t\tpassive = passiveClaudeSnapshot(apiKey);\n\t}\n\tfor (const passiveWindow of [\n\t\tpassive?.fiveHour ? withLabel(\"5H\", passive.fiveHour) : undefined,\n\t\tpassive?.sevenDay ? withLabel(\"7D\", passive.sevenDay) : undefined,\n\t].filter(isDefined)) {\n\t\tif (!windows.some((window) => window.label === passiveWindow.label)) windows.push(passiveWindow);\n\t}\n\treturn windows.length > 0\n\t\t? { label, windows }\n\t\t: { label, windows: [], message: response.status === 429 ? \"rate limited · retry later\" : \"usage unavailable\" };\n}\n\n/**\n * Claude Code 2.1.177 performs the same `quota`/`max_tokens: 1` request during startup.\n * Keep it account-scoped and hourly so a pinned sidebar cannot turn the fallback into polling.\n */\nasync function probeClaudeQuota(apiKey: string, fetchImpl: FetchLike, nowMs = Date.now()): Promise<void> {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return;\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst activeProbe = claudeQuotaProbesInFlight.get(cacheKey);\n\tif (activeProbe) return activeProbe;\n\tconst lastAttempt = claudeQuotaProbeAttempts.get(cacheKey);\n\tif (lastAttempt !== undefined && nowMs - lastAttempt < CLAUDE_QUOTA_PROBE_COOLDOWN_MS) return;\n\tif (claudeQuotaProbesInFlight.size >= MAX_PASSIVE_ACCOUNTS) return;\n\n\tclaudeQuotaProbeAttempts.delete(cacheKey);\n\tclaudeQuotaProbeAttempts.set(cacheKey, nowMs);\n\twhile (claudeQuotaProbeAttempts.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = claudeQuotaProbeAttempts.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tclaudeQuotaProbeAttempts.delete(oldestCacheKey);\n\t}\n\n\tconst probe = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetchImpl(CLAUDE_MESSAGES_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n\t\t\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"User-Agent\": CLAUDE_CODE_EXTERNAL_USER_AGENT,\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel: \"claude-haiku-4-5\",\n\t\t\t\t\tmax_tokens: 1,\n\t\t\t\t\tmessages: [{ role: \"user\", content: \"quota\" }],\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(CLAUDE_QUOTA_PROBE_TIMEOUT_MS),\n\t\t\t});\n\t\t\tconst snapshot = parseClaudeQuotaProbeHeaders(response.headers, nowMs);\n\t\t\tif (snapshot) recordClaudePassiveUsage(apiKey, snapshot, nowMs);\n\t\t\ttry {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t} catch {\n\t\t\t\t// The quota snapshot lives entirely in response headers.\n\t\t\t}\n\t\t} catch {\n\t\t\t// This mirrors Claude Code's best-effort startup quota check.\n\t\t}\n\t})().finally(() => {\n\t\tclaudeQuotaProbesInFlight.delete(cacheKey);\n\t});\n\tclaudeQuotaProbesInFlight.set(cacheKey, probe);\n\treturn probe;\n}\n\nfunction parseClaudeQuotaProbeHeaders(headers: Headers, nowMs: number): ProviderRateLimitSnapshot | undefined {\n\tconst parseWindow = (prefix: \"5h\" | \"7d\", windowSeconds: number): ProviderRateLimitWindow | undefined => {\n\t\tconst rawUtilization = headers.get(`anthropic-ratelimit-unified-${prefix}-utilization`);\n\t\tconst rawReset = headers.get(`anthropic-ratelimit-unified-${prefix}-reset`);\n\t\tif (rawUtilization === null || rawReset === null) return undefined;\n\t\tconst utilization = Number(rawUtilization);\n\t\tconst resetsAt = Number(rawReset);\n\t\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\t\tif (\n\t\t\t!Number.isFinite(utilization) ||\n\t\t\tutilization < 0 ||\n\t\t\tutilization > 1 ||\n\t\t\t!Number.isSafeInteger(resetsAt) ||\n\t\t\tresetsAt <= 0 ||\n\t\t\tresetsAt > maxResetAt\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { usedPercent: Math.round(utilization * 10_000) / 100, windowSeconds, resetsAt };\n\t};\n\tconst primary = parseWindow(\"5h\", FIVE_HOUR_SECONDS);\n\tconst secondary = parseWindow(\"7d\", SEVEN_DAY_SECONDS);\n\treturn primary || secondary ? { limitId: \"anthropic-unified\", primary, secondary } : undefined;\n}\n\nasync function fetchGrokUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, GROK_BILLING_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"x-xai-token-auth\": \"xai-grok-cli\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseGrokUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchKimiUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, KIMI_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"KimiCLI/1.5\",\n\t\t\t\"X-Msh-Platform\": \"kimi_cli\",\n\t\t\t\"X-Msh-Version\": \"1.5\",\n\t\t},\n\t});\n\tconst windows = parseKimiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchZaiUsage(\n\tlabel: string,\n\tmodelProvider: string,\n\tcredential: { readonly provider: string; readonly apiKey: string },\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst origin =\n\t\tmodelProvider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zhipu-coding-plan\"\n\t\t\t? \"https://open.bigmodel.cn\"\n\t\t\t: \"https://api.z.ai\";\n\tconst payload = await fetchJson(fetchImpl, `${origin}/api/monitor/usage/quota/limit`, {\n\t\theaders: {\n\t\t\tAuthorization: credential.apiKey,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseZaiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchJson(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<unknown> {\n\treturn (await fetchJsonResult(fetchImpl, url, init)).payload;\n}\n\nasync function fetchJsonResult(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<FetchJsonResult> {\n\tconst response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(10_000) });\n\tif (!response.ok) return { status: response.status };\n\tconst declaredBytes = Number(response.headers?.get(\"content-length\"));\n\tif (Number.isFinite(declaredBytes) && declaredBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\treturn { status: response.status };\n\t}\n\tif (!response.body || typeof response.body.getReader !== \"function\") {\n\t\treturn { status: response.status, payload: await response.json() };\n\t}\n\n\tconst reader = response.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet totalBytes = 0;\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\treturn { status: response.status };\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst body = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\ttry {\n\t\treturn { status: response.status, payload: JSON.parse(new TextDecoder().decode(body)) as unknown };\n\t} catch {\n\t\treturn { status: response.status };\n\t}\n}\n\nfunction credentialConfigured(session: UsageSession, candidate: CredentialCandidate): boolean {\n\tif (candidate.oauthOnly) return session.modelRegistry.isUsingOAuthProvider(candidate.provider);\n\tconst status = session.modelRegistry.getProviderAuthStatus(candidate.provider);\n\treturn status.configured || status.source !== undefined;\n}\n\nasync function resolveCredential(\n\tsession: UsageSession,\n\tusageSource: SubscriptionUsageSource,\n): Promise<{ readonly provider: string; readonly apiKey: string } | undefined> {\n\tfor (const candidate of usageSource.credentials) {\n\t\tif (!credentialConfigured(session, candidate)) continue;\n\t\tconst apiKey = await session.modelRegistry.getApiKeyForProvider(candidate.provider);\n\t\tif (apiKey) return { provider: candidate.provider, apiKey };\n\t}\n\treturn undefined;\n}\n\nfunction codexWindow(value: unknown, nowSeconds: number): ParsedCodexWindow | undefined {\n\tconst window = record(value);\n\tconst usedPercent = finiteNumber(window?.used_percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst windowSeconds = finiteNumber(window?.limit_window_seconds);\n\tconst resetAt = finiteNumber(window?.reset_at);\n\tconst resetAfter = finiteNumber(window?.reset_after_seconds);\n\tconst resetsAt = resetAt ?? (resetAfter === undefined ? undefined : nowSeconds + resetAfter);\n\treturn {\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction claudeWindow(value: unknown): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tconst bucket = record(value);\n\tif (!bucket || bucket.is_active === false) return undefined;\n\tconst usedPercent = finiteNumber(bucket.utilization ?? bucket.percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst resetsAt = epochSeconds(bucket.resets_at);\n\treturn { usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) };\n}\n\nfunction usageRatio(\n\tdata: Record<string, unknown> | undefined,\n\tnowSeconds: number,\n): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tif (!data) return undefined;\n\tconst limit = finiteNumber(data.limit);\n\tlet used = finiteNumber(data.used);\n\tconst remaining = finiteNumber(data.remaining);\n\tif (used === undefined && limit !== undefined && remaining !== undefined) used = limit - remaining;\n\tif (used === undefined || limit === undefined || limit <= 0) return undefined;\n\tconst resetsAt = parseReset(data, nowSeconds);\n\treturn {\n\t\tusedPercent: clampPercent((used / limit) * 100),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiWindow(value: unknown):\n\t| (SubscriptionUsageWindow & {\n\t\t\treadonly type: string;\n\t\t\treadonly durationSeconds: number;\n\t\t\treadonly featureOnly: boolean;\n\t })\n\t| undefined {\n\tconst item = record(value);\n\tif (!item || (item.type !== \"TIME_LIMIT\" && item.type !== \"TOKENS_LIMIT\")) return undefined;\n\tconst percentage = finiteNumber(item.percentage);\n\tconst current = finiteNumber(item.currentValue);\n\tconst limit = finiteNumber(item.usage);\n\tconst usedPercent =\n\t\tpercentage ?? (current !== undefined && limit !== undefined && limit > 0 ? (current / limit) * 100 : undefined);\n\tif (usedPercent === undefined) return undefined;\n\tconst duration = zaiDuration(finiteNumber(item.unit), finiteNumber(item.number));\n\tconst resetsAt = epochSeconds(item.nextResetTime);\n\tconst detailCodes = Array.isArray(item.usageDetails)\n\t\t? item.usageDetails\n\t\t\t\t.map((detail) => record(detail)?.modelCode)\n\t\t\t\t.filter((code): code is string => typeof code === \"string\")\n\t\t: [];\n\treturn {\n\t\ttype: item.type,\n\t\tlabel: duration.label,\n\t\tdurationSeconds: duration.seconds,\n\t\tfeatureOnly: [\"search-prime\", \"web-reader\", \"zread\"].every((code) => detailCodes.includes(code)),\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiDuration(unit: number | undefined, countValue: number | undefined): { label: string; seconds: number } {\n\tconst count = countValue && countValue > 0 ? countValue : 1;\n\tif (unit === 3) return { label: `${count}H`, seconds: count * 60 * 60 };\n\tif (unit === 4) return { label: `${count}D`, seconds: count * 24 * 60 * 60 };\n\tif (unit === 5) return { label: count === 1 ? \"30D\" : `${count}MO`, seconds: count * 30 * 24 * 60 * 60 };\n\tif (unit === 6) return { label: \"7D\", seconds: 7 * 24 * 60 * 60 };\n\treturn { label: \"QUOTA\", seconds: Number.POSITIVE_INFINITY };\n}\n\nfunction durationLabel(window: Record<string, unknown> | undefined): string | undefined {\n\tif (!window) return undefined;\n\tconst duration = finiteNumber(window.duration);\n\tconst unit = typeof window.timeUnit === \"string\" ? window.timeUnit.toUpperCase() : \"\";\n\tif (duration === undefined) return undefined;\n\tif (unit.includes(\"MINUTE\")) return duration % 60 === 0 ? `${duration / 60}H` : `${duration}M`;\n\tif (unit.includes(\"HOUR\")) return `${duration}H`;\n\tif (unit.includes(\"DAY\")) return `${duration}D`;\n\tif (unit.includes(\"SECOND\")) return `${duration}S`;\n\treturn undefined;\n}\n\nfunction parseReset(data: Record<string, unknown> | undefined, nowSeconds: number): number | undefined {\n\tif (!data) return undefined;\n\tfor (const key of [\"reset_at\", \"resetAt\", \"reset_time\", \"resetTime\"] as const) {\n\t\tconst parsed = epochSeconds(data[key]);\n\t\tif (parsed !== undefined) return parsed;\n\t}\n\tfor (const key of [\"reset_in\", \"resetIn\", \"ttl\"] as const) {\n\t\tconst seconds = finiteNumber(data[key]);\n\t\tif (seconds !== undefined) return nowSeconds + seconds;\n\t}\n\treturn undefined;\n}\n\nfunction epochSeconds(value: unknown): number | undefined {\n\tconst numeric = finiteNumber(value);\n\tif (numeric !== undefined) return numeric > 1_000_000_000_000 ? numeric / 1000 : numeric;\n\tif (typeof value !== \"string\" || !value.trim()) return undefined;\n\tconst parsed = Date.parse(value);\n\treturn Number.isFinite(parsed) ? parsed / 1000 : undefined;\n}\n\nfunction normalizePassiveCodexWindow(\n\twindow: ProviderRateLimitWindow | undefined,\n\tnowMs: number,\n): ParsedCodexWindow | undefined {\n\tif (!window || !Number.isFinite(window.usedPercent)) return undefined;\n\tconst windowSeconds =\n\t\twindow.windowSeconds !== undefined &&\n\t\tNumber.isFinite(window.windowSeconds) &&\n\t\twindow.windowSeconds > 0 &&\n\t\twindow.windowSeconds <= Number.MAX_SAFE_INTEGER\n\t\t\t? Math.round(window.windowSeconds)\n\t\t\t: undefined;\n\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\tconst resetsAtValue = window.resetsAt === undefined ? undefined : Math.floor(window.resetsAt);\n\tconst resetsAt =\n\t\tresetsAtValue !== undefined &&\n\t\tNumber.isSafeInteger(resetsAtValue) &&\n\t\tresetsAtValue > 0 &&\n\t\tresetsAtValue <= maxResetAt\n\t\t\t? resetsAtValue\n\t\t\t: undefined;\n\treturn {\n\t\tusedPercent: clampPercent(window.usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction passiveCredentialCacheKey(identifier: string): string {\n\treturn createHash(\"sha256\").update(identifier).digest(\"base64url\");\n}\n\nfunction freshObservedCodexWindow(\n\tobserved: ObservedCodexWindow | undefined,\n\tnowMs: number,\n): ObservedCodexWindow | undefined {\n\tif (!observed || nowMs - observed.observedAt > PASSIVE_USAGE_TTL_MS) return undefined;\n\tif (observed.window.resetsAt !== undefined && observed.window.resetsAt <= nowMs / 1000) return undefined;\n\treturn observed;\n}\n\nfunction prunePassiveCodexUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveCodexUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveCodexUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction prunePassiveClaudeUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveClaudeUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction passiveCodexSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst entry = passiveCodexUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveCodexUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tconst freshEntry = { primary, secondary };\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, freshEntry);\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction passiveClaudeSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst entry = passiveClaudeUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, { primary, secondary });\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction codexAccountId(token: string): string | undefined {\n\ttry {\n\t\tconst payload = token.split(\".\")[1];\n\t\tif (!payload) return undefined;\n\t\tconst claims = record(JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\")));\n\t\tconst auth = record(claims?.[OPENAI_AUTH_CLAIM]);\n\t\tconst accountId = typeof auth?.chatgpt_account_id === \"string\" ? auth.chatgpt_account_id.trim() : \"\";\n\t\treturn accountId && accountId.length <= 256 ? accountId : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction publicCodexWindow(window: ParsedCodexWindow): CodexUsageWindow {\n\treturn { usedPercent: window.usedPercent, ...(window.resetsAt === undefined ? {} : { resetsAt: window.resetsAt }) };\n}\n\nfunction withLabel(label: string, window: Omit<SubscriptionUsageWindow, \"label\">): SubscriptionUsageWindow {\n\treturn { label, ...window };\n}\n\nfunction shortLabel(value: unknown, index: number): string {\n\tif (typeof value !== \"string\") return `LIMIT${index + 1}`;\n\tconst safe = value\n\t\t.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u206f]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn safe ? safe.toUpperCase().slice(0, 8) : `LIMIT${index + 1}`;\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n\tconst number =\n\t\ttypeof value === \"number\" ? value : typeof value === \"string\" && value.trim() ? Number(value) : Number.NaN;\n\treturn Number.isFinite(number) ? number : undefined;\n}\n\nfunction clampPercent(value: number): number {\n\treturn Number(Math.max(0, Math.min(100, value)).toFixed(2));\n}\n\nfunction near(actual: number | undefined, expected: number): boolean {\n\treturn actual !== undefined && Math.abs(actual - expected) <= WINDOW_TOLERANCE_SECONDS;\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isDefined<T>(value: T | undefined): value is T {\n\treturn value !== undefined;\n}\n\nfunction offline(): boolean {\n\tconst value = process.env.OMK_OFFLINE?.toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
+ import { CLAUDE_CODE_EXTERNAL_USER_AGENT } from "omk-ai";
3
4
  const FIVE_HOUR_SECONDS = 5 * 60 * 60;
4
5
  const SEVEN_DAY_SECONDS = 7 * 24 * 60 * 60;
5
6
  const WINDOW_TOLERANCE_SECONDS = 120;
@@ -509,7 +510,7 @@ async function fetchClaudeUsage(label, apiKey, fetchImpl) {
509
510
  Authorization: `Bearer ${apiKey}`,
510
511
  Accept: "application/json",
511
512
  "anthropic-beta": "claude-code-20250219,oauth-2025-04-20",
512
- "User-Agent": "claude-cli/2.1.177 (external, cli)",
513
+ "User-Agent": CLAUDE_CODE_EXTERNAL_USER_AGENT,
513
514
  },
514
515
  });
515
516
  const windows = [...(parseClaudeUsageSnapshot(response.payload) ?? [])];
@@ -563,7 +564,7 @@ async function probeClaudeQuota(apiKey, fetchImpl, nowMs = Date.now()) {
563
564
  "anthropic-version": "2023-06-01",
564
565
  "anthropic-beta": "claude-code-20250219,oauth-2025-04-20",
565
566
  "anthropic-dangerous-direct-browser-access": "true",
566
- "User-Agent": "claude-cli/2.1.177 (external, cli)",
567
+ "User-Agent": CLAUDE_CODE_EXTERNAL_USER_AGENT,
567
568
  "x-app": "cli",
568
569
  },
569
570
  body: JSON.stringify({