open-multi-agent-kit 0.94.1 → 0.95.1
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 +49 -1
- package/README.md +100 -647
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +11 -11
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +27 -2
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +239 -56
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/context-budget-v2-cache-invalidation.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-invalidation.js +1 -1
- package/dist/core/context-budget-v2-cache-invalidation.js.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.d.ts +5 -1
- package/dist/core/context-budget-v2-cache-provider.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.js +37 -7
- package/dist/core/context-budget-v2-cache-provider.js.map +1 -1
- package/dist/core/context-budget-v2-cache-telemetry.d.ts +1 -1
- package/dist/core/context-budget-v2-cache-telemetry.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-telemetry.js +2 -1
- package/dist/core/context-budget-v2-cache-telemetry.js.map +1 -1
- package/dist/core/context-budget-v2-cache.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache.js +3 -0
- package/dist/core/context-budget-v2-cache.js.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.js +39 -5
- package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-representation-cache.d.ts.map +1 -1
- package/dist/core/context-budget-v2-representation-cache.js +4 -3
- package/dist/core/context-budget-v2-representation-cache.js.map +1 -1
- package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
- package/dist/core/context-budget-v2-selection.js +4 -0
- package/dist/core/context-budget-v2-selection.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +3 -0
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/github-repository.d.ts +3 -0
- package/dist/core/github-repository.d.ts.map +1 -0
- package/dist/core/github-repository.js +3 -0
- package/dist/core/github-repository.js.map +1 -0
- package/dist/core/headroom.d.ts.map +1 -1
- package/dist/core/headroom.js +7 -2
- package/dist/core/headroom.js.map +1 -1
- package/dist/core/model-registry.d.ts +3 -3
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +9 -8
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/provider-usage.d.ts +48 -0
- package/dist/core/provider-usage.d.ts.map +1 -0
- package/dist/core/provider-usage.js +780 -0
- package/dist/core/provider-usage.js.map +1 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +10 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-termination.d.ts.map +1 -1
- package/dist/core/session-termination.js +8 -1
- package/dist/core/session-termination.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +15 -17
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills-catalog-cache.d.ts +1 -0
- package/dist/core/skills-catalog-cache.d.ts.map +1 -1
- package/dist/core/skills-catalog-cache.js +42 -11
- package/dist/core/skills-catalog-cache.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -4
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/read.d.ts +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/index.d.ts +1 -0
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +1 -0
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +5 -3
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-account-selector.d.ts +16 -0
- package/dist/modes/interactive/components/oauth-account-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/oauth-account-selector.js +61 -0
- package/dist/modes/interactive/components/oauth-account-selector.js.map +1 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +25 -4
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-sidebar.d.ts +21 -1
- package/dist/modes/interactive/components/status-sidebar.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-sidebar.js +165 -6
- package/dist/modes/interactive/components/status-sidebar.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +89 -60
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +2 -2
- package/dist/utils/image-resize-core.js.map +1 -1
- package/docs/development.md +3 -2
- package/docs/providers.md +19 -4
- package/docs/settings.md +9 -20
- package/docs/usage.md +10 -10
- 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/subagent/agents/planner.md +1 -1
- package/examples/extensions/subagent/agents/reviewer.md +1 -1
- package/examples/extensions/subagent/agents/scout.md +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 +24 -24
- package/package.json +6 -6
- package/dist/core/context-budget-compressors.d.ts +0 -50
- package/dist/core/context-budget-compressors.d.ts.map +0 -1
- package/dist/core/context-budget-compressors.js +0 -166
- package/dist/core/context-budget-compressors.js.map +0 -1
- package/dist/core/github-star-nudge.d.ts +0 -15
- package/dist/core/github-star-nudge.d.ts.map +0 -1
- package/dist/core/github-star-nudge.js +0 -21
- package/dist/core/github-star-nudge.js.map +0 -1
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ProviderRateLimitSnapshot } from "omk-ai";
|
|
2
|
+
import type { AgentSession } from "./agent-session.ts";
|
|
3
|
+
export type SubscriptionUsageWindow = {
|
|
4
|
+
readonly label: string;
|
|
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" | "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
|
+
};
|
|
33
|
+
type UsageSession = Pick<AgentSession, "state" | "modelRegistry">;
|
|
34
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
35
|
+
export declare function getSubscriptionUsageSource(provider: string | undefined): SubscriptionUsageSource | undefined;
|
|
36
|
+
export declare function getSubscriptionUsageRevision(provider: string): number;
|
|
37
|
+
export declare function supportsSubscriptionUsage(session: UsageSession, provider?: string): boolean;
|
|
38
|
+
/** Configured quota groups shown in the rail, with the active group first. */
|
|
39
|
+
export declare function getConfiguredSubscriptionUsageProviders(session: UsageSession): readonly string[];
|
|
40
|
+
export declare function loadSubscriptionUsage(session: UsageSession, fetchImpl?: FetchLike, provider?: string): Promise<SubscriptionUsageSnapshot | undefined>;
|
|
41
|
+
export declare function parseCodexUsageSnapshot(value: unknown, nowSeconds?: number): CodexUsageSnapshot | undefined;
|
|
42
|
+
export declare function parseClaudeUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined;
|
|
43
|
+
export declare function parseKimiUsageSnapshot(value: unknown, nowSeconds?: number): readonly SubscriptionUsageWindow[] | undefined;
|
|
44
|
+
export declare function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined;
|
|
45
|
+
export declare function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs?: number): void;
|
|
46
|
+
export declare function recordClaudePassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs?: number): void;
|
|
47
|
+
export {};
|
|
48
|
+
//# sourceMappingURL=provider-usage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-usage.d.ts","sourceRoot":"","sources":["../../src/core/provider-usage.ts"],"names":[],"mappings":"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","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { ProviderRateLimitSnapshot, ProviderRateLimitWindow } from \"omk-ai\";\nimport type { AgentSession } from \"./agent-session.ts\";\n\nconst FIVE_HOUR_SECONDS = 5 * 60 * 60;\nconst SEVEN_DAY_SECONDS = 7 * 24 * 60 * 60;\nconst WINDOW_TOLERANCE_SECONDS = 120;\nconst CODEX_USAGE_URL = \"https://chatgpt.com/backend-api/wham/usage\";\nconst CLAUDE_USAGE_URL = \"https://api.anthropic.com/api/oauth/usage\";\nconst CLAUDE_MESSAGES_URL = \"https://api.anthropic.com/v1/messages\";\nconst KIMI_USAGE_URL = \"https://api.kimi.com/coding/v1/usages\";\nconst 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;\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\" | \"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\"grok-oauth-proxy\",\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\"modelstudio-maas\": source(\n\t\t\"QWEN TOKEN PLAN\",\n\t\t\"unavailable\",\n\t\t[{ provider: \"modelstudio-maas\", oauthOnly: false }],\n\t\tMINUTE_TTL_MS,\n\t\t\"console-only quota\",\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\t\"grok-oauth-proxy\": source(\"GROK\", \"unavailable\", [\n\t\t{ provider: \"grok-oauth-proxy\", oauthOnly: true },\n\t\t{ provider: \"xai\", oauthOnly: true },\n\t]),\n\txai: source(\"GROK\", \"unavailable\", [{ 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): 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\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}\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\nexport function parseZaiUsageSnapshot(value: unknown): readonly SubscriptionUsageWindow[] | undefined {\n\tconst payload = record(value);\n\tconst limits = record(payload?.data)?.limits;\n\tif (payload?.success !== true || !Array.isArray(limits)) return undefined;\n\tconst parsed = limits.slice(0, MAX_USAGE_LIMITS).map(zaiWindow).filter(isDefined);\n\tconst requestWindows = parsed.filter((window) => window.type === \"TIME_LIMIT\" && !window.featureOnly);\n\tconst selected =\n\t\trequestWindows.length > 0 ? requestWindows : parsed.filter((window) => window.type === \"TOKENS_LIMIT\");\n\tselected.sort((left, right) => left.durationSeconds - right.durationSeconds);\n\tconst windows = selected\n\t\t.slice(0, 4)\n\t\t.map(({ type: _type, durationSeconds: _duration, featureOnly: _feature, ...window }) => window);\n\treturn windows.length > 0 ? windows : undefined;\n}\n\nexport function recordCodexPassiveUsage(apiKey: string, snapshot: ProviderRateLimitSnapshot, nowMs = Date.now()): void {\n\tconst accountId = codexAccountId(apiKey);\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (!accountId || !Number.isFinite(nowMs) || nowMs < 0 || (limitId && limitId !== \"codex\")) return;\n\tprunePassiveCodexUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(accountId);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveCodexUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveCodexUsage.delete(cacheKey);\n\tpassiveCodexUsage.set(cacheKey, next);\n\twhile (passiveCodexUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveCodexUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveCodexUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"openai-codex\");\n}\n\nexport function recordClaudePassiveUsage(\n\tapiKey: string,\n\tsnapshot: ProviderRateLimitSnapshot,\n\tnowMs = Date.now(),\n): void {\n\tconst limitId = snapshot.limitId?.trim().toLowerCase().replace(/-/g, \"_\");\n\tif (\n\t\t!apiKey ||\n\t\tapiKey.length > 32_768 ||\n\t\t!Number.isFinite(nowMs) ||\n\t\tnowMs < 0 ||\n\t\t(limitId && limitId !== \"anthropic_unified\")\n\t) {\n\t\treturn;\n\t}\n\tprunePassiveClaudeUsage(nowMs);\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst primary = normalizePassiveCodexWindow(snapshot.primary, nowMs);\n\tconst secondary = normalizePassiveCodexWindow(snapshot.secondary, nowMs);\n\tif (!primary && !secondary) return;\n\n\tconst previous = passiveClaudeUsage.get(cacheKey);\n\tconst next: PassiveUsageEntry = {\n\t\tprimary: primary ? { window: primary, observedAt: nowMs } : freshObservedCodexWindow(previous?.primary, nowMs),\n\t\tsecondary: secondary\n\t\t\t? { window: secondary, observedAt: nowMs }\n\t\t\t: freshObservedCodexWindow(previous?.secondary, nowMs),\n\t};\n\tpassiveClaudeUsage.delete(cacheKey);\n\tpassiveClaudeUsage.set(cacheKey, next);\n\twhile (passiveClaudeUsage.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = passiveClaudeUsage.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tpassiveClaudeUsage.delete(oldestCacheKey);\n\t}\n\tbumpSubscriptionUsageRevision(\"anthropic\");\n}\n\nasync function fetchCodexUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tconst accountId = codexAccountId(apiKey);\n\tif (!accountId) return { label, windows: [], message: \"usage unavailable\" };\n\tconst passive = passiveCodexSnapshot(apiKey);\n\tlet polled: CodexUsageSnapshot | undefined;\n\ttry {\n\t\tconst payload = await fetchJson(fetchImpl, CODEX_USAGE_URL, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"chatgpt-account-id\": accountId,\n\t\t\t\t\"User-Agent\": \"omk\",\n\t\t\t},\n\t\t});\n\t\tpolled = parseCodexUsageSnapshot(payload);\n\t} catch (error) {\n\t\tif (!passive) throw error;\n\t}\n\tconst merged: CodexUsageSnapshot = {\n\t\tfiveHour: polled?.fiveHour ?? passive?.fiveHour,\n\t\tsevenDay: polled?.sevenDay ?? passive?.sevenDay,\n\t};\n\tif (!merged.fiveHour && !merged.sevenDay) return { label, windows: [], message: \"usage unavailable\" };\n\treturn {\n\t\tlabel,\n\t\twindows: [\n\t\t\tmerged.fiveHour ? withLabel(\"5H\", merged.fiveHour) : undefined,\n\t\t\tmerged.sevenDay ? withLabel(\"7D\", merged.sevenDay) : undefined,\n\t\t].filter(isDefined),\n\t};\n}\n\nasync function fetchClaudeUsage(\n\tlabel: string,\n\tapiKey: string,\n\tfetchImpl: FetchLike,\n): Promise<SubscriptionUsageSnapshot> {\n\tlet passive = passiveClaudeSnapshot(apiKey);\n\tconst response = await fetchJsonResult(fetchImpl, CLAUDE_USAGE_URL, {\n\t\theaders: {\n\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\tAccept: \"application/json\",\n\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\"User-Agent\": \"claude-cli/2.1.177 (external, cli)\",\n\t\t},\n\t});\n\tconst windows = [...(parseClaudeUsageSnapshot(response.payload) ?? [])];\n\tif (response.status === 429 && (!passive?.fiveHour || !passive?.sevenDay)) {\n\t\tawait probeClaudeQuota(apiKey, fetchImpl);\n\t\tpassive = passiveClaudeSnapshot(apiKey);\n\t}\n\tfor (const passiveWindow of [\n\t\tpassive?.fiveHour ? withLabel(\"5H\", passive.fiveHour) : undefined,\n\t\tpassive?.sevenDay ? withLabel(\"7D\", passive.sevenDay) : undefined,\n\t].filter(isDefined)) {\n\t\tif (!windows.some((window) => window.label === passiveWindow.label)) windows.push(passiveWindow);\n\t}\n\treturn windows.length > 0\n\t\t? { label, windows }\n\t\t: { label, windows: [], message: response.status === 429 ? \"rate limited · retry later\" : \"usage unavailable\" };\n}\n\n/**\n * Claude Code 2.1.177 performs the same `quota`/`max_tokens: 1` request during startup.\n * Keep it account-scoped and hourly so a pinned sidebar cannot turn the fallback into polling.\n */\nasync function probeClaudeQuota(apiKey: string, fetchImpl: FetchLike, nowMs = Date.now()): Promise<void> {\n\tif (!apiKey || apiKey.length > 32_768 || !Number.isFinite(nowMs) || nowMs < 0) return;\n\tconst cacheKey = passiveCredentialCacheKey(apiKey);\n\tconst activeProbe = claudeQuotaProbesInFlight.get(cacheKey);\n\tif (activeProbe) return activeProbe;\n\tconst lastAttempt = claudeQuotaProbeAttempts.get(cacheKey);\n\tif (lastAttempt !== undefined && nowMs - lastAttempt < CLAUDE_QUOTA_PROBE_COOLDOWN_MS) return;\n\tif (claudeQuotaProbesInFlight.size >= MAX_PASSIVE_ACCOUNTS) return;\n\n\tclaudeQuotaProbeAttempts.delete(cacheKey);\n\tclaudeQuotaProbeAttempts.set(cacheKey, nowMs);\n\twhile (claudeQuotaProbeAttempts.size > MAX_PASSIVE_ACCOUNTS) {\n\t\tconst oldestCacheKey = claudeQuotaProbeAttempts.keys().next().value;\n\t\tif (oldestCacheKey === undefined) break;\n\t\tclaudeQuotaProbeAttempts.delete(oldestCacheKey);\n\t}\n\n\tconst probe = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetchImpl(CLAUDE_MESSAGES_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n\t\t\t\t\t\"anthropic-beta\": \"claude-code-20250219,oauth-2025-04-20\",\n\t\t\t\t\t\"anthropic-dangerous-direct-browser-access\": \"true\",\n\t\t\t\t\t\"User-Agent\": \"claude-cli/2.1.177 (external, cli)\",\n\t\t\t\t\t\"x-app\": \"cli\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel: \"claude-haiku-4-5\",\n\t\t\t\t\tmax_tokens: 1,\n\t\t\t\t\tmessages: [{ role: \"user\", content: \"quota\" }],\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(CLAUDE_QUOTA_PROBE_TIMEOUT_MS),\n\t\t\t});\n\t\t\tconst snapshot = parseClaudeQuotaProbeHeaders(response.headers, nowMs);\n\t\t\tif (snapshot) recordClaudePassiveUsage(apiKey, snapshot, nowMs);\n\t\t\ttry {\n\t\t\t\tawait response.body?.cancel();\n\t\t\t} catch {\n\t\t\t\t// The quota snapshot lives entirely in response headers.\n\t\t\t}\n\t\t} catch {\n\t\t\t// This mirrors Claude Code's best-effort startup quota check.\n\t\t}\n\t})().finally(() => {\n\t\tclaudeQuotaProbesInFlight.delete(cacheKey);\n\t});\n\tclaudeQuotaProbesInFlight.set(cacheKey, probe);\n\treturn probe;\n}\n\nfunction parseClaudeQuotaProbeHeaders(headers: Headers, nowMs: number): ProviderRateLimitSnapshot | undefined {\n\tconst parseWindow = (prefix: \"5h\" | \"7d\", windowSeconds: number): ProviderRateLimitWindow | undefined => {\n\t\tconst rawUtilization = headers.get(`anthropic-ratelimit-unified-${prefix}-utilization`);\n\t\tconst rawReset = headers.get(`anthropic-ratelimit-unified-${prefix}-reset`);\n\t\tif (rawUtilization === null || rawReset === null) return undefined;\n\t\tconst utilization = Number(rawUtilization);\n\t\tconst resetsAt = Number(rawReset);\n\t\tconst maxResetAt = nowMs / 1000 + 10 * 365 * 24 * 60 * 60;\n\t\tif (\n\t\t\t!Number.isFinite(utilization) ||\n\t\t\tutilization < 0 ||\n\t\t\tutilization > 1 ||\n\t\t\t!Number.isSafeInteger(resetsAt) ||\n\t\t\tresetsAt <= 0 ||\n\t\t\tresetsAt > maxResetAt\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn { usedPercent: Math.round(utilization * 10_000) / 100, windowSeconds, resetsAt };\n\t};\n\tconst primary = parseWindow(\"5h\", FIVE_HOUR_SECONDS);\n\tconst secondary = parseWindow(\"7d\", SEVEN_DAY_SECONDS);\n\treturn primary || secondary ? { limitId: \"anthropic-unified\", primary, secondary } : undefined;\n}\n\nasync function 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"]}
|