open-multi-agent-kit 0.98.3 → 0.98.5
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.
- package/CHANGELOG.md +44 -0
- package/README.md +12 -2
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +14 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/help.d.ts.map +1 -1
- package/dist/cli/help.js +3 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli/mcp-attach.d.ts +3 -3
- package/dist/cli/mcp-attach.d.ts.map +1 -1
- package/dist/cli/mcp-attach.js +5 -4
- package/dist/cli/mcp-attach.js.map +1 -1
- package/dist/cli/model-contract.d.ts +5 -0
- package/dist/cli/model-contract.d.ts.map +1 -0
- package/dist/cli/model-contract.js +45 -0
- package/dist/cli/model-contract.js.map +1 -0
- package/dist/commands/adaptorch-doctor-cli.d.ts.map +1 -1
- package/dist/commands/adaptorch-doctor-cli.js +32 -10
- package/dist/commands/adaptorch-doctor-cli.js.map +1 -1
- package/dist/commands/init-cli.d.ts +12 -0
- package/dist/commands/init-cli.d.ts.map +1 -0
- package/dist/commands/init-cli.js +76 -0
- package/dist/commands/init-cli.js.map +1 -0
- package/dist/commands/provider-sync-cli.d.ts +27 -0
- package/dist/commands/provider-sync-cli.d.ts.map +1 -0
- package/dist/commands/provider-sync-cli.js +177 -0
- package/dist/commands/provider-sync-cli.js.map +1 -0
- package/dist/commands/run-command.d.ts +9 -0
- package/dist/commands/run-command.d.ts.map +1 -0
- package/dist/commands/run-command.js +34 -0
- package/dist/commands/run-command.js.map +1 -0
- package/dist/commands/verified-run-cli.d.ts +6 -0
- package/dist/commands/verified-run-cli.d.ts.map +1 -0
- package/dist/commands/verified-run-cli.js +190 -0
- package/dist/commands/verified-run-cli.js.map +1 -0
- package/dist/core/active-skill-state.d.ts +7 -0
- package/dist/core/active-skill-state.d.ts.map +1 -0
- package/dist/core/active-skill-state.js +25 -0
- package/dist/core/active-skill-state.js.map +1 -0
- package/dist/core/agent-session-services.d.ts +10 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +43 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +7 -9
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +91 -126
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/codex-chatgpt-web-bridge.d.ts +99 -0
- package/dist/core/codex-chatgpt-web-bridge.d.ts.map +1 -0
- package/dist/core/codex-chatgpt-web-bridge.js +192 -0
- package/dist/core/codex-chatgpt-web-bridge.js.map +1 -0
- package/dist/core/codex-chatgpt-web-sync.d.ts +50 -0
- package/dist/core/codex-chatgpt-web-sync.d.ts.map +1 -0
- package/dist/core/codex-chatgpt-web-sync.js +119 -0
- package/dist/core/codex-chatgpt-web-sync.js.map +1 -0
- package/dist/core/compaction/compaction-headroom.d.ts +30 -0
- package/dist/core/compaction/compaction-headroom.d.ts.map +1 -0
- package/dist/core/compaction/compaction-headroom.js +48 -0
- package/dist/core/compaction/compaction-headroom.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +2 -29
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +19 -47
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/overflow-retry-guard.d.ts +20 -0
- package/dist/core/compaction/overflow-retry-guard.d.ts.map +1 -0
- package/dist/core/compaction/overflow-retry-guard.js +38 -0
- package/dist/core/compaction/overflow-retry-guard.js.map +1 -0
- package/dist/core/context-budget-headroom-types.d.ts.map +1 -1
- package/dist/core/context-budget-headroom-types.js +1 -1
- package/dist/core/context-budget-headroom-types.js.map +1 -1
- package/dist/core/context-budget-token-counter-types.d.ts +27 -0
- package/dist/core/context-budget-token-counter-types.d.ts.map +1 -0
- package/dist/core/context-budget-token-counter-types.js +2 -0
- package/dist/core/context-budget-token-counter-types.js.map +1 -0
- package/dist/core/context-budget-token-counter.d.ts +2 -26
- package/dist/core/context-budget-token-counter.d.ts.map +1 -1
- package/dist/core/context-budget-token-counter.js +2 -0
- package/dist/core/context-budget-token-counter.js.map +1 -1
- package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
- package/dist/core/context-budget-v2-scoring.js +14 -10
- package/dist/core/context-budget-v2-scoring.js.map +1 -1
- package/dist/core/domain-router.d.ts.map +1 -1
- package/dist/core/domain-router.js +1 -1
- package/dist/core/domain-router.js.map +1 -1
- package/dist/core/grok-harness-dispatch.d.ts +4 -0
- package/dist/core/grok-harness-dispatch.d.ts.map +1 -1
- package/dist/core/grok-harness-dispatch.js +20 -3
- package/dist/core/grok-harness-dispatch.js.map +1 -1
- package/dist/core/grok-harness.d.ts +15 -9
- package/dist/core/grok-harness.d.ts.map +1 -1
- package/dist/core/grok-harness.js +34 -8
- package/dist/core/grok-harness.js.map +1 -1
- package/dist/core/mcp/tools.d.ts +2 -2
- package/dist/core/mcp/tools.d.ts.map +1 -1
- package/dist/core/mcp/tools.js +29 -3
- package/dist/core/mcp/tools.js.map +1 -1
- package/dist/core/model-registry-schema.d.ts +1081 -0
- package/dist/core/model-registry-schema.d.ts.map +1 -0
- package/dist/core/model-registry-schema.js +148 -0
- package/dist/core/model-registry-schema.js.map +1 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +1 -146
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +2 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +2 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/prompt-preset.d.ts +1 -1
- package/dist/core/prompt-preset.d.ts.map +1 -1
- package/dist/core/prompt-preset.js +16 -1
- package/dist/core/prompt-preset.js.map +1 -1
- package/dist/core/prompt-settlement.d.ts +4 -3
- package/dist/core/prompt-settlement.d.ts.map +1 -1
- package/dist/core/prompt-settlement.js.map +1 -1
- package/dist/core/provider-display-names.d.ts.map +1 -1
- package/dist/core/provider-display-names.js +1 -0
- package/dist/core/provider-display-names.js.map +1 -1
- package/dist/core/provider-resilience.d.ts +8 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +20 -3
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/provider-usage-types.d.ts +42 -0
- package/dist/core/provider-usage-types.d.ts.map +1 -0
- package/dist/core/provider-usage-types.js +2 -0
- package/dist/core/provider-usage-types.js.map +1 -0
- package/dist/core/provider-usage.d.ts +2 -31
- package/dist/core/provider-usage.d.ts.map +1 -1
- package/dist/core/provider-usage.js +4 -0
- package/dist/core/provider-usage.js.map +1 -1
- package/dist/core/redaction.d.ts.map +1 -1
- package/dist/core/redaction.js +18 -2
- package/dist/core/redaction.js.map +1 -1
- package/dist/core/run-budget-policy.d.ts +18 -0
- package/dist/core/run-budget-policy.d.ts.map +1 -0
- package/dist/core/run-budget-policy.js +52 -0
- package/dist/core/run-budget-policy.js.map +1 -0
- package/dist/core/run-budget.d.ts +33 -0
- package/dist/core/run-budget.d.ts.map +1 -0
- package/dist/core/run-budget.js +89 -0
- package/dist/core/run-budget.js.map +1 -0
- package/dist/core/run-execution-api.d.ts +15 -0
- package/dist/core/run-execution-api.d.ts.map +1 -0
- package/dist/core/run-execution-api.js +7 -0
- package/dist/core/run-execution-api.js.map +1 -0
- package/dist/core/run-journal.d.ts.map +1 -1
- package/dist/core/run-journal.js +30 -208
- package/dist/core/run-journal.js.map +1 -1
- package/dist/core/sandbox/policy-merge.d.ts +6 -0
- package/dist/core/sandbox/policy-merge.d.ts.map +1 -0
- package/dist/core/sandbox/policy-merge.js +74 -0
- package/dist/core/sandbox/policy-merge.js.map +1 -0
- package/dist/core/sandbox/policy-paths.d.ts +4 -0
- package/dist/core/sandbox/policy-paths.d.ts.map +1 -0
- package/dist/core/sandbox/policy-paths.js +21 -0
- package/dist/core/sandbox/policy-paths.js.map +1 -0
- package/dist/core/sandbox/policy-types.d.ts +75 -0
- package/dist/core/sandbox/policy-types.d.ts.map +1 -0
- package/dist/core/sandbox/policy-types.js +2 -0
- package/dist/core/sandbox/policy-types.js.map +1 -0
- package/dist/core/sandbox/policy.d.ts +3 -77
- package/dist/core/sandbox/policy.d.ts.map +1 -1
- package/dist/core/sandbox/policy.js +3 -98
- package/dist/core/sandbox/policy.js.map +1 -1
- package/dist/core/sdk-provider-stream.d.ts +14 -0
- package/dist/core/sdk-provider-stream.d.ts.map +1 -0
- package/dist/core/sdk-provider-stream.js +38 -0
- package/dist/core/sdk-provider-stream.js.map +1 -0
- package/dist/core/sdk.d.ts +5 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +17 -33
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-bash-service.d.ts +2 -2
- package/dist/core/session-bash-service.d.ts.map +1 -1
- package/dist/core/session-bash-service.js +21 -9
- package/dist/core/session-bash-service.js.map +1 -1
- package/dist/core/session-failure-cause.d.ts.map +1 -1
- package/dist/core/session-failure-cause.js +15 -3
- package/dist/core/session-failure-cause.js.map +1 -1
- package/dist/core/session-prompt-lifecycle.d.ts +25 -0
- package/dist/core/session-prompt-lifecycle.d.ts.map +1 -0
- package/dist/core/session-prompt-lifecycle.js +87 -0
- package/dist/core/session-prompt-lifecycle.js.map +1 -0
- package/dist/core/session-run-budget.d.ts +28 -0
- package/dist/core/session-run-budget.d.ts.map +1 -0
- package/dist/core/session-run-budget.js +127 -0
- package/dist/core/session-run-budget.js.map +1 -0
- package/dist/core/session-run-termination.d.ts +18 -0
- package/dist/core/session-run-termination.d.ts.map +1 -0
- package/dist/core/session-run-termination.js +72 -0
- package/dist/core/session-run-termination.js.map +1 -0
- package/dist/core/session-termination-types.d.ts +97 -0
- package/dist/core/session-termination-types.d.ts.map +1 -0
- package/dist/core/session-termination-types.js +26 -0
- package/dist/core/session-termination-types.js.map +1 -0
- package/dist/core/session-termination.d.ts +3 -97
- package/dist/core/session-termination.d.ts.map +1 -1
- package/dist/core/session-termination.js +25 -29
- package/dist/core/session-termination.js.map +1 -1
- package/dist/core/skill-selector.d.ts +40 -0
- package/dist/core/skill-selector.d.ts.map +1 -0
- package/dist/core/skill-selector.js +102 -0
- package/dist/core/skill-selector.js.map +1 -0
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/subagent-lane-launcher.d.ts +3 -2
- package/dist/core/subagent-lane-launcher.d.ts.map +1 -1
- package/dist/core/subagent-lane-launcher.js +24 -13
- package/dist/core/subagent-lane-launcher.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +2 -4
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/turn-metrics-record.d.ts +55 -0
- package/dist/core/turn-metrics-record.d.ts.map +1 -0
- package/dist/core/turn-metrics-record.js +149 -0
- package/dist/core/turn-metrics-record.js.map +1 -0
- package/dist/core/turn-metrics.d.ts +4 -56
- package/dist/core/turn-metrics.d.ts.map +1 -1
- package/dist/core/turn-metrics.js +12 -60
- package/dist/core/turn-metrics.js.map +1 -1
- package/dist/core/verified-run/broker.d.ts +26 -0
- package/dist/core/verified-run/broker.d.ts.map +1 -0
- package/dist/core/verified-run/broker.js +210 -0
- package/dist/core/verified-run/broker.js.map +1 -0
- package/dist/core/verified-run/candidate.d.ts +24 -0
- package/dist/core/verified-run/candidate.d.ts.map +1 -0
- package/dist/core/verified-run/candidate.js +167 -0
- package/dist/core/verified-run/candidate.js.map +1 -0
- package/dist/core/verified-run/check-receipt.d.ts +18 -0
- package/dist/core/verified-run/check-receipt.d.ts.map +1 -0
- package/dist/core/verified-run/check-receipt.js +92 -0
- package/dist/core/verified-run/check-receipt.js.map +1 -0
- package/dist/core/verified-run/coordinator.d.ts +39 -0
- package/dist/core/verified-run/coordinator.d.ts.map +1 -0
- package/dist/core/verified-run/coordinator.js +190 -0
- package/dist/core/verified-run/coordinator.js.map +1 -0
- package/dist/core/verified-run/dag-candidates.d.ts +8 -0
- package/dist/core/verified-run/dag-candidates.d.ts.map +1 -0
- package/dist/core/verified-run/dag-candidates.js +65 -0
- package/dist/core/verified-run/dag-candidates.js.map +1 -0
- package/dist/core/verified-run/dag-phase.d.ts +7 -0
- package/dist/core/verified-run/dag-phase.d.ts.map +1 -0
- package/dist/core/verified-run/dag-phase.js +92 -0
- package/dist/core/verified-run/dag-phase.js.map +1 -0
- package/dist/core/verified-run/dag-projection.d.ts +7 -0
- package/dist/core/verified-run/dag-projection.d.ts.map +1 -0
- package/dist/core/verified-run/dag-projection.js +90 -0
- package/dist/core/verified-run/dag-projection.js.map +1 -0
- package/dist/core/verified-run/dag-recovery.d.ts +13 -0
- package/dist/core/verified-run/dag-recovery.d.ts.map +1 -0
- package/dist/core/verified-run/dag-recovery.js +98 -0
- package/dist/core/verified-run/dag-recovery.js.map +1 -0
- package/dist/core/verified-run/dag-retry-projection.d.ts +9 -0
- package/dist/core/verified-run/dag-retry-projection.d.ts.map +1 -0
- package/dist/core/verified-run/dag-retry-projection.js +43 -0
- package/dist/core/verified-run/dag-retry-projection.js.map +1 -0
- package/dist/core/verified-run/dag-types.d.ts +47 -0
- package/dist/core/verified-run/dag-types.d.ts.map +1 -0
- package/dist/core/verified-run/dag-types.js +2 -0
- package/dist/core/verified-run/dag-types.js.map +1 -0
- package/dist/core/verified-run/event-parser.d.ts +3 -0
- package/dist/core/verified-run/event-parser.d.ts.map +1 -0
- package/dist/core/verified-run/event-parser.js +153 -0
- package/dist/core/verified-run/event-parser.js.map +1 -0
- package/dist/core/verified-run/events.d.ts +4 -0
- package/dist/core/verified-run/events.d.ts.map +1 -0
- package/dist/core/verified-run/events.js +3 -0
- package/dist/core/verified-run/events.js.map +1 -0
- package/dist/core/verified-run/evidence-binding.d.ts +18 -0
- package/dist/core/verified-run/evidence-binding.d.ts.map +1 -0
- package/dist/core/verified-run/evidence-binding.js +81 -0
- package/dist/core/verified-run/evidence-binding.js.map +1 -0
- package/dist/core/verified-run/evidence.d.ts +27 -0
- package/dist/core/verified-run/evidence.d.ts.map +1 -0
- package/dist/core/verified-run/evidence.js +100 -0
- package/dist/core/verified-run/evidence.js.map +1 -0
- package/dist/core/verified-run/journal.d.ts +32 -0
- package/dist/core/verified-run/journal.d.ts.map +1 -0
- package/dist/core/verified-run/journal.js +103 -0
- package/dist/core/verified-run/journal.js.map +1 -0
- package/dist/core/verified-run/namespace-identity.d.ts +11 -0
- package/dist/core/verified-run/namespace-identity.d.ts.map +1 -0
- package/dist/core/verified-run/namespace-identity.js +77 -0
- package/dist/core/verified-run/namespace-identity.js.map +1 -0
- package/dist/core/verified-run/owned-execution.d.ts +21 -0
- package/dist/core/verified-run/owned-execution.d.ts.map +1 -0
- package/dist/core/verified-run/owned-execution.js +43 -0
- package/dist/core/verified-run/owned-execution.js.map +1 -0
- package/dist/core/verified-run/phase-context.d.ts +9 -0
- package/dist/core/verified-run/phase-context.d.ts.map +1 -0
- package/dist/core/verified-run/phase-context.js +2 -0
- package/dist/core/verified-run/phase-context.js.map +1 -0
- package/dist/core/verified-run/process-gate.d.ts +5 -0
- package/dist/core/verified-run/process-gate.d.ts.map +1 -0
- package/dist/core/verified-run/process-gate.js +31 -0
- package/dist/core/verified-run/process-gate.js.map +1 -0
- package/dist/core/verified-run/projection.d.ts +4 -0
- package/dist/core/verified-run/projection.d.ts.map +1 -0
- package/dist/core/verified-run/projection.js +219 -0
- package/dist/core/verified-run/projection.js.map +1 -0
- package/dist/core/verified-run/recovery-clock.d.ts +19 -0
- package/dist/core/verified-run/recovery-clock.d.ts.map +1 -0
- package/dist/core/verified-run/recovery-clock.js +69 -0
- package/dist/core/verified-run/recovery-clock.js.map +1 -0
- package/dist/core/verified-run/recovery-command.d.ts +11 -0
- package/dist/core/verified-run/recovery-command.d.ts.map +1 -0
- package/dist/core/verified-run/recovery-command.js +73 -0
- package/dist/core/verified-run/recovery-command.js.map +1 -0
- package/dist/core/verified-run/recovery-projection.d.ts +12 -0
- package/dist/core/verified-run/recovery-projection.d.ts.map +1 -0
- package/dist/core/verified-run/recovery-projection.js +88 -0
- package/dist/core/verified-run/recovery-projection.js.map +1 -0
- package/dist/core/verified-run/recovery.d.ts +12 -0
- package/dist/core/verified-run/recovery.d.ts.map +1 -0
- package/dist/core/verified-run/recovery.js +115 -0
- package/dist/core/verified-run/recovery.js.map +1 -0
- package/dist/core/verified-run/run-types.d.ts +103 -0
- package/dist/core/verified-run/run-types.d.ts.map +1 -0
- package/dist/core/verified-run/run-types.js +2 -0
- package/dist/core/verified-run/run-types.js.map +1 -0
- package/dist/core/verified-run/scripted-writer.d.ts +15 -0
- package/dist/core/verified-run/scripted-writer.d.ts.map +1 -0
- package/dist/core/verified-run/scripted-writer.js +94 -0
- package/dist/core/verified-run/scripted-writer.js.map +1 -0
- package/dist/core/verified-run/session-port.d.ts +27 -0
- package/dist/core/verified-run/session-port.d.ts.map +1 -0
- package/dist/core/verified-run/session-port.js +2 -0
- package/dist/core/verified-run/session-port.js.map +1 -0
- package/dist/core/verified-run/storage.d.ts +15 -0
- package/dist/core/verified-run/storage.d.ts.map +1 -0
- package/dist/core/verified-run/storage.js +96 -0
- package/dist/core/verified-run/storage.js.map +1 -0
- package/dist/core/verified-run/verification-phase.d.ts +5 -0
- package/dist/core/verified-run/verification-phase.d.ts.map +1 -0
- package/dist/core/verified-run/verification-phase.js +56 -0
- package/dist/core/verified-run/verification-phase.js.map +1 -0
- package/dist/core/verified-run/work-recovery.d.ts +8 -0
- package/dist/core/verified-run/work-recovery.d.ts.map +1 -0
- package/dist/core/verified-run/work-recovery.js +44 -0
- package/dist/core/verified-run/work-recovery.js.map +1 -0
- package/dist/core/verified-run/writer-completion.d.ts +4 -0
- package/dist/core/verified-run/writer-completion.d.ts.map +1 -0
- package/dist/core/verified-run/writer-completion.js +27 -0
- package/dist/core/verified-run/writer-completion.js.map +1 -0
- package/dist/core/verified-run/writer-phase.d.ts +8 -0
- package/dist/core/verified-run/writer-phase.d.ts.map +1 -0
- package/dist/core/verified-run/writer-phase.js +76 -0
- package/dist/core/verified-run/writer-phase.js.map +1 -0
- package/dist/core/verified-run/writer-projection.d.ts +11 -0
- package/dist/core/verified-run/writer-projection.d.ts.map +1 -0
- package/dist/core/verified-run/writer-projection.js +70 -0
- package/dist/core/verified-run/writer-projection.js.map +1 -0
- package/dist/core/verified-run/writer-recovery.d.ts +16 -0
- package/dist/core/verified-run/writer-recovery.d.ts.map +1 -0
- package/dist/core/verified-run/writer-recovery.js +107 -0
- package/dist/core/verified-run/writer-recovery.js.map +1 -0
- package/dist/core/workload-permit-pool.d.ts +1 -3
- package/dist/core/workload-permit-pool.d.ts.map +1 -1
- package/dist/core/workload-permit-pool.js +11 -11
- package/dist/core/workload-permit-pool.js.map +1 -1
- package/dist/guardrails/evidence-system.d.ts +1 -1
- package/dist/guardrails/evidence-system.d.ts.map +1 -1
- package/dist/guardrails/evidence-system.js +18 -29
- package/dist/guardrails/evidence-system.js.map +1 -1
- package/dist/guardrails/merge-gate-result.d.ts +4 -0
- package/dist/guardrails/merge-gate-result.d.ts.map +1 -0
- package/dist/guardrails/merge-gate-result.js +32 -0
- package/dist/guardrails/merge-gate-result.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +17 -23
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/session-failure.d.ts +13 -0
- package/dist/modes/interactive/components/session-failure.d.ts.map +1 -0
- package/dist/modes/interactive/components/session-failure.js +81 -0
- package/dist/modes/interactive/components/session-failure.js.map +1 -0
- package/dist/modes/interactive/interactive-login-options.d.ts +27 -0
- package/dist/modes/interactive/interactive-login-options.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-login-options.js +54 -0
- package/dist/modes/interactive/interactive-login-options.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +8 -4
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +183 -171
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/interactive-resume-command.d.ts +3 -0
- package/dist/modes/interactive/interactive-resume-command.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-resume-command.js +24 -0
- package/dist/modes/interactive/interactive-resume-command.js.map +1 -0
- package/dist/modes/interactive/interactive-tool-result.d.ts +32 -0
- package/dist/modes/interactive/interactive-tool-result.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-tool-result.js +59 -0
- package/dist/modes/interactive/interactive-tool-result.js.map +1 -0
- package/dist/modes/interactive/tui-diagnostics.d.ts +36 -0
- package/dist/modes/interactive/tui-diagnostics.d.ts.map +1 -0
- package/dist/modes/interactive/tui-diagnostics.js +105 -0
- package/dist/modes/interactive/tui-diagnostics.js.map +1 -0
- package/dist/modes/interactive/tui-runtime-info.d.ts +20 -0
- package/dist/modes/interactive/tui-runtime-info.d.ts.map +1 -0
- package/dist/modes/interactive/tui-runtime-info.js +76 -0
- package/dist/modes/interactive/tui-runtime-info.js.map +1 -0
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +22 -0
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +10 -60
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/terminal-links.d.ts +13 -0
- package/dist/utils/terminal-links.d.ts.map +1 -0
- package/dist/utils/terminal-links.js +68 -0
- package/dist/utils/terminal-links.js.map +1 -0
- package/dist/utils/windows-clipboard-image.d.ts +16 -0
- package/dist/utils/windows-clipboard-image.d.ts.map +1 -0
- package/dist/utils/windows-clipboard-image.js +87 -0
- package/dist/utils/windows-clipboard-image.js.map +1 -0
- package/docs/adaptorch-onboarding.md +80 -0
- package/docs/containerization.md +12 -0
- package/docs/context-files.md +97 -0
- package/docs/correctness-wall.md +8 -0
- package/docs/custom-provider.md +35 -0
- package/docs/development.md +28 -3
- package/docs/environment-variables.md +2 -0
- package/docs/grok-harness.md +4 -0
- package/docs/harness-boundaries.md +154 -0
- package/docs/harness-improvements.md +90 -0
- package/docs/json.md +19 -0
- package/docs/keybindings.md +2 -2
- package/docs/mcp.md +22 -2
- package/docs/metrics.md +66 -16
- package/docs/model-catalog-refresh.md +190 -0
- package/docs/model-contract.md +168 -0
- package/docs/models.md +21 -4
- package/docs/provider-resilience.md +5 -3
- package/docs/providers.md +68 -1
- package/docs/quickstart.md +4 -0
- package/docs/release-audit-0.98.4.md +112 -0
- package/docs/release-audit-0.98.5.md +84 -0
- package/docs/review-bundle-followup.md +195 -0
- package/docs/run-protocol.md +33 -1
- package/docs/runtime-algorithms.md +45 -0
- package/docs/sdk.md +204 -2
- package/docs/sessions.md +1 -1
- package/docs/settings.md +17 -1
- package/docs/skills.md +2 -0
- package/docs/tb21-audit.md +131 -0
- package/docs/terminal-setup.md +20 -0
- package/docs/usage.md +77 -1
- package/docs/verified-run-testing.md +417 -0
- package/docs/verified-run.md +388 -0
- package/docs/windows.md +48 -0
- package/examples/README.md +4 -0
- package/examples/context/AGENTS.md +64 -0
- package/examples/context/CLAUDE.md +17 -0
- package/examples/context/INTERNET.md +42 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +18 -18
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-resilience.js","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAA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AAI,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC,EAAE,KAAK,OAAO,CAAC,EAAE;YAAE,SAAS;QAChF,IAAI,mBAAmB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC;YAAE,SAAS;QACpD,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;YAAE,SAAS;QAC5B,OAAO,CAAC,CAAC;IACV,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,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/**\n * Anthropic rejecting the spoofed Claude Code client version because the target\n * model is gated on a newer one (`claude_code_version_too_old`, HTTP 400).\n * Permanent for this build: every retry and every failover re-sends the same\n * user-agent, so the fix is bumping `CLAUDE_CODE_VERSION` in omk-ai (or\n * selecting an ungated model).\n */\nexport function isClaudeCodeVersionTooOldMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /claude_code_version_too_old|does not support this model;\\s*version\\s+[\\d.]+\\s+or newer is required/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\t// Checked first: the payload carries `invalid_request_error`, which the\n\t// pattern below treats as transient, but a stale client version never heals\n\t// by retrying.\n\tif (isClaudeCodeVersionTooOldMessage(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,EAAE,IAAI,EAAE;IACrC,EAAE,QAAQ,EAAE,kBAAkB,EAAE,EAAE,EAAE,aAAa,EAAE;IACnD,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAE,UAAU,EAAE;IACnC,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,EAAE,iBAAiB,EAAE;IAC/C,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,EAAE,mBAAmB,EAAE;IACjD,EAAE,QAAQ,EAAE,kBAAkB,EAAE,EAAE,EAAE,iBAAiB,EAAE;IACvD,EAAE,QAAQ,EAAE,aAAa,EAAE,EAAE,EAAE,iBAAiB,EAAE;CACzC,CAAC;AAWX,M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AO,CACN,+BAA+B,QAAQ,IAAI,OAAO,iDAAiD;QACnG,2EAA2E;QAC3E,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\" },\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/**\n * Anthropic rejecting the spoofed Claude Code client version because the target\n * model is gated on a newer one (`claude_code_version_too_old`, HTTP 400).\n * Permanent for this build: every retry and every failover re-sends the same\n * user-agent, so the fix is bumping `CLAUDE_CODE_VERSION` in omk-ai (or\n * selecting an ungated model).\n */\nexport function isClaudeCodeVersionTooOldMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /claude_code_version_too_old|does not support this model;\\s*version\\s+[\\d.]+\\s+or newer is required/i.test(\n\t\ttext,\n\t);\n}\n\n/**\n * Codex HTTP 400 when a ChatGPT-account OAuth session asks for a model the\n * account catalog does not serve (`gpt-6-astra` during the 2026-09-04 rollout).\n * Permanent for this login: same-model retry, transcript sanitize, and /new\n * session all re-send the same slug and get the same 400. Switch model or use\n * an API-key route that has the model.\n */\nexport function isCodexChatgptAccountUnsupportedModelMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /model is not supported when using Codex with a ChatGPT account/i.test(text);\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\t// Checked first: the payload carries `invalid_request_error`, which the\n\t// pattern below treats as transient, but a stale client version never heals\n\t// by retrying.\n\tif (isClaudeCodeVersionTooOldMessage(text)) return false;\n\tif (isCodexChatgptAccountUnsupportedModelMessage(text)) return false;\n\t// `at capacity|high demand`: xAI serves overload as HTTP 429 whose body carries\n\t// no status or limit token, so the message-level classifier misses it and the\n\t// turn never auto-retries (observed 2026-09-03, xai/grok-4.6).\n\treturn /overloaded|at capacity|high demand|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, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\n}\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export type SubscriptionUsageWindow = {
|
|
2
|
+
readonly label: string;
|
|
3
|
+
readonly usedPercent: number;
|
|
4
|
+
readonly resetsAt?: number;
|
|
5
|
+
};
|
|
6
|
+
export type SubscriptionUsageSnapshot = {
|
|
7
|
+
readonly label: string;
|
|
8
|
+
readonly windows: readonly SubscriptionUsageWindow[];
|
|
9
|
+
readonly message?: string;
|
|
10
|
+
};
|
|
11
|
+
export type CodexUsageWindow = {
|
|
12
|
+
readonly usedPercent: number;
|
|
13
|
+
readonly resetsAt?: number;
|
|
14
|
+
};
|
|
15
|
+
export type CodexUsageSnapshot = {
|
|
16
|
+
readonly fiveHour?: CodexUsageWindow;
|
|
17
|
+
readonly sevenDay?: CodexUsageWindow;
|
|
18
|
+
};
|
|
19
|
+
export type ParsedCodexWindow = CodexUsageWindow & {
|
|
20
|
+
readonly windowSeconds?: number;
|
|
21
|
+
};
|
|
22
|
+
export type ObservedCodexWindow = {
|
|
23
|
+
readonly window: ParsedCodexWindow;
|
|
24
|
+
readonly observedAt: number;
|
|
25
|
+
};
|
|
26
|
+
export type PassiveUsageEntry = {
|
|
27
|
+
readonly primary?: ObservedCodexWindow;
|
|
28
|
+
readonly secondary?: ObservedCodexWindow;
|
|
29
|
+
};
|
|
30
|
+
export type UsageKind = "codex" | "claude" | "kimi" | "zai" | "grok" | "qwen-token-plan" | "unavailable";
|
|
31
|
+
export type CredentialCandidate = {
|
|
32
|
+
readonly provider: string;
|
|
33
|
+
readonly oauthOnly: boolean;
|
|
34
|
+
};
|
|
35
|
+
export type SubscriptionUsageSource = {
|
|
36
|
+
readonly label: string;
|
|
37
|
+
readonly kind: UsageKind;
|
|
38
|
+
readonly credentials: readonly CredentialCandidate[];
|
|
39
|
+
readonly ttlMs: number;
|
|
40
|
+
readonly unavailableMessage?: string;
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=provider-usage-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-usage-types.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage-types.ts"],"names":[],"mappings":"AAAA,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,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,SAAS,uBAAuB,EAAE,CAAC;IACrD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAC5F,MAAM,MAAM,kBAAkB,GAAG;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IACrC,QAAQ,CAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;CACrC,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,gBAAgB,GAAG;IAAE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AACvF,MAAM,MAAM,mBAAmB,GAAG;IAAE,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC;AACtG,MAAM,MAAM,iBAAiB,GAAG;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,mBAAmB,CAAA;CAAE,CAAC;AACrH,MAAM,MAAM,SAAS,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,iBAAiB,GAAG,aAAa,CAAC;AACzG,MAAM,MAAM,mBAAmB,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAAC;AAE7F,MAAM,MAAM,uBAAuB,GAAG;IACrC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,WAAW,EAAE,SAAS,mBAAmB,EAAE,CAAC;IACrD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CACrC,CAAC","sourcesContent":["export 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\nexport type CodexUsageWindow = { readonly usedPercent: number; readonly resetsAt?: number };\nexport type CodexUsageSnapshot = {\n\treadonly fiveHour?: CodexUsageWindow;\n\treadonly sevenDay?: CodexUsageWindow;\n};\n\nexport type ParsedCodexWindow = CodexUsageWindow & { readonly windowSeconds?: number };\nexport type ObservedCodexWindow = { readonly window: ParsedCodexWindow; readonly observedAt: number };\nexport type PassiveUsageEntry = { readonly primary?: ObservedCodexWindow; readonly secondary?: ObservedCodexWindow };\nexport type UsageKind = \"codex\" | \"claude\" | \"kimi\" | \"zai\" | \"grok\" | \"qwen-token-plan\" | \"unavailable\";\nexport type 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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-usage-types.js","sourceRoot":"","sources":["../../src/core/provider-usage-types.ts"],"names":[],"mappings":"","sourcesContent":["export 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\nexport type CodexUsageWindow = { readonly usedPercent: number; readonly resetsAt?: number };\nexport type CodexUsageSnapshot = {\n\treadonly fiveHour?: CodexUsageWindow;\n\treadonly sevenDay?: CodexUsageWindow;\n};\n\nexport type ParsedCodexWindow = CodexUsageWindow & { readonly windowSeconds?: number };\nexport type ObservedCodexWindow = { readonly window: ParsedCodexWindow; readonly observedAt: number };\nexport type PassiveUsageEntry = { readonly primary?: ObservedCodexWindow; readonly secondary?: ObservedCodexWindow };\nexport type UsageKind = \"codex\" | \"claude\" | \"kimi\" | \"zai\" | \"grok\" | \"qwen-token-plan\" | \"unavailable\";\nexport type 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"]}
|
|
@@ -1,35 +1,7 @@
|
|
|
1
1
|
import { type ProviderRateLimitSnapshot } from "omk-ai";
|
|
2
2
|
import type { AgentSession } from "./agent-session.ts";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
readonly usedPercent: number;
|
|
6
|
-
readonly resetsAt?: number;
|
|
7
|
-
};
|
|
8
|
-
export type SubscriptionUsageSnapshot = {
|
|
9
|
-
readonly label: string;
|
|
10
|
-
readonly windows: readonly SubscriptionUsageWindow[];
|
|
11
|
-
readonly message?: string;
|
|
12
|
-
};
|
|
13
|
-
type CodexUsageWindow = {
|
|
14
|
-
readonly usedPercent: number;
|
|
15
|
-
readonly resetsAt?: number;
|
|
16
|
-
};
|
|
17
|
-
export type CodexUsageSnapshot = {
|
|
18
|
-
readonly fiveHour?: CodexUsageWindow;
|
|
19
|
-
readonly sevenDay?: CodexUsageWindow;
|
|
20
|
-
};
|
|
21
|
-
type UsageKind = "codex" | "claude" | "kimi" | "zai" | "grok" | "qwen-token-plan" | "unavailable";
|
|
22
|
-
type CredentialCandidate = {
|
|
23
|
-
readonly provider: string;
|
|
24
|
-
readonly oauthOnly: boolean;
|
|
25
|
-
};
|
|
26
|
-
export type SubscriptionUsageSource = {
|
|
27
|
-
readonly label: string;
|
|
28
|
-
readonly kind: UsageKind;
|
|
29
|
-
readonly credentials: readonly CredentialCandidate[];
|
|
30
|
-
readonly ttlMs: number;
|
|
31
|
-
readonly unavailableMessage?: string;
|
|
32
|
-
};
|
|
3
|
+
import type { CodexUsageSnapshot, SubscriptionUsageSnapshot, SubscriptionUsageSource, SubscriptionUsageWindow } from "./provider-usage-types.ts";
|
|
4
|
+
export type { CodexUsageSnapshot, SubscriptionUsageSnapshot, SubscriptionUsageSource, SubscriptionUsageWindow, } from "./provider-usage-types.ts";
|
|
33
5
|
type UsageSession = Pick<AgentSession, "state" | "modelRegistry">;
|
|
34
6
|
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
35
7
|
export declare function getSubscriptionUsageSource(provider: string | undefined): SubscriptionUsageSource | undefined;
|
|
@@ -58,5 +30,4 @@ export declare function parseGrokUsageSnapshot(value: unknown): readonly Subscri
|
|
|
58
30
|
export declare function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined;
|
|
59
31
|
export declare function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs?: number): void;
|
|
60
32
|
export declare function recordClaudePassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs?: number): void;
|
|
61
|
-
export {};
|
|
62
33
|
//# sourceMappingURL=provider-usage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-usage.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAmC,KAAK,yBAAyB,EAAgC,MAAM,QAAQ,CAAC;AACvH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAiDvD,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,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,SAAS,uBAAuB,EAAE,CAAC;IACrD,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,KAAK,gBAAgB,GAAG;IAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AACrF,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BrG;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 { CLAUDE_CODE_EXTERNAL_USER_AGENT, type ProviderRateLimitSnapshot, type ProviderRateLimitWindow } from \"omk-ai\";\nimport type { AgentSession } from \"./agent-session.ts\";\n\nconst FIVE_HOUR_SECONDS = 5 * 60 * 60;\nconst SEVEN_DAY_SECONDS = 7 * 24 * 60 * 60;\nconst WINDOW_TOLERANCE_SECONDS = 120;\nconst CODEX_USAGE_URL = \"https://chatgpt.com/backend-api/wham/usage\";\nconst CLAUDE_USAGE_URL = \"https://api.anthropic.com/api/oauth/usage\";\nconst CLAUDE_MESSAGES_URL = \"https://api.anthropic.com/v1/messages\";\nconst KIMI_USAGE_URL = \"https://api.kimi.com/coding/v1/usages\";\nconst GROK_BILLING_URL = \"https://cli-chat-proxy.grok.com/v1/billing?format=credits\";\nconst OPENAI_AUTH_CLAIM = \"https://api.openai.com/auth\";\nconst MAX_USAGE_RESPONSE_BYTES = 1024 * 1024;\nconst MAX_USAGE_LIMITS = 64;\nconst MAX_PASSIVE_ACCOUNTS = 64;\nconst PASSIVE_USAGE_TTL_MS = 6 * 60 * 60 * 1000;\nconst CLAUDE_QUOTA_PROBE_COOLDOWN_MS = 60 * 60 * 1000;\nconst CLAUDE_QUOTA_PROBE_TIMEOUT_MS = 10_000;\nconst QWEN_CLI_TIMEOUT_MS = 15_000;\nconst QWEN_CLI_ARGS = [\"usage\", \"summary\", \"--format\", \"json\"] as const;\nconst qwenBillingArgs = (month: string): readonly string[] =>\n\t[\"billing\", \"breakdown\", \"--from\", month, \"--to\", month, \"--group-by\", \"model\", \"--format\", \"json\"] as const;\nconst QWEN_CONNECT_HINT = \"connect: npm i -g @qwencloud/qwencloud-cli && qwencloud auth login\";\nconst QWEN_CLI_ENV_KEYS = [\n\t\"PATH\",\n\t\"Path\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"HOMEDRIVE\",\n\t\"HOMEPATH\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"XDG_CONFIG_HOME\",\n\t\"XDG_DATA_HOME\",\n\t\"XDG_CACHE_HOME\",\n\t\"TMPDIR\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"SystemRoot\",\n\t\"WINDIR\",\n\t\"ComSpec\",\n\t\"PATHEXT\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"LC_CTYPE\",\n\t\"TERM\",\n\t\"SSL_CERT_FILE\",\n\t\"SSL_CERT_DIR\",\n] as const;\n\nexport type SubscriptionUsageWindow = {\n\treadonly label: string;\n\treadonly usedPercent: number;\n\treadonly resetsAt?: number;\n};\n\nexport type SubscriptionUsageSnapshot = {\n\treadonly label: string;\n\treadonly windows: readonly SubscriptionUsageWindow[];\n\treadonly message?: string;\n};\n\ntype CodexUsageWindow = { readonly usedPercent: number; readonly resetsAt?: number };\nexport type CodexUsageSnapshot = {\n\treadonly fiveHour?: CodexUsageWindow;\n\treadonly sevenDay?: CodexUsageWindow;\n};\n\ntype ParsedCodexWindow = CodexUsageWindow & { readonly windowSeconds?: number };\ntype ObservedCodexWindow = { readonly window: ParsedCodexWindow; readonly observedAt: number };\ntype PassiveUsageEntry = { readonly primary?: ObservedCodexWindow; readonly secondary?: ObservedCodexWindow };\ntype UsageKind = \"codex\" | \"claude\" | \"kimi\" | \"zai\" | \"grok\" | \"qwen-token-plan\" | \"unavailable\";\ntype CredentialCandidate = { readonly provider: string; readonly oauthOnly: boolean };\n\nexport type SubscriptionUsageSource = {\n\treadonly label: string;\n\treadonly kind: UsageKind;\n\treadonly credentials: readonly CredentialCandidate[];\n\treadonly ttlMs: number;\n\treadonly unavailableMessage?: string;\n};\n\ntype UsageSession = Pick<AgentSession, \"state\" | \"modelRegistry\">;\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\ntype FetchJsonResult = { readonly status: number; readonly payload?: unknown };\n\nconst passiveCodexUsage = new Map<string, PassiveUsageEntry>();\nconst passiveClaudeUsage = new Map<string, PassiveUsageEntry>();\nconst claudeQuotaProbeAttempts = new Map<string, number>();\nconst claudeQuotaProbesInFlight = new Map<string, Promise<void>>();\nconst subscriptionUsageRevisions = new Map<string, number>();\nconst MINUTE_TTL_MS = 60_000;\nconst VISIBLE_USAGE_PROVIDERS = [\n\t\"openai-codex\",\n\t\"anthropic\",\n\t\"kimi-coding\",\n\t\"zai\",\n\t\"modelstudio-maas\",\n\t\"qwen-oauth\",\n\t\"xai\",\n] as const;\nconst SOURCES: Readonly<Record<string, SubscriptionUsageSource>> = {\n\t\"openai-codex\": source(\"CODEX\", \"codex\", [{ provider: \"openai-codex\", oauthOnly: true }]),\n\tanthropic: source(\"CLAUDE\", \"claude\", [{ provider: \"anthropic\", oauthOnly: true }], 5 * MINUTE_TTL_MS),\n\t\"qwen-oauth\": source(\"QWEN\", \"unavailable\", [{ provider: \"qwen-oauth\", oauthOnly: true }]),\n\t// Model Studio exposes no API-key quota endpoint (console gateway is\n\t// session-only), so the token-plan quota rides the official QwenCloud\n\t// management CLI, which holds its own OAuth credential.\n\t\"modelstudio-maas\": source(\n\t\t\"QWEN TOKEN PLAN\",\n\t\t\"qwen-token-plan\",\n\t\t[{ provider: \"modelstudio-maas\", oauthOnly: false }],\n\t\t5 * MINUTE_TTL_MS,\n\t),\n\t\"kimi-code\": source(\"KIMI\", \"kimi\", [\n\t\t{ provider: \"kimi-code\", oauthOnly: true },\n\t\t{ provider: \"kimi-coding\", oauthOnly: false },\n\t]),\n\t\"kimi-coding\": source(\"KIMI\", \"kimi\", [\n\t\t{ provider: \"kimi-code\", oauthOnly: true },\n\t\t{ provider: \"kimi-coding\", oauthOnly: false },\n\t]),\n\t\"zhipu-coding-plan\": source(\"GLM\", \"zai\", [{ provider: \"zhipu-coding-plan\", oauthOnly: true }]),\n\tzai: source(\"GLM\", \"zai\", [\n\t\t{ provider: \"zai\", oauthOnly: false },\n\t\t{ provider: \"zai-coding-cn\", oauthOnly: false },\n\t\t{ provider: \"zhipu-coding-plan\", oauthOnly: true },\n\t]),\n\t\"zai-coding-cn\": source(\"GLM\", \"zai\", [\n\t\t{ provider: \"zai-coding-cn\", oauthOnly: false },\n\t\t{ provider: \"zhipu-coding-plan\", oauthOnly: true },\n\t]),\n\txai: source(\"GROK\", \"grok\", [{ provider: \"xai\", oauthOnly: true }]),\n};\n\nfunction source(\n\tlabel: string,\n\tkind: UsageKind,\n\tcredentials: readonly CredentialCandidate[],\n\tttlMs = MINUTE_TTL_MS,\n\tunavailableMessage?: string,\n): SubscriptionUsageSource {\n\treturn { label, kind, credentials, ttlMs, unavailableMessage };\n}\n\nexport function getSubscriptionUsageSource(provider: string | undefined): SubscriptionUsageSource | undefined {\n\tif (!provider) return undefined;\n\tconst configured = SOURCES[provider];\n\tif (configured) return configured;\n\tif (/^openai-codex-\\d+$/.test(provider)) {\n\t\treturn source(\"CODEX\", \"codex\", [\n\t\t\t{ provider, oauthOnly: true },\n\t\t\t{ provider: \"openai-codex\", oauthOnly: true },\n\t\t]);\n\t}\n\treturn undefined;\n}\n\nfunction usageRevisionKey(provider: string): string {\n\tconst kind = getSubscriptionUsageSource(provider)?.kind;\n\tif (kind === \"codex\") return \"codex\";\n\tif (kind === \"claude\") return \"claude\";\n\treturn provider;\n}\n\nexport function getSubscriptionUsageRevision(provider: string): number {\n\treturn subscriptionUsageRevisions.get(usageRevisionKey(provider)) ?? 0;\n}\n\nfunction bumpSubscriptionUsageRevision(provider: string): void {\n\tconst key = usageRevisionKey(provider);\n\tsubscriptionUsageRevisions.set(key, (subscriptionUsageRevisions.get(key) ?? 0) + 1);\n}\n\nexport function supportsSubscriptionUsage(session: UsageSession, provider = session.state.model?.provider): boolean {\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\treturn usageSource?.credentials.some((candidate) => credentialConfigured(session, candidate)) ?? false;\n}\n\n/** Configured quota groups shown in the rail, with the active group first. */\nexport function getConfiguredSubscriptionUsageProviders(session: UsageSession): readonly string[] {\n\tconst activeProvider = session.state.model?.provider;\n\tconst activeSource = getSubscriptionUsageSource(activeProvider);\n\tconst providers = VISIBLE_USAGE_PROVIDERS.filter((provider) => supportsSubscriptionUsage(session, provider));\n\tif (!activeProvider || !activeSource || !supportsSubscriptionUsage(session, activeProvider)) return providers;\n\tconst activeCanonical = providers.find(\n\t\t(provider) => getSubscriptionUsageSource(provider)?.label === activeSource.label,\n\t);\n\tif (!activeCanonical) return [activeProvider, ...providers];\n\treturn [activeCanonical, ...providers.filter((provider) => provider !== activeCanonical)];\n}\n\nexport async function loadSubscriptionUsage(\n\tsession: UsageSession,\n\tfetchImpl: FetchLike = fetch,\n\tprovider = session.state.model?.provider,\n\tqwenCliRunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot | undefined> {\n\tconst model = session.state.model;\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\tif (!model || !usageSource || !supportsSubscriptionUsage(session, provider)) return undefined;\n\tif (usageSource.kind === \"unavailable\") {\n\t\treturn {\n\t\t\tlabel: usageSource.label,\n\t\t\twindows: [],\n\t\t\tmessage: usageSource.unavailableMessage ?? \"quota API unavailable\",\n\t\t};\n\t}\n\tif (offline()) return { label: usageSource.label, windows: [], message: \"offline\" };\n\tif (usageSource.kind === \"qwen-token-plan\") {\n\t\t// The QwenCloud CLI authenticates itself; no OMK-held credential is used.\n\t\treturn await fetchQwenTokenPlanUsage(usageSource.label, qwenCliRunner);\n\t}\n\n\tconst credential = await resolveCredential(session, usageSource);\n\tif (!credential) return { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\n\ttry {\n\t\tswitch (usageSource.kind) {\n\t\t\tcase \"codex\":\n\t\t\t\treturn await fetchCodexUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"claude\":\n\t\t\t\treturn await fetchClaudeUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"kimi\":\n\t\t\t\treturn await fetchKimiUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"zai\":\n\t\t\t\treturn await fetchZaiUsage(usageSource.label, provider ?? model.provider, credential, fetchImpl);\n\t\t\tcase \"grok\":\n\t\t\t\treturn await fetchGrokUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tdefault:\n\t\t\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t\t}\n\t} catch {\n\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t}\n}\n\nexport function parseCodexUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): CodexUsageSnapshot | undefined {\n\tconst rateLimit = record(record(value)?.rate_limit);\n\tconst primary = codexWindow(rateLimit?.primary_window, nowSeconds);\n\tconst secondary = codexWindow(rateLimit?.secondary_window, nowSeconds);\n\tconst windows = [primary, secondary].filter((window): window is ParsedCodexWindow => window !== undefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tconst fallbackFiveHour = fiveHour ?? (primary?.windowSeconds === undefined ? primary : undefined);\n\tconst fallbackSevenDay = sevenDay ?? (secondary?.windowSeconds === undefined ? secondary : undefined);\n\tif (!fallbackFiveHour && !fallbackSevenDay) return undefined;\n\treturn {\n\t\t...(fallbackFiveHour ? { fiveHour: publicCodexWindow(fallbackFiveHour) } : {}),\n\t\t...(fallbackSevenDay ? { sevenDay: publicCodexWindow(fallbackSevenDay) } : {}),\n\t};\n}\n\nexport function parseClaudeUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst entries = Array.isArray(payload.limits)\n\t\t? payload.limits.slice(0, MAX_USAGE_LIMITS).map(record).filter(isDefined)\n\t\t: [];\n\tconst fiveHour = claudeWindow(payload.five_hour) ?? claudeWindow(entries.find((entry) => entry.kind === \"session\"));\n\tconst sevenDay =\n\t\tclaudeWindow(payload.seven_day) ?? claudeWindow(entries.find((entry) => entry.kind === \"weekly_all\"));\n\tconst windows = [\n\t\tfiveHour ? withLabel(\"5H\", fiveHour) : undefined,\n\t\tsevenDay ? withLabel(\"7D\", sevenDay) : undefined,\n\t].filter(isDefined);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function parseKimiUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst windows: SubscriptionUsageWindow[] = [];\n\tconst total = usageRatio(record(payload.usage), nowSeconds);\n\tif (total) windows.push(withLabel(\"TOTAL\", total));\n\tif (Array.isArray(payload.limits)) {\n\t\tfor (const rawLimit of payload.limits.slice(0, MAX_USAGE_LIMITS)) {\n\t\t\tconst limit = record(rawLimit);\n\t\t\tif (!limit) continue;\n\t\t\tconst detail = record(limit.detail) ?? limit;\n\t\t\tconst windowData = record(limit.window);\n\t\t\tconst parsed = usageRatio(detail, nowSeconds);\n\t\t\tif (!parsed) continue;\n\t\t\tconst resetsAt = parseReset(windowData, nowSeconds) ?? parsed.resetsAt;\n\t\t\twindows.push({\n\t\t\t\tlabel: durationLabel(windowData) ?? shortLabel(limit.name ?? limit.title ?? limit.scope, windows.length),\n\t\t\t\tusedPercent: parsed.usedPercent,\n\t\t\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t\t\t});\n\t\t}\n\t}\n\treturn windows.length > 0 ? windows.slice(0, 4) : undefined;\n}\n\n/** Result of one `qwencloud` invocation; `missing` means the CLI is not installed. */\nexport type QwenCliResult =\n\t| { readonly kind: \"missing\" }\n\t| { readonly kind: \"ran\"; readonly exitCode: number; readonly stdout: string };\nexport type QwenCliRunner = (args: readonly string[], timeoutMs: number) => Promise<QwenCliResult>;\n\nexport function buildQwenCliEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n\tconst childEnvironment: NodeJS.ProcessEnv = {};\n\tfor (const key of QWEN_CLI_ENV_KEYS) {\n\t\tconst value = source[key];\n\t\tif (value !== undefined) childEnvironment[key] = value;\n\t}\n\treturn childEnvironment;\n}\n\n/** Parse `qwencloud usage summary --format json` → the token-plan 7-day window. */\nexport function parseQwenTokenPlanUsage(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst tokenPlan = record(record(value)?.token_plan);\n\tif (!tokenPlan || tokenPlan.subscribed === false) return undefined;\n\tconst resetsAt = epochSeconds(tokenPlan.resetDate);\n\tlet usedPercent = finiteNumber(tokenPlan.usedPct) ?? finiteNumber(tokenPlan.used_pct);\n\tif (usedPercent === undefined) {\n\t\tconst total = finiteNumber(tokenPlan.totalCredits);\n\t\tconst remaining = finiteNumber(tokenPlan.remainingCredits);\n\t\tif (total !== undefined && remaining !== undefined && total > 0) {\n\t\t\tusedPercent = ((total - remaining) / total) * 100;\n\t\t}\n\t}\n\tif (usedPercent === undefined) return undefined;\n\treturn [{ label: \"7D\", usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport async function fetchQwenTokenPlanUsage(\n\tlabel: string,\n\trunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst unavailable = (message: string): SubscriptionUsageSnapshot => ({ label, windows: [], message });\n\ttry {\n\t\tconst result = await runner(QWEN_CLI_ARGS, QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind === \"missing\") return unavailable(QWEN_CONNECT_HINT);\n\t\tif (result.exitCode === 2) return unavailable(\"run: qwencloud auth login\");\n\t\tif (result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn unavailable(\"usage unavailable\");\n\t\t}\n\t\tconst payload: unknown = JSON.parse(result.stdout);\n\t\tconst tokenPlan = record(record(payload)?.token_plan);\n\t\tif (tokenPlan?.subscribed === false) {\n\t\t\tconst periodTo = record(record(payload)?.period)?.to;\n\t\t\tconst month = typeof periodTo === \"string\" ? periodTo.slice(0, 7) : new Date().toISOString().slice(0, 7);\n\t\t\treturn unavailable(await billingFallbackMessage(runner, month, payload));\n\t\t}\n\t\tconst windows = parseQwenTokenPlanUsage(payload);\n\t\treturn windows ? { label, windows } : unavailable(\"usage unavailable\");\n\t} catch {\n\t\treturn unavailable(\"usage unavailable\");\n\t}\n}\n\n/** No active token plan: fall back to settled billing — subscription charge + PAYG spend — when the CLI reports it. */\nasync function billingFallbackMessage(runner: QwenCliRunner, month: string, summaryPayload: unknown): Promise<string> {\n\ttry {\n\t\tconst result = await runner(qwenBillingArgs(month), QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind !== \"ran\" || result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn paygFallbackMessage(summaryPayload);\n\t\t}\n\t\tconst billing = parseBillingBreakdown(JSON.parse(result.stdout));\n\t\tconst cur = billing.currency === undefined || billing.currency === \"USD\" ? \"$\" : `${billing.currency} `;\n\t\tconst parts: string[] = [];\n\t\tif (billing.subscription !== undefined && billing.subscription > 0) {\n\t\t\tparts.push(`subscription ${cur}${billing.subscription.toFixed(2)}`);\n\t\t}\n\t\tconst payg = billing.payg ?? paygTotalCost(summaryPayload);\n\t\tif (payg !== undefined && payg > 0) parts.push(`PAYG ${cur}${payg.toFixed(2)}`);\n\t\tif (parts.length === 0) return \"no active token plan\";\n\t\treturn `${parts.join(\" · \")} (${month})`;\n\t} catch {\n\t\treturn paygFallbackMessage(summaryPayload);\n\t}\n}\n\n/** Split settled billing rows into the fixed subscription charge vs per-model PAYG spend. */\nfunction parseBillingBreakdown(payload: unknown): { subscription?: number; payg?: number; currency?: string } {\n\tconst data = record(payload);\n\tconst rows = Array.isArray(data?.rows) ? data.rows : [];\n\tlet subscription: number | undefined;\n\tlet payg = 0;\n\tlet paygSeen = false;\n\tfor (const raw of rows) {\n\t\tconst row = record(raw);\n\t\tconst amount = finiteNumber(row?.amount);\n\t\tif (amount === undefined) continue;\n\t\tconst key = typeof row?.groupKey === \"string\" ? row.groupKey : \"\";\n\t\tif (key === \"__tax__\") continue;\n\t\tif (key === \"DIMENSION_FILTER_NULL_VALUE\") subscription = (subscription ?? 0) + amount;\n\t\telse {\n\t\t\tpayg += amount;\n\t\t\tpaygSeen = true;\n\t\t}\n\t}\n\tconst currency = typeof data?.currency === \"string\" ? data.currency : undefined;\n\treturn { subscription, payg: paygSeen ? payg : undefined, currency };\n}\n\nfunction paygTotalCost(payload: unknown): number | undefined {\n\treturn finiteNumber(record(record(record(payload)?.pay_as_you_go)?.total)?.cost);\n}\n\n/** No active token plan: fall back to the account's pay-as-you-go spend when the CLI reports it. */\nfunction paygFallbackMessage(payload: unknown): string {\n\tconst cost = paygTotalCost(payload);\n\tif (cost === undefined) return \"no active token plan\";\n\tconst currency = \"$\";\n\tconst period = record(record(payload)?.period);\n\tconst from = typeof period?.from === \"string\" ? period.from.slice(0, 7) : undefined;\n\treturn `no token plan · PAYG ${currency}${cost.toFixed(2)}${from ? ` (${from})` : \"\"}`;\n}\n\nfunction runQwenCli(args: readonly string[], timeoutMs: number): Promise<QwenCliResult> {\n\treturn new Promise((resolve) => {\n\t\tconst binary = process.env.QWENCLOUD_CLI ?? \"qwencloud\";\n\t\texecFile(\n\t\t\tbinary,\n\t\t\t[...args],\n\t\t\t{\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tmaxBuffer: MAX_USAGE_RESPONSE_BYTES,\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv: buildQwenCliEnvironment(process.env),\n\t\t\t},\n\t\t\t(error, stdout) => {\n\t\t\t\tif (!error) {\n\t\t\t\t\tresolve({ kind: \"ran\", exitCode: 0, stdout });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst errno = (error as NodeJS.ErrnoException).code;\n\t\t\t\tif (errno === \"ENOENT\") {\n\t\t\t\t\tresolve({ kind: \"missing\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve({ kind: \"ran\", exitCode: typeof errno === \"number\" ? errno : 1, stdout: stdout ?? \"\" });\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport function parseGrokUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst config = record(record(value)?.config);\n\tif (!config) return undefined;\n\tconst period = record(config.currentPeriod);\n\tconst resetsAt = epochSeconds(period?.end) ?? epochSeconds(config.billingPeriodEnd);\n\tconst percent = finiteNumber(config.creditUsagePercent);\n\tconst onDemandUsed = finiteNumber(record(config.onDemandUsed)?.val);\n\tconst onDemandCap = finiteNumber(record(config.onDemandCap)?.val);\n\tlet usedPercent = percent;\n\tif (usedPercent === undefined && onDemandUsed !== undefined && onDemandCap !== undefined && onDemandCap > 0) {\n\t\tusedPercent = (onDemandUsed / onDemandCap) * 100;\n\t}\n\tif (usedPercent === undefined && (period || resetsAt !== undefined)) usedPercent = 0;\n\tif (usedPercent === undefined) return undefined;\n\tconst periodType = typeof period?.type === \"string\" ? period.type : \"\";\n\tconst label = periodType.includes(\"MONTHLY\") ? \"30D\" : \"7D\";\n\treturn [{ label, usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tconst limits = record(payload?.data)?.limits;\n\tif (payload?.success !== true || !Array.isArray(limits)) return undefined;\n\tconst parsed = limits.slice(0, MAX_USAGE_LIMITS).map(zaiWindow).filter(isDefined);\n\tconst requestWindows = parsed.filter((window) => window.type === \"TIME_LIMIT\" && !window.featureOnly);\n\tconst selected =\n\t\trequestWindows.length > 0 ? requestWindows : parsed.filter((window) => window.type === \"TOKENS_LIMIT\");\n\tselected.sort((left, right) => left.durationSeconds - right.durationSeconds);\n\tconst windows = selected\n\t\t.slice(0, 4)\n\t\t.map(({ type: _type, durationSeconds: _duration, featureOnly: _feature, ...window }) => window);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs = Date.now()): void {\n\tconst accountId = codexAccountId(apiKey);\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0 || (limitId && limitId !== \"codex\")) return;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveCodexUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, next);\n\twhile (passiveCodexUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveCodexUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveCodexUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"openai-codex\");\n}\n\nexport function recordClaudePassiveUsage(\n\tapiKey: string,\n\tsnapshot: ProviderRateLimitSnapshot,\n\tnowMs = Date.now(),\n): void {\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (\n\t\t!apiKey ||\n\t\tapiKey.length > 32_768 ||\n\t\t!Number.isFinite(nowMs) ||\n\t\tnowMs < 0 ||\n\t\t(limitId && limitId !== \"anthropic_unified\")\n\t) {\n\t\treturn;\n\t}\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveClaudeUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, next);\n\twhile (passiveClaudeUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveClaudeUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveClaudeUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"anthropic\");\n}\n\nasync function fetchCodexUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId) return { label, windows: [], message: \"usage unavailable\" };\n\tconst passive = passiveCodexSnapshot(apiKey);\n\tlet polled: CodexUsageSnapshot | undefined;\n\ttry {\n\t\tconst payload = await fetchJson(fetchImpl, CODEX_USAGE_URL, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\t\"User-Agent\": \"omk\",\n\t\t\t},\n\t\t});\n\t\tpolled = parseCodexUsageSnapshot(payload);\n\t} catch (error) {\n\t\tif (!passive) throw error;\n\t}\n\tconst merged: CodexUsageSnapshot = {\n\t\tfiveHour: polled?.fiveHour ?? passive?.fiveHour,\n\t\tsevenDay: polled?.sevenDay ?? passive?.sevenDay,\n\t};\n\tif (!merged.fiveHour && !merged.sevenDay) return { label, windows: [], message: \"usage unavailable\" };\n\treturn {\n\t\tlabel,\n\t\twindows: [\n\t\t\tmerged.fiveHour ? withLabel(\"5H\", merged.fiveHour) : undefined,\n\t\t\tmerged.sevenDay ? withLabel(\"7D\", merged.sevenDay) : undefined,\n\t\t].filter(isDefined),\n\t};\n}\n\nasync function fetchClaudeUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tlet passive = passiveClaudeSnapshot(apiKey);\n\tconst response = await fetchJsonResult(fetchImpl, CLAUDE_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\"User-Agent\": CLAUDE_CODE_EXTERNAL_USER_AGENT,\n\t\t},\n\t});\n\tconst windows = [...(parseClaudeUsageSnapshot(response.payload) ?? [])];\n\tif (response.status === 429 && (!passive?.fiveHour || !passive?.sevenDay)) {\n\t\tawait probeClaudeQuota(apiKey, fetchImpl);\n\t\tpassive = passiveClaudeSnapshot(apiKey);\n\t}\n\tfor (const passiveWindow of [\n\t\tpassive?.fiveHour ? withLabel(\"5H\", passive.fiveHour) : undefined,\n\t\tpassive?.sevenDay ? withLabel(\"7D\", passive.sevenDay) : undefined,\n\t].filter(isDefined)) {\n\t\tif (!windows.some((window) => window.label === passiveWindow.label)) windows.push(passiveWindow);\n\t}\n\treturn windows.length > 0\n\t\t? { label, windows }\n\t\t: { label, windows: [], message: response.status === 429 ? \"rate limited · retry later\" : \"usage unavailable\" };\n}\n\n/**\n * Claude Code 2.1.177 performs the same `quota`/`max_tokens: 1` request during startup.\n * Keep it account-scoped and hourly so a pinned sidebar cannot turn the fallback into polling.\n */\nasync function probeClaudeQuota(apiKey: string, fetchImpl: FetchLike, nowMs = Date.now()): Promise<void> {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return;\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst activeProbe = claudeQuotaProbesInFlight.get(cacheKey);\n\tif (activeProbe) return activeProbe;\n\tconst lastAttempt = claudeQuotaProbeAttempts.get(cacheKey);\n\tif (lastAttempt !== undefined && nowMs - lastAttempt < CLAUDE_QUOTA_PROBE_COOLDOWN_MS) return;\n\tif (claudeQuotaProbesInFlight.size >= MAX_PASSIVE_ACCOUNTS) return;\n\n\tclaudeQuotaProbeAttempts.delete(cacheKey);\n\tclaudeQuotaProbeAttempts.set(cacheKey, nowMs);\n\twhile (claudeQuotaProbeAttempts.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = claudeQuotaProbeAttempts.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tclaudeQuotaProbeAttempts.delete(oldestCacheKey);\n\t}\n\n\tconst probe = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetchImpl(CLAUDE_MESSAGES_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n\t\t\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"User-Agent\": CLAUDE_CODE_EXTERNAL_USER_AGENT,\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel: \"claude-haiku-4-5\",\n\t\t\t\t\tmax_tokens: 1,\n\t\t\t\t\tmessages: [{ role: \"user\", content: \"quota\" }],\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(CLAUDE_QUOTA_PROBE_TIMEOUT_MS),\n\t\t\t});\n\t\t\tconst snapshot = parseClaudeQuotaProbeHeaders(response.headers, nowMs);\n\t\t\tif (snapshot) recordClaudePassiveUsage(apiKey, snapshot, nowMs);\n\t\t\ttry {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t} catch {\n\t\t\t\t// The quota snapshot lives entirely in response headers.\n\t\t\t}\n\t\t} catch {\n\t\t\t// This mirrors Claude Code's best-effort startup quota check.\n\t\t}\n\t})().finally(() => {\n\t\tclaudeQuotaProbesInFlight.delete(cacheKey);\n\t});\n\tclaudeQuotaProbesInFlight.set(cacheKey, probe);\n\treturn probe;\n}\n\nfunction parseClaudeQuotaProbeHeaders(headers: Headers, nowMs: number): ProviderRateLimitSnapshot | undefined {\n\tconst parseWindow = (prefix: \"5h\" | \"7d\", windowSeconds: number): ProviderRateLimitWindow | undefined => {\n\t\tconst rawUtilization = headers.get(`anthropic-ratelimit-unified-${prefix}-utilization`);\n\t\tconst rawReset = headers.get(`anthropic-ratelimit-unified-${prefix}-reset`);\n\t\tif (rawUtilization === null || rawReset === null) return undefined;\n\t\tconst utilization = Number(rawUtilization);\n\t\tconst resetsAt = Number(rawReset);\n\t\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\t\tif (\n\t\t\t!Number.isFinite(utilization) ||\n\t\t\tutilization < 0 ||\n\t\t\tutilization > 1 ||\n\t\t\t!Number.isSafeInteger(resetsAt) ||\n\t\t\tresetsAt <= 0 ||\n\t\t\tresetsAt > maxResetAt\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { usedPercent: Math.round(utilization * 10_000) / 100, windowSeconds, resetsAt };\n\t};\n\tconst primary = parseWindow(\"5h\", FIVE_HOUR_SECONDS);\n\tconst secondary = parseWindow(\"7d\", SEVEN_DAY_SECONDS);\n\treturn primary || secondary ? { limitId: \"anthropic-unified\", primary, secondary } : undefined;\n}\n\nasync function fetchGrokUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, GROK_BILLING_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"x-xai-token-auth\": \"xai-grok-cli\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseGrokUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchKimiUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, KIMI_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"KimiCLI/1.5\",\n\t\t\t\"X-Msh-Platform\": \"kimi_cli\",\n\t\t\t\"X-Msh-Version\": \"1.5\",\n\t\t},\n\t});\n\tconst windows = parseKimiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchZaiUsage(\n\tlabel: string,\n\tmodelProvider: string,\n\tcredential: { readonly provider: string; readonly apiKey: string },\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst origin =\n\t\tmodelProvider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zhipu-coding-plan\"\n\t\t\t? \"https://open.bigmodel.cn\"\n\t\t\t: \"https://api.z.ai\";\n\tconst payload = await fetchJson(fetchImpl, `${origin}/api/monitor/usage/quota/limit`, {\n\t\theaders: {\n\t\t\tAuthorization: credential.apiKey,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseZaiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchJson(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<unknown> {\n\treturn (await fetchJsonResult(fetchImpl, url, init)).payload;\n}\n\nasync function fetchJsonResult(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<FetchJsonResult> {\n\tconst response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(10_000) });\n\tif (!response.ok) return { status: response.status };\n\tconst declaredBytes = Number(response.headers?.get(\"content-length\"));\n\tif (Number.isFinite(declaredBytes) && declaredBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\treturn { status: response.status };\n\t}\n\tif (!response.body || typeof response.body.getReader !== \"function\") {\n\t\treturn { status: response.status, payload: await response.json() };\n\t}\n\n\tconst reader = response.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet totalBytes = 0;\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\treturn { status: response.status };\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst body = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\ttry {\n\t\treturn { status: response.status, payload: JSON.parse(new TextDecoder().decode(body)) as unknown };\n\t} catch {\n\t\treturn { status: response.status };\n\t}\n}\n\nfunction credentialConfigured(session: UsageSession, candidate: CredentialCandidate): boolean {\n\tif (candidate.oauthOnly) return session.modelRegistry.isUsingOAuthProvider(candidate.provider);\n\tconst status = session.modelRegistry.getProviderAuthStatus(candidate.provider);\n\treturn status.configured || status.source !== undefined;\n}\n\nasync function resolveCredential(\n\tsession: UsageSession,\n\tusageSource: SubscriptionUsageSource,\n): Promise<{ readonly provider: string; readonly apiKey: string } | undefined> {\n\tfor (const candidate of usageSource.credentials) {\n\t\tif (!credentialConfigured(session, candidate)) continue;\n\t\tconst apiKey = await session.modelRegistry.getApiKeyForProvider(candidate.provider);\n\t\tif (apiKey) return { provider: candidate.provider, apiKey };\n\t}\n\treturn undefined;\n}\n\nfunction codexWindow(value: unknown, nowSeconds: number): ParsedCodexWindow | undefined {\n\tconst window = record(value);\n\tconst usedPercent = finiteNumber(window?.used_percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst windowSeconds = finiteNumber(window?.limit_window_seconds);\n\tconst resetAt = finiteNumber(window?.reset_at);\n\tconst resetAfter = finiteNumber(window?.reset_after_seconds);\n\tconst resetsAt = resetAt ?? (resetAfter === undefined ? undefined : nowSeconds + resetAfter);\n\treturn {\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction claudeWindow(value: unknown): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tconst bucket = record(value);\n\tif (!bucket || bucket.is_active === false) return undefined;\n\tconst usedPercent = finiteNumber(bucket.utilization ?? bucket.percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst resetsAt = epochSeconds(bucket.resets_at);\n\treturn { usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) };\n}\n\nfunction usageRatio(\n\tdata: Record<string, unknown> | undefined,\n\tnowSeconds: number,\n): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tif (!data) return undefined;\n\tconst limit = finiteNumber(data.limit);\n\tlet used = finiteNumber(data.used);\n\tconst remaining = finiteNumber(data.remaining);\n\tif (used === undefined && limit !== undefined && remaining !== undefined) used = limit - remaining;\n\tif (used === undefined || limit === undefined || limit <= 0) return undefined;\n\tconst resetsAt = parseReset(data, nowSeconds);\n\treturn {\n\t\tusedPercent: clampPercent((used / limit) * 100),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiWindow(value: unknown):\n\t| (SubscriptionUsageWindow & {\n\t\t\treadonly type: string;\n\t\t\treadonly durationSeconds: number;\n\t\t\treadonly featureOnly: boolean;\n\t })\n\t| undefined {\n\tconst item = record(value);\n\tif (!item || (item.type !== \"TIME_LIMIT\" && item.type !== \"TOKENS_LIMIT\")) return undefined;\n\tconst percentage = finiteNumber(item.percentage);\n\tconst current = finiteNumber(item.currentValue);\n\tconst limit = finiteNumber(item.usage);\n\tconst usedPercent =\n\t\tpercentage ?? (current !== undefined && limit !== undefined && limit > 0 ? (current / limit) * 100 : undefined);\n\tif (usedPercent === undefined) return undefined;\n\tconst duration = zaiDuration(finiteNumber(item.unit), finiteNumber(item.number));\n\tconst resetsAt = epochSeconds(item.nextResetTime);\n\tconst detailCodes = Array.isArray(item.usageDetails)\n\t\t? item.usageDetails\n\t\t\t\t.map((detail) => record(detail)?.modelCode)\n\t\t\t\t.filter((code): code is string => typeof code === \"string\")\n\t\t: [];\n\treturn {\n\t\ttype: item.type,\n\t\tlabel: duration.label,\n\t\tdurationSeconds: duration.seconds,\n\t\tfeatureOnly: [\"search-prime\", \"web-reader\", \"zread\"].every((code) => detailCodes.includes(code)),\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiDuration(unit: number | undefined, countValue: number | undefined): { label: string; seconds: number } {\n\tconst count = countValue && countValue > 0 ? countValue : 1;\n\tif (unit === 3) return { label: `${count}H`, seconds: count * 60 * 60 };\n\tif (unit === 4) return { label: `${count}D`, seconds: count * 24 * 60 * 60 };\n\tif (unit === 5) return { label: count === 1 ? \"30D\" : `${count}MO`, seconds: count * 30 * 24 * 60 * 60 };\n\tif (unit === 6) return { label: \"7D\", seconds: 7 * 24 * 60 * 60 };\n\treturn { label: \"QUOTA\", seconds: Number.POSITIVE_INFINITY };\n}\n\nfunction durationLabel(window: Record<string, unknown> | undefined): string | undefined {\n\tif (!window) return undefined;\n\tconst duration = finiteNumber(window.duration);\n\tconst unit = typeof window.timeUnit === \"string\" ? window.timeUnit.toUpperCase() : \"\";\n\tif (duration === undefined) return undefined;\n\tif (unit.includes(\"MINUTE\")) return duration % 60 === 0 ? `${duration / 60}H` : `${duration}M`;\n\tif (unit.includes(\"HOUR\")) return `${duration}H`;\n\tif (unit.includes(\"DAY\")) return `${duration}D`;\n\tif (unit.includes(\"SECOND\")) return `${duration}S`;\n\treturn undefined;\n}\n\nfunction parseReset(data: Record<string, unknown> | undefined, nowSeconds: number): number | undefined {\n\tif (!data) return undefined;\n\tfor (const key of [\"reset_at\", \"resetAt\", \"reset_time\", \"resetTime\"] as const) {\n\t\tconst parsed = epochSeconds(data[key]);\n\t\tif (parsed !== undefined) return parsed;\n\t}\n\tfor (const key of [\"reset_in\", \"resetIn\", \"ttl\"] as const) {\n\t\tconst seconds = finiteNumber(data[key]);\n\t\tif (seconds !== undefined) return nowSeconds + seconds;\n\t}\n\treturn undefined;\n}\n\nfunction epochSeconds(value: unknown): number | undefined {\n\tconst numeric = finiteNumber(value);\n\tif (numeric !== undefined) return numeric > 1_000_000_000_000 ? numeric / 1000 : numeric;\n\tif (typeof value !== \"string\" || !value.trim()) return undefined;\n\tconst parsed = Date.parse(value);\n\treturn Number.isFinite(parsed) ? parsed / 1000 : undefined;\n}\n\nfunction normalizePassiveCodexWindow(\n\twindow: ProviderRateLimitWindow | undefined,\n\tnowMs: number,\n): ParsedCodexWindow | undefined {\n\tif (!window || !Number.isFinite(window.usedPercent)) return undefined;\n\tconst windowSeconds =\n\t\twindow.windowSeconds !== undefined &&\n\t\tNumber.isFinite(window.windowSeconds) &&\n\t\twindow.windowSeconds > 0 &&\n\t\twindow.windowSeconds <= Number.MAX_SAFE_INTEGER\n\t\t\t? Math.round(window.windowSeconds)\n\t\t\t: undefined;\n\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\tconst resetsAtValue = window.resetsAt === undefined ? undefined : Math.floor(window.resetsAt);\n\tconst resetsAt =\n\t\tresetsAtValue !== undefined &&\n\t\tNumber.isSafeInteger(resetsAtValue) &&\n\t\tresetsAtValue > 0 &&\n\t\tresetsAtValue <= maxResetAt\n\t\t\t? resetsAtValue\n\t\t\t: undefined;\n\treturn {\n\t\tusedPercent: clampPercent(window.usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction passiveCredentialCacheKey(identifier: string): string {\n\treturn createHash(\"sha256\").update(identifier).digest(\"base64url\");\n}\n\nfunction freshObservedCodexWindow(\n\tobserved: ObservedCodexWindow | undefined,\n\tnowMs: number,\n): ObservedCodexWindow | undefined {\n\tif (!observed || nowMs - observed.observedAt > PASSIVE_USAGE_TTL_MS) return undefined;\n\tif (observed.window.resetsAt !== undefined && observed.window.resetsAt <= nowMs / 1000) return undefined;\n\treturn observed;\n}\n\nfunction prunePassiveCodexUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveCodexUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveCodexUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction prunePassiveClaudeUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveClaudeUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction passiveCodexSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst entry = passiveCodexUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveCodexUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tconst freshEntry = { primary, secondary };\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, freshEntry);\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction passiveClaudeSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst entry = passiveClaudeUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, { primary, secondary });\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction codexAccountId(token: string): string | undefined {\n\ttry {\n\t\tconst payload = token.split(\".\")[1];\n\t\tif (!payload) return undefined;\n\t\tconst claims = record(JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\")));\n\t\tconst auth = record(claims?.[OPENAI_AUTH_CLAIM]);\n\t\tconst accountId = typeof auth?.chatgpt_account_id === \"string\" ? auth.chatgpt_account_id.trim() : \"\";\n\t\treturn accountId && accountId.length <= 256 ? accountId : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction publicCodexWindow(window: ParsedCodexWindow): CodexUsageWindow {\n\treturn { usedPercent: window.usedPercent, ...(window.resetsAt === undefined ? {} : { resetsAt: window.resetsAt }) };\n}\n\nfunction withLabel(label: string, window: Omit<SubscriptionUsageWindow, \"label\">): SubscriptionUsageWindow {\n\treturn { label, ...window };\n}\n\nfunction shortLabel(value: unknown, index: number): string {\n\tif (typeof value !== \"string\") return `LIMIT${index + 1}`;\n\tconst safe = value\n\t\t.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u206f]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn safe ? safe.toUpperCase().slice(0, 8) : `LIMIT${index + 1}`;\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n\tconst number =\n\t\ttypeof value === \"number\" ? value : typeof value === \"string\" && value.trim() ? Number(value) : Number.NaN;\n\treturn Number.isFinite(number) ? number : undefined;\n}\n\nfunction clampPercent(value: number): number {\n\treturn Number(Math.max(0, Math.min(100, value)).toFixed(2));\n}\n\nfunction near(actual: number | undefined, expected: number): boolean {\n\treturn actual !== undefined && Math.abs(actual - expected) <= WINDOW_TOLERANCE_SECONDS;\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isDefined<T>(value: T | undefined): value is T {\n\treturn value !== undefined;\n}\n\nfunction offline(): boolean {\n\tconst value = process.env.OMK_OFFLINE?.toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider-usage.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAmC,KAAK,yBAAyB,EAAgC,MAAM,QAAQ,CAAC;AACvH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EACX,kBAAkB,EAMlB,yBAAyB,EACzB,uBAAuB,EACvB,uBAAuB,EAEvB,MAAM,2BAA2B,CAAC;AAEnC,YAAY,EACX,kBAAkB,EAClB,yBAAyB,EACzB,uBAAuB,EACvB,uBAAuB,GACvB,MAAM,2BAA2B,CAAC;AAiDnC,KAAK,YAAY,GAAG,IAAI,CAAC,YAAY,EAAE,OAAO,GAAG,eAAe,CAAC,CAAC;AAClE,KAAK,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAkE1F,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,uBAAuB,GAAG,SAAS,CAW5G;AASD,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAErE;AAOD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,QAAQ,SAAgC,GAAG,OAAO,CAGlH;AAED,8EAA8E;AAC9E,wBAAgB,uC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,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 { CLAUDE_CODE_EXTERNAL_USER_AGENT, type ProviderRateLimitSnapshot, type ProviderRateLimitWindow } from \"omk-ai\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type {\n\tCodexUsageSnapshot,\n\tCodexUsageWindow,\n\tCredentialCandidate,\n\tObservedCodexWindow,\n\tParsedCodexWindow,\n\tPassiveUsageEntry,\n\tSubscriptionUsageSnapshot,\n\tSubscriptionUsageSource,\n\tSubscriptionUsageWindow,\n\tUsageKind,\n} from \"./provider-usage-types.ts\";\n\nexport type {\n\tCodexUsageSnapshot,\n\tSubscriptionUsageSnapshot,\n\tSubscriptionUsageSource,\n\tSubscriptionUsageWindow,\n} from \"./provider-usage-types.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\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\t\"meta\",\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\t// Muse Code exposes no public quota endpoint, so the rail shows\n\t// the subscription entry without live usage windows (qwen-oauth precedent).\n\tmeta: source(\"META\", \"unavailable\", [{ provider: \"meta\", oauthOnly: true }]),\n};\n\nfunction source(\n\tlabel: string,\n\tkind: UsageKind,\n\tcredentials: readonly CredentialCandidate[],\n\tttlMs = MINUTE_TTL_MS,\n\tunavailableMessage?: string,\n): SubscriptionUsageSource {\n\treturn { label, kind, credentials, ttlMs, unavailableMessage };\n}\n\nexport function getSubscriptionUsageSource(provider: string | undefined): SubscriptionUsageSource | undefined {\n\tif (!provider) return undefined;\n\tconst configured = SOURCES[provider];\n\tif (configured) return configured;\n\tif (/^openai-codex-\\d+$/.test(provider)) {\n\t\treturn source(\"CODEX\", \"codex\", [\n\t\t\t{ provider, oauthOnly: true },\n\t\t\t{ provider: \"openai-codex\", oauthOnly: true },\n\t\t]);\n\t}\n\treturn undefined;\n}\n\nfunction usageRevisionKey(provider: string): string {\n\tconst kind = getSubscriptionUsageSource(provider)?.kind;\n\tif (kind === \"codex\") return \"codex\";\n\tif (kind === \"claude\") return \"claude\";\n\treturn provider;\n}\n\nexport function getSubscriptionUsageRevision(provider: string): number {\n\treturn subscriptionUsageRevisions.get(usageRevisionKey(provider)) ?? 0;\n}\n\nfunction bumpSubscriptionUsageRevision(provider: string): void {\n\tconst key = usageRevisionKey(provider);\n\tsubscriptionUsageRevisions.set(key, (subscriptionUsageRevisions.get(key) ?? 0) + 1);\n}\n\nexport function supportsSubscriptionUsage(session: UsageSession, provider = session.state.model?.provider): boolean {\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\treturn usageSource?.credentials.some((candidate) => credentialConfigured(session, candidate)) ?? false;\n}\n\n/** Configured quota groups shown in the rail, with the active group first. */\nexport function getConfiguredSubscriptionUsageProviders(session: UsageSession): readonly string[] {\n\tconst activeProvider = session.state.model?.provider;\n\tconst activeSource = getSubscriptionUsageSource(activeProvider);\n\tconst providers = VISIBLE_USAGE_PROVIDERS.filter((provider) => supportsSubscriptionUsage(session, provider));\n\tif (!activeProvider || !activeSource || !supportsSubscriptionUsage(session, activeProvider)) return providers;\n\tconst activeCanonical = providers.find(\n\t\t(provider) => getSubscriptionUsageSource(provider)?.label === activeSource.label,\n\t);\n\tif (!activeCanonical) return [activeProvider, ...providers];\n\treturn [activeCanonical, ...providers.filter((provider) => provider !== activeCanonical)];\n}\n\nexport async function loadSubscriptionUsage(\n\tsession: UsageSession,\n\tfetchImpl: FetchLike = fetch,\n\tprovider = session.state.model?.provider,\n\tqwenCliRunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot | undefined> {\n\tconst model = session.state.model;\n\tconst usageSource = getSubscriptionUsageSource(provider);\n\tif (!model || !usageSource || !supportsSubscriptionUsage(session, provider)) return undefined;\n\tif (usageSource.kind === \"unavailable\") {\n\t\treturn {\n\t\t\tlabel: usageSource.label,\n\t\t\twindows: [],\n\t\t\tmessage: usageSource.unavailableMessage ?? \"quota API unavailable\",\n\t\t};\n\t}\n\tif (offline()) return { label: usageSource.label, windows: [], message: \"offline\" };\n\tif (usageSource.kind === \"qwen-token-plan\") {\n\t\t// The QwenCloud CLI authenticates itself; no OMK-held credential is used.\n\t\treturn await fetchQwenTokenPlanUsage(usageSource.label, qwenCliRunner);\n\t}\n\n\tconst credential = await resolveCredential(session, usageSource);\n\tif (!credential) return { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\n\ttry {\n\t\tswitch (usageSource.kind) {\n\t\t\tcase \"codex\":\n\t\t\t\treturn await fetchCodexUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"claude\":\n\t\t\t\treturn await fetchClaudeUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"kimi\":\n\t\t\t\treturn await fetchKimiUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tcase \"zai\":\n\t\t\t\treturn await fetchZaiUsage(usageSource.label, provider ?? model.provider, credential, fetchImpl);\n\t\t\tcase \"grok\":\n\t\t\t\treturn await fetchGrokUsage(usageSource.label, credential.apiKey, fetchImpl);\n\t\t\tdefault:\n\t\t\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t\t}\n\t} catch {\n\t\treturn { label: usageSource.label, windows: [], message: \"usage unavailable\" };\n\t}\n}\n\nexport function parseCodexUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): CodexUsageSnapshot | undefined {\n\tconst rateLimit = record(record(value)?.rate_limit);\n\tconst primary = codexWindow(rateLimit?.primary_window, nowSeconds);\n\tconst secondary = codexWindow(rateLimit?.secondary_window, nowSeconds);\n\tconst windows = [primary, secondary].filter((window): window is ParsedCodexWindow => window !== undefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tconst fallbackFiveHour = fiveHour ?? (primary?.windowSeconds === undefined ? primary : undefined);\n\tconst fallbackSevenDay = sevenDay ?? (secondary?.windowSeconds === undefined ? secondary : undefined);\n\tif (!fallbackFiveHour && !fallbackSevenDay) return undefined;\n\treturn {\n\t\t...(fallbackFiveHour ? { fiveHour: publicCodexWindow(fallbackFiveHour) } : {}),\n\t\t...(fallbackSevenDay ? { sevenDay: publicCodexWindow(fallbackSevenDay) } : {}),\n\t};\n}\n\nexport function parseClaudeUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst entries = Array.isArray(payload.limits)\n\t\t? payload.limits.slice(0, MAX_USAGE_LIMITS).map(record).filter(isDefined)\n\t\t: [];\n\tconst fiveHour = claudeWindow(payload.five_hour) ?? claudeWindow(entries.find((entry) => entry.kind === \"session\"));\n\tconst sevenDay =\n\t\tclaudeWindow(payload.seven_day) ?? claudeWindow(entries.find((entry) => entry.kind === \"weekly_all\"));\n\tconst windows = [\n\t\tfiveHour ? withLabel(\"5H\", fiveHour) : undefined,\n\t\tsevenDay ? withLabel(\"7D\", sevenDay) : undefined,\n\t].filter(isDefined);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function parseKimiUsageSnapshot(\n\tvalue: unknown,\n\tnowSeconds = Date.now() / 1000,\n): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tif (!payload) return undefined;\n\tconst windows: SubscriptionUsageWindow[] = [];\n\tconst total = usageRatio(record(payload.usage), nowSeconds);\n\tif (total) windows.push(withLabel(\"TOTAL\", total));\n\tif (Array.isArray(payload.limits)) {\n\t\tfor (const rawLimit of payload.limits.slice(0, MAX_USAGE_LIMITS)) {\n\t\t\tconst limit = record(rawLimit);\n\t\t\tif (!limit) continue;\n\t\t\tconst detail = record(limit.detail) ?? limit;\n\t\t\tconst windowData = record(limit.window);\n\t\t\tconst parsed = usageRatio(detail, nowSeconds);\n\t\t\tif (!parsed) continue;\n\t\t\tconst resetsAt = parseReset(windowData, nowSeconds) ?? parsed.resetsAt;\n\t\t\twindows.push({\n\t\t\t\tlabel: durationLabel(windowData) ?? shortLabel(limit.name ?? limit.title ?? limit.scope, windows.length),\n\t\t\t\tusedPercent: parsed.usedPercent,\n\t\t\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t\t\t});\n\t\t}\n\t}\n\treturn windows.length > 0 ? windows.slice(0, 4) : undefined;\n}\n\n/** Result of one `qwencloud` invocation; `missing` means the CLI is not installed. */\nexport type QwenCliResult =\n\t| { readonly kind: \"missing\" }\n\t| { readonly kind: \"ran\"; readonly exitCode: number; readonly stdout: string };\nexport type QwenCliRunner = (args: readonly string[], timeoutMs: number) => Promise<QwenCliResult>;\n\nexport function buildQwenCliEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n\tconst childEnvironment: NodeJS.ProcessEnv = {};\n\tfor (const key of QWEN_CLI_ENV_KEYS) {\n\t\tconst value = source[key];\n\t\tif (value !== undefined) childEnvironment[key] = value;\n\t}\n\treturn childEnvironment;\n}\n\n/** Parse `qwencloud usage summary --format json` → the token-plan 7-day window. */\nexport function parseQwenTokenPlanUsage(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst tokenPlan = record(record(value)?.token_plan);\n\tif (!tokenPlan || tokenPlan.subscribed === false) return undefined;\n\tconst resetsAt = epochSeconds(tokenPlan.resetDate);\n\tlet usedPercent = finiteNumber(tokenPlan.usedPct) ?? finiteNumber(tokenPlan.used_pct);\n\tif (usedPercent === undefined) {\n\t\tconst total = finiteNumber(tokenPlan.totalCredits);\n\t\tconst remaining = finiteNumber(tokenPlan.remainingCredits);\n\t\tif (total !== undefined && remaining !== undefined && total > 0) {\n\t\t\tusedPercent = ((total - remaining) / total) * 100;\n\t\t}\n\t}\n\tif (usedPercent === undefined) return undefined;\n\treturn [{ label: \"7D\", usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport async function fetchQwenTokenPlanUsage(\n\tlabel: string,\n\trunner: QwenCliRunner = runQwenCli,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst unavailable = (message: string): SubscriptionUsageSnapshot => ({ label, windows: [], message });\n\ttry {\n\t\tconst result = await runner(QWEN_CLI_ARGS, QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind === \"missing\") return unavailable(QWEN_CONNECT_HINT);\n\t\tif (result.exitCode === 2) return unavailable(\"run: qwencloud auth login\");\n\t\tif (result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn unavailable(\"usage unavailable\");\n\t\t}\n\t\tconst payload: unknown = JSON.parse(result.stdout);\n\t\tconst tokenPlan = record(record(payload)?.token_plan);\n\t\tif (tokenPlan?.subscribed === false) {\n\t\t\tconst periodTo = record(record(payload)?.period)?.to;\n\t\t\tconst month = typeof periodTo === \"string\" ? periodTo.slice(0, 7) : new Date().toISOString().slice(0, 7);\n\t\t\treturn unavailable(await billingFallbackMessage(runner, month, payload));\n\t\t}\n\t\tconst windows = parseQwenTokenPlanUsage(payload);\n\t\treturn windows ? { label, windows } : unavailable(\"usage unavailable\");\n\t} catch {\n\t\treturn unavailable(\"usage unavailable\");\n\t}\n}\n\n/** No active token plan: fall back to settled billing — subscription charge + PAYG spend — when the CLI reports it. */\nasync function billingFallbackMessage(runner: QwenCliRunner, month: string, summaryPayload: unknown): Promise<string> {\n\ttry {\n\t\tconst result = await runner(qwenBillingArgs(month), QWEN_CLI_TIMEOUT_MS);\n\t\tif (result.kind !== \"ran\" || result.exitCode !== 0 || result.stdout.length > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\treturn paygFallbackMessage(summaryPayload);\n\t\t}\n\t\tconst billing = parseBillingBreakdown(JSON.parse(result.stdout));\n\t\tconst cur = billing.currency === undefined || billing.currency === \"USD\" ? \"$\" : `${billing.currency} `;\n\t\tconst parts: string[] = [];\n\t\tif (billing.subscription !== undefined && billing.subscription > 0) {\n\t\t\tparts.push(`subscription ${cur}${billing.subscription.toFixed(2)}`);\n\t\t}\n\t\tconst payg = billing.payg ?? paygTotalCost(summaryPayload);\n\t\tif (payg !== undefined && payg > 0) parts.push(`PAYG ${cur}${payg.toFixed(2)}`);\n\t\tif (parts.length === 0) return \"no active token plan\";\n\t\treturn `${parts.join(\" · \")} (${month})`;\n\t} catch {\n\t\treturn paygFallbackMessage(summaryPayload);\n\t}\n}\n\n/** Split settled billing rows into the fixed subscription charge vs per-model PAYG spend. */\nfunction parseBillingBreakdown(payload: unknown): { subscription?: number; payg?: number; currency?: string } {\n\tconst data = record(payload);\n\tconst rows = Array.isArray(data?.rows) ? data.rows : [];\n\tlet subscription: number | undefined;\n\tlet payg = 0;\n\tlet paygSeen = false;\n\tfor (const raw of rows) {\n\t\tconst row = record(raw);\n\t\tconst amount = finiteNumber(row?.amount);\n\t\tif (amount === undefined) continue;\n\t\tconst key = typeof row?.groupKey === \"string\" ? row.groupKey : \"\";\n\t\tif (key === \"__tax__\") continue;\n\t\tif (key === \"DIMENSION_FILTER_NULL_VALUE\") subscription = (subscription ?? 0) + amount;\n\t\telse {\n\t\t\tpayg += amount;\n\t\t\tpaygSeen = true;\n\t\t}\n\t}\n\tconst currency = typeof data?.currency === \"string\" ? data.currency : undefined;\n\treturn { subscription, payg: paygSeen ? payg : undefined, currency };\n}\n\nfunction paygTotalCost(payload: unknown): number | undefined {\n\treturn finiteNumber(record(record(record(payload)?.pay_as_you_go)?.total)?.cost);\n}\n\n/** No active token plan: fall back to the account's pay-as-you-go spend when the CLI reports it. */\nfunction paygFallbackMessage(payload: unknown): string {\n\tconst cost = paygTotalCost(payload);\n\tif (cost === undefined) return \"no active token plan\";\n\tconst currency = \"$\";\n\tconst period = record(record(payload)?.period);\n\tconst from = typeof period?.from === \"string\" ? period.from.slice(0, 7) : undefined;\n\treturn `no token plan · PAYG ${currency}${cost.toFixed(2)}${from ? ` (${from})` : \"\"}`;\n}\n\nfunction runQwenCli(args: readonly string[], timeoutMs: number): Promise<QwenCliResult> {\n\treturn new Promise((resolve) => {\n\t\tconst binary = process.env.QWENCLOUD_CLI ?? \"qwencloud\";\n\t\texecFile(\n\t\t\tbinary,\n\t\t\t[...args],\n\t\t\t{\n\t\t\t\ttimeout: timeoutMs,\n\t\t\t\tmaxBuffer: MAX_USAGE_RESPONSE_BYTES,\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv: buildQwenCliEnvironment(process.env),\n\t\t\t},\n\t\t\t(error, stdout) => {\n\t\t\t\tif (!error) {\n\t\t\t\t\tresolve({ kind: \"ran\", exitCode: 0, stdout });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst errno = (error as NodeJS.ErrnoException).code;\n\t\t\t\tif (errno === \"ENOENT\") {\n\t\t\t\t\tresolve({ kind: \"missing\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolve({ kind: \"ran\", exitCode: typeof errno === \"number\" ? errno : 1, stdout: stdout ?? \"\" });\n\t\t\t},\n\t\t);\n\t});\n}\n\nexport function parseGrokUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst config = record(record(value)?.config);\n\tif (!config) return undefined;\n\tconst period = record(config.currentPeriod);\n\tconst resetsAt = epochSeconds(period?.end) ?? epochSeconds(config.billingPeriodEnd);\n\tconst percent = finiteNumber(config.creditUsagePercent);\n\tconst onDemandUsed = finiteNumber(record(config.onDemandUsed)?.val);\n\tconst onDemandCap = finiteNumber(record(config.onDemandCap)?.val);\n\tlet usedPercent = percent;\n\tif (usedPercent === undefined && onDemandUsed !== undefined && onDemandCap !== undefined && onDemandCap > 0) {\n\t\tusedPercent = (onDemandUsed / onDemandCap) * 100;\n\t}\n\tif (usedPercent === undefined && (period || resetsAt !== undefined)) usedPercent = 0;\n\tif (usedPercent === undefined) return undefined;\n\tconst periodType = typeof period?.type === \"string\" ? period.type : \"\";\n\tconst label = periodType.includes(\"MONTHLY\") ? \"30D\" : \"7D\";\n\treturn [{ label, usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) }];\n}\n\nexport function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tconst limits = record(payload?.data)?.limits;\n\tif (payload?.success !== true || !Array.isArray(limits)) return undefined;\n\tconst parsed = limits.slice(0, MAX_USAGE_LIMITS).map(zaiWindow).filter(isDefined);\n\tconst requestWindows = parsed.filter((window) => window.type === \"TIME_LIMIT\" && !window.featureOnly);\n\tconst selected =\n\t\trequestWindows.length > 0 ? requestWindows : parsed.filter((window) => window.type === \"TOKENS_LIMIT\");\n\tselected.sort((left, right) => left.durationSeconds - right.durationSeconds);\n\tconst windows = selected\n\t\t.slice(0, 4)\n\t\t.map(({ type: _type, durationSeconds: _duration, featureOnly: _feature, ...window }) => window);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs = Date.now()): void {\n\tconst accountId = codexAccountId(apiKey);\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0 || (limitId && limitId !== \"codex\")) return;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveCodexUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, next);\n\twhile (passiveCodexUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveCodexUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveCodexUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"openai-codex\");\n}\n\nexport function recordClaudePassiveUsage(\n\tapiKey: string,\n\tsnapshot: ProviderRateLimitSnapshot,\n\tnowMs = Date.now(),\n): void {\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (\n\t\t!apiKey ||\n\t\tapiKey.length > 32_768 ||\n\t\t!Number.isFinite(nowMs) ||\n\t\tnowMs < 0 ||\n\t\t(limitId && limitId !== \"anthropic_unified\")\n\t) {\n\t\treturn;\n\t}\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveClaudeUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, next);\n\twhile (passiveClaudeUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveClaudeUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveClaudeUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"anthropic\");\n}\n\nasync function fetchCodexUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId) return { label, windows: [], message: \"usage unavailable\" };\n\tconst passive = passiveCodexSnapshot(apiKey);\n\tlet polled: CodexUsageSnapshot | undefined;\n\ttry {\n\t\tconst payload = await fetchJson(fetchImpl, CODEX_USAGE_URL, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\t\"User-Agent\": \"omk\",\n\t\t\t},\n\t\t});\n\t\tpolled = parseCodexUsageSnapshot(payload);\n\t} catch (error) {\n\t\tif (!passive) throw error;\n\t}\n\tconst merged: CodexUsageSnapshot = {\n\t\tfiveHour: polled?.fiveHour ?? passive?.fiveHour,\n\t\tsevenDay: polled?.sevenDay ?? passive?.sevenDay,\n\t};\n\tif (!merged.fiveHour && !merged.sevenDay) return { label, windows: [], message: \"usage unavailable\" };\n\treturn {\n\t\tlabel,\n\t\twindows: [\n\t\t\tmerged.fiveHour ? withLabel(\"5H\", merged.fiveHour) : undefined,\n\t\t\tmerged.sevenDay ? withLabel(\"7D\", merged.sevenDay) : undefined,\n\t\t].filter(isDefined),\n\t};\n}\n\nasync function fetchClaudeUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tlet passive = passiveClaudeSnapshot(apiKey);\n\tconst response = await fetchJsonResult(fetchImpl, CLAUDE_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\"User-Agent\": CLAUDE_CODE_EXTERNAL_USER_AGENT,\n\t\t},\n\t});\n\tconst windows = [...(parseClaudeUsageSnapshot(response.payload) ?? [])];\n\tif (response.status === 429 && (!passive?.fiveHour || !passive?.sevenDay)) {\n\t\tawait probeClaudeQuota(apiKey, fetchImpl);\n\t\tpassive = passiveClaudeSnapshot(apiKey);\n\t}\n\tfor (const passiveWindow of [\n\t\tpassive?.fiveHour ? withLabel(\"5H\", passive.fiveHour) : undefined,\n\t\tpassive?.sevenDay ? withLabel(\"7D\", passive.sevenDay) : undefined,\n\t].filter(isDefined)) {\n\t\tif (!windows.some((window) => window.label === passiveWindow.label)) windows.push(passiveWindow);\n\t}\n\treturn windows.length > 0\n\t\t? { label, windows }\n\t\t: { label, windows: [], message: response.status === 429 ? \"rate limited · retry later\" : \"usage unavailable\" };\n}\n\n/**\n * Claude Code 2.1.177 performs the same `quota`/`max_tokens: 1` request during startup.\n * Keep it account-scoped and hourly so a pinned sidebar cannot turn the fallback into polling.\n */\nasync function probeClaudeQuota(apiKey: string, fetchImpl: FetchLike, nowMs = Date.now()): Promise<void> {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return;\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst activeProbe = claudeQuotaProbesInFlight.get(cacheKey);\n\tif (activeProbe) return activeProbe;\n\tconst lastAttempt = claudeQuotaProbeAttempts.get(cacheKey);\n\tif (lastAttempt !== undefined && nowMs - lastAttempt < CLAUDE_QUOTA_PROBE_COOLDOWN_MS) return;\n\tif (claudeQuotaProbesInFlight.size >= MAX_PASSIVE_ACCOUNTS) return;\n\n\tclaudeQuotaProbeAttempts.delete(cacheKey);\n\tclaudeQuotaProbeAttempts.set(cacheKey, nowMs);\n\twhile (claudeQuotaProbeAttempts.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = claudeQuotaProbeAttempts.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tclaudeQuotaProbeAttempts.delete(oldestCacheKey);\n\t}\n\n\tconst probe = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetchImpl(CLAUDE_MESSAGES_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n\t\t\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"User-Agent\": CLAUDE_CODE_EXTERNAL_USER_AGENT,\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel: \"claude-haiku-4-5\",\n\t\t\t\t\tmax_tokens: 1,\n\t\t\t\t\tmessages: [{ role: \"user\", content: \"quota\" }],\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(CLAUDE_QUOTA_PROBE_TIMEOUT_MS),\n\t\t\t});\n\t\t\tconst snapshot = parseClaudeQuotaProbeHeaders(response.headers, nowMs);\n\t\t\tif (snapshot) recordClaudePassiveUsage(apiKey, snapshot, nowMs);\n\t\t\ttry {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t} catch {\n\t\t\t\t// The quota snapshot lives entirely in response headers.\n\t\t\t}\n\t\t} catch {\n\t\t\t// This mirrors Claude Code's best-effort startup quota check.\n\t\t}\n\t})().finally(() => {\n\t\tclaudeQuotaProbesInFlight.delete(cacheKey);\n\t});\n\tclaudeQuotaProbesInFlight.set(cacheKey, probe);\n\treturn probe;\n}\n\nfunction parseClaudeQuotaProbeHeaders(headers: Headers, nowMs: number): ProviderRateLimitSnapshot | undefined {\n\tconst parseWindow = (prefix: \"5h\" | \"7d\", windowSeconds: number): ProviderRateLimitWindow | undefined => {\n\t\tconst rawUtilization = headers.get(`anthropic-ratelimit-unified-${prefix}-utilization`);\n\t\tconst rawReset = headers.get(`anthropic-ratelimit-unified-${prefix}-reset`);\n\t\tif (rawUtilization === null || rawReset === null) return undefined;\n\t\tconst utilization = Number(rawUtilization);\n\t\tconst resetsAt = Number(rawReset);\n\t\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\t\tif (\n\t\t\t!Number.isFinite(utilization) ||\n\t\t\tutilization < 0 ||\n\t\t\tutilization > 1 ||\n\t\t\t!Number.isSafeInteger(resetsAt) ||\n\t\t\tresetsAt <= 0 ||\n\t\t\tresetsAt > maxResetAt\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { usedPercent: Math.round(utilization * 10_000) / 100, windowSeconds, resetsAt };\n\t};\n\tconst primary = parseWindow(\"5h\", FIVE_HOUR_SECONDS);\n\tconst secondary = parseWindow(\"7d\", SEVEN_DAY_SECONDS);\n\treturn primary || secondary ? { limitId: \"anthropic-unified\", primary, secondary } : undefined;\n}\n\nasync function fetchGrokUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, GROK_BILLING_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"x-xai-token-auth\": \"xai-grok-cli\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseGrokUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchKimiUsage(label: string, apiKey: string, fetchImpl: FetchLike): Promise<SubscriptionUsageSnapshot> {\n\tconst payload = await fetchJson(fetchImpl, KIMI_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"KimiCLI/1.5\",\n\t\t\t\"X-Msh-Platform\": \"kimi_cli\",\n\t\t\t\"X-Msh-Version\": \"1.5\",\n\t\t},\n\t});\n\tconst windows = parseKimiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchZaiUsage(\n\tlabel: string,\n\tmodelProvider: string,\n\tcredential: { readonly provider: string; readonly apiKey: string },\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst origin =\n\t\tmodelProvider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zai-coding-cn\" ||\n\t\tcredential.provider === \"zhipu-coding-plan\"\n\t\t\t? \"https://open.bigmodel.cn\"\n\t\t\t: \"https://api.z.ai\";\n\tconst payload = await fetchJson(fetchImpl, `${origin}/api/monitor/usage/quota/limit`, {\n\t\theaders: {\n\t\t\tAuthorization: credential.apiKey,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"User-Agent\": \"omk\",\n\t\t},\n\t});\n\tconst windows = parseZaiUsageSnapshot(payload);\n\treturn windows ? { label, windows } : { label, windows: [], message: \"usage unavailable\" };\n}\n\nasync function fetchJson(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<unknown> {\n\treturn (await fetchJsonResult(fetchImpl, url, init)).payload;\n}\n\nasync function fetchJsonResult(fetchImpl: FetchLike, url: string, init: RequestInit): Promise<FetchJsonResult> {\n\tconst response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(10_000) });\n\tif (!response.ok) return { status: response.status };\n\tconst declaredBytes = Number(response.headers?.get(\"content-length\"));\n\tif (Number.isFinite(declaredBytes) && declaredBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\treturn { status: response.status };\n\t}\n\tif (!response.body || typeof response.body.getReader !== \"function\") {\n\t\treturn { status: response.status, payload: await response.json() };\n\t}\n\n\tconst reader = response.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet totalBytes = 0;\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_USAGE_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\treturn { status: response.status };\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst body = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\ttry {\n\t\treturn { status: response.status, payload: JSON.parse(new TextDecoder().decode(body)) as unknown };\n\t} catch {\n\t\treturn { status: response.status };\n\t}\n}\n\nfunction credentialConfigured(session: UsageSession, candidate: CredentialCandidate): boolean {\n\tif (candidate.oauthOnly) return session.modelRegistry.isUsingOAuthProvider(candidate.provider);\n\tconst status = session.modelRegistry.getProviderAuthStatus(candidate.provider);\n\treturn status.configured || status.source !== undefined;\n}\n\nasync function resolveCredential(\n\tsession: UsageSession,\n\tusageSource: SubscriptionUsageSource,\n): Promise<{ readonly provider: string; readonly apiKey: string } | undefined> {\n\tfor (const candidate of usageSource.credentials) {\n\t\tif (!credentialConfigured(session, candidate)) continue;\n\t\tconst apiKey = await session.modelRegistry.getApiKeyForProvider(candidate.provider);\n\t\tif (apiKey) return { provider: candidate.provider, apiKey };\n\t}\n\treturn undefined;\n}\n\nfunction codexWindow(value: unknown, nowSeconds: number): ParsedCodexWindow | undefined {\n\tconst window = record(value);\n\tconst usedPercent = finiteNumber(window?.used_percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst windowSeconds = finiteNumber(window?.limit_window_seconds);\n\tconst resetAt = finiteNumber(window?.reset_at);\n\tconst resetAfter = finiteNumber(window?.reset_after_seconds);\n\tconst resetsAt = resetAt ?? (resetAfter === undefined ? undefined : nowSeconds + resetAfter);\n\treturn {\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction claudeWindow(value: unknown): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tconst bucket = record(value);\n\tif (!bucket || bucket.is_active === false) return undefined;\n\tconst usedPercent = finiteNumber(bucket.utilization ?? bucket.percent);\n\tif (usedPercent === undefined) return undefined;\n\tconst resetsAt = epochSeconds(bucket.resets_at);\n\treturn { usedPercent: clampPercent(usedPercent), ...(resetsAt === undefined ? {} : { resetsAt }) };\n}\n\nfunction usageRatio(\n\tdata: Record<string, unknown> | undefined,\n\tnowSeconds: number,\n): Omit<SubscriptionUsageWindow, \"label\"> | undefined {\n\tif (!data) return undefined;\n\tconst limit = finiteNumber(data.limit);\n\tlet used = finiteNumber(data.used);\n\tconst remaining = finiteNumber(data.remaining);\n\tif (used === undefined && limit !== undefined && remaining !== undefined) used = limit - remaining;\n\tif (used === undefined || limit === undefined || limit <= 0) return undefined;\n\tconst resetsAt = parseReset(data, nowSeconds);\n\treturn {\n\t\tusedPercent: clampPercent((used / limit) * 100),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiWindow(value: unknown):\n\t| (SubscriptionUsageWindow & {\n\t\t\treadonly type: string;\n\t\t\treadonly durationSeconds: number;\n\t\t\treadonly featureOnly: boolean;\n\t })\n\t| undefined {\n\tconst item = record(value);\n\tif (!item || (item.type !== \"TIME_LIMIT\" && item.type !== \"TOKENS_LIMIT\")) return undefined;\n\tconst percentage = finiteNumber(item.percentage);\n\tconst current = finiteNumber(item.currentValue);\n\tconst limit = finiteNumber(item.usage);\n\tconst usedPercent =\n\t\tpercentage ?? (current !== undefined && limit !== undefined && limit > 0 ? (current / limit) * 100 : undefined);\n\tif (usedPercent === undefined) return undefined;\n\tconst duration = zaiDuration(finiteNumber(item.unit), finiteNumber(item.number));\n\tconst resetsAt = epochSeconds(item.nextResetTime);\n\tconst detailCodes = Array.isArray(item.usageDetails)\n\t\t? item.usageDetails\n\t\t\t\t.map((detail) => record(detail)?.modelCode)\n\t\t\t\t.filter((code): code is string => typeof code === \"string\")\n\t\t: [];\n\treturn {\n\t\ttype: item.type,\n\t\tlabel: duration.label,\n\t\tdurationSeconds: duration.seconds,\n\t\tfeatureOnly: [\"search-prime\", \"web-reader\", \"zread\"].every((code) => detailCodes.includes(code)),\n\t\tusedPercent: clampPercent(usedPercent),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction zaiDuration(unit: number | undefined, countValue: number | undefined): { label: string; seconds: number } {\n\tconst count = countValue && countValue > 0 ? countValue : 1;\n\tif (unit === 3) return { label: `${count}H`, seconds: count * 60 * 60 };\n\tif (unit === 4) return { label: `${count}D`, seconds: count * 24 * 60 * 60 };\n\tif (unit === 5) return { label: count === 1 ? \"30D\" : `${count}MO`, seconds: count * 30 * 24 * 60 * 60 };\n\tif (unit === 6) return { label: \"7D\", seconds: 7 * 24 * 60 * 60 };\n\treturn { label: \"QUOTA\", seconds: Number.POSITIVE_INFINITY };\n}\n\nfunction durationLabel(window: Record<string, unknown> | undefined): string | undefined {\n\tif (!window) return undefined;\n\tconst duration = finiteNumber(window.duration);\n\tconst unit = typeof window.timeUnit === \"string\" ? window.timeUnit.toUpperCase() : \"\";\n\tif (duration === undefined) return undefined;\n\tif (unit.includes(\"MINUTE\")) return duration % 60 === 0 ? `${duration / 60}H` : `${duration}M`;\n\tif (unit.includes(\"HOUR\")) return `${duration}H`;\n\tif (unit.includes(\"DAY\")) return `${duration}D`;\n\tif (unit.includes(\"SECOND\")) return `${duration}S`;\n\treturn undefined;\n}\n\nfunction parseReset(data: Record<string, unknown> | undefined, nowSeconds: number): number | undefined {\n\tif (!data) return undefined;\n\tfor (const key of [\"reset_at\", \"resetAt\", \"reset_time\", \"resetTime\"] as const) {\n\t\tconst parsed = epochSeconds(data[key]);\n\t\tif (parsed !== undefined) return parsed;\n\t}\n\tfor (const key of [\"reset_in\", \"resetIn\", \"ttl\"] as const) {\n\t\tconst seconds = finiteNumber(data[key]);\n\t\tif (seconds !== undefined) return nowSeconds + seconds;\n\t}\n\treturn undefined;\n}\n\nfunction epochSeconds(value: unknown): number | undefined {\n\tconst numeric = finiteNumber(value);\n\tif (numeric !== undefined) return numeric > 1_000_000_000_000 ? numeric / 1000 : numeric;\n\tif (typeof value !== \"string\" || !value.trim()) return undefined;\n\tconst parsed = Date.parse(value);\n\treturn Number.isFinite(parsed) ? parsed / 1000 : undefined;\n}\n\nfunction normalizePassiveCodexWindow(\n\twindow: ProviderRateLimitWindow | undefined,\n\tnowMs: number,\n): ParsedCodexWindow | undefined {\n\tif (!window || !Number.isFinite(window.usedPercent)) return undefined;\n\tconst windowSeconds =\n\t\twindow.windowSeconds !== undefined &&\n\t\tNumber.isFinite(window.windowSeconds) &&\n\t\twindow.windowSeconds > 0 &&\n\t\twindow.windowSeconds <= Number.MAX_SAFE_INTEGER\n\t\t\t? Math.round(window.windowSeconds)\n\t\t\t: undefined;\n\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\tconst resetsAtValue = window.resetsAt === undefined ? undefined : Math.floor(window.resetsAt);\n\tconst resetsAt =\n\t\tresetsAtValue !== undefined &&\n\t\tNumber.isSafeInteger(resetsAtValue) &&\n\t\tresetsAtValue > 0 &&\n\t\tresetsAtValue <= maxResetAt\n\t\t\t? resetsAtValue\n\t\t\t: undefined;\n\treturn {\n\t\tusedPercent: clampPercent(window.usedPercent),\n\t\t...(windowSeconds === undefined ? {} : { windowSeconds }),\n\t\t...(resetsAt === undefined ? {} : { resetsAt }),\n\t};\n}\n\nfunction passiveCredentialCacheKey(identifier: string): string {\n\treturn createHash(\"sha256\").update(identifier).digest(\"base64url\");\n}\n\nfunction freshObservedCodexWindow(\n\tobserved: ObservedCodexWindow | undefined,\n\tnowMs: number,\n): ObservedCodexWindow | undefined {\n\tif (!observed || nowMs - observed.observedAt > PASSIVE_USAGE_TTL_MS) return undefined;\n\tif (observed.window.resetsAt !== undefined && observed.window.resetsAt <= nowMs / 1000) return undefined;\n\treturn observed;\n}\n\nfunction prunePassiveCodexUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveCodexUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveCodexUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction prunePassiveClaudeUsage(nowMs: number): void {\n\tfor (const [cacheKey, entry] of passiveClaudeUsage) {\n\t\tif (!freshObservedCodexWindow(entry.primary, nowMs) && !freshObservedCodexWindow(entry.secondary, nowMs)) {\n\t\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\t}\n\t}\n}\n\nfunction passiveCodexSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst entry = passiveCodexUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveCodexUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tconst freshEntry = { primary, secondary };\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, freshEntry);\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction passiveClaudeSnapshot(apiKey: string, nowMs = Date.now()): CodexUsageSnapshot | undefined {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return undefined;\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst entry = passiveClaudeUsage.get(cacheKey);\n\tif (!entry) return undefined;\n\tconst primary = freshObservedCodexWindow(entry.primary, nowMs);\n\tconst secondary = freshObservedCodexWindow(entry.secondary, nowMs);\n\tif (!primary && !secondary) {\n\t\tpassiveClaudeUsage.delete(cacheKey);\n\t\treturn undefined;\n\t}\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, { primary, secondary });\n\n\tconst windows = [primary?.window, secondary?.window].filter(isDefined);\n\tconst fiveHour = windows.find((window) => near(window.windowSeconds, FIVE_HOUR_SECONDS));\n\tconst sevenDay = windows.find((window) => near(window.windowSeconds, SEVEN_DAY_SECONDS));\n\tif (!fiveHour && !sevenDay) return undefined;\n\treturn {\n\t\t...(fiveHour ? { fiveHour: publicCodexWindow(fiveHour) } : {}),\n\t\t...(sevenDay ? { sevenDay: publicCodexWindow(sevenDay) } : {}),\n\t};\n}\n\nfunction codexAccountId(token: string): string | undefined {\n\ttry {\n\t\tconst payload = token.split(\".\")[1];\n\t\tif (!payload) return undefined;\n\t\tconst claims = record(JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\")));\n\t\tconst auth = record(claims?.[OPENAI_AUTH_CLAIM]);\n\t\tconst accountId = typeof auth?.chatgpt_account_id === \"string\" ? auth.chatgpt_account_id.trim() : \"\";\n\t\treturn accountId && accountId.length <= 256 ? accountId : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction publicCodexWindow(window: ParsedCodexWindow): CodexUsageWindow {\n\treturn { usedPercent: window.usedPercent, ...(window.resetsAt === undefined ? {} : { resetsAt: window.resetsAt }) };\n}\n\nfunction withLabel(label: string, window: Omit<SubscriptionUsageWindow, \"label\">): SubscriptionUsageWindow {\n\treturn { label, ...window };\n}\n\nfunction shortLabel(value: unknown, index: number): string {\n\tif (typeof value !== \"string\") return `LIMIT${index + 1}`;\n\tconst safe = value\n\t\t.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u206f]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn safe ? safe.toUpperCase().slice(0, 8) : `LIMIT${index + 1}`;\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n\tconst number =\n\t\ttypeof value === \"number\" ? value : typeof value === \"string\" && value.trim() ? Number(value) : Number.NaN;\n\treturn Number.isFinite(number) ? number : undefined;\n}\n\nfunction clampPercent(value: number): number {\n\treturn Number(Math.max(0, Math.min(100, value)).toFixed(2));\n}\n\nfunction near(actual: number | undefined, expected: number): boolean {\n\treturn actual !== undefined && Math.abs(actual - expected) <= WINDOW_TOLERANCE_SECONDS;\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction isDefined<T>(value: T | undefined): value is T {\n\treturn value !== undefined;\n}\n\nfunction offline(): boolean {\n\tconst value = process.env.OMK_OFFLINE?.toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n"]}
|
|
@@ -60,6 +60,7 @@ const VISIBLE_USAGE_PROVIDERS = [
|
|
|
60
60
|
"modelstudio-maas",
|
|
61
61
|
"qwen-oauth",
|
|
62
62
|
"xai",
|
|
63
|
+
"meta",
|
|
63
64
|
];
|
|
64
65
|
const SOURCES = {
|
|
65
66
|
"openai-codex": source("CODEX", "codex", [{ provider: "openai-codex", oauthOnly: true }]),
|
|
@@ -88,6 +89,9 @@ const SOURCES = {
|
|
|
88
89
|
{ provider: "zhipu-coding-plan", oauthOnly: true },
|
|
89
90
|
]),
|
|
90
91
|
xai: source("GROK", "grok", [{ provider: "xai", oauthOnly: true }]),
|
|
92
|
+
// Muse Code exposes no public quota endpoint, so the rail shows
|
|
93
|
+
// the subscription entry without live usage windows (qwen-oauth precedent).
|
|
94
|
+
meta: source("META", "unavailable", [{ provider: "meta", oauthOnly: true }]),
|
|
91
95
|
};
|
|
92
96
|
function source(label, kind, credentials, ttlMs = MINUTE_TTL_MS, unavailableMessage) {
|
|
93
97
|
return { label, kind, credentials, ttlMs, unavailableMessage };
|