open-multi-agent-kit 0.96.2 → 0.97.0

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 (138) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +4 -2
  3. package/dist/core/agent-session.d.ts +9 -1
  4. package/dist/core/agent-session.d.ts.map +1 -1
  5. package/dist/core/agent-session.js +84 -7
  6. package/dist/core/agent-session.js.map +1 -1
  7. package/dist/core/attachment-store.d.ts +39 -0
  8. package/dist/core/attachment-store.d.ts.map +1 -0
  9. package/dist/core/attachment-store.js +81 -0
  10. package/dist/core/attachment-store.js.map +1 -0
  11. package/dist/core/command-safety.d.ts +8 -0
  12. package/dist/core/command-safety.d.ts.map +1 -1
  13. package/dist/core/command-safety.js +140 -14
  14. package/dist/core/command-safety.js.map +1 -1
  15. package/dist/core/compaction/compaction.d.ts +6 -1
  16. package/dist/core/compaction/compaction.d.ts.map +1 -1
  17. package/dist/core/compaction/compaction.js +35 -1
  18. package/dist/core/compaction/compaction.js.map +1 -1
  19. package/dist/core/context-budget-governor-v2.d.ts +1 -1
  20. package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
  21. package/dist/core/context-budget-governor-v2.js +1 -1
  22. package/dist/core/context-budget-governor-v2.js.map +1 -1
  23. package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
  24. package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
  25. package/dist/core/context-budget-v2-cache-keys.js +2 -0
  26. package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
  27. package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
  28. package/dist/core/context-budget-v2-plan-cache-keys.js +3 -0
  29. package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
  30. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  31. package/dist/core/context-budget-v2-planner.js +2 -1
  32. package/dist/core/context-budget-v2-planner.js.map +1 -1
  33. package/dist/core/context-budget-v2-scoring.d.ts +17 -0
  34. package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
  35. package/dist/core/context-budget-v2-scoring.js +25 -8
  36. package/dist/core/context-budget-v2-scoring.js.map +1 -1
  37. package/dist/core/context-budget-v2-selection.d.ts +2 -2
  38. package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
  39. package/dist/core/context-budget-v2-selection.js +18 -1
  40. package/dist/core/context-budget-v2-selection.js.map +1 -1
  41. package/dist/core/context-budget-v2-types.d.ts +17 -0
  42. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  43. package/dist/core/context-budget-v2-types.js +15 -0
  44. package/dist/core/context-budget-v2-types.js.map +1 -1
  45. package/dist/core/extensions/builtin/command-safety-gate.d.ts +3 -1
  46. package/dist/core/extensions/builtin/command-safety-gate.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/command-safety-gate.js +7 -0
  48. package/dist/core/extensions/builtin/command-safety-gate.js.map +1 -1
  49. package/dist/core/extensions/types.d.ts +12 -1
  50. package/dist/core/extensions/types.d.ts.map +1 -1
  51. package/dist/core/extensions/types.js.map +1 -1
  52. package/dist/core/model-registry.d.ts +8 -3
  53. package/dist/core/model-registry.d.ts.map +1 -1
  54. package/dist/core/model-registry.js +71 -1
  55. package/dist/core/model-registry.js.map +1 -1
  56. package/dist/core/package-doctor-source-scan.d.ts +9 -0
  57. package/dist/core/package-doctor-source-scan.d.ts.map +1 -1
  58. package/dist/core/package-doctor-source-scan.js +77 -4
  59. package/dist/core/package-doctor-source-scan.js.map +1 -1
  60. package/dist/core/prompt-attachment.d.ts +51 -0
  61. package/dist/core/prompt-attachment.d.ts.map +1 -0
  62. package/dist/core/prompt-attachment.js +186 -0
  63. package/dist/core/prompt-attachment.js.map +1 -0
  64. package/dist/core/provider-resilience.d.ts +28 -0
  65. package/dist/core/provider-resilience.d.ts.map +1 -1
  66. package/dist/core/provider-resilience.js +50 -0
  67. package/dist/core/provider-resilience.js.map +1 -1
  68. package/dist/core/provider-retry.d.ts +1 -1
  69. package/dist/core/provider-retry.d.ts.map +1 -1
  70. package/dist/core/provider-retry.js +1 -1
  71. package/dist/core/provider-retry.js.map +1 -1
  72. package/dist/core/provider-usage.d.ts.map +1 -1
  73. package/dist/core/provider-usage.js +68 -2
  74. package/dist/core/provider-usage.js.map +1 -1
  75. package/dist/core/reasoning-router-promotion.d.ts +84 -0
  76. package/dist/core/reasoning-router-promotion.d.ts.map +1 -0
  77. package/dist/core/reasoning-router-promotion.js +92 -0
  78. package/dist/core/reasoning-router-promotion.js.map +1 -0
  79. package/dist/core/session-bash-service.d.ts.map +1 -1
  80. package/dist/core/session-bash-service.js +4 -3
  81. package/dist/core/session-bash-service.js.map +1 -1
  82. package/dist/core/session-termination.d.ts +1 -1
  83. package/dist/core/session-termination.d.ts.map +1 -1
  84. package/dist/core/session-termination.js +11 -2
  85. package/dist/core/session-termination.js.map +1 -1
  86. package/dist/core/tools/bash.d.ts.map +1 -1
  87. package/dist/core/tools/bash.js +3 -7
  88. package/dist/core/tools/bash.js.map +1 -1
  89. package/dist/core/tools/grep.d.ts.map +1 -1
  90. package/dist/core/tools/grep.js +13 -48
  91. package/dist/core/tools/grep.js.map +1 -1
  92. package/dist/core/tools/read.d.ts.map +1 -1
  93. package/dist/core/tools/read.js +1 -34
  94. package/dist/core/tools/read.js.map +1 -1
  95. package/dist/index.d.ts +1 -1
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +1 -1
  98. package/dist/index.js.map +1 -1
  99. package/dist/modes/interactive/components/attachment-strip.d.ts +21 -0
  100. package/dist/modes/interactive/components/attachment-strip.d.ts.map +1 -0
  101. package/dist/modes/interactive/components/attachment-strip.js +136 -0
  102. package/dist/modes/interactive/components/attachment-strip.js.map +1 -0
  103. package/dist/modes/interactive/components/footer.d.ts +6 -0
  104. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  105. package/dist/modes/interactive/components/footer.js +26 -1
  106. package/dist/modes/interactive/components/footer.js.map +1 -1
  107. package/dist/modes/interactive/components/status-sidebar.d.ts.map +1 -1
  108. package/dist/modes/interactive/components/status-sidebar.js +12 -1
  109. package/dist/modes/interactive/components/status-sidebar.js.map +1 -1
  110. package/dist/modes/interactive/interactive-mode.d.ts +23 -4
  111. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  112. package/dist/modes/interactive/interactive-mode.js +174 -53
  113. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  114. package/docs/compaction.md +1 -1
  115. package/docs/extensions.md +12 -3
  116. package/docs/index.md +4 -1
  117. package/docs/metrics.md +74 -2
  118. package/docs/provider-resilience.md +11 -0
  119. package/docs/usage.md +1 -1
  120. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  121. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  122. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  123. package/examples/extensions/gondolin/package-lock.json +2 -2
  124. package/examples/extensions/gondolin/package.json +1 -1
  125. package/examples/extensions/sandbox/package-lock.json +2 -2
  126. package/examples/extensions/sandbox/package.json +1 -1
  127. package/examples/extensions/with-deps/package-lock.json +2 -2
  128. package/examples/extensions/with-deps/package.json +1 -1
  129. package/npm-shrinkwrap.json +18 -18
  130. package/package.json +7 -7
  131. package/dist/core/tools/omp-pure-seams.d.ts +0 -41
  132. package/dist/core/tools/omp-pure-seams.d.ts.map +0 -1
  133. package/dist/core/tools/omp-pure-seams.js +0 -142
  134. package/dist/core/tools/omp-pure-seams.js.map +0 -1
  135. package/dist/core/tools/omp-seam-runtime.d.ts +0 -100
  136. package/dist/core/tools/omp-seam-runtime.d.ts.map +0 -1
  137. package/dist/core/tools/omp-seam-runtime.js +0 -40
  138. package/dist/core/tools/omp-seam-runtime.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"provider-resilience.js","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,oFAAoF;AACpF,MAAM,CAAC,MAAM,sBAAsB,GAAG,QAAQ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,MAAM,UAAU,wBAAwB,CAAC,OAAe,EAAE,QAAgB,EAAU;IACnF,OAAO,CACN,+BAA+B,QAAQ,IAAI,OAAO,iDAAiD;QACnG,mFAAmF;QACnF,0DAA0D,CAC1D,CAAC;AAAA,CACF","sourcesContent":["/**\n * Provider resilience — root-level recovery for sticky safety models and\n * sanitize-and-retry protocol failures (orphan tool_call_id, terminated streams).\n *\n * This is not a jailbreak layer. It keeps sessions alive when a provider\n * false-positives or returns a sticky transcript-shape error.\n */\n\nexport type FailoverCandidate = Readonly<{\n\treadonly provider: string;\n\treadonly id: string;\n}>;\n\n/** Models known to emit high false-positive content/safety stops on coding work. */\nexport const STICKY_SAFETY_MODEL_RE = /fable/i;\n\n/** Claude lines that must stay on-model when they refuse. No DeepSeek hop. */\nexport const NO_SAFETY_FAILOVER_MODEL_RE = /(?:claude-)?(?:fable|opus|sonnet)/i;\n\n/** Default failover chain when a sticky safety model refuses a turn. */\nexport const DEFAULT_SAFETY_FAILOVER_CANDIDATES: readonly FailoverCandidate[] = [\n\t{ provider: \"kimi-coding\", id: \"k3\" },\n\t{ provider: \"modelstudio-maas\", id: \"qwen3.8-max-preview\" },\n\t{ provider: \"xai\", id: \"grok-4.5\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-flash\" },\n\t{ provider: \"modelstudio-maas\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"kimi-coding\", id: \"kimi-for-coding\" },\n] as const;\n\nexport type ProviderResilienceSettings = Readonly<{\n\t/** When true (default), refuse selecting sticky safety models (e.g. claude-fable-5). */\n\treadonly blockStickySafetyModels?: boolean;\n\t/** When true (default), auto-switch model on content/safety stop before retry. */\n\treadonly autoFailoverOnSafetyStop?: boolean;\n\t/** Ordered failover targets. Falls back to DEFAULT_SAFETY_FAILOVER_CANDIDATES. */\n\treadonly failoverCandidates?: readonly FailoverCandidate[];\n}>;\n\nexport const DEFAULT_PROVIDER_RESILIENCE: Required<\n\tPick<ProviderResilienceSettings, \"blockStickySafetyModels\" | \"autoFailoverOnSafetyStop\">\n> & {\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} = {\n\tblockStickySafetyModels: true,\n\tautoFailoverOnSafetyStop: true,\n\tfailoverCandidates: DEFAULT_SAFETY_FAILOVER_CANDIDATES,\n};\n\nexport function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (STICKY_SAFETY_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && STICKY_SAFETY_MODEL_RE.test(id);\n}\n\n/** Fable / Opus / Sonnet stay on the requested id after a safety stop. */\nexport function isNoSafetyFailoverModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (NO_SAFETY_FAILOVER_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && NO_SAFETY_FAILOVER_MODEL_RE.test(id);\n}\n\nexport function isContentSafetyStopMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\ttext,\n\t);\n}\n\n/**\n * Billing/quota exhaustion (\"usage limit for this billing cycle\",\n * \"insufficient_quota\", zero balance, ...). Same-model retry is useless until\n * the cycle resets, but the turn can still be saved by failing over to another\n * candidate — so these classify as retryable-with-failover, not auth-fatal.\n */\nexport function isQuotaExhaustionMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /usage limit|GoUsageLimitError|FreeUsageLimitError|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(\n\t\ttext,\n\t);\n}\n\n/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */\nexport function isOrphanToolCallIdError(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text);\n}\n\n/**\n * Errors the agent loop may auto-retry (after optional failover / message sanitize).\n * Kept in one place so agent-session and tests share the same contract.\n */\nexport function isTransientProviderErrorMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|\\bterminated\\b|retry delay|content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|invalid_request_error|json error injected into sse stream|injected into sse/i.test(\n\t\ttext,\n\t);\n}\n\nexport function resolveFailoverCandidates(\n\tsettings: ProviderResilienceSettings | undefined,\n): readonly FailoverCandidate[] {\n\tconst custom = settings?.failoverCandidates;\n\tif (custom && custom.length > 0) return custom;\n\treturn DEFAULT_SAFETY_FAILOVER_CANDIDATES;\n}\n\n/** Explicit `--model` / `--provider` pins stay on the requested model. */\nexport function shouldHonorSafetyFailover(options: {\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly modelPinned: boolean;\n\treadonly modelId?: string;\n\treadonly provider?: string;\n}): boolean {\n\tif (!options.autoFailoverOnSafetyStop || options.modelPinned) return false;\n\treturn !isNoSafetyFailoverModel(options.modelId, options.provider);\n}\n\n/** Sticky-model eject still applies unless the user pinned that model. */\nexport function shouldEjectStickySafetyModel(options: {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly modelPinned: boolean;\n}): boolean {\n\treturn options.blockStickySafetyModels && !options.modelPinned;\n}\n\nexport function resolveProviderResilience(settings: ProviderResilienceSettings | undefined): {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} {\n\treturn {\n\t\tblockStickySafetyModels: settings?.blockStickySafetyModels ?? DEFAULT_PROVIDER_RESILIENCE.blockStickySafetyModels,\n\t\tautoFailoverOnSafetyStop:\n\t\t\tsettings?.autoFailoverOnSafetyStop ?? DEFAULT_PROVIDER_RESILIENCE.autoFailoverOnSafetyStop,\n\t\tfailoverCandidates: resolveFailoverCandidates(settings),\n\t};\n}\n\n/**\n * Pick first failover candidate that is not the current model and passes `isAllowed`.\n * Pure — caller performs auth checks and setModel.\n */\nexport function pickFailoverCandidate(\n\tcandidates: readonly FailoverCandidate[],\n\tcurrent: { readonly provider?: string; readonly id?: string } | undefined,\n\tisAllowed: (candidate: FailoverCandidate) => boolean,\n): FailoverCandidate | undefined {\n\tfor (const c of candidates) {\n\t\tif (current && c.provider === current.provider && c.id === current.id) continue;\n\t\tif (isStickySafetyModel(c.id, c.provider)) continue;\n\t\tif (!isAllowed(c)) continue;\n\t\treturn c;\n\t}\n\treturn undefined;\n}\n\nexport function stickySafetyBlockMessage(modelId: string, provider: string): string {\n\treturn (\n\t\t`Blocked sticky safety model ${provider}/${modelId} (providerResilience.blockStickySafetyModels). ` +\n\t\t`Use kimi-coding/k3, modelstudio-maas/qwen3.8-max-preview, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\n}\n"]}
1
+ {"version":3,"file":"provider-resilience.js","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,oFAAoF;AACpF,MAAM,CAAC,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AAE/C,8EAA8E;AAC9E,MAAM,CAAC,MAAM,2BAA2B,GAAG,oCAAoC,CAAC;AAEhF,wEAAwE;AACxE,MAAM,CAAC,MAAM,kCAAkC,GAAiC;IAC/E,EAAE,QAAQ,EAAE,aAAa,EAAE,EAAE,EA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ize-and-retry protocol failures (orphan tool_call_id, terminated streams).\n *\n * This is not a jailbreak layer. It keeps sessions alive when a provider\n * false-positives or returns a sticky transcript-shape error.\n */\n\nexport type FailoverCandidate = Readonly<{\n\treadonly provider: string;\n\treadonly id: string;\n}>;\n\n/** Models known to emit high false-positive content/safety stops on coding work. */\nexport const STICKY_SAFETY_MODEL_RE = /fable/i;\n\n/** Claude lines that must stay on-model when they refuse. No DeepSeek hop. */\nexport const NO_SAFETY_FAILOVER_MODEL_RE = /(?:claude-)?(?:fable|opus|sonnet)/i;\n\n/** Default failover chain when a sticky safety model refuses a turn. */\nexport const DEFAULT_SAFETY_FAILOVER_CANDIDATES: readonly FailoverCandidate[] = [\n\t{ provider: \"kimi-coding\", id: \"k3\" },\n\t{ provider: \"modelstudio-maas\", id: \"qwen3.8-max-preview\" },\n\t{ provider: \"xai\", id: \"grok-4.5\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-flash\" },\n\t{ provider: \"modelstudio-maas\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"kimi-coding\", id: \"kimi-for-coding\" },\n] as const;\n\nexport type ProviderResilienceSettings = Readonly<{\n\t/** When true (default), refuse selecting sticky safety models (e.g. claude-fable-5). */\n\treadonly blockStickySafetyModels?: boolean;\n\t/** When true (default), auto-switch model on content/safety stop before retry. */\n\treadonly autoFailoverOnSafetyStop?: boolean;\n\t/** Ordered failover targets. Falls back to DEFAULT_SAFETY_FAILOVER_CANDIDATES. */\n\treadonly failoverCandidates?: readonly FailoverCandidate[];\n}>;\n\nexport const DEFAULT_PROVIDER_RESILIENCE: Required<\n\tPick<ProviderResilienceSettings, \"blockStickySafetyModels\" | \"autoFailoverOnSafetyStop\">\n> & {\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} = {\n\tblockStickySafetyModels: true,\n\tautoFailoverOnSafetyStop: true,\n\tfailoverCandidates: DEFAULT_SAFETY_FAILOVER_CANDIDATES,\n};\n\nexport function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (STICKY_SAFETY_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && STICKY_SAFETY_MODEL_RE.test(id);\n}\n\n/** Fable / Opus / Sonnet stay on the requested id after a safety stop. */\nexport function isNoSafetyFailoverModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (NO_SAFETY_FAILOVER_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && NO_SAFETY_FAILOVER_MODEL_RE.test(id);\n}\n\nexport function isContentSafetyStopMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\ttext,\n\t);\n}\n\n/**\n * Billing/quota exhaustion (\"usage limit for this billing cycle\",\n * \"insufficient_quota\", zero balance, ...). Same-model retry is useless until\n * the cycle resets, but the turn can still be saved by failing over to another\n * candidate — so these classify as retryable-with-failover, not auth-fatal.\n */\nexport function isQuotaExhaustionMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /usage limit|GoUsageLimitError|FreeUsageLimitError|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(\n\t\ttext,\n\t);\n}\n\n/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */\nexport function isOrphanToolCallIdError(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text);\n}\n\n/**\n * Transient upstream availability failures: gateway 5xx passthroughs\n * (\"503 Upstream request failed\", \"Endpoint is unavailable\") and dropped\n * streams that never carried a finish reason (\"Stream ended without\n * finish_reason\"). Transport problems, not transcript-shape problems — they\n * heal by backoff/retry or switching model, never by transcript sanitization.\n */\nexport function isUpstreamUnavailableMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /upstream(?: request)? failed|upstream connect|endpoint (?:is )?unavailable|stream ended without finish_reason|\\b50[0234]\\b/i.test(\n\t\ttext,\n\t);\n}\n\n/**\n * Route families: the same underlying model served by several provider\n * routes. Matched on the model id OR display name so alias routes like\n * `openrouter/stealth/ox-alpha`, `opencode-go/ox-alpha-free`, and\n * `opencode/x-preview-f-free` (\"Ox Alpha Free (Unlimited)\") rotate as one\n * ox-alpha family.\n */\nconst MODEL_ROUTE_FAMILIES: readonly { readonly pattern: RegExp; readonly family: string }[] = [\n\t{ pattern: /(?:^|[-_/])ox[-_ ]?alpha(?:[-_/\\s(]|$)/i, family: \"ox-alpha\" },\n];\n\n/** Family key for a model route, or undefined when it has no known alias group. */\nexport function modelRouteFamily(model: {\n\treadonly provider?: string | undefined;\n\treadonly id: string;\n\treadonly name?: string | undefined;\n}): string | undefined {\n\tfor (const { pattern, family } of MODEL_ROUTE_FAMILIES) {\n\t\tif (pattern.test(model.id)) return family;\n\t\tif (model.name && pattern.test(model.name)) return family;\n\t}\n\treturn undefined;\n}\n\n/**\n * Alternative provider routes serving the same model family as\n * {@link failed}, in registry order, excluding the failed route itself.\n * Callers filter by authentication and per-turn failure bookkeeping.\n */\nexport function sameModelRouteCandidates<\n\tT extends { readonly provider: string; readonly id: string; readonly name?: string | undefined },\n>(\n\tfailed: { readonly provider: string; readonly id: string; readonly name?: string | undefined },\n\tavailable: readonly T[],\n): T[] {\n\tconst family = modelRouteFamily(failed);\n\tif (!family) return [];\n\tconst candidates: T[] = [];\n\tfor (const model of available) {\n\t\tif (model.provider === failed.provider && model.id === failed.id) continue;\n\t\tif (modelRouteFamily(model) === family) candidates.push(model);\n\t}\n\treturn candidates;\n}\n\n/**\n * Errors the agent loop may auto-retry (after optional failover / message sanitize).\n * Kept in one place so agent-session and tests share the same contract.\n */\nexport function isTransientProviderErrorMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|\\bterminated\\b|retry delay|content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|invalid_request_error|json error injected into sse stream|injected into sse/i.test(\n\t\ttext,\n\t);\n}\n\nexport function resolveFailoverCandidates(\n\tsettings: ProviderResilienceSettings | undefined,\n): readonly FailoverCandidate[] {\n\tconst custom = settings?.failoverCandidates;\n\tif (custom && custom.length > 0) return custom;\n\treturn DEFAULT_SAFETY_FAILOVER_CANDIDATES;\n}\n\n/** Explicit `--model` / `--provider` pins stay on the requested model. */\nexport function shouldHonorSafetyFailover(options: {\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly modelPinned: boolean;\n\treadonly modelId?: string;\n\treadonly provider?: string;\n}): boolean {\n\tif (!options.autoFailoverOnSafetyStop || options.modelPinned) return false;\n\treturn !isNoSafetyFailoverModel(options.modelId, options.provider);\n}\n\n/** Sticky-model eject still applies unless the user pinned that model. */\nexport function shouldEjectStickySafetyModel(options: {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly modelPinned: boolean;\n}): boolean {\n\treturn options.blockStickySafetyModels && !options.modelPinned;\n}\n\nexport function resolveProviderResilience(settings: ProviderResilienceSettings | undefined): {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} {\n\treturn {\n\t\tblockStickySafetyModels: settings?.blockStickySafetyModels ?? DEFAULT_PROVIDER_RESILIENCE.blockStickySafetyModels,\n\t\tautoFailoverOnSafetyStop:\n\t\t\tsettings?.autoFailoverOnSafetyStop ?? DEFAULT_PROVIDER_RESILIENCE.autoFailoverOnSafetyStop,\n\t\tfailoverCandidates: resolveFailoverCandidates(settings),\n\t};\n}\n\n/**\n * Pick first failover candidate that is not the current model and passes `isAllowed`.\n * Pure — caller performs auth checks and setModel.\n */\nexport function pickFailoverCandidate(\n\tcandidates: readonly FailoverCandidate[],\n\tcurrent: { readonly provider?: string; readonly id?: string } | undefined,\n\tisAllowed: (candidate: FailoverCandidate) => boolean,\n): FailoverCandidate | undefined {\n\tfor (const c of candidates) {\n\t\tif (current && c.provider === current.provider && c.id === current.id) continue;\n\t\tif (isStickySafetyModel(c.id, c.provider)) continue;\n\t\tif (!isAllowed(c)) continue;\n\t\treturn c;\n\t}\n\treturn undefined;\n}\n\nexport function stickySafetyBlockMessage(modelId: string, provider: string): string {\n\treturn (\n\t\t`Blocked sticky safety model ${provider}/${modelId} (providerResilience.blockStickySafetyModels). ` +\n\t\t`Use kimi-coding/k3, modelstudio-maas/qwen3.8-max-preview, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\n}\n"]}
@@ -7,7 +7,7 @@ import type { AssistantMessage } from "omk-ai";
7
7
  /**
8
8
  * Empty streamed completion — stop=stop but zero usable output (no text,
9
9
  * thinking, or toolCall). Live signature of relay first-token timeouts
10
- * (~181s silent kill on thinking-heavy ox-alpha turns, 2026-08-22 log evidence).
10
+ * killing long silent thinking turns.
11
11
  * These are transport failures wearing a success shape.
12
12
  */
13
13
  export declare function isEmptyStreamedCompletion(message: AssistantMessage): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"provider-retry.d.ts","sourceRoot":"","sources":["../../src/core/provider-retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAQ/C;;;;GAIG;AACH;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAW5E;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAQnG;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,GAAG,MAAM,CAG5G;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE;IACvC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B,GAAG,MAAM,GAAG,SAAS,CAIrB;AAED,iFAAiF;AACjF,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,gBAAgB,EAAE,OAAO,GAAG,MAAM,CAE3G;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAEhF;AAED,iEAAiE;AACjE,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAErE","sourcesContent":["import type { AssistantMessage } from \"omk-ai\";\nimport { isContextOverflow } from \"omk-ai\";\nimport {\n\tisContentSafetyStopMessage,\n\tisQuotaExhaustionMessage,\n\tisTransientProviderErrorMessage,\n} from \"./provider-resilience.ts\";\n\n/**\n * Pure retry/failover decisions for agent-turn provider errors.\n * Context overflow is never retryable here — compaction owns that path.\n * Quota exhaustion is retryable so the failover chain can save the turn.\n */\n/**\n * Empty streamed completion — stop=stop but zero usable output (no text,\n * thinking, or toolCall). Live signature of relay first-token timeouts\n * (~181s silent kill on thinking-heavy ox-alpha turns, 2026-08-22 log evidence).\n * These are transport failures wearing a success shape.\n */\nexport function isEmptyStreamedCompletion(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"stop\") return false;\n\tconst content: unknown = message.content;\n\tif (!Array.isArray(content)) {\n\t\treturn typeof content === \"string\" ? content.trim().length === 0 : true;\n\t}\n\treturn content.every((block) => {\n\t\tconst t = (block as { type?: string } | null)?.type;\n\t\tif (t !== \"text\") return false; // thinking/toolCall/image = real output\n\t\treturn !String((block as { text?: string }).text ?? \"\").trim();\n\t});\n}\n\nexport function isRetryableAssistantError(message: AssistantMessage, contextWindow: number): boolean {\n\t// An empty streamed completion is a dead stream, not an answer — retry it\n\t// regardless of its success-shaped stopReason (bounded by maxRetries).\n\tif (isEmptyStreamedCompletion(message)) return true;\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tif (isQuotaExhaustionMessage(message.errorMessage)) return true;\n\treturn isTransientProviderErrorMessage(message.errorMessage);\n}\n\n/**\n * Next attempt number within the retry budget, or undefined when retry is\n * disabled or the budget is exhausted. The caller's completed-attempt count\n * stays unchanged when undefined is returned.\n */\nexport function retryBudgetForAssistantError(message: AssistantMessage, configuredMaxRetries: number): number {\n\tif (configuredMaxRetries <= 0) return 0;\n\treturn isContentSafetyStopMessage(message.errorMessage) ? Math.min(1, configuredMaxRetries) : configuredMaxRetries;\n}\n\nexport function nextRetryAttempt(input: {\n\treadonly enabled: boolean;\n\treadonly completedAttempts: number;\n\treadonly maxRetries: number;\n}): number | undefined {\n\tif (!input.enabled) return undefined;\n\tconst attempt = input.completedAttempts + 1;\n\treturn attempt > input.maxRetries ? undefined : attempt;\n}\n\n/** Same-model retry backs off exponentially; a failed-over retry starts fast. */\nexport function computeRetryDelayMs(baseDelayMs: number, attempt: number, failoverOccurred: boolean): number {\n\treturn failoverOccurred ? Math.min(400, baseDelayMs) : baseDelayMs * 2 ** (attempt - 1);\n}\n\n/**\n * Errors that justify an immediate model switch instead of a same-model retry:\n * safety-stop false positives and billing/quota exhaustion. Both mean the\n * current model cannot finish this turn.\n */\nexport function isFailoverTriggerError(errorMessage: string | undefined): boolean {\n\treturn isContentSafetyStopMessage(errorMessage) || isQuotaExhaustionMessage(errorMessage);\n}\n\n/** Bookkeeping key for the per-turn refused/failed model set. */\nexport function failoverModelKey(provider: string, id: string): string {\n\treturn `${provider}/${id}`;\n}\n"]}
1
+ {"version":3,"file":"provider-retry.d.ts","sourceRoot":"","sources":["../../src/core/provider-retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAQ/C;;;;GAIG;AACH;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAW5E;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAQnG;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,GAAG,MAAM,CAG5G;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE;IACvC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B,GAAG,MAAM,GAAG,SAAS,CAIrB;AAED,iFAAiF;AACjF,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,gBAAgB,EAAE,OAAO,GAAG,MAAM,CAE3G;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAEhF;AAED,iEAAiE;AACjE,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAErE","sourcesContent":["import type { AssistantMessage } from \"omk-ai\";\nimport { isContextOverflow } from \"omk-ai\";\nimport {\n\tisContentSafetyStopMessage,\n\tisQuotaExhaustionMessage,\n\tisTransientProviderErrorMessage,\n} from \"./provider-resilience.ts\";\n\n/**\n * Pure retry/failover decisions for agent-turn provider errors.\n * Context overflow is never retryable here — compaction owns that path.\n * Quota exhaustion is retryable so the failover chain can save the turn.\n */\n/**\n * Empty streamed completion — stop=stop but zero usable output (no text,\n * thinking, or toolCall). Live signature of relay first-token timeouts\n * killing long silent thinking turns.\n * These are transport failures wearing a success shape.\n */\nexport function isEmptyStreamedCompletion(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"stop\") return false;\n\tconst content: unknown = message.content;\n\tif (!Array.isArray(content)) {\n\t\treturn typeof content === \"string\" ? content.trim().length === 0 : true;\n\t}\n\treturn content.every((block) => {\n\t\tconst t = (block as { type?: string } | null)?.type;\n\t\tif (t !== \"text\") return false; // thinking/toolCall/image = real output\n\t\treturn !String((block as { text?: string }).text ?? \"\").trim();\n\t});\n}\n\nexport function isRetryableAssistantError(message: AssistantMessage, contextWindow: number): boolean {\n\t// An empty streamed completion is a dead stream, not an answer — retry it\n\t// regardless of its success-shaped stopReason (bounded by maxRetries).\n\tif (isEmptyStreamedCompletion(message)) return true;\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tif (isQuotaExhaustionMessage(message.errorMessage)) return true;\n\treturn isTransientProviderErrorMessage(message.errorMessage);\n}\n\n/**\n * Next attempt number within the retry budget, or undefined when retry is\n * disabled or the budget is exhausted. The caller's completed-attempt count\n * stays unchanged when undefined is returned.\n */\nexport function retryBudgetForAssistantError(message: AssistantMessage, configuredMaxRetries: number): number {\n\tif (configuredMaxRetries <= 0) return 0;\n\treturn isContentSafetyStopMessage(message.errorMessage) ? Math.min(1, configuredMaxRetries) : configuredMaxRetries;\n}\n\nexport function nextRetryAttempt(input: {\n\treadonly enabled: boolean;\n\treadonly completedAttempts: number;\n\treadonly maxRetries: number;\n}): number | undefined {\n\tif (!input.enabled) return undefined;\n\tconst attempt = input.completedAttempts + 1;\n\treturn attempt > input.maxRetries ? undefined : attempt;\n}\n\n/** Same-model retry backs off exponentially; a failed-over retry starts fast. */\nexport function computeRetryDelayMs(baseDelayMs: number, attempt: number, failoverOccurred: boolean): number {\n\treturn failoverOccurred ? Math.min(400, baseDelayMs) : baseDelayMs * 2 ** (attempt - 1);\n}\n\n/**\n * Errors that justify an immediate model switch instead of a same-model retry:\n * safety-stop false positives and billing/quota exhaustion. Both mean the\n * current model cannot finish this turn.\n */\nexport function isFailoverTriggerError(errorMessage: string | undefined): boolean {\n\treturn isContentSafetyStopMessage(errorMessage) || isQuotaExhaustionMessage(errorMessage);\n}\n\n/** Bookkeeping key for the per-turn refused/failed model set. */\nexport function failoverModelKey(provider: string, id: string): string {\n\treturn `${provider}/${id}`;\n}\n"]}
@@ -8,7 +8,7 @@ import { isContentSafetyStopMessage, isQuotaExhaustionMessage, isTransientProvid
8
8
  /**
9
9
  * Empty streamed completion — stop=stop but zero usable output (no text,
10
10
  * thinking, or toolCall). Live signature of relay first-token timeouts
11
- * (~181s silent kill on thinking-heavy ox-alpha turns, 2026-08-22 log evidence).
11
+ * killing long silent thinking turns.
12
12
  * These are transport failures wearing a success shape.
13
13
  */
14
14
  export function isEmptyStreamedCompletion(message) {
@@ -1 +1 @@
1
- {"version":3,"file":"provider-retry.js","sourceRoot":"","sources":["../../src/core/provider-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAC3C,OAAO,EACN,0BAA0B,EAC1B,wBAAwB,EACxB,+BAA+B,GAC/B,MAAM,0BAA0B,CAAC;AAElC;;;;GAIG;AACH;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAyB,EAAW;IAC7E,IAAI,OAAO,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IAChD,MAAM,OAAO,GAAY,OAAO,CAAC,OAAO,CAAC;IACzC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,C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CACnH;AAED,MAAM,UAAU,gBAAgB,CAAC,KAIhC,EAAsB;IACtB,IAAI,CAAC,KAAK,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IACrC,MAAM,OAAO,GAAG,KAAK,CAAC,iBAAiB,GAAG,CAAC,CAAC;IAC5C,OAAO,OAAO,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;AAAA,CACxD;AAED,iFAAiF;AACjF,MAAM,UAAU,mBAAmB,CAAC,WAAmB,EAAE,OAAe,EAAE,gBAAyB,EAAU;IAC5G,OAAO,gBAAgB,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;AAAA,CACxF;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,YAAgC,EAAW;IACjF,OAAO,0BAA0B,CAAC,YAAY,CAAC,IAAI,wBAAwB,CAAC,YAAY,CAAC,CAAC;AAAA,CAC1F;AAED,iEAAiE;AACjE,MAAM,UAAU,gBAAgB,CAAC,QAAgB,EAAE,EAAU,EAAU;IACtE,OAAO,GAAG,QAAQ,IAAI,EAAE,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["import type { AssistantMessage } from \"omk-ai\";\nimport { isContextOverflow } from \"omk-ai\";\nimport {\n\tisContentSafetyStopMessage,\n\tisQuotaExhaustionMessage,\n\tisTransientProviderErrorMessage,\n} from \"./provider-resilience.ts\";\n\n/**\n * Pure retry/failover decisions for agent-turn provider errors.\n * Context overflow is never retryable here — compaction owns that path.\n * Quota exhaustion is retryable so the failover chain can save the turn.\n */\n/**\n * Empty streamed completion — stop=stop but zero usable output (no text,\n * thinking, or toolCall). Live signature of relay first-token timeouts\n * (~181s silent kill on thinking-heavy ox-alpha turns, 2026-08-22 log evidence).\n * These are transport failures wearing a success shape.\n */\nexport function isEmptyStreamedCompletion(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"stop\") return false;\n\tconst content: unknown = message.content;\n\tif (!Array.isArray(content)) {\n\t\treturn typeof content === \"string\" ? content.trim().length === 0 : true;\n\t}\n\treturn content.every((block) => {\n\t\tconst t = (block as { type?: string } | null)?.type;\n\t\tif (t !== \"text\") return false; // thinking/toolCall/image = real output\n\t\treturn !String((block as { text?: string }).text ?? \"\").trim();\n\t});\n}\n\nexport function isRetryableAssistantError(message: AssistantMessage, contextWindow: number): boolean {\n\t// An empty streamed completion is a dead stream, not an answer — retry it\n\t// regardless of its success-shaped stopReason (bounded by maxRetries).\n\tif (isEmptyStreamedCompletion(message)) return true;\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tif (isQuotaExhaustionMessage(message.errorMessage)) return true;\n\treturn isTransientProviderErrorMessage(message.errorMessage);\n}\n\n/**\n * Next attempt number within the retry budget, or undefined when retry is\n * disabled or the budget is exhausted. The caller's completed-attempt count\n * stays unchanged when undefined is returned.\n */\nexport function retryBudgetForAssistantError(message: AssistantMessage, configuredMaxRetries: number): number {\n\tif (configuredMaxRetries <= 0) return 0;\n\treturn isContentSafetyStopMessage(message.errorMessage) ? Math.min(1, configuredMaxRetries) : configuredMaxRetries;\n}\n\nexport function nextRetryAttempt(input: {\n\treadonly enabled: boolean;\n\treadonly completedAttempts: number;\n\treadonly maxRetries: number;\n}): number | undefined {\n\tif (!input.enabled) return undefined;\n\tconst attempt = input.completedAttempts + 1;\n\treturn attempt > input.maxRetries ? undefined : attempt;\n}\n\n/** Same-model retry backs off exponentially; a failed-over retry starts fast. */\nexport function computeRetryDelayMs(baseDelayMs: number, attempt: number, failoverOccurred: boolean): number {\n\treturn failoverOccurred ? Math.min(400, baseDelayMs) : baseDelayMs * 2 ** (attempt - 1);\n}\n\n/**\n * Errors that justify an immediate model switch instead of a same-model retry:\n * safety-stop false positives and billing/quota exhaustion. Both mean the\n * current model cannot finish this turn.\n */\nexport function isFailoverTriggerError(errorMessage: string | undefined): boolean {\n\treturn isContentSafetyStopMessage(errorMessage) || isQuotaExhaustionMessage(errorMessage);\n}\n\n/** Bookkeeping key for the per-turn refused/failed model set. */\nexport function failoverModelKey(provider: string, id: string): string {\n\treturn `${provider}/${id}`;\n}\n"]}
1
+ {"version":3,"file":"provider-retry.js","sourceRoot":"","sources":["../../src/core/provider-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAC3C,OAAO,EACN,0BAA0B,EAC1B,wBAAwB,EACxB,+BAA+B,GAC/B,MAAM,0BAA0B,CAAC;AAElC;;;;GAIG;AACH;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAyB,EAAW;IAC7E,IAAI,OAAO,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IAChD,MAAM,OAAO,GAAY,OAAO,CAAC,OAAO,CAAC;IACzC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7B,OAAO,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzE,CAAC;IACD,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QAC/B,MAAM,CAAC,GAAI,KAAkC,EAAE,IAAI,CAAC;QACpD,IAAI,CAAC,KAAK,MAAM;YAAE,OAAO,KAAK,CAAC,CAAC,wCAAwC;QACxE,OAAO,CAAC,MAAM,CAAE,KAA2B,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAAA,CAC/D,CAAC,CAAC;AAAA,CACH;AAED,MAAM,UAAU,yBAAyB,CAAC,OAAyB,EAAE,aAAqB,EAAW;IACpG,4EAA0E;IAC1E,uEAAuE;IACvE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AAM,UAAU,sBAAsB,CAAC,YAAgC,EAAW;IACjF,OAAO,0BAA0B,CAAC,YAAY,CAAC,IAAI,wBAAwB,CAAC,YAAY,CAAC,CAAC;AAAA,CAC1F;AAED,iEAAiE;AACjE,MAAM,UAAU,gBAAgB,CAAC,QAAgB,EAAE,EAAU,EAAU;IACtE,OAAO,GAAG,QAAQ,IAAI,EAAE,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["import type { AssistantMessage } from \"omk-ai\";\nimport { isContextOverflow } from \"omk-ai\";\nimport {\n\tisContentSafetyStopMessage,\n\tisQuotaExhaustionMessage,\n\tisTransientProviderErrorMessage,\n} from \"./provider-resilience.ts\";\n\n/**\n * Pure retry/failover decisions for agent-turn provider errors.\n * Context overflow is never retryable here — compaction owns that path.\n * Quota exhaustion is retryable so the failover chain can save the turn.\n */\n/**\n * Empty streamed completion — stop=stop but zero usable output (no text,\n * thinking, or toolCall). Live signature of relay first-token timeouts\n * killing long silent thinking turns.\n * These are transport failures wearing a success shape.\n */\nexport function isEmptyStreamedCompletion(message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"stop\") return false;\n\tconst content: unknown = message.content;\n\tif (!Array.isArray(content)) {\n\t\treturn typeof content === \"string\" ? content.trim().length === 0 : true;\n\t}\n\treturn content.every((block) => {\n\t\tconst t = (block as { type?: string } | null)?.type;\n\t\tif (t !== \"text\") return false; // thinking/toolCall/image = real output\n\t\treturn !String((block as { text?: string }).text ?? \"\").trim();\n\t});\n}\n\nexport function isRetryableAssistantError(message: AssistantMessage, contextWindow: number): boolean {\n\t// An empty streamed completion is a dead stream, not an answer — retry it\n\t// regardless of its success-shaped stopReason (bounded by maxRetries).\n\tif (isEmptyStreamedCompletion(message)) return true;\n\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tif (isQuotaExhaustionMessage(message.errorMessage)) return true;\n\treturn isTransientProviderErrorMessage(message.errorMessage);\n}\n\n/**\n * Next attempt number within the retry budget, or undefined when retry is\n * disabled or the budget is exhausted. The caller's completed-attempt count\n * stays unchanged when undefined is returned.\n */\nexport function retryBudgetForAssistantError(message: AssistantMessage, configuredMaxRetries: number): number {\n\tif (configuredMaxRetries <= 0) return 0;\n\treturn isContentSafetyStopMessage(message.errorMessage) ? Math.min(1, configuredMaxRetries) : configuredMaxRetries;\n}\n\nexport function nextRetryAttempt(input: {\n\treadonly enabled: boolean;\n\treadonly completedAttempts: number;\n\treadonly maxRetries: number;\n}): number | undefined {\n\tif (!input.enabled) return undefined;\n\tconst attempt = input.completedAttempts + 1;\n\treturn attempt > input.maxRetries ? undefined : attempt;\n}\n\n/** Same-model retry backs off exponentially; a failed-over retry starts fast. */\nexport function computeRetryDelayMs(baseDelayMs: number, attempt: number, failoverOccurred: boolean): number {\n\treturn failoverOccurred ? Math.min(400, baseDelayMs) : baseDelayMs * 2 ** (attempt - 1);\n}\n\n/**\n * Errors that justify an immediate model switch instead of a same-model retry:\n * safety-stop false positives and billing/quota exhaustion. Both mean the\n * current model cannot finish this turn.\n */\nexport function isFailoverTriggerError(errorMessage: string | undefined): boolean {\n\treturn isContentSafetyStopMessage(errorMessage) || isQuotaExhaustionMessage(errorMessage);\n}\n\n/** Bookkeeping key for the per-turn refused/failed model set. */\nexport function failoverModelKey(provider: string, id: string): string {\n\treturn `${provider}/${id}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"provider-usage.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,yBAAyB,EAA2B,MAAM,QAAQ,CAAC;AACjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA+CvD,MAAM,MAAM,uBAAuB,GAAG;IACrC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC3B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AAU,GAAG,MAAM,CAAC,UAAU,CAOpF;AAED,qFAAmF;AACnF,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,uBAAuB,EAAE,GAAG,SAAS,CActG;AAED,wBAAsB,uBAAuB,CAC5C,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,aAA0B,GAChC,OAAO,CAAC,yBAAyB,CAAC,CAiBpC;AA8BD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,uBAAuB,EAAE,GAAG,SAAS,CAiBrG;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,uBAAuB,EAAE,GAAG,SAAS,CAapG;AAED,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,yBAAyB,EAAE,KAAK,SAAa,GAAG,IAAI,CAyBrH;AAED,wBAAgB,wBAAwB,CACvC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,yBAAyB,EACnC,KAAK,SAAa,GAChB,IAAI,CAgCN","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 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) return unavailable(\"no active token plan\");\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\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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AAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAChF,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC;AAEnG,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAOpF;AAED,qFAAmF;AACnF,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,uBAAuB,EAAE,GAAG,SAAS,CActG;AAED,wBAAsB,uBAAuB,CAC5C,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,aAA0B,GAChC,OAAO,CAAC,yBAAyB,CAAC,CAqBpC;AAyFD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,uBAAuB,EAAE,GAAG,SAAS,CAiBrG;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,uBAAuB,EAAE,GAAG,SAAS,CAapG;AAED,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,yBAAyB,EAAE,KAAK,SAAa,GAAG,IAAI,CAyBrH;AAED,wBAAgB,wBAAwB,CACvC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,yBAAyB,EACnC,KAAK,SAAa,GAChB,IAAI,CAgCN","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"]}
@@ -17,6 +17,7 @@ const CLAUDE_QUOTA_PROBE_COOLDOWN_MS = 60 * 60 * 1000;
17
17
  const CLAUDE_QUOTA_PROBE_TIMEOUT_MS = 10_000;
18
18
  const QWEN_CLI_TIMEOUT_MS = 15_000;
19
19
  const QWEN_CLI_ARGS = ["usage", "summary", "--format", "json"];
20
+ const qwenBillingArgs = (month) => ["billing", "breakdown", "--from", month, "--to", month, "--group-by", "model", "--format", "json"];
20
21
  const QWEN_CONNECT_HINT = "connect: npm i -g @qwencloud/qwencloud-cli && qwencloud auth login";
21
22
  const QWEN_CLI_ENV_KEYS = [
22
23
  "PATH",
@@ -275,8 +276,11 @@ export async function fetchQwenTokenPlanUsage(label, runner = runQwenCli) {
275
276
  }
276
277
  const payload = JSON.parse(result.stdout);
277
278
  const tokenPlan = record(record(payload)?.token_plan);
278
- if (tokenPlan?.subscribed === false)
279
- return unavailable("no active token plan");
279
+ if (tokenPlan?.subscribed === false) {
280
+ const periodTo = record(record(payload)?.period)?.to;
281
+ const month = typeof periodTo === "string" ? periodTo.slice(0, 7) : new Date().toISOString().slice(0, 7);
282
+ return unavailable(await billingFallbackMessage(runner, month, payload));
283
+ }
280
284
  const windows = parseQwenTokenPlanUsage(payload);
281
285
  return windows ? { label, windows } : unavailable("usage unavailable");
282
286
  }
@@ -284,6 +288,68 @@ export async function fetchQwenTokenPlanUsage(label, runner = runQwenCli) {
284
288
  return unavailable("usage unavailable");
285
289
  }
286
290
  }
291
+ /** No active token plan: fall back to settled billing — subscription charge + PAYG spend — when the CLI reports it. */
292
+ async function billingFallbackMessage(runner, month, summaryPayload) {
293
+ try {
294
+ const result = await runner(qwenBillingArgs(month), QWEN_CLI_TIMEOUT_MS);
295
+ if (result.kind !== "ran" || result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {
296
+ return paygFallbackMessage(summaryPayload);
297
+ }
298
+ const billing = parseBillingBreakdown(JSON.parse(result.stdout));
299
+ const cur = billing.currency === undefined || billing.currency === "USD" ? "$" : `${billing.currency} `;
300
+ const parts = [];
301
+ if (billing.subscription !== undefined && billing.subscription > 0) {
302
+ parts.push(`subscription ${cur}${billing.subscription.toFixed(2)}`);
303
+ }
304
+ const payg = billing.payg ?? paygTotalCost(summaryPayload);
305
+ if (payg !== undefined && payg > 0)
306
+ parts.push(`PAYG ${cur}${payg.toFixed(2)}`);
307
+ if (parts.length === 0)
308
+ return "no active token plan";
309
+ return `${parts.join(" · ")} (${month})`;
310
+ }
311
+ catch {
312
+ return paygFallbackMessage(summaryPayload);
313
+ }
314
+ }
315
+ /** Split settled billing rows into the fixed subscription charge vs per-model PAYG spend. */
316
+ function parseBillingBreakdown(payload) {
317
+ const data = record(payload);
318
+ const rows = Array.isArray(data?.rows) ? data.rows : [];
319
+ let subscription;
320
+ let payg = 0;
321
+ let paygSeen = false;
322
+ for (const raw of rows) {
323
+ const row = record(raw);
324
+ const amount = finiteNumber(row?.amount);
325
+ if (amount === undefined)
326
+ continue;
327
+ const key = typeof row?.groupKey === "string" ? row.groupKey : "";
328
+ if (key === "__tax__")
329
+ continue;
330
+ if (key === "DIMENSION_FILTER_NULL_VALUE")
331
+ subscription = (subscription ?? 0) + amount;
332
+ else {
333
+ payg += amount;
334
+ paygSeen = true;
335
+ }
336
+ }
337
+ const currency = typeof data?.currency === "string" ? data.currency : undefined;
338
+ return { subscription, payg: paygSeen ? payg : undefined, currency };
339
+ }
340
+ function paygTotalCost(payload) {
341
+ return finiteNumber(record(record(record(payload)?.pay_as_you_go)?.total)?.cost);
342
+ }
343
+ /** No active token plan: fall back to the account's pay-as-you-go spend when the CLI reports it. */
344
+ function paygFallbackMessage(payload) {
345
+ const cost = paygTotalCost(payload);
346
+ if (cost === undefined)
347
+ return "no active token plan";
348
+ const currency = "$";
349
+ const period = record(record(payload)?.period);
350
+ const from = typeof period?.from === "string" ? period.from.slice(0, 7) : undefined;
351
+ return `no token plan · PAYG ${currency}${cost.toFixed(2)}${from ? ` (${from})` : ""}`;
352
+ }
287
353
  function runQwenCli(args, timeoutMs) {
288
354
  return new Promise((resolve) => {
289
355
  const binary = process.env.QWENCLOUD_CLI ?? "qwencloud";