@aeondave/pi-theme-1337 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +263 -0
- package/LICENSE +21 -0
- package/README.md +166 -2
- package/assets/banner.png +0 -0
- package/assets/palettes.gif +0 -0
- package/docs/architecture.md +172 -0
- package/docs/configuration.md +103 -0
- package/docs/palette-design.md +51 -0
- package/docs/theme-motion.md +88 -0
- package/package.json +68 -4
- package/src/avatar.ts +174 -0
- package/src/background.ts +82 -0
- package/src/config.ts +400 -0
- package/src/diff-spans.ts +77 -0
- package/src/draft.ts +10 -0
- package/src/editor.ts +545 -0
- package/src/format.ts +464 -0
- package/src/frame.ts +380 -0
- package/src/git-status-cache.ts +198 -0
- package/src/git-status-reader.ts +28 -0
- package/src/git-status.ts +72 -0
- package/src/header-controller.ts +58 -0
- package/src/header.ts +151 -0
- package/src/index.ts +1264 -0
- package/src/quota.ts +581 -0
- package/src/redraw-guard.ts +79 -0
- package/src/run-summary.ts +623 -0
- package/src/spinner.ts +72 -0
- package/src/status-style.ts +26 -0
- package/src/terminal-title.ts +67 -0
- package/src/tool-activity.ts +216 -0
- package/src/tool-adapter.ts +491 -0
- package/src/tool-groups.ts +192 -0
- package/src/tool-lexicon.ts +200 -0
- package/src/tool-view.ts +788 -0
- package/src/width.ts +246 -0
- package/themes/1337-amber.json +94 -0
- package/themes/1337-amber.pi1337 +3 -0
- package/themes/1337-cosmos.json +94 -0
- package/themes/1337-cosmos.pi1337 +3 -0
- package/themes/1337-cyber.json +94 -0
- package/themes/1337-cyber.pi1337 +3 -0
- package/themes/1337-cyberpunk-2077-edgerunner.json +94 -0
- package/themes/1337-cyberpunk-2077-edgerunner.pi1337 +7 -0
- package/themes/1337-cyberpunk-2077.json +94 -0
- package/themes/1337-cyberpunk-2077.pi1337 +7 -0
- package/themes/1337-fallout.json +94 -0
- package/themes/1337-fallout.pi1337 +4 -0
- package/themes/1337-ice.json +94 -0
- package/themes/1337-ice.pi1337 +3 -0
- package/themes/1337-magma.json +94 -0
- package/themes/1337-magma.pi1337 +1 -0
- package/themes/1337-neon.json +94 -0
- package/themes/1337-neon.pi1337 +3 -0
- package/themes/1337-poison.json +94 -0
- package/themes/1337-poison.pi1337 +3 -0
- package/themes/1337-skynet-dark.json +94 -0
- package/themes/1337-skynet-dark.pi1337 +4 -0
- package/themes/1337-skynet.json +94 -0
- package/themes/1337-skynet.pi1337 +4 -0
- package/themes/1337.json +95 -0
- package/themes/1337.pi1337 +3 -0
package/src/quota.ts
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure subscription-quota tracking for the status row.
|
|
3
|
+
*
|
|
4
|
+
* Some providers say, on a response, how much of a subscription's rate window
|
|
5
|
+
* is used. This module turns what Pi already hands extensions into the two or
|
|
6
|
+
* three numbers the row prints. It makes no request of its own, starts no
|
|
7
|
+
* timer and reads no clock: time is injected, and every exported function is
|
|
8
|
+
* total — no input makes one throw.
|
|
9
|
+
*
|
|
10
|
+
* Three observations feed one state, kept per provider:
|
|
11
|
+
*
|
|
12
|
+
* - response headers (`after_provider_response`), in one of two vocabularies
|
|
13
|
+
* chosen by the model's api and read by exact name: Anthropic's
|
|
14
|
+
* `anthropic-ratelimit-unified-{5h,7d}-*` (a FRACTION used, reset in epoch
|
|
15
|
+
* SECONDS) and Codex's `x-codex-{primary,secondary}-*` (a PERCENT used, a
|
|
16
|
+
* declared window length, reset in epoch seconds or seconds from now);
|
|
17
|
+
* - the Codex stream event `codex.rate_limits` (`provider_stream_event`),
|
|
18
|
+
* which carries the same figures as JSON numbers;
|
|
19
|
+
* - an assistant message that ended in a usage-limit error (`message_end`),
|
|
20
|
+
* the only signal some routes give.
|
|
21
|
+
*
|
|
22
|
+
* Headers, events and error text are foreign. Nothing read from one is ever
|
|
23
|
+
* returned as text: values are matched against strict numeric patterns (or
|
|
24
|
+
* `typeof === "number"`), only parsed numbers leave, and every label is
|
|
25
|
+
* generated here from a canonical duration.
|
|
26
|
+
*
|
|
27
|
+
* A response rarely carries every window, so windows are kept per canonical
|
|
28
|
+
* duration, each with the time it was last seen. A window leaves when its
|
|
29
|
+
* reset passes, or — without a believable reset — QUOTA_STALE_MS after it was
|
|
30
|
+
* last seen. Two successful responses in a row without any quota mean the
|
|
31
|
+
* account or its auth changed, and drop everything known about that provider.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { usageLevel, type UsageLevel } from "./format.ts";
|
|
35
|
+
|
|
36
|
+
/** Which header vocabulary a response speaks. Chosen by the model's api, never by provider id. */
|
|
37
|
+
export type QuotaFamily = "anthropic" | "codex";
|
|
38
|
+
|
|
39
|
+
/** One rate window as last reported. */
|
|
40
|
+
export interface QuotaWindow {
|
|
41
|
+
/** Canonical length: whole hours under a day, whole days from there. */
|
|
42
|
+
readonly minutes: number;
|
|
43
|
+
/** Generated from `minutes`: "5h", "wk", "30d". Never copied from a header. */
|
|
44
|
+
readonly label: string;
|
|
45
|
+
/** Whole percent USED, 0..100. */
|
|
46
|
+
readonly percent: number;
|
|
47
|
+
/** When the window renews. Absent when it was missing or implausible; the window then ages out. */
|
|
48
|
+
readonly resetAtMs?: number;
|
|
49
|
+
/** When this figure was last reported. */
|
|
50
|
+
readonly seenAtMs: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** What one response or stream event said: one or two windows, shortest first. */
|
|
54
|
+
export interface QuotaSnapshot {
|
|
55
|
+
readonly family: QuotaFamily;
|
|
56
|
+
readonly windows: readonly QuotaWindow[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Everything known about one provider's subscription. Never stored without a provider. */
|
|
60
|
+
export interface QuotaAccount {
|
|
61
|
+
readonly provider: string;
|
|
62
|
+
/** The family `windows` were read in; absent while there are none. */
|
|
63
|
+
readonly family?: QuotaFamily;
|
|
64
|
+
/** One per canonical duration, shortest first, at most MAX_WINDOWS. */
|
|
65
|
+
readonly windows: readonly QuotaWindow[];
|
|
66
|
+
/** Consecutive successful responses that carried no quota. */
|
|
67
|
+
readonly misses: number;
|
|
68
|
+
/** The last assistant message from this provider ended in a usage-limit error. */
|
|
69
|
+
readonly limited: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** One account per provider, so a model switch away and back finds its figures again. */
|
|
73
|
+
export interface QuotaState {
|
|
74
|
+
readonly accounts: readonly QuotaAccount[];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const EMPTY_QUOTA: QuotaState = { accounts: [] };
|
|
78
|
+
|
|
79
|
+
/** The slice of a provider response the reducer needs. */
|
|
80
|
+
export interface QuotaResponse {
|
|
81
|
+
readonly status: number;
|
|
82
|
+
readonly headers: unknown;
|
|
83
|
+
readonly api?: string;
|
|
84
|
+
readonly provider?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The slice of a raw provider stream event the reducer needs. */
|
|
88
|
+
export interface QuotaStreamEvent {
|
|
89
|
+
readonly provider?: string;
|
|
90
|
+
readonly api?: string;
|
|
91
|
+
readonly data: unknown;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface QuotaViewWindow {
|
|
95
|
+
readonly label: string;
|
|
96
|
+
readonly percent: number;
|
|
97
|
+
/** Same thresholds as the context percentage: above 70 warn, above 90 critical. */
|
|
98
|
+
readonly level: UsageLevel;
|
|
99
|
+
/** "5h 43%". */
|
|
100
|
+
readonly text: string;
|
|
101
|
+
/** Not heard of for QUOTA_STALE_MS (or dated in the future): a calm figure may recede. */
|
|
102
|
+
readonly aged: boolean;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Everything the status row needs, and nothing else. */
|
|
106
|
+
export interface QuotaView {
|
|
107
|
+
/** Live windows, shortest first; empty when only the limit is known. */
|
|
108
|
+
readonly windows: readonly QuotaViewWindow[];
|
|
109
|
+
/** The window closest to its limit (a tie goes to the longer one); one of `windows`. */
|
|
110
|
+
readonly binding?: QuotaViewWindow;
|
|
111
|
+
/** The binding window is above 70%, or the limit is reached: never paint it dim, never drop it as an ornament. */
|
|
112
|
+
readonly hot: boolean;
|
|
113
|
+
/** The binding window's figure is aged. */
|
|
114
|
+
readonly aged: boolean;
|
|
115
|
+
/** The provider's last assistant message ended in a usage-limit error. */
|
|
116
|
+
readonly limited: boolean;
|
|
117
|
+
/** Two-window form, "5h 43% · wk 12%"; "" unless two windows are live and the limit is not reached. */
|
|
118
|
+
readonly two: string;
|
|
119
|
+
/** One-window form, the binding window alone, "wk 85%"; "" when the limit is reached. */
|
|
120
|
+
readonly one: string;
|
|
121
|
+
/** Limit form, "limit"; "" unless the limit is reached. It replaces the windows. */
|
|
122
|
+
readonly limit: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Past this age a figure is `aged`, and a window with no known reset is dropped. */
|
|
126
|
+
export const QUOTA_STALE_MS = 30 * 60_000;
|
|
127
|
+
|
|
128
|
+
/** Joins the windows of the two-window form; the status row's own item separator. */
|
|
129
|
+
export const QUOTA_SEPARATOR = " · ";
|
|
130
|
+
|
|
131
|
+
/** What the row prints in place of the windows once the limit is reached. */
|
|
132
|
+
export const QUOTA_LIMIT_TEXT = "limit";
|
|
133
|
+
|
|
134
|
+
/** The api whose raw stream carries `codex.rate_limits` events. */
|
|
135
|
+
export const CODEX_STREAM_API = "openai-codex-responses";
|
|
136
|
+
/** The `type` of that event. */
|
|
137
|
+
export const CODEX_RATE_LIMITS_EVENT = "codex.rate_limits";
|
|
138
|
+
|
|
139
|
+
/** Successful responses without quota before a provider's account is dropped. */
|
|
140
|
+
const MISSES_TO_CLEAR = 2;
|
|
141
|
+
/** Windows kept and shown per account. */
|
|
142
|
+
const MAX_WINDOWS = 2;
|
|
143
|
+
/** Accounts kept; the least recently touched goes first. */
|
|
144
|
+
const MAX_ACCOUNTS = 8;
|
|
145
|
+
/** A provider id longer than this is not one worth keying on. */
|
|
146
|
+
const MAX_PROVIDER_LENGTH = 128;
|
|
147
|
+
/** Only this much of an error message is inspected for the usage-limit phrase. */
|
|
148
|
+
const MAX_ERROR_LENGTH = 512;
|
|
149
|
+
const MINUTE_MS = 60_000;
|
|
150
|
+
const DAY_MINUTES = 1440;
|
|
151
|
+
const WEEK_MINUTES = 7 * DAY_MINUTES;
|
|
152
|
+
/** A window longer than a year is not a rate window. */
|
|
153
|
+
const MAX_DAYS = 365;
|
|
154
|
+
/** A declared length this close to a whole hour or day is that length (299 → 300, 10079 → 10080). */
|
|
155
|
+
const SNAP_TOLERANCE = 0.05;
|
|
156
|
+
/** A reset may sit this far past now + the window's own length before it is disbelieved. */
|
|
157
|
+
const RESET_SLACK_MS = DAY_MINUTES * MINUTE_MS;
|
|
158
|
+
/** A percent (or a fraction ×100) above this is not a reading of a window; up to it, it clamps to 100. */
|
|
159
|
+
const MAX_PERCENT = 1000;
|
|
160
|
+
/** The widest integer the header patterns admit: nine digits. */
|
|
161
|
+
const MAX_INTEGER = 999_999_999;
|
|
162
|
+
/** Epoch seconds are ten digits from 2001 to 2286. */
|
|
163
|
+
const MIN_EPOCH_SECONDS = 1_000_000_000;
|
|
164
|
+
const MAX_EPOCH_SECONDS = 9_999_999_999;
|
|
165
|
+
|
|
166
|
+
// No sign, exponent, radix prefix, whitespace or leading zero; `\d` without the
|
|
167
|
+
// `u`/`v` flag is ASCII only. Twenty fraction digits cover a float printed in
|
|
168
|
+
// full. Each pattern is anchored with bounded repetition, so it bounds the
|
|
169
|
+
// length it reads by itself: a megabyte of header fails after a few characters.
|
|
170
|
+
const DECIMAL = /^(?:0|[1-9]\d{0,2})(?:\.\d{1,20})?$/;
|
|
171
|
+
const INTEGER = /^(?:0|[1-9]\d{0,8})$/;
|
|
172
|
+
const EPOCH_SECONDS = /^[1-9]\d{9}$/;
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The account-wide windows of the Anthropic family, a closed set: both have a
|
|
176
|
+
* fixed, known duration, which the header name states and nothing else does.
|
|
177
|
+
* Other `unified-*` claims are left out on purpose — a model-scoped weekly
|
|
178
|
+
* figure would collide with "wk" while measuring something else, and overage
|
|
179
|
+
* is a spend allowance, not a window.
|
|
180
|
+
*/
|
|
181
|
+
const ANTHROPIC_WINDOWS = [
|
|
182
|
+
{ minutes: 300, used: "anthropic-ratelimit-unified-5h-utilization", reset: "anthropic-ratelimit-unified-5h-reset" },
|
|
183
|
+
{ minutes: WEEK_MINUTES, used: "anthropic-ratelimit-unified-7d-utilization", reset: "anthropic-ratelimit-unified-7d-reset" },
|
|
184
|
+
] as const;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The Codex family names its slots "primary"/"secondary", which says nothing
|
|
188
|
+
* about their length: each slot declares its own `window-minutes`.
|
|
189
|
+
*/
|
|
190
|
+
const CODEX_WINDOWS = [
|
|
191
|
+
{
|
|
192
|
+
slot: "primary",
|
|
193
|
+
used: "x-codex-primary-used-percent",
|
|
194
|
+
minutes: "x-codex-primary-window-minutes",
|
|
195
|
+
resetAt: "x-codex-primary-reset-at",
|
|
196
|
+
resetAfter: "x-codex-primary-reset-after-seconds",
|
|
197
|
+
},
|
|
198
|
+
{
|
|
199
|
+
slot: "secondary",
|
|
200
|
+
used: "x-codex-secondary-used-percent",
|
|
201
|
+
minutes: "x-codex-secondary-window-minutes",
|
|
202
|
+
resetAt: "x-codex-secondary-reset-at",
|
|
203
|
+
resetAfter: "x-codex-secondary-reset-after-seconds",
|
|
204
|
+
},
|
|
205
|
+
] as const;
|
|
206
|
+
|
|
207
|
+
/** A header under one of these belongs to its family's quota, readable or not. */
|
|
208
|
+
const FAMILY_PREFIXES: Record<QuotaFamily, readonly string[]> = {
|
|
209
|
+
anthropic: ["anthropic-ratelimit-unified-"],
|
|
210
|
+
codex: ["x-codex-primary-", "x-codex-secondary-"],
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/** The header family an api speaks; `undefined` keeps gateways and virtual models out. */
|
|
214
|
+
export function quotaFamily(api: unknown): QuotaFamily | undefined {
|
|
215
|
+
if (api === "anthropic-messages") return "anthropic";
|
|
216
|
+
if (api === "openai-responses" || api === CODEX_STREAM_API) return "codex";
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The label of a canonical window length, or `undefined` when it has no clean name. */
|
|
221
|
+
export function quotaLabel(minutes: number): string | undefined {
|
|
222
|
+
if (!Number.isInteger(minutes) || minutes <= 0) return undefined;
|
|
223
|
+
if (minutes === WEEK_MINUTES) return "wk";
|
|
224
|
+
if (minutes % DAY_MINUTES === 0) return minutes / DAY_MINUTES <= MAX_DAYS ? `${minutes / DAY_MINUTES}d` : undefined;
|
|
225
|
+
return minutes < DAY_MINUTES && minutes % 60 === 0 ? `${minutes / 60}h` : undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The whole multiple of `unit` nearest to `minutes` when it lies within the tolerance, the nearer neighbour first. */
|
|
229
|
+
function snapTo(minutes: number, unit: number): number | undefined {
|
|
230
|
+
const below = Math.floor(minutes / unit) * unit;
|
|
231
|
+
const above = below + unit;
|
|
232
|
+
const candidates = minutes - below <= above - minutes ? [below, above] : [above, below];
|
|
233
|
+
return candidates.find((candidate) => candidate > 0 && Math.abs(minutes - candidate) <= candidate * SNAP_TOLERANCE);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The canonical length a declared one stands for: itself when it is whole
|
|
238
|
+
* hours under a day or whole days; otherwise the whole hour (under a day) or
|
|
239
|
+
* the whole day it lies within 5% of, as servers report 299 and 10079 for the
|
|
240
|
+
* five-hour and weekly windows. `undefined` when it is neither.
|
|
241
|
+
*/
|
|
242
|
+
export function canonicalMinutes(minutes: number): number | undefined {
|
|
243
|
+
if (!Number.isInteger(minutes) || minutes <= 0 || minutes > (MAX_DAYS + 1) * DAY_MINUTES) return undefined;
|
|
244
|
+
if (quotaLabel(minutes) !== undefined) return minutes;
|
|
245
|
+
const hours = snapTo(minutes, 60);
|
|
246
|
+
const snapped = hours !== undefined && hours < DAY_MINUTES ? hours : snapTo(minutes, DAY_MINUTES);
|
|
247
|
+
return snapped !== undefined && quotaLabel(snapped) !== undefined ? snapped : undefined;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function plainObject(value: unknown): Record<string, unknown> | undefined {
|
|
251
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
|
252
|
+
const proto: unknown = Object.getPrototypeOf(value);
|
|
253
|
+
return proto === Object.prototype || proto === null ? (value as Record<string, unknown>) : undefined;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function own(record: Record<string, unknown>, key: string): unknown {
|
|
257
|
+
return Object.hasOwn(record, key) ? record[key] : undefined;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function decimal(value: unknown): number | undefined {
|
|
261
|
+
return typeof value === "string" && DECIMAL.test(value) ? Number(value) : undefined;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function integer(value: unknown): number | undefined {
|
|
265
|
+
return typeof value === "string" && INTEGER.test(value) ? Number(value) : undefined;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function epochSeconds(value: unknown): number | undefined {
|
|
269
|
+
return typeof value === "string" && EPOCH_SECONDS.test(value) ? Number(value) : undefined;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** A JSON number that is a whole count within `min..max`. */
|
|
273
|
+
function wholeNumber(value: unknown, min: number, max: number): number | undefined {
|
|
274
|
+
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max ? value : undefined;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function providerOf(value: unknown): string | undefined {
|
|
278
|
+
return typeof value === "string" && value.length > 0 && value.length <= MAX_PROVIDER_LENGTH ? value : undefined;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Whole percent, clamped: a window can be reported past its limit. */
|
|
282
|
+
function percentOf(value: number | undefined): number | undefined {
|
|
283
|
+
return value === undefined || !(value >= 0 && value <= MAX_PERCENT) ? undefined : Math.min(100, Math.round(value));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function windowOf(minutes: number | undefined, percent: number | undefined, resetAtMs: number | undefined, nowMs: number): QuotaWindow | undefined {
|
|
287
|
+
if (minutes === undefined || percent === undefined) return undefined;
|
|
288
|
+
const label = quotaLabel(minutes);
|
|
289
|
+
if (label === undefined) return undefined;
|
|
290
|
+
const undated: QuotaWindow = { minutes, label, percent, seenAtMs: nowMs };
|
|
291
|
+
if (resetAtMs === undefined) return undated;
|
|
292
|
+
// Already renewed: the figure describes a window that is over.
|
|
293
|
+
if (resetAtMs <= nowMs) return undefined;
|
|
294
|
+
// A reset further away than the window is long is not this window's: keep the figure, let it age out.
|
|
295
|
+
if (resetAtMs > nowMs + minutes * MINUTE_MS + RESET_SLACK_MS) return undated;
|
|
296
|
+
return { ...undated, resetAtMs };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The four numbers a Codex slot states, from headers or from the stream event. */
|
|
300
|
+
interface CodexSlot {
|
|
301
|
+
readonly used?: number;
|
|
302
|
+
readonly minutes?: number;
|
|
303
|
+
readonly resetAtSeconds?: number;
|
|
304
|
+
readonly resetAfterSeconds?: number;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function codexWindow(slot: CodexSlot, nowMs: number): QuotaWindow | undefined {
|
|
308
|
+
// A PERCENT already: 0.73 is under one percent, not 73.
|
|
309
|
+
const percent = percentOf(slot.used);
|
|
310
|
+
const minutes = slot.minutes === undefined ? undefined : canonicalMinutes(slot.minutes);
|
|
311
|
+
const resetAtMs = slot.resetAtSeconds !== undefined ? slot.resetAtSeconds * 1000
|
|
312
|
+
: slot.resetAfterSeconds !== undefined ? nowMs + slot.resetAfterSeconds * 1000 : undefined;
|
|
313
|
+
return windowOf(minutes, percent, resetAtMs, nowMs);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function anthropicWindows(headers: Record<string, unknown>, nowMs: number): (QuotaWindow | undefined)[] {
|
|
317
|
+
return ANTHROPIC_WINDOWS.map((keys) => {
|
|
318
|
+
// A FRACTION of the window: 0.81 is 81% used, and it can pass 1.
|
|
319
|
+
const fraction = decimal(own(headers, keys.used));
|
|
320
|
+
const reset = epochSeconds(own(headers, keys.reset));
|
|
321
|
+
return windowOf(keys.minutes, percentOf(fraction === undefined ? undefined : fraction * 100), reset === undefined ? undefined : reset * 1000, nowMs);
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function codexHeaderWindows(headers: Record<string, unknown>, nowMs: number): (QuotaWindow | undefined)[] {
|
|
326
|
+
return CODEX_WINDOWS.map((keys) => codexWindow({
|
|
327
|
+
used: decimal(own(headers, keys.used)),
|
|
328
|
+
minutes: integer(own(headers, keys.minutes)),
|
|
329
|
+
resetAtSeconds: epochSeconds(own(headers, keys.resetAt)),
|
|
330
|
+
resetAfterSeconds: integer(own(headers, keys.resetAfter)),
|
|
331
|
+
}, nowMs));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** The fuller of two readings of one window; a tie goes to the one that knows its reset, then to the first. */
|
|
335
|
+
function fuller(kept: QuotaWindow, next: QuotaWindow): QuotaWindow {
|
|
336
|
+
if (next.percent !== kept.percent) return next.percent > kept.percent ? next : kept;
|
|
337
|
+
return kept.resetAtMs === undefined && next.resetAtMs !== undefined ? next : kept;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** One window per canonical duration, shortest first. */
|
|
341
|
+
function arrange(found: readonly (QuotaWindow | undefined)[]): QuotaWindow[] {
|
|
342
|
+
const byDuration = new Map<number, QuotaWindow>();
|
|
343
|
+
for (const window of found) {
|
|
344
|
+
if (!window) continue;
|
|
345
|
+
const kept = byDuration.get(window.minutes);
|
|
346
|
+
byDuration.set(window.minutes, kept ? fuller(kept, window) : window);
|
|
347
|
+
}
|
|
348
|
+
return [...byDuration.values()].sort((a, b) => a.minutes - b.minutes).slice(0, MAX_WINDOWS);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function readHeaders(headers: unknown, api: unknown, nowMs: number): { snapshot?: QuotaSnapshot; present: boolean } {
|
|
352
|
+
try {
|
|
353
|
+
const family = quotaFamily(api);
|
|
354
|
+
const record = plainObject(headers);
|
|
355
|
+
if (!family || !record) return { present: false };
|
|
356
|
+
const windows = arrange(family === "anthropic" ? anthropicWindows(record, nowMs) : codexHeaderWindows(record, nowMs));
|
|
357
|
+
if (windows.length > 0) return { snapshot: { family, windows }, present: true };
|
|
358
|
+
const prefixes = FAMILY_PREFIXES[family];
|
|
359
|
+
return { present: Object.keys(record).some((key) => prefixes.some((prefix) => key.startsWith(prefix))) };
|
|
360
|
+
} catch {
|
|
361
|
+
// A hostile object (a throwing getter or proxy trap) is just a response without quota.
|
|
362
|
+
return { present: false };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Read one response's quota headers. Never throws; `undefined` when the api
|
|
368
|
+
* speaks no known family or the headers carry no valid window of it.
|
|
369
|
+
*/
|
|
370
|
+
export function parseQuotaHeaders(headers: unknown, api: string | undefined, nowMs: number): QuotaSnapshot | undefined {
|
|
371
|
+
return readHeaders(headers, api, nowMs).snapshot;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Read one raw stream event of the Codex api. The shape is the one Pi's own
|
|
376
|
+
* Codex stream test replays (pi `packages/ai/test/openai-codex-stream.test.ts`):
|
|
377
|
+
*
|
|
378
|
+
* { type: "codex.rate_limits",
|
|
379
|
+
* rate_limits: { primary: { used_percent: 7, window_minutes: 10080,
|
|
380
|
+
* reset_after_seconds: 556112, reset_at: 1785269351 }, secondary: null } }
|
|
381
|
+
*
|
|
382
|
+
* Only `typeof === "number"` fields are read, with the bounds the headers
|
|
383
|
+
* have. Never throws; `undefined` for any other api, event or shape.
|
|
384
|
+
*/
|
|
385
|
+
export function parseQuotaEvent(data: unknown, api: string | undefined, nowMs: number): QuotaSnapshot | undefined {
|
|
386
|
+
try {
|
|
387
|
+
if (api !== CODEX_STREAM_API) return undefined;
|
|
388
|
+
const event = plainObject(data);
|
|
389
|
+
if (!event || own(event, "type") !== CODEX_RATE_LIMITS_EVENT) return undefined;
|
|
390
|
+
const limits = plainObject(own(event, "rate_limits"));
|
|
391
|
+
if (!limits) return undefined;
|
|
392
|
+
const windows = arrange(CODEX_WINDOWS.map(({ slot }) => {
|
|
393
|
+
const fields = plainObject(own(limits, slot));
|
|
394
|
+
if (!fields) return undefined;
|
|
395
|
+
const used = own(fields, "used_percent");
|
|
396
|
+
return codexWindow({
|
|
397
|
+
used: typeof used === "number" && Number.isFinite(used) ? used : undefined,
|
|
398
|
+
minutes: wholeNumber(own(fields, "window_minutes"), 0, MAX_INTEGER),
|
|
399
|
+
resetAtSeconds: wholeNumber(own(fields, "reset_at"), MIN_EPOCH_SECONDS, MAX_EPOCH_SECONDS),
|
|
400
|
+
resetAfterSeconds: wholeNumber(own(fields, "reset_after_seconds"), 0, MAX_INTEGER),
|
|
401
|
+
}, nowMs);
|
|
402
|
+
}));
|
|
403
|
+
return windows.length > 0 ? { family: "codex", windows } : undefined;
|
|
404
|
+
} catch {
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Still describing a running window: before its reset, or — undated — within QUOTA_STALE_MS of when it was seen. */
|
|
410
|
+
function alive(window: QuotaWindow, nowMs: number): boolean {
|
|
411
|
+
return window.resetAtMs !== undefined ? nowMs < window.resetAtMs : Math.abs(nowMs - window.seenAtMs) <= QUOTA_STALE_MS;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function accountOf(state: QuotaState | undefined, provider: string | undefined): QuotaAccount | undefined {
|
|
415
|
+
return provider === undefined ? undefined : state?.accounts.find((account) => account.provider === provider);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Replace (or, with `undefined`, remove) one provider's account; the touched one moves last, the oldest falls off. */
|
|
419
|
+
function withAccount(state: QuotaState | undefined, provider: string, account: QuotaAccount | undefined): QuotaState {
|
|
420
|
+
const others = (state?.accounts ?? []).filter((kept) => kept.provider !== provider);
|
|
421
|
+
const accounts = account ? [...others, account] : others;
|
|
422
|
+
return { accounts: accounts.slice(Math.max(0, accounts.length - MAX_ACCOUNTS)) };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Fold fresh windows into what is known: one per duration, the fresh reading
|
|
427
|
+
* replacing the kept one, expired ones gone. Another family's windows are not
|
|
428
|
+
* this account's any more. Over MAX_WINDOWS, the most recently seen stay.
|
|
429
|
+
*/
|
|
430
|
+
function mergeWindows(account: QuotaAccount | undefined, snapshot: QuotaSnapshot, nowMs: number): QuotaWindow[] {
|
|
431
|
+
const byDuration = new Map<number, QuotaWindow>();
|
|
432
|
+
if (account?.family === snapshot.family) {
|
|
433
|
+
for (const window of account.windows) if (alive(window, nowMs)) byDuration.set(window.minutes, window);
|
|
434
|
+
}
|
|
435
|
+
for (const window of snapshot.windows) byDuration.set(window.minutes, window);
|
|
436
|
+
return [...byDuration.values()]
|
|
437
|
+
.sort((a, b) => b.seenAtMs - a.seenAtMs || b.percent - a.percent || b.minutes - a.minutes)
|
|
438
|
+
.slice(0, MAX_WINDOWS)
|
|
439
|
+
.sort((a, b) => a.minutes - b.minutes);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function withSnapshot(state: QuotaState | undefined, provider: string, snapshot: QuotaSnapshot, nowMs: number): QuotaState {
|
|
443
|
+
const account = accountOf(state, provider);
|
|
444
|
+
return withAccount(state, provider, {
|
|
445
|
+
provider,
|
|
446
|
+
family: snapshot.family,
|
|
447
|
+
windows: mergeWindows(account, snapshot, nowMs),
|
|
448
|
+
misses: 0,
|
|
449
|
+
limited: account?.limited ?? false,
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Fold one provider response into the state.
|
|
455
|
+
*
|
|
456
|
+
* Valid windows update the provider's account whatever the status: a 429 at
|
|
457
|
+
* 100% is the most useful figure there is. A successful response without any
|
|
458
|
+
* header of the family is a miss, and two in a row drop the account — the
|
|
459
|
+
* account or its auth changed. A response whose family headers are present but
|
|
460
|
+
* unusable is not a miss, and an unsuccessful one without quota says nothing.
|
|
461
|
+
* Without a provider nothing is stored.
|
|
462
|
+
*/
|
|
463
|
+
export function nextQuota(state: QuotaState | undefined, response: QuotaResponse, nowMs: number): QuotaState {
|
|
464
|
+
const before = state ?? EMPTY_QUOTA;
|
|
465
|
+
try {
|
|
466
|
+
const provider = providerOf(response.provider);
|
|
467
|
+
if (provider === undefined) return before;
|
|
468
|
+
const { status } = response;
|
|
469
|
+
const { snapshot, present } = readHeaders(response.headers, response.api, nowMs);
|
|
470
|
+
if (snapshot) return withSnapshot(before, provider, snapshot, nowMs);
|
|
471
|
+
if (typeof status !== "number" || !(status >= 200 && status < 300) || present) return before;
|
|
472
|
+
const account = accountOf(before, provider);
|
|
473
|
+
if (!account) return before;
|
|
474
|
+
const misses = account.misses + 1;
|
|
475
|
+
return withAccount(before, provider, misses >= MISSES_TO_CLEAR ? undefined : { ...account, misses });
|
|
476
|
+
} catch {
|
|
477
|
+
return before;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Fold one raw stream event into the state; anything but a readable Codex rate-limit event changes nothing. */
|
|
482
|
+
export function nextQuotaEvent(state: QuotaState | undefined, event: QuotaStreamEvent, nowMs: number): QuotaState {
|
|
483
|
+
const before = state ?? EMPTY_QUOTA;
|
|
484
|
+
try {
|
|
485
|
+
const provider = providerOf(event.provider);
|
|
486
|
+
const snapshot = provider === undefined ? undefined : parseQuotaEvent(event.data, event.api, nowMs);
|
|
487
|
+
return provider !== undefined && snapshot ? withSnapshot(before, provider, snapshot, nowMs) : before;
|
|
488
|
+
} catch {
|
|
489
|
+
return before;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* An assistant message that ended because the subscription's usage limit was
|
|
495
|
+
* reached. On OpenAI's ChatGPT route this is the only signal there is: the
|
|
496
|
+
* response is a 200 without quota headers and the message ends with
|
|
497
|
+
* `stopReason: "error"` and "The ChatGPT user has reached their Subscription
|
|
498
|
+
* Sharing usage limit. …". The test is deliberately narrow — the phrase "usage
|
|
499
|
+
* limit", any case, within the first MAX_ERROR_LENGTH characters — so the
|
|
500
|
+
* generic "rate limit" errors of pay-per-use APIs do not match.
|
|
501
|
+
*/
|
|
502
|
+
export function isUsageLimitMessage(message: unknown): boolean {
|
|
503
|
+
try {
|
|
504
|
+
if (typeof message !== "object" || message === null) return false;
|
|
505
|
+
const { role, stopReason, errorMessage } = message as { role?: unknown; stopReason?: unknown; errorMessage?: unknown };
|
|
506
|
+
return role === "assistant" && stopReason === "error" && typeof errorMessage === "string"
|
|
507
|
+
&& errorMessage.slice(0, MAX_ERROR_LENGTH).toLowerCase().includes("usage limit");
|
|
508
|
+
} catch {
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Fold the end of one message into the state. An assistant message that ended
|
|
515
|
+
* in a usage-limit error marks its provider as limited (and is news about the
|
|
516
|
+
* account, so the miss count starts again); that provider's next assistant
|
|
517
|
+
* message that is an answer — neither an error nor an abort — clears the mark. The provider is the message's own, else
|
|
518
|
+
* `fallbackProvider` (the current model's).
|
|
519
|
+
*/
|
|
520
|
+
export function nextQuotaMessage(state: QuotaState | undefined, message: unknown, fallbackProvider: string | undefined, nowMs: number): QuotaState {
|
|
521
|
+
const before = state ?? EMPTY_QUOTA;
|
|
522
|
+
try {
|
|
523
|
+
if (typeof message !== "object" || message === null || (message as { role?: unknown }).role !== "assistant") return before;
|
|
524
|
+
const provider = providerOf((message as { provider?: unknown }).provider) ?? providerOf(fallbackProvider);
|
|
525
|
+
if (provider === undefined) return before;
|
|
526
|
+
const account = accountOf(before, provider);
|
|
527
|
+
if (isUsageLimitMessage(message)) {
|
|
528
|
+
if (account?.limited && account.misses === 0) return before;
|
|
529
|
+
const windows = (account?.windows ?? []).filter((window) => alive(window, nowMs));
|
|
530
|
+
return withAccount(before, provider, { provider, family: windows.length > 0 ? account?.family : undefined, windows, misses: 0, limited: true });
|
|
531
|
+
}
|
|
532
|
+
if (!account?.limited) return before;
|
|
533
|
+
// Only an answer proves the limit lifted: an interrupted attempt or another
|
|
534
|
+
// error (overloaded, network) says nothing about the account.
|
|
535
|
+
const stopReason = (message as { stopReason?: unknown }).stopReason;
|
|
536
|
+
if (stopReason === "error" || stopReason === "aborted") return before;
|
|
537
|
+
// Never keep an account that says nothing.
|
|
538
|
+
return withAccount(before, provider, account.windows.length > 0 ? { ...account, limited: false } : undefined);
|
|
539
|
+
} catch {
|
|
540
|
+
return before;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* What the status row shows for the current model, or `undefined` for nothing:
|
|
546
|
+
* no account for its provider, or an account that is not limited and whose
|
|
547
|
+
* windows are all over or were read in a family the current api does not speak.
|
|
548
|
+
*/
|
|
549
|
+
export function quotaView(
|
|
550
|
+
state: QuotaState | undefined,
|
|
551
|
+
current: { readonly provider?: string; readonly api?: string },
|
|
552
|
+
nowMs: number,
|
|
553
|
+
): QuotaView | undefined {
|
|
554
|
+
try {
|
|
555
|
+
const account = accountOf(state, providerOf(current.provider));
|
|
556
|
+
if (!account) return undefined;
|
|
557
|
+
const live = account.family !== undefined && quotaFamily(current.api) === account.family
|
|
558
|
+
? account.windows.filter((window) => alive(window, nowMs)).slice(0, MAX_WINDOWS) : [];
|
|
559
|
+
const windows: QuotaViewWindow[] = live.map(({ label, percent, seenAtMs }) => {
|
|
560
|
+
const age = nowMs - seenAtMs;
|
|
561
|
+
return { label, percent, level: usageLevel(percent), text: `${label} ${percent}%`, aged: age < 0 || age > QUOTA_STALE_MS };
|
|
562
|
+
});
|
|
563
|
+
let binding = windows[0];
|
|
564
|
+
// `>=` over a shortest-first list: a tie goes to the longer window, the one that takes longer to clear.
|
|
565
|
+
for (const window of windows) if (binding && window.percent >= binding.percent) binding = window;
|
|
566
|
+
const { limited } = account;
|
|
567
|
+
if (!binding && !limited) return undefined;
|
|
568
|
+
return {
|
|
569
|
+
windows,
|
|
570
|
+
...(binding ? { binding } : {}),
|
|
571
|
+
hot: limited || (binding !== undefined && binding.level !== "normal"),
|
|
572
|
+
aged: binding?.aged ?? false,
|
|
573
|
+
limited,
|
|
574
|
+
two: !limited && windows.length === 2 ? windows.map((window) => window.text).join(QUOTA_SEPARATOR) : "",
|
|
575
|
+
one: !limited && binding ? binding.text : "",
|
|
576
|
+
limit: limited ? QUOTA_LIMIT_TEXT : "",
|
|
577
|
+
};
|
|
578
|
+
} catch {
|
|
579
|
+
return undefined;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal writable surface for observing out-of-band terminal diagnostics.
|
|
3
|
+
* The guard never changes, suppresses, buffers, or duplicates the bytes written.
|
|
4
|
+
*/
|
|
5
|
+
export interface RedrawWritable {
|
|
6
|
+
write: (this: RedrawWritable, ...args: unknown[]) => boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface FullRedrawTarget {
|
|
10
|
+
requestRender(force?: boolean): void;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type RedrawScheduler = (task: () => void, delayMs?: number) => void;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Keep one frame of distance from a foreign write burst. A microtask only
|
|
17
|
+
* coalesces synchronous chunks; diagnostics arriving from an async stream
|
|
18
|
+
* would otherwise force one immediate full repaint per chunk and bypass
|
|
19
|
+
* pi-tui's normal render throttle.
|
|
20
|
+
*/
|
|
21
|
+
const REDRAW_COALESCE_MS = 16;
|
|
22
|
+
const requestAfterBurst: RedrawScheduler = (task, delayMs = REDRAW_COALESCE_MS) => {
|
|
23
|
+
setTimeout(task, delayMs);
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Reset Pi TUI's cached lines/cursor and repaint the complete screen. */
|
|
27
|
+
export function forceFullRedraw(target: FullRedrawTarget | undefined): void {
|
|
28
|
+
target?.requestRender(true);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Observe a stream that writes outside Pi TUI's renderer and request a repair
|
|
33
|
+
* after the original short write burst. The original is called first, with the
|
|
34
|
+
* exact receiver, arguments and return value; only a redraw side effect follows.
|
|
35
|
+
* The default scheduler coalesces adjacent chunks into a short frame window
|
|
36
|
+
* before Pi's next render, including writes arriving from asynchronous streams.
|
|
37
|
+
*
|
|
38
|
+
* Disposal is ownership-safe: if another extension wrapped the stream after us,
|
|
39
|
+
* its writer is left installed and this inactive wrapper becomes pass-through.
|
|
40
|
+
*/
|
|
41
|
+
export function installOutOfBandRedrawGuard(
|
|
42
|
+
target: RedrawWritable,
|
|
43
|
+
requestFullRedraw: () => void,
|
|
44
|
+
schedule: RedrawScheduler = requestAfterBurst,
|
|
45
|
+
): () => void {
|
|
46
|
+
const original = target.write;
|
|
47
|
+
let active = true;
|
|
48
|
+
let queued = false;
|
|
49
|
+
|
|
50
|
+
const flush = (): void => {
|
|
51
|
+
queued = false;
|
|
52
|
+
if (!active) return;
|
|
53
|
+
try {
|
|
54
|
+
requestFullRedraw();
|
|
55
|
+
} catch {
|
|
56
|
+
// Cosmetic recovery must never turn a foreign diagnostic into a failure.
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const guarded = function (this: RedrawWritable, ...args: unknown[]): boolean {
|
|
61
|
+
const result = Reflect.apply(original, this, args) as boolean;
|
|
62
|
+
if (active && !queued) {
|
|
63
|
+
queued = true;
|
|
64
|
+
try {
|
|
65
|
+
schedule(flush, REDRAW_COALESCE_MS);
|
|
66
|
+
} catch {
|
|
67
|
+
queued = false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
target.write = guarded;
|
|
74
|
+
return () => {
|
|
75
|
+
active = false;
|
|
76
|
+
queued = false;
|
|
77
|
+
if (target.write === guarded) target.write = original;
|
|
78
|
+
};
|
|
79
|
+
}
|