pi-cliproxyapi 0.4.2 → 0.5.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.
@@ -0,0 +1,74 @@
1
+ // Pure formatters shared by the footer and the Usage tab.
2
+ //
3
+ // Durations always round DOWN: a countdown that says 4:40 never resets before
4
+ // 4 hours 40 minutes have passed, and the footer re-renders on every poll.
5
+
6
+ const MINUTE_MS = 60_000;
7
+ const MINUTES_PER_DAY = 24 * 60;
8
+
9
+ /**
10
+ * Time left as `h:mm` under a day, `NдNч` from a day up (`д`/`ч` are the
11
+ * owner-approved day/hour suffixes). Negative or invalid input reads `0:00`.
12
+ */
13
+ export function formatDuration(ms: number): string {
14
+ const total = Number.isFinite(ms) && ms > 0 ? Math.floor(ms / MINUTE_MS) : 0;
15
+ if (total < MINUTES_PER_DAY) {
16
+ const h = Math.floor(total / 60);
17
+ const m = total % 60;
18
+ return `${h}:${String(m).padStart(2, "0")}`;
19
+ }
20
+ const d = Math.floor(total / MINUTES_PER_DAY);
21
+ const h = Math.floor((total % MINUTES_PER_DAY) / 60);
22
+ return `${d}д${h}ч`;
23
+ }
24
+
25
+ /** Countdown to an RFC 3339 instant, or null when there is no usable time. */
26
+ export function formatCountdown(
27
+ iso: string | null | undefined,
28
+ now: number,
29
+ ): string | null {
30
+ if (!iso) return null;
31
+ const t = Date.parse(iso);
32
+ if (!Number.isFinite(t)) return null;
33
+ return formatDuration(t - now);
34
+ }
35
+
36
+ /**
37
+ * Multiplier with one decimal and an `x` suffix, truncated rather than
38
+ * rounded so the digits never disagree with the colour: 1.49 reads `1.4x`
39
+ * (yellow), not `1.5x`.
40
+ */
41
+ export function formatMultiplier(m: number): string {
42
+ const x = Number.isFinite(m) ? Math.max(0, m) : 0;
43
+ // The epsilon keeps 2.3 from flooring to 2.2 through binary representation.
44
+ let v = Math.floor(x * 10 + 1e-9) / 10;
45
+ // ...but it must not lift a value across a colour boundary: 1.49999999999
46
+ // is yellow, so it reads 1.4x, never 1.5x.
47
+ if (x < 1.0) v = Math.min(v, 0.9);
48
+ else if (x < 1.5) v = Math.min(v, 1.4);
49
+ return `${v.toFixed(1)}x`;
50
+ }
51
+
52
+ /** How alarming a pace is: below 1.0 it lasts, 1.0–1.5 warns, from 1.5 it is red. */
53
+ export type PaceLevel = "ok" | "warning" | "error";
54
+
55
+ export function paceLevel(m: number): PaceLevel {
56
+ if (!Number.isFinite(m) || m < 1.0) return "ok";
57
+ if (m < 1.5) return "warning";
58
+ return "error";
59
+ }
60
+
61
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
62
+
63
+ /**
64
+ * Local wall-clock time of an instant: `14:20` within the next 24 hours,
65
+ * `Tue 14:20` further out so a weekly projection is not mistaken for today.
66
+ */
67
+ export function formatClock(iso: string, now: number): string | null {
68
+ const t = Date.parse(iso);
69
+ if (!Number.isFinite(t)) return null;
70
+ const d = new Date(t);
71
+ const hm = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
72
+ if (t - now < MINUTES_PER_DAY * MINUTE_MS) return hm;
73
+ return `${WEEKDAYS[d.getDay()]} ${hm}`;
74
+ }
@@ -1,7 +1,12 @@
1
1
  // Status-line quota renderer: produces the compact segment shown in the footer.
2
2
  //
3
- // Format: <gauge-icon> <braille-5h><braille-7d> <5h%>/<7d%>
4
- // Example: 󰐧 ⣷⣤ 83/23 (claude: 5h=83% green, 7d=23% yellow)
3
+ // Format: <gauge-icon> <label> <braille><pct> ↻<reset> [<pace>x] <label> ...
4
+ // Example: 󰐧 5h ⣶69 ↻4:40 7d ⣷81 ↻2д4ч
5
+ // 󰐧 5h ⣀31 ↻4:40 2.1x 7d ⣷81 ↻2д4ч (5h burning 2.1x too fast)
6
+ //
7
+ // The reset countdown is `h:mm` under a day and `NдNч` above. The pace
8
+ // multiplier comes from the bridge and is shown only when it is >= 1.0, i.e.
9
+ // when the window would run out before it resets: yellow below 1.5, red above.
5
10
  //
6
11
  // Context-aware: only the windows of the CURRENT model's provider are shown.
7
12
  // Provider mapping (Pi provider → usage-API provider):
@@ -9,15 +14,32 @@
9
14
  // openai → codex (5h Window / 7d Window)
10
15
  // custom → (hidden, no quota windows)
11
16
  //
12
- // Aggregation: MAX remaining fraction across live accounts (not disabled,
13
- // not unavailable) for each 5h/7d window label.
17
+ // Account, first that applies:
18
+ // 1. the account the bridge bound the session to (`session.status = bound`);
19
+ // 2. the router's active tier (`routing.active`): share-weighted average of
20
+ // remaining and of pace across its accounts with a share above 0
21
+ // (fill-first's zero-share accounts receive nothing and never count);
22
+ // 3. old bridge: MAX remaining fraction across live accounts (not disabled,
23
+ // not unavailable) for each 5h/7d window label.
24
+ // Single requests served by another account (`session.lastServed`) never
25
+ // change the footer; it follows the binding, and so the session's moves.
14
26
  //
15
27
  // Colors: green ≥70% · yellow 30–69% · red <30%
16
28
 
17
29
  // The renderer accepts a structural theme type (anything with fg()) so it
18
30
  // stays decoupled from Pi's internal Theme class.
19
31
 
20
- import type { UsageAccount, UsageDocument, UsageGroup } from "./fetch-usage.ts";
32
+ import type {
33
+ UsageAccount,
34
+ UsageDocument,
35
+ UsageGroup,
36
+ UsagePace,
37
+ } from "./fetch-usage.ts";
38
+ import {
39
+ formatCountdown,
40
+ formatMultiplier,
41
+ paceLevel,
42
+ } from "./quota-format.ts";
21
43
 
22
44
  /** nf-md-gauge (Nerd Font Material Design speedometer). */
23
45
  const GAUGE_ICON = "\u{F0627}";
@@ -90,6 +112,21 @@ function scopeMatchesModel(scope: string, modelID: string): boolean {
90
112
 
91
113
  interface WindowAggregate {
92
114
  fraction: number;
115
+ /** The group the figure came from: its reset time and pace are shown. */
116
+ group: UsageGroup;
117
+ }
118
+
119
+ /** An account's bottleneck for a period: the matching group with least left. */
120
+ function tightestGroup(
121
+ a: UsageAccount,
122
+ predicate: (g: UsageGroup) => boolean,
123
+ ): UsageGroup | null {
124
+ let best: UsageGroup | null = null;
125
+ for (const g of a.groups ?? []) {
126
+ if (predicate(g) && (!best || g.remainingFraction < best.remainingFraction))
127
+ best = g;
128
+ }
129
+ return best;
93
130
  }
94
131
 
95
132
  /**
@@ -103,21 +140,97 @@ function aggregateWindow(
103
140
  accounts: UsageAccount[],
104
141
  predicate: (g: UsageGroup) => boolean,
105
142
  ): WindowAggregate | null {
106
- let maxAcross = -1;
143
+ let chosen: UsageGroup | null = null;
107
144
  for (const a of accounts) {
108
145
  if (!isLiveAccount(a)) continue;
109
- let minWithin = Infinity;
110
- for (const g of a.groups ?? []) {
111
- if (predicate(g)) {
112
- if (g.remainingFraction < minWithin) minWithin = g.remainingFraction;
113
- }
114
- }
115
- if (minWithin !== Infinity && minWithin > maxAcross) {
116
- maxAcross = minWithin;
146
+ const g = tightestGroup(a, predicate);
147
+ if (g && (!chosen || g.remainingFraction > chosen.remainingFraction)) {
148
+ chosen = g;
117
149
  }
118
150
  }
119
- if (maxAcross < 0) return null;
120
- return { fraction: clamp(maxAcross) };
151
+ return chosen ? { fraction: clamp(chosen.remainingFraction), group: chosen } : null;
152
+ }
153
+
154
+ /**
155
+ * The account the bridge bound this session to, when it is one of the
156
+ * provider's accounts and reports quota; null means "use the aggregate".
157
+ */
158
+ export function boundAccount(
159
+ doc: UsageDocument,
160
+ accounts: UsageAccount[],
161
+ ): UsageAccount | null {
162
+ const s = doc.session;
163
+ if (!s || s.status !== "bound" || !s.authIndex) return null;
164
+ const a = accounts.find((x) => x.authIndex === s.authIndex);
165
+ if (!a || !a.supported || !a.groups || a.groups.length === 0) return null;
166
+ return a;
167
+ }
168
+
169
+ /**
170
+ * The live accounts of the router's active tier that receive requests, with
171
+ * their weights. When the bridge reports shares, only accounts with a share
172
+ * above 0 count: under fill-first the whole top priority is active but only
173
+ * the first account gets traffic, and the others' quota says nothing about
174
+ * this session. The policy is chosen on the whole tier, before accounts
175
+ * without quota data are dropped, so a lead account that reports no windows
176
+ * never hands its place to a zero-share one. Without any positive share the
177
+ * tier is spread evenly.
178
+ */
179
+ function activeTier(
180
+ accounts: UsageAccount[],
181
+ ): { account: UsageAccount; weight: number }[] {
182
+ const tier = accounts.filter((a) => a.routing?.active === true);
183
+ const sharesKnown = tier.some((a) => (a.routing?.share ?? 0) > 0);
184
+ return tier
185
+ .filter((a) => isLiveAccount(a) && (!sharesKnown || (a.routing?.share ?? 0) > 0))
186
+ .map((account) => ({
187
+ account,
188
+ weight: sharesKnown ? account.routing!.share! : 1,
189
+ }));
190
+ }
191
+
192
+ /**
193
+ * A period across the active tier: remaining and pace averaged by share over
194
+ * the accounts that report the window. The reset countdown comes from the
195
+ * account receiving the largest share. Every weight is positive.
196
+ */
197
+ function tierWindow(
198
+ tier: { account: UsageAccount; weight: number }[],
199
+ predicate: (g: UsageGroup) => boolean,
200
+ ): WindowAggregate | null {
201
+ const parts: { g: UsageGroup; w: number }[] = [];
202
+ for (const { account, weight } of tier) {
203
+ const g = tightestGroup(account, predicate);
204
+ if (g) parts.push({ g, w: weight });
205
+ }
206
+ if (parts.length === 0) return null;
207
+ const sum = parts.reduce((s, p) => s + p.w, 0);
208
+ const fraction =
209
+ parts.reduce((s, p) => s + p.w * clamp(p.g.remainingFraction), 0) / sum;
210
+ const lead = parts.reduce((best, p) => (p.w > best.w ? p : best));
211
+ const paced = parts.filter((p) => p.g.pace);
212
+ const paceSum = paced.reduce((s, p) => s + p.w, 0);
213
+ const group: UsageGroup = { ...lead.g, remainingFraction: fraction };
214
+ delete group.pace;
215
+ if (paced.length > 0 && paceSum > 0) {
216
+ const avg = (pick: (pace: UsagePace) => number) =>
217
+ paced.reduce((s, p) => s + p.w * pick(p.g.pace!), 0) / paceSum;
218
+ group.pace = {
219
+ multiplier: avg((p) => p.multiplier),
220
+ burnPerHour: avg((p) => p.burnPerHour),
221
+ sampleMinutes: Math.min(...paced.map((p) => p.g.pace!.sampleMinutes)),
222
+ };
223
+ }
224
+ return { fraction: clamp(fraction), group };
225
+ }
226
+
227
+ /** One account's figure for a period, shaped like an aggregate. */
228
+ function accountWindow(
229
+ a: UsageAccount,
230
+ predicate: (g: UsageGroup) => boolean,
231
+ ): WindowAggregate | null {
232
+ const g = tightestGroup(a, predicate);
233
+ return g ? { fraction: clamp(g.remainingFraction), group: g } : null;
121
234
  }
122
235
 
123
236
  function clamp(f: number): number {
@@ -155,6 +268,7 @@ function pct(fraction: number): number {
155
268
  * @param modelID - id of the selected model (e.g. "claude-fable-5"). When the
156
269
  * provider reports a weekly window scoped to that model, it is shown as its
157
270
  * own segment and excluded from the account-wide figure.
271
+ * @param now - clock for the reset countdown (tests pass a fixed one)
158
272
  */
159
273
  export function renderQuotaSegment(
160
274
  doc: UsageDocument,
@@ -164,6 +278,7 @@ export function renderQuotaSegment(
164
278
  fg(color: "success" | "warning" | "error" | "dim", text: string): string;
165
279
  },
166
280
  modelID?: string,
281
+ now: number = Date.now(),
167
282
  ): string | null {
168
283
  const usageKey = providerToUsageKey(piProvider);
169
284
  if (!usageKey) return null;
@@ -180,32 +295,71 @@ export function renderQuotaSegment(
180
295
  return scope !== null && scopeMatchesModel(scope, modelID as string);
181
296
  };
182
297
 
183
- const w5 = aggregateWindow(accounts, is5hGroup);
298
+ // The session's own account when the bridge knows it: the max across
299
+ // accounts would show headroom this session cannot use. Without one, the
300
+ // tier the router dispatches a new request to.
301
+ const own = boundAccount(doc, accounts);
302
+ // A known tier is used even when none of its routed accounts reports a
303
+ // window: the max would show a zero-share account's quota instead.
304
+ const hasTier = accounts.some((a) => a.routing?.active === true);
305
+ const tier = own || !hasTier ? [] : activeTier(accounts);
306
+ const windowOf = (predicate: (g: UsageGroup) => boolean) => {
307
+ if (own) return accountWindow(own, predicate);
308
+ if (hasTier) return tierWindow(tier, predicate);
309
+ return aggregateWindow(accounts, predicate);
310
+ };
311
+
312
+ const w5 = windowOf(is5hGroup);
184
313
  // Other models' scoped windows say nothing about the model in use, and
185
314
  // including them used to drag the weekly figure down for no reason.
186
- const w7 = aggregateWindow(
187
- accounts,
188
- (g) => is7dGroup(g) && scopeOf(g) === null,
189
- );
190
- const wModel = aggregateWindow(accounts, isSelectedModelWindow);
315
+ const w7 = windowOf((g) => is7dGroup(g) && scopeOf(g) === null);
316
+ const wModel = windowOf(isSelectedModelWindow);
191
317
 
192
318
  // Nothing to show → hide the segment entirely
193
319
  if (!w5 && !w7 && !wModel) return null;
194
320
 
195
- const parts: string[] = [theme.fg("dim", GAUGE_ICON)];
196
- const push = (label: string, fraction: number) => {
197
- const color = colorForFraction(fraction);
198
- parts.push(
199
- `${theme.fg("dim", label)} ${theme.fg(color, brailleFor(fraction))} ${theme.fg(color, String(pct(fraction)))}`,
200
- );
201
- };
321
+ const windows: string[] = [];
322
+ if (w5) windows.push(renderWindow(theme, "5h", w5, now));
323
+ if (w7) windows.push(renderWindow(theme, "7d", w7, now));
324
+ if (wModel) {
325
+ const label = modelWindowLabel(accounts, modelID as string);
326
+ windows.push(renderWindow(theme, label, wModel, now));
327
+ }
202
328
 
203
- if (w5) push("5h", w5.fraction);
204
- if (w7) push("7d", w7.fraction);
205
- if (wModel)
206
- push(modelWindowLabel(accounts, modelID as string), wModel.fraction);
329
+ return `${theme.fg("dim", GAUGE_ICON)} ${windows.join(" ")}`;
330
+ }
207
331
 
208
- return parts.join(" ");
332
+ /** One window: `5h ⣶69 ↻4:40`, plus the multiplier when it will not last. */
333
+ function renderWindow(
334
+ theme: {
335
+ fg(color: "success" | "warning" | "error" | "dim", text: string): string;
336
+ },
337
+ label: string,
338
+ w: WindowAggregate,
339
+ now: number,
340
+ ): string {
341
+ const color = colorForFraction(w.fraction);
342
+ let text = `${theme.fg("dim", label)} ${theme.fg(color, brailleFor(w.fraction))}${theme.fg(color, String(pct(w.fraction)))}`;
343
+ const reset = formatCountdown(w.group.resetTime, now);
344
+ if (reset) text += ` ${theme.fg("dim", `↻${reset}`)}`;
345
+ const pace = paceWarning(w.group);
346
+ if (pace) text += ` ${theme.fg(pace.color, pace.text)}`;
347
+ return text;
348
+ }
349
+
350
+ /**
351
+ * The multiplier, only when the window will not last at the current pace.
352
+ * A sustainable pace, or no pace at all (old bridge, too little history),
353
+ * adds nothing: the footer stays as short as possible when all is well.
354
+ */
355
+ function paceWarning(
356
+ g: UsageGroup,
357
+ ): { text: string; color: "warning" | "error" } | null {
358
+ const m = g.pace?.multiplier;
359
+ if (typeof m !== "number") return null;
360
+ const level = paceLevel(m);
361
+ if (level === "ok") return null;
362
+ return { text: formatMultiplier(m), color: level };
209
363
  }
210
364
 
211
365
  /**
package/src/ui-hub/hub.ts CHANGED
@@ -59,7 +59,16 @@ export function buildHub(
59
59
  flash = "";
60
60
  },
61
61
  });
62
- const usage: UsageView = buildUsageView({ tui, theme, cfg });
62
+ // The session and model let the bridge mark the account serving this session.
63
+ const usage: UsageView = buildUsageView({
64
+ tui,
65
+ theme,
66
+ cfg,
67
+ session: () => {
68
+ const id = ctx.sessionManager.getSessionId();
69
+ return id ? { id, model: ctx.model?.id } : undefined;
70
+ },
71
+ });
63
72
  const diagnostics: HubView = buildDiagnosticsView({
64
73
  theme,
65
74
  cfg,
@@ -9,6 +9,7 @@ import {
9
9
  clearUsageCache,
10
10
  fetchUsage,
11
11
  type UsageDocument,
12
+ type UsageSessionQuery,
12
13
  } from "../fetch-usage.ts";
13
14
  import { pad } from "../ui-picker/render-text.ts";
14
15
  import type { OverlayTui, Theme } from "../ui-picker/types.ts";
@@ -20,6 +21,8 @@ export interface UsageViewDeps {
20
21
  tui: OverlayTui;
21
22
  theme: Theme;
22
23
  cfg: ProxyConfig;
24
+ /** The Pi session viewing the tab, so its account can be marked. */
25
+ session?: () => UsageSessionQuery | undefined;
23
26
  }
24
27
 
25
28
  export interface UsageView extends HubView {
@@ -40,7 +43,7 @@ export function buildUsageView(deps: UsageViewDeps): UsageView {
40
43
  status = "loading";
41
44
  tui.requestRender();
42
45
  const usageKey = resolveConfigValue(cfg.proxy.usageKey);
43
- void fetchUsage(cfg, usageKey, { force })
46
+ void fetchUsage(cfg, usageKey, { force, session: deps.session?.() })
44
47
  .then((d) => {
45
48
  doc = d;
46
49
  status = "ready";
@@ -54,16 +57,20 @@ export function buildUsageView(deps: UsageViewDeps): UsageView {
54
57
  });
55
58
  };
56
59
 
60
+ let lastWidth: number | undefined;
57
61
  const lines = (): string[] => {
58
62
  if (status === "idle" || status === "loading")
59
63
  return [theme.fg("dim", " loading usage\u2026")];
60
64
  if (status === "error")
61
65
  return [theme.fg("error", ` usage failed: ${errMsg}`)];
62
66
  if (!doc) return [theme.fg("dim", " (no data)")];
63
- return renderUsage(doc, { showDisabled, verbose });
67
+ // One column goes to the left margin added in render().
68
+ const width = lastWidth === undefined ? undefined : lastWidth - 1;
69
+ return renderUsage(doc, { showDisabled, verbose, width });
64
70
  };
65
71
 
66
72
  const render = (width: number, height: number): string[] => {
73
+ lastWidth = width;
67
74
  const body = lines();
68
75
  offset = clampOffset(offset, height, body.length);
69
76
  return takeSlice(body, offset, height).map((ln) => pad(` ${ln}`, width));