@ulysseszh/pi-quota-status 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zheng Yongjie and pi-quota-status contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,108 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # pi-quota-status
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@ulysseszh/pi-quota-status.svg)](https://www.npmjs.com/package/@ulysseszh/pi-quota-status)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+
6
+ `pi-quota-status` is a Pi extension package that adds a compact subscription quota/reset indicator beside Pi's default footer statusline.
7
+
8
+ ```text
9
+ 5h 78% 1:57PM · weekly 30% 8:57AM | 28/06
10
+ ```
11
+
12
+ It uses its own `ctx.ui.setStatus("pi-quota-status", ...)` slot, so Pi's default footer stays intact.
13
+
14
+ The extension is intentionally scoped to `/login` subscription models. API-key, environment-key, runtime-key, and custom-key providers are hidden.
15
+
16
+ ## Supported quota sources
17
+
18
+ - Anthropic `/login` models (`anthropic/claude-*`): subscription polling, response-header parsing, and optional fixed-window fallback.
19
+ - OpenAI Codex `/login` models (`openai-codex/*`): subscription polling from the ChatGPT Codex usage endpoint. Returned rate-limit windows are identified by their reported duration: 5h and weekly windows show `5h` and `weekly`, while unclassified or duration-less windows show their `Pri` or `Sec` endpoint role. Local Codex CLI RPC reconciliation handles a healthy-but-stale 5h zero when that window exists.
20
+ - Generic OpenAI-compatible headers: optional named header mappings for OpenAI-compatible providers or proxies.
21
+
22
+ The extension only displays quota for models Pi reports as using `/login` OAuth. If the same provider/model is configured with an API key, it is ignored.
23
+
24
+ ## Requirements
25
+
26
+ - Pi coding agent with extension package support.
27
+ - Node.js `>=22.19.0`.
28
+ - A provider/model authenticated through Pi's `/login` OAuth flow for subscription quota display.
29
+ - Optional: the `codex` CLI on `PATH` for OpenAI Codex stale-zero reconciliation. If unavailable, the extension keeps the last trusted value and retries instead of failing.
30
+
31
+ This package is a Pi extension package, not a standalone CLI.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pi install npm:@ulysseszh/pi-quota-status
37
+ ```
38
+
39
+ Try it for one run:
40
+
41
+ ```bash
42
+ pi -e npm:@ulysseszh/pi-quota-status
43
+ ```
44
+
45
+ From GitHub:
46
+
47
+ ```bash
48
+ pi install git:github.com/zhengyongjie16/pi-quota-status
49
+ ```
50
+
51
+ ## Quick start
52
+
53
+ 1. Install the package with one of the commands above.
54
+ 2. Start Pi with a `/login` subscription model.
55
+ 3. Run `/quota` to view tracked quota rows.
56
+ 4. Run `/quota config` if you want to create or edit adapter settings.
57
+ 5. After editing config, run `/quota reload` in Pi.
58
+
59
+ See [docs/configuration.md](docs/configuration.md) for config schema, adapter examples, fallback quotas, polling details, and UI behavior.
60
+
61
+ ## Commands
62
+
63
+ - `/quota` - table for tracked `/login` subscription models: provider/model, remaining %, reset, source, dimension, freshness.
64
+ - `/quota config` - shows config/state paths and creates a static template config if missing.
65
+ - `/quota reload` - reloads config and state from disk.
66
+ - `/quota debug` - shows adapter/debug status without raw headers.
67
+
68
+ ## Storage and privacy
69
+
70
+ Global files are kept separate:
71
+
72
+ ```text
73
+ ~/.pi/agent/pi-quota-status/config.json
74
+ ~/.pi/agent/pi-quota-status/state.json
75
+ ```
76
+
77
+ `config.json` is user-editable. `state.json` contains parsed quota observations only. Raw provider headers, prompts, responses, and tokens are never persisted.
78
+
79
+ State writes use a small lock plus atomic rename so concurrent Pi sessions merge state instead of overwriting the whole file blindly. `/quota debug` reports sanitized status fields only, not raw provider payloads.
80
+
81
+ ## Configuration
82
+
83
+ If `config.json` is absent, the extension uses built-in defaults at runtime. Running `/quota config` creates an editable template with enabled Anthropic and generic OpenAI header adapters.
84
+
85
+ Anthropic and OpenAI Codex subscription polling do not require config adapter entries; they run whenever the active supported provider/model is using `/login` OAuth and Pi can provide the OAuth token.
86
+
87
+ Read the [configuration reference](docs/configuration.md) for:
88
+
89
+ - Top-level config and adapter fields.
90
+ - Anthropic and generic header adapter examples.
91
+ - Manual fixed-window fallback quotas.
92
+ - Subscription polling behavior, Codex CLI reconciliation, and suspicious OpenAI Codex observation handling.
93
+
94
+ ## UI behavior
95
+
96
+ - Footer status shows only the active model.
97
+ - API-key, environment-key, runtime-key, and custom-key providers are hidden.
98
+ - Subscription models with no quota data show `quota n/a (sub)`.
99
+ - If subscription quota polling fails, the footer shows `quota offline (sub)` in the theme `error` color.
100
+ - Footer colors the `5h` window with Catppuccin Mocha yellow (`#f9e2af`) and weekly windows with red (`#f38ba8`). Other quota dimensions retain threshold colors: warning below 25%, critical below 10% by default. Multi-window status uses the lowest displayed remaining percentage.
101
+ - Quota polling and countdown refresh run once per minute by default.
102
+ - On HTTP 429 with retry/reset data, the footer shows a compact zero-remaining segment such as `Req 0% 1:57PM`.
103
+
104
+ ## Known limitations
105
+
106
+ - Providers and transports vary in whether they expose rate-limit headers to Pi extensions.
107
+ - Header naming differs across providers and proxies; use a generic adapter mapping for custom headers.
108
+ - Token/cost fallback units are reserved for later expansion; v1's automatic fallback deduction is turn-based.
@@ -0,0 +1,192 @@
1
+ # Configuration reference
2
+
3
+ This page covers the advanced configuration and behavior details for `pi-quota-status`. For install and quick-start instructions, see the [README](../README.md).
4
+
5
+ ## Storage
6
+
7
+ Global files are kept separate:
8
+
9
+ ```text
10
+ ~/.pi/agent/pi-quota-status/config.json
11
+ ~/.pi/agent/pi-quota-status/state.json
12
+ ```
13
+
14
+ `config.json` is user-editable. `state.json` contains parsed quota observations only. Raw provider headers, prompts, responses, and tokens are never persisted.
15
+
16
+ State writes use a small lock plus atomic rename so concurrent Pi sessions merge state instead of overwriting the whole file blindly.
17
+
18
+ ## Config schema
19
+
20
+ If `config.json` is absent, the extension uses built-in defaults at runtime. Running `/quota config` creates an editable template file with both an enabled Anthropic adapter and an enabled generic OpenAI header adapter.
21
+
22
+ Anthropic and OpenAI Codex subscription polling do not require config adapter entries. They run whenever the active supported provider/model is using `/login` OAuth and Pi can provide the OAuth token.
23
+
24
+ Top-level fields:
25
+
26
+ ```json
27
+ {
28
+ "version": 1,
29
+ "refreshIntervalMs": 60000,
30
+ "warningThreshold": 25,
31
+ "criticalThreshold": 10,
32
+ "adapters": []
33
+ }
34
+ ```
35
+
36
+ Adapter fields:
37
+
38
+ ```json
39
+ {
40
+ "name": "anthropic",
41
+ "type": "anthropic",
42
+ "enabled": true,
43
+ "provider": "anthropic",
44
+ "models": ["claude-*"],
45
+ "fallback": {
46
+ "enabled": false,
47
+ "dimension": "messages",
48
+ "limit": 45,
49
+ "windowSeconds": 18000,
50
+ "consume": { "unit": "turns", "amount": 1 }
51
+ }
52
+ }
53
+ ```
54
+
55
+ Matching uses `provider` plus model globs. `*` and `?` are supported. Omitted `name`, `type`, `provider`, and `models` fields retain their defaults: `name` uses the resolved type, while `type`, `provider`, and `models` default to `generic`, `*`, and `[*]`. When supplied, `name` and `provider` must be non-empty strings, `type` must be supported, and `models` must be an array whose entries are non-empty model globs. An empty `models` array retains the existing `[*]` default. An invalid adapter is skipped while valid entries continue to load; after `/quota reload`, `/quota debug` lists the load error.
56
+
57
+ ## Adding missing default adapters
58
+
59
+ `/quota config` creates a config only when one does not already exist. If you already have `config.json`, add whichever entry is missing to its `adapters` array, then run `/quota reload`.
60
+
61
+ Anthropic:
62
+
63
+ ```json
64
+ {
65
+ "name": "anthropic",
66
+ "type": "anthropic",
67
+ "enabled": true,
68
+ "provider": "anthropic",
69
+ "models": ["claude-*"]
70
+ }
71
+ ```
72
+
73
+ OpenAI header adapter:
74
+
75
+ ```json
76
+ {
77
+ "name": "openai",
78
+ "type": "generic",
79
+ "enabled": true,
80
+ "provider": "openai*",
81
+ "models": ["gpt-*", "o*", "chatgpt-*"],
82
+ "dimensions": [
83
+ {
84
+ "dimension": "requests",
85
+ "limit": "x-ratelimit-limit-requests",
86
+ "remaining": "x-ratelimit-remaining-requests",
87
+ "reset": "x-ratelimit-reset-requests",
88
+ "retryAfter": "retry-after"
89
+ },
90
+ {
91
+ "dimension": "tokens",
92
+ "limit": "x-ratelimit-limit-tokens",
93
+ "remaining": "x-ratelimit-remaining-tokens",
94
+ "reset": "x-ratelimit-reset-tokens",
95
+ "retryAfter": "retry-after"
96
+ }
97
+ ]
98
+ }
99
+ ```
100
+
101
+ ## Header adapters
102
+
103
+ Header parsing ships with:
104
+
105
+ - `anthropic` - parses common Anthropic rate-limit headers such as request/token/message dimensions.
106
+ - `generic` - parses named header mappings for OpenAI-compatible or proxy headers. The default OpenAI entry is a generic adapter scoped to `provider: "openai*"`.
107
+
108
+ These adapters parse provider response headers only. Anthropic and OpenAI Codex `/login` quota windows are handled by subscription polling, not by the generic OpenAI header adapter.
109
+
110
+ Adapters are evaluated only after Pi reports that the active model uses OAuth subscription auth from `/login`. API-key and custom-key providers are ignored even if their headers match an adapter.
111
+
112
+ Generic mappings use named fields only; no user-supplied JavaScript parser functions are executed.
113
+
114
+ ```json
115
+ {
116
+ "name": "custom-generic",
117
+ "type": "generic",
118
+ "provider": "openai*",
119
+ "models": ["gpt-*", "o*", "chatgpt-*"],
120
+ "dimensions": [
121
+ {
122
+ "dimension": "requests",
123
+ "limit": "x-ratelimit-limit-requests",
124
+ "remaining": "x-ratelimit-remaining-requests",
125
+ "reset": "x-ratelimit-reset-requests",
126
+ "retryAfter": "retry-after"
127
+ },
128
+ {
129
+ "dimension": "tokens",
130
+ "limit": "x-ratelimit-limit-tokens",
131
+ "remaining": "x-ratelimit-remaining-tokens",
132
+ "reset": "x-ratelimit-reset-tokens",
133
+ "retryAfter": "retry-after"
134
+ }
135
+ ]
136
+ }
137
+ ```
138
+
139
+ If multiple provider-header dimensions are present, the compact footer uses the most constrained remaining percentage as a single segment. For polled Anthropic subscription quota, the footer shows short and weekly windows together, such as `5h 78% 1:57PM · weekly 30% 8:57AM | 28/06`. Codex windows are labeled `5h` or `weekly` only when the endpoint reports those durations; otherwise, the footer shows the endpoint role as `Pri` or `Sec` rather than silently omitting or mislabeling that quota.
140
+
141
+ ## Manual fallback
142
+
143
+ When provider headers are absent for a `/login` subscription model, an adapter can declare a fixed-window fallback quota. v1 automatically deducts `turns` after successful provider responses, including internal provider calls that Pi routes through the same response hook.
144
+
145
+ ```json
146
+ {
147
+ "fallback": {
148
+ "enabled": true,
149
+ "dimension": "messages",
150
+ "limit": 45,
151
+ "windowSeconds": 18000,
152
+ "consume": { "unit": "turns", "amount": 1 }
153
+ }
154
+ }
155
+ ```
156
+
157
+ After the reset time passes, fallback observations recompute the next fixed window. Header-only observations are hidden from the footer after their reset time until fresh headers arrive.
158
+
159
+ ## Subscription polling
160
+
161
+ On session start, model selection, `/quota reload`, and every `refreshIntervalMs`, the extension polls known subscription quota sources when Pi can provide an OAuth access token.
162
+
163
+ Currently supported poll sources:
164
+
165
+ - `anthropic` - polls Anthropic's OAuth usage endpoint and maps `five_hour`, `seven_day`, and active-model weekly buckets into quota dimensions. The footer shows `5h` plus the stricter relevant weekly bucket (`weekly`, `Son`, or `Opus`).
166
+ - `openai-codex` - polls the ChatGPT Codex usage endpoint and maps rate-limit windows by their reported duration. Reported 5h and weekly windows use those labels; unclassified or duration-less primary and secondary windows retain the `Pri` and `Sec` endpoint roles. When the OAuth access token contains a ChatGPT account id, the request includes `ChatGPT-Account-Id` to avoid ambiguous account selection.
167
+
168
+ For OpenAI Codex, a sudden 5h drop from high remaining quota to near-zero is treated as suspicious unless the server explicitly reports a block (`allowed: false`, `limit_reached: true`, or a non-null `rate_limit_reached_type`). This includes drops seen immediately after a 5h window rolls over. If the server simultaneously reports healthy metadata (`allowed: true`, `limit_reached: false`, and no reached type), the extension attempts to reconcile the stale `/wham/usage` value with the local Codex CLI JSON-RPC app server (`codex -s read-only -a untrusted app-server`, `account/rateLimits/read`) when `codex` is available on `PATH`. A successful RPC reconciliation replaces the stale 5h/weekly windows and `/quota debug` reports `codex_rpc=yes`. If RPC is unavailable or also returns near-zero, the near-zero value is kept pending and is not accepted merely because a quick retry repeats it. The extension keeps the last trusted value, stores the suspicious observation as pending, and schedules one quick retry. If a confirmable second poll repeats the near-zero value, it is accepted; if a sane value returns, the pending observation is discarded. `/quota debug` reports this using sanitized fields only.
169
+
170
+ Polling is conditional on the model being authenticated through `/login`; the config template is not personalized based on which user is logged in. Provider response headers and fallback observations remain supported for other `/login` subscription providers.
171
+
172
+ ## UI behavior
173
+
174
+ - Footer status shows only the active model.
175
+ - API-key, environment-key, runtime-key, and custom-key providers are hidden.
176
+ - Subscription models with no quota data show `quota n/a (sub)`.
177
+ - If subscription quota polling fails, the footer shows `quota offline (sub)` in the theme `error` color.
178
+ - Footer colors the `5h` window with Catppuccin Mocha yellow (`#f9e2af`) and weekly windows with red (`#f38ba8`). Other quota dimensions retain threshold colors: warning below 25%, critical below 10% by default. Multi-window status uses the lowest displayed remaining percentage.
179
+ - Quota polling and countdown refresh run once per minute by default.
180
+ - On HTTP 429 with retry/reset data, the footer shows a compact zero-remaining segment such as `Req 0% 1:57PM`.
181
+
182
+ ## Privacy notes
183
+
184
+ The extension stores parsed numbers, reset timestamps, and optional pending suspicious-observation metadata only. It does not persist raw headers, prompts, responses, OAuth tokens, account ids, emails, or API keys.
185
+
186
+ `/quota debug` reports adapter names, model ids, status categories, parsed-dimension counts, and sanitized quota-poll flags, not raw provider payloads.
187
+
188
+ ## Known limitations
189
+
190
+ - Providers and transports vary in whether they expose rate-limit headers to Pi extensions.
191
+ - Header naming differs across providers and proxies; use a generic adapter mapping for custom headers.
192
+ - Token/cost fallback units are reserved for later expansion; v1's automatic fallback deduction is turn-based.
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
- {
2
- "name": "@ulysseszh/pi-quota-status",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@ulysseszh/pi-quota-status",
3
+ "version": "0.3.5",
4
+ "description": "Pi extension package that adds compact provider quota/reset status to the footer.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/zhengyongjie16/pi-quota-status.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/zhengyongjie16/pi-quota-status/issues"
13
+ },
14
+ "homepage": "https://github.com/zhengyongjie16/pi-quota-status#readme",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "pi-package",
20
+ "pi-extension",
21
+ "quota",
22
+ "statusline"
23
+ ],
24
+ "main": "./src/index.ts",
25
+ "exports": {
26
+ ".": "./src/index.ts"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "docs",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "pi": {
35
+ "extensions": [
36
+ "./src/index.ts"
37
+ ]
38
+ },
39
+ "scripts": {
40
+ "test": "node -e \"require('node:fs').rmSync('.tmp-test',{recursive:true,force:true})\" && tsc -p tsconfig.test.json && node --test .tmp-test/tests/*.test.js",
41
+ "typecheck": "tsc --noEmit"
42
+ },
43
+ "peerDependencies": {
44
+ "@earendil-works/pi-coding-agent": "*"
45
+ },
46
+ "devDependencies": {
47
+ "@earendil-works/pi-coding-agent": "*",
48
+ "@types/node": "^24.0.0",
49
+ "typescript": "^6.0.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=22.19.0"
53
+ }
54
+ }
@@ -0,0 +1,282 @@
1
+ import type {
2
+ AdapterConfig,
3
+ HeaderFieldMapping,
4
+ HeaderNames,
5
+ ParsedQuotaObservation,
6
+ } from "./types.js";
7
+
8
+ const DEFAULT_RETRY_HEADERS = ["retry-after", "x-retry-after"];
9
+
10
+ const ANTHROPIC_MAPPINGS: HeaderFieldMapping[] = [
11
+ {
12
+ dimension: "requests",
13
+ limit: "anthropic-ratelimit-requests-limit",
14
+ remaining: "anthropic-ratelimit-requests-remaining",
15
+ reset: "anthropic-ratelimit-requests-reset",
16
+ retryAfter: DEFAULT_RETRY_HEADERS,
17
+ },
18
+ {
19
+ dimension: "tokens",
20
+ limit: "anthropic-ratelimit-tokens-limit",
21
+ remaining: "anthropic-ratelimit-tokens-remaining",
22
+ reset: "anthropic-ratelimit-tokens-reset",
23
+ retryAfter: DEFAULT_RETRY_HEADERS,
24
+ },
25
+ {
26
+ dimension: "input_tokens",
27
+ limit: "anthropic-ratelimit-input-tokens-limit",
28
+ remaining: "anthropic-ratelimit-input-tokens-remaining",
29
+ reset: "anthropic-ratelimit-input-tokens-reset",
30
+ retryAfter: DEFAULT_RETRY_HEADERS,
31
+ },
32
+ {
33
+ dimension: "output_tokens",
34
+ limit: "anthropic-ratelimit-output-tokens-limit",
35
+ remaining: "anthropic-ratelimit-output-tokens-remaining",
36
+ reset: "anthropic-ratelimit-output-tokens-reset",
37
+ retryAfter: DEFAULT_RETRY_HEADERS,
38
+ },
39
+ {
40
+ dimension: "messages",
41
+ limit: [
42
+ "anthropic-ratelimit-messages-limit",
43
+ "anthropic-ratelimit-message-limit",
44
+ ],
45
+ remaining: [
46
+ "anthropic-ratelimit-messages-remaining",
47
+ "anthropic-ratelimit-message-remaining",
48
+ ],
49
+ reset: [
50
+ "anthropic-ratelimit-messages-reset",
51
+ "anthropic-ratelimit-message-reset",
52
+ ],
53
+ retryAfter: DEFAULT_RETRY_HEADERS,
54
+ },
55
+ ];
56
+
57
+ const GENERIC_MAPPINGS: HeaderFieldMapping[] = [
58
+ {
59
+ dimension: "requests",
60
+ limit: [
61
+ "x-ratelimit-limit-requests",
62
+ "x-rate-limit-limit",
63
+ "ratelimit-limit",
64
+ ],
65
+ remaining: [
66
+ "x-ratelimit-remaining-requests",
67
+ "x-rate-limit-remaining",
68
+ "ratelimit-remaining",
69
+ ],
70
+ reset: [
71
+ "x-ratelimit-reset-requests",
72
+ "x-rate-limit-reset",
73
+ "ratelimit-reset",
74
+ ],
75
+ retryAfter: DEFAULT_RETRY_HEADERS,
76
+ },
77
+ {
78
+ dimension: "tokens",
79
+ limit: "x-ratelimit-limit-tokens",
80
+ remaining: "x-ratelimit-remaining-tokens",
81
+ reset: "x-ratelimit-reset-tokens",
82
+ retryAfter: DEFAULT_RETRY_HEADERS,
83
+ },
84
+ ];
85
+
86
+ export function normalizeHeaders(
87
+ headers: Record<string, string>,
88
+ ): Record<string, string> {
89
+ const normalized: Record<string, string> = {};
90
+ for (const [name, value] of Object.entries(headers)) {
91
+ normalized[name.toLowerCase()] = String(value).trim();
92
+ }
93
+ return normalized;
94
+ }
95
+
96
+ export function getAdapterMappings(
97
+ adapter: AdapterConfig,
98
+ ): HeaderFieldMapping[] {
99
+ const configured = [
100
+ ...(Array.isArray(adapter.dimensions) ? adapter.dimensions : []),
101
+ ...normalizeHeaderMappings(adapter.headers),
102
+ ];
103
+ if (configured.length > 0) return configured;
104
+ return adapter.type === "anthropic" ? ANTHROPIC_MAPPINGS : GENERIC_MAPPINGS;
105
+ }
106
+
107
+ export function parseQuotaHeaders(
108
+ headers: Record<string, string>,
109
+ adapter: AdapterConfig,
110
+ now = Date.now(),
111
+ status = 200,
112
+ ): ParsedQuotaObservation | undefined {
113
+ const normalized = normalizeHeaders(headers);
114
+ const mappings = getAdapterMappings(adapter);
115
+ const dimensions = mappings
116
+ .map((mapping) => parseDimension(normalized, mapping, now))
117
+ .filter(
118
+ (dimension) =>
119
+ dimension.limit !== undefined ||
120
+ dimension.remaining !== undefined ||
121
+ dimension.resetAt !== undefined,
122
+ );
123
+ const retryAt = parseRetryAfterFromMappings(normalized, mappings, now);
124
+
125
+ if (status === 429) {
126
+ if (dimensions.length === 0) {
127
+ const resetAt =
128
+ retryAt ??
129
+ parseRetryAfterFromNames(normalized, DEFAULT_RETRY_HEADERS, now);
130
+ return {
131
+ resetAt,
132
+ dimensions: [
133
+ {
134
+ name: "requests",
135
+ limit: 1,
136
+ remaining: 0,
137
+ resetAt,
138
+ },
139
+ ],
140
+ };
141
+ }
142
+ const rateLimited = dimensions.map((dimension) => ({
143
+ ...dimension,
144
+ limit: dimension.limit ?? 1,
145
+ remaining: 0,
146
+ resetAt: dimension.resetAt ?? retryAt,
147
+ }));
148
+ return { resetAt: retryAt, dimensions: rateLimited };
149
+ }
150
+
151
+ const valid = dimensions.filter(
152
+ (dimension) =>
153
+ dimension.limit !== undefined && dimension.remaining !== undefined,
154
+ );
155
+ if (valid.length === 0) return undefined;
156
+ return { resetAt: retryAt, dimensions: valid };
157
+ }
158
+
159
+ export function parseNumberHeader(
160
+ value: string | undefined,
161
+ ): number | undefined {
162
+ if (!value) return undefined;
163
+ const match = new RegExp(/-?\d+(?:\.\d+)?/).exec(value);
164
+ if (!match) return undefined;
165
+ const parsed = Number(match[0]);
166
+ return Number.isFinite(parsed) ? parsed : undefined;
167
+ }
168
+
169
+ export function parseResetTime(
170
+ value: string | undefined,
171
+ now = Date.now(),
172
+ ): number | undefined {
173
+ if (!value) return undefined;
174
+ const trimmed = value.trim();
175
+ if (!trimmed) return undefined;
176
+ const duration = parseDurationMs(trimmed);
177
+ if (duration !== undefined) return now + duration;
178
+ const numeric = Number(trimmed);
179
+ if (Number.isFinite(numeric)) {
180
+ if (numeric > 1_000_000_000_000) return numeric;
181
+ if (numeric > 1_000_000_000) return numeric * 1000;
182
+ return now + numeric * 1000;
183
+ }
184
+ const parsedDate = Date.parse(trimmed);
185
+ return Number.isFinite(parsedDate) ? parsedDate : undefined;
186
+ }
187
+
188
+ export function parseDurationMs(value: string): number | undefined {
189
+ const compact = value.trim().toLowerCase();
190
+ if (!compact) return undefined;
191
+ let index = 0;
192
+ let total = 0;
193
+ const matcher = /(\d+(?:\.\d+)?)(ms|s|m|h|d)/y;
194
+ let match: RegExpExecArray | null;
195
+ while ((match = matcher.exec(compact)) !== null) {
196
+ if (match.index !== index) return undefined;
197
+ index = matcher.lastIndex;
198
+ const amount = Number(match[1]);
199
+ const unit = match[2];
200
+ if (!Number.isFinite(amount)) return undefined;
201
+ total += amount * durationUnitMs(unit);
202
+ }
203
+ return index === compact.length && index > 0 ? total : undefined;
204
+ }
205
+
206
+ function durationUnitMs(unit: string | undefined): number {
207
+ switch (unit) {
208
+ case "ms":
209
+ return 1;
210
+ case "s":
211
+ return 1000;
212
+ case "m":
213
+ return 60_000;
214
+ case "h":
215
+ return 3_600_000;
216
+ case "d":
217
+ return 86_400_000;
218
+ default:
219
+ return 0;
220
+ }
221
+ }
222
+
223
+ function parseDimension(
224
+ headers: Record<string, string>,
225
+ mapping: HeaderFieldMapping,
226
+ now: number,
227
+ ) {
228
+ const retryNames =
229
+ mapping.retryAfter ?? mapping["retry-after"] ?? DEFAULT_RETRY_HEADERS;
230
+ return {
231
+ name: mapping.dimension ?? "requests",
232
+ limit: parseNumberHeader(getFirstHeader(headers, mapping.limit)),
233
+ remaining: parseNumberHeader(getFirstHeader(headers, mapping.remaining)),
234
+ resetAt:
235
+ parseResetTime(getFirstHeader(headers, mapping.reset), now) ??
236
+ parseRetryAfterFromNames(headers, retryNames, now),
237
+ };
238
+ }
239
+
240
+ function parseRetryAfterFromMappings(
241
+ headers: Record<string, string>,
242
+ mappings: HeaderFieldMapping[],
243
+ now: number,
244
+ ): number | undefined {
245
+ for (const mapping of mappings) {
246
+ const value = parseRetryAfterFromNames(
247
+ headers,
248
+ mapping.retryAfter ?? mapping["retry-after"] ?? DEFAULT_RETRY_HEADERS,
249
+ now,
250
+ );
251
+ if (value !== undefined) return value;
252
+ }
253
+ return parseRetryAfterFromNames(headers, DEFAULT_RETRY_HEADERS, now);
254
+ }
255
+
256
+ function parseRetryAfterFromNames(
257
+ headers: Record<string, string>,
258
+ names: HeaderNames | undefined,
259
+ now: number,
260
+ ): number | undefined {
261
+ return parseResetTime(getFirstHeader(headers, names), now);
262
+ }
263
+
264
+ function getFirstHeader(
265
+ headers: Record<string, string>,
266
+ names: HeaderNames | undefined,
267
+ ): string | undefined {
268
+ if (!names) return undefined;
269
+ const list = Array.isArray(names) ? names : [names];
270
+ for (const name of list) {
271
+ const value = headers[name.toLowerCase()];
272
+ if (value !== undefined && value !== "") return value;
273
+ }
274
+ return undefined;
275
+ }
276
+
277
+ function normalizeHeaderMappings(
278
+ headers: AdapterConfig["headers"],
279
+ ): HeaderFieldMapping[] {
280
+ if (!headers) return [];
281
+ return Array.isArray(headers) ? headers : [headers];
282
+ }