pi-cliproxyapi 0.4.3 → 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.
- package/README.md +78 -7
- package/index.ts +182 -105
- package/package.json +2 -1
- package/src/aliases.ts +520 -0
- package/src/apply.ts +80 -3
- package/src/cache-namespace.ts +21 -0
- package/src/cache.ts +58 -3
- package/src/config.ts +2 -0
- package/src/fetch-models.ts +119 -15
- package/src/fetch-usage.ts +297 -11
- package/src/quota-footer.ts +255 -0
- package/src/quota-format.ts +74 -0
- package/src/status-quota.ts +188 -34
- package/src/ui-hub/hub.ts +10 -1
- package/src/ui-hub/view-usage.ts +9 -2
- package/src/ui-usage.ts +178 -34
- package/src/usage-shared-cache.ts +303 -24
package/README.md
CHANGED
|
@@ -23,18 +23,82 @@ The footer shows how much of each provider window is left for the model you are
|
|
|
23
23
|
currently using, so a limit is visible before it bites rather than after:
|
|
24
24
|
|
|
25
25
|
```text
|
|
26
|
-
claude-sonnet-5 5h ⣶
|
|
27
|
-
claude-fable-5 5h ⣶
|
|
26
|
+
claude-sonnet-5 5h ⣶69 ↻4:40 7d ⣷81 ↻2д4ч
|
|
27
|
+
claude-fable-5 5h ⣶69 ↻4:40 7d ⣷81 ↻2д4ч Fable ⣾91 ↻2д4ч
|
|
28
|
+
burning too fast 5h ⣀31 ↻4:40 2.1x 7d ⣷81 ↻2д4ч
|
|
28
29
|
```
|
|
29
30
|
|
|
31
|
+
Each window shows what is left and the time until it resets: `↻4:40` under a
|
|
32
|
+
day, `↻2д4ч` (days and hours) beyond. Durations round down. When everything is
|
|
33
|
+
fine that is all you see. Only when the current pace would exhaust a window
|
|
34
|
+
before it resets does the pace multiplier appear after it — `2.1x` means quota
|
|
35
|
+
is going 2.1 times faster than would last until the reset; yellow from 1.0x,
|
|
36
|
+
red from 1.5x. The pace is computed by the bridge from its own history, so
|
|
37
|
+
every Pi instance sees the same number; an older bridge simply shows no
|
|
38
|
+
multiplier.
|
|
39
|
+
|
|
40
|
+
The figures are for the account your session is actually bound to when the
|
|
41
|
+
bridge knows it; otherwise for the account with the most headroom, which is
|
|
42
|
+
where the router sends the next request.
|
|
43
|
+
|
|
30
44
|
Windows are read live, not guessed. Anthropic caps some models against a slice
|
|
31
45
|
of the weekly pool — Fable may draw down half of it, and draws faster than other
|
|
32
46
|
models — so that per-model window is shown **alongside** the weekly figure
|
|
33
47
|
rather than folded into it. Switching models switches the window on display.
|
|
34
48
|
Other models' windows never drag down the general figure.
|
|
35
49
|
|
|
36
|
-
Green ≥
|
|
37
|
-
down per account
|
|
50
|
+
Green ≥ 70%, yellow 30–69%, red < 30%. The **Usage** tab breaks the same data
|
|
51
|
+
down per account and answers "how fast and until when":
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
▌ claude
|
|
55
|
+
● daniil@example.com ✓12 ✗0 ◆ this session
|
|
56
|
+
[██████░░░░░░░░░░░░] 31% 5h Session ↻4:40 2.1x 20%/h out 14:20
|
|
57
|
+
[███████████████░░░] 81% 7d Weekly ↻2д4ч 0.4x 2%/h lasts
|
|
58
|
+
[███████████████░░░] 81% 7d Fable ↻2д4ч pace: collecting
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Per window: remaining, reset countdown, pace multiplier, burn per hour (percent
|
|
62
|
+
of the window) and the clock time it runs out — or `lasts` when the pace is
|
|
63
|
+
sustainable. `pace: collecting` means the bridge does not have enough history
|
|
64
|
+
yet (about 15 minutes). `◆ this session` marks the account serving the
|
|
65
|
+
current session.
|
|
66
|
+
|
|
67
|
+
## `latest/*` models
|
|
68
|
+
|
|
69
|
+
Model ids carry versions, so sessions and agent definitions keep pointing at
|
|
70
|
+
retired models. With pi-bridge 0.11.0 or newer, `/model` also lists aliases
|
|
71
|
+
that always mean the newest model of a family:
|
|
72
|
+
|
|
73
|
+
| Alias | Resolves to (example) |
|
|
74
|
+
| --- | --- |
|
|
75
|
+
| `latest/opus`, `latest/sonnet`, `latest/haiku`, `latest/fable` | `claude-opus-5-5`, … |
|
|
76
|
+
| `latest/gpt-astra`, `latest/gpt-sol`, `latest/gpt-terra`, `latest/gpt-luna` | `gpt-6.1-sol`, … |
|
|
77
|
+
|
|
78
|
+
Each is named after its current resolution, e.g. `Opus (latest: claude-opus-5-5)`,
|
|
79
|
+
and carries that model's context window, limits and cost. Only aliases whose
|
|
80
|
+
family is enabled in this extension are listed: when one model of a family is
|
|
81
|
+
in your whitelist (say `gpt-6.1-sol`), newer versions the proxy serves are
|
|
82
|
+
registered too, so the alias can point at them. A family pattern from the
|
|
83
|
+
bridge is only used if it is a plain version pattern like
|
|
84
|
+
`^claude-opus-(\d+)(?:-(\d+))?$`; anything else is ignored with a warning.
|
|
85
|
+
|
|
86
|
+
Selecting an alias — with `/model`, as the default model, or with
|
|
87
|
+
`model: latest/opus` in an agent definition — switches the session to the
|
|
88
|
+
concrete model straight away. The session records that model, so it keeps its
|
|
89
|
+
version for its whole lifetime: a resumed session stays on it after the alias
|
|
90
|
+
moves on, as long as the proxy still serves it, and the prompt cache is never
|
|
91
|
+
broken by a silent upgrade. The next new session picks up whatever is newest
|
|
92
|
+
then.
|
|
93
|
+
|
|
94
|
+
Resolutions are refreshed before a pin when they are older than 30 minutes,
|
|
95
|
+
waiting at most 8 seconds; if the bridge cannot answer (also when only
|
|
96
|
+
`/v1/models` does), the last known resolution is used. If an alias cannot be
|
|
97
|
+
resolved at all, a warning names it and the session stays on the alias
|
|
98
|
+
itself, unpinned: while `latest/<alias>` is still registered, requests go out
|
|
99
|
+
under the alias and the bridge resolves it per request, so the version can
|
|
100
|
+
change between turns; if it is no longer registered, Pi has no model to send
|
|
101
|
+
to.
|
|
38
102
|
|
|
39
103
|
## How the numbers get here
|
|
40
104
|
|
|
@@ -70,7 +134,8 @@ installing it into CliProxyAPI.
|
|
|
70
134
|
|
|
71
135
|
## Features
|
|
72
136
|
|
|
73
|
-
- **Live quota** — status-line windows for the model in use, per-account bars in the **Usage** tab, no LLM call
|
|
137
|
+
- **Live quota** — status-line windows for the model in use with reset countdown and a pace warning, per-account bars with burn rate and forecast in the **Usage** tab, no LLM call
|
|
138
|
+
- **`latest/*` aliases** — pick a model family; each session pins the newest concrete model
|
|
74
139
|
- **Unified hub** — one `/cliproxy` overlay with **Models / Usage / Diagnostics** tabs (number hotkeys `1` `2` `3`) plus global actions: `r` refresh, `e` setup, `s` save
|
|
75
140
|
- **Built-in provider routing** — whitelist which Anthropic / OpenAI / etc. models are available through the proxy
|
|
76
141
|
- **Custom provider groups** — create named groups (e.g. `corp-glm`, `corp-gemini`) for proxy-only models with automatic metadata from [models.dev](https://models.dev)
|
|
@@ -99,7 +164,7 @@ Global keys: `[` / `]` or `1` `2` `3` switch tabs · `r` refresh discovery + rea
|
|
|
99
164
|
|
|
100
165
|
Extra Models keys: `d` removes a custom group (with confirmation).
|
|
101
166
|
|
|
102
|
-
**Usage tab** — per-account quota bars; `d` shows disabled accounts, `v` shows verbose errors.
|
|
167
|
+
**Usage tab** — per-account quota bars with reset countdown, pace, burn per hour and exhaustion forecast; the session's account is marked. `d` shows disabled accounts, `v` shows verbose errors.
|
|
103
168
|
|
|
104
169
|
**Diagnostics tab** — connectivity, key resolution, and discovery shape.
|
|
105
170
|
|
|
@@ -162,12 +227,18 @@ cache.
|
|
|
162
227
|
"customProviders": {
|
|
163
228
|
"corp-glm": {
|
|
164
229
|
"api": "openai-completions",
|
|
165
|
-
"models": [{ "id": "glm-4.7", "name": "GLM 4.7" }]
|
|
230
|
+
"models": [{ "id": "glm-4.7", "name": "GLM 4.7", "input": ["text", "image"] }]
|
|
166
231
|
}
|
|
167
232
|
}
|
|
168
233
|
}
|
|
169
234
|
```
|
|
170
235
|
|
|
236
|
+
`input` is optional per model and lists the input modalities the model
|
|
237
|
+
accepts (`"text"`, `"image"`). When the pi-bridge plugin is present this is
|
|
238
|
+
usually supplied automatically from models.dev; setting it by hand is useful
|
|
239
|
+
for proxies that cannot serve the enriched catalogue. Omitting it defaults to
|
|
240
|
+
`["text"]`.
|
|
241
|
+
|
|
171
242
|
Values support `!command` (shell exec), `$ENV_VAR`, or literal strings. The `/cliproxy-setup` wizard also accepts bare `~/path` values and saves them as `!cat` commands; when editing the file by hand, write the `!cat ~/path` form explicitly.
|
|
172
243
|
|
|
173
244
|
## Setup
|
package/index.ts
CHANGED
|
@@ -18,36 +18,32 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
18
18
|
import fs from "node:fs";
|
|
19
19
|
import path from "node:path";
|
|
20
20
|
|
|
21
|
+
import { aliasCatalogueAgeMs, registerAliasPin } from "./src/aliases.ts";
|
|
21
22
|
import { applyAll } from "./src/apply.ts";
|
|
22
|
-
import { readDiscoveryCache } from "./src/cache.ts";
|
|
23
|
+
import { discoveryNamespace, readDiscoveryCache } from "./src/cache.ts";
|
|
23
24
|
import { registerCommands } from "./src/commands.ts";
|
|
24
25
|
import { loadConfig, resolveConfigValue } from "./src/config.ts";
|
|
25
26
|
import { detectConflicts } from "./src/conflicts.ts";
|
|
26
27
|
import { fetchDiscovery } from "./src/fetch-models.ts";
|
|
27
28
|
import type { ProxyConfig } from "./src/config.ts";
|
|
28
|
-
import type { UsageDocument } from "./src/fetch-usage.ts";
|
|
29
29
|
import {
|
|
30
|
-
fetchUsage,
|
|
31
30
|
lastUsageContract,
|
|
32
31
|
lastUsageSource,
|
|
33
32
|
PREFERRED_CONTRACT,
|
|
34
33
|
} from "./src/fetch-usage.ts";
|
|
35
34
|
import { log, setLogSink } from "./src/log.ts";
|
|
35
|
+
import { SESSION_BINDING_TTL_MS } from "./src/usage-shared-cache.ts";
|
|
36
36
|
import {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
writeUsageCache,
|
|
42
|
-
} from "./src/usage-shared-cache.ts";
|
|
43
|
-
import { renderQuotaSegment } from "./src/status-quota.ts";
|
|
37
|
+
createQuotaFooter,
|
|
38
|
+
type QuotaTarget,
|
|
39
|
+
sharedCacheSource,
|
|
40
|
+
} from "./src/quota-footer.ts";
|
|
44
41
|
|
|
45
|
-
/** Status-line key. The leading "0" makes it sort before alphabetic keys so
|
|
46
|
-
* the quota segment appears first on the footer's extension-status line. */
|
|
47
|
-
const QUOTA_STATUS_KEY = "0quota";
|
|
48
42
|
/** Minimum gap between network fetches triggered by turn_end, even if the
|
|
49
43
|
* shared file cache is stale (prevents burst fetches during rapid turns). */
|
|
50
44
|
const TURN_FETCH_DEBOUNCE_MS = 5_000;
|
|
45
|
+
/** Footer repaint interval: the countdown shows minutes. */
|
|
46
|
+
export const QUOTA_TICK_MS = 30_000;
|
|
51
47
|
|
|
52
48
|
/** Guards the legacy-source warning so it appears once per session. */
|
|
53
49
|
let legacyUsageWarned = false;
|
|
@@ -67,65 +63,81 @@ export function isHeadlessRun(argv = process.argv): boolean {
|
|
|
67
63
|
);
|
|
68
64
|
}
|
|
69
65
|
|
|
70
|
-
/**
|
|
71
|
-
* Fetch usage data through the shared file cache: if the on-disk cache is
|
|
72
|
-
* fresh (within TTL), return it without any network call; otherwise acquire
|
|
73
|
-
* a cross-process lock and fetch at most once. Returns the best available
|
|
74
|
-
* doc (possibly stale) or null on failure.
|
|
75
|
-
*/
|
|
76
|
-
async function loadUsageCached(
|
|
77
|
-
cfg: ProxyConfig,
|
|
78
|
-
resolvedUsageKey: string,
|
|
79
|
-
opts: { readOnly?: boolean } = {},
|
|
80
|
-
): Promise<UsageDocument | null> {
|
|
81
|
-
const cached = readUsageCache();
|
|
82
|
-
if (cached && isUsageFresh(cached.ageMs)) return cached.doc;
|
|
83
|
-
// readOnly mode (debounce path): never fetch, serve stale cache if available.
|
|
84
|
-
if (opts.readOnly) return cached?.doc ?? null;
|
|
85
|
-
// Stale or missing — try to become the fetcher.
|
|
86
|
-
const token = tryAcquireUsageLock();
|
|
87
|
-
if (!token) {
|
|
88
|
-
// Another instance is fetching; serve stale data if we have it.
|
|
89
|
-
return cached?.doc ?? null;
|
|
90
|
-
}
|
|
91
|
-
try {
|
|
92
|
-
const doc = await fetchUsage(cfg, resolvedUsageKey, { force: true });
|
|
93
|
-
writeUsageCache(doc);
|
|
94
|
-
return doc;
|
|
95
|
-
} catch (e) {
|
|
96
|
-
log.debug("usage fetch failed in shared cache:", (e as Error).message);
|
|
97
|
-
return cached?.doc ?? null;
|
|
98
|
-
} finally {
|
|
99
|
-
releaseUsageLock(token);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
66
|
/**
|
|
104
67
|
* Refresh discovery over the network after the cached copy was applied.
|
|
105
68
|
*
|
|
106
69
|
* The extension handle captured at startup becomes invalid once pi replaces or
|
|
107
70
|
* reloads the session, so a slow refresh that finishes afterwards must not try
|
|
108
71
|
* to register providers with it. That case is expected, not an error.
|
|
72
|
+
* Resolves true when a fresh catalogue was applied (false when its aliases
|
|
73
|
+
* had to be carried over from the cache). Never rejects.
|
|
109
74
|
*/
|
|
110
75
|
async function revalidateDiscovery(
|
|
111
76
|
pi: ExtensionAPI,
|
|
112
77
|
cfg: ProxyConfig,
|
|
113
78
|
resolvedKey: string,
|
|
114
|
-
): Promise<
|
|
79
|
+
): Promise<boolean> {
|
|
115
80
|
try {
|
|
116
81
|
const fresh = await fetchDiscovery(cfg, resolvedKey);
|
|
117
82
|
await applyAll(pi, cfg, fresh);
|
|
118
83
|
log.debug("discovery revalidated from network");
|
|
84
|
+
// Aliases carried over from an older catalogue are not fresh: report
|
|
85
|
+
// failure so the pin does not wait for another refresh right away.
|
|
86
|
+
return fresh.aliasesFetchedAt === undefined;
|
|
119
87
|
} catch (e) {
|
|
120
88
|
const message = (e as Error).message ?? "";
|
|
121
89
|
if (message.includes("stale after session replacement")) {
|
|
122
90
|
log.debug("discovery revalidate skipped: session was replaced");
|
|
123
|
-
return;
|
|
91
|
+
return false;
|
|
124
92
|
}
|
|
125
93
|
log.warn("background discovery revalidate failed:", message);
|
|
94
|
+
return false;
|
|
126
95
|
}
|
|
127
96
|
}
|
|
128
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Alias freshness policy. A `latest/*` resolution older than this is
|
|
100
|
+
* revalidated before a session is pinned with it, waiting at most
|
|
101
|
+
* ALIAS_REFRESH_WAIT_MS; if the bridge cannot answer in time the last known
|
|
102
|
+
* resolution is used (deliberate offline fallback). A failed attempt is not
|
|
103
|
+
* repeated for ALIAS_RETRY_MS, so an offline bridge costs one wait, not one
|
|
104
|
+
* per selection.
|
|
105
|
+
*/
|
|
106
|
+
export const ALIAS_MAX_AGE_MS = 30 * 60_000;
|
|
107
|
+
export const ALIAS_REFRESH_WAIT_MS = 8_000;
|
|
108
|
+
const ALIAS_RETRY_MS = 60_000;
|
|
109
|
+
|
|
110
|
+
/** Resolve after `ms` without keeping the process alive. */
|
|
111
|
+
function delay(ms: number): Promise<void> {
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
const t = setTimeout(resolve, ms);
|
|
114
|
+
(t as { unref?: () => void }).unref?.();
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Single-flight catalogue refresh shared by boot revalidation and the pin. */
|
|
119
|
+
function createDiscoveryRefresher(run: () => Promise<boolean>) {
|
|
120
|
+
let inFlight: Promise<boolean> | null = null;
|
|
121
|
+
let lastFailureAt = 0;
|
|
122
|
+
const start = (): Promise<boolean> => {
|
|
123
|
+
inFlight ??= run().then((ok) => {
|
|
124
|
+
inFlight = null;
|
|
125
|
+
if (!ok) lastFailureAt = Date.now();
|
|
126
|
+
return ok;
|
|
127
|
+
});
|
|
128
|
+
return inFlight;
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
start,
|
|
132
|
+
/** Make the alias resolutions fresh if possible, within a bounded wait. */
|
|
133
|
+
async ensureAliasesFresh(): Promise<void> {
|
|
134
|
+
if (aliasCatalogueAgeMs() < ALIAS_MAX_AGE_MS) return;
|
|
135
|
+
if (!inFlight && Date.now() - lastFailureAt < ALIAS_RETRY_MS) return;
|
|
136
|
+
await Promise.race([start(), delay(ALIAS_REFRESH_WAIT_MS)]);
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
129
141
|
/** Warn once per session when quota still comes from a pre-contract source, so
|
|
130
142
|
* a deprecated path is visible rather than silently permanent. */
|
|
131
143
|
function warnIfLegacyUsageSource(ui: {
|
|
@@ -157,31 +169,15 @@ function warnIfLegacyUsageSource(ui: {
|
|
|
157
169
|
}
|
|
158
170
|
}
|
|
159
171
|
|
|
160
|
-
/**
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
};
|
|
169
|
-
setStatus(key: string, text: string | undefined): void;
|
|
170
|
-
},
|
|
171
|
-
model: { provider: string; id?: string } | undefined,
|
|
172
|
-
opts: { readOnly?: boolean } = {},
|
|
173
|
-
): Promise<void> {
|
|
174
|
-
if (!model) {
|
|
175
|
-
ui.setStatus(QUOTA_STATUS_KEY, undefined);
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
const doc = await loadUsageCached(cfg, resolvedUsageKey, opts);
|
|
179
|
-
if (!doc) {
|
|
180
|
-
ui.setStatus(QUOTA_STATUS_KEY, undefined);
|
|
181
|
-
return;
|
|
172
|
+
/** The Pi session id, or undefined when the session manager cannot tell. */
|
|
173
|
+
function sessionIdOf(ctx: {
|
|
174
|
+
sessionManager?: { getSessionId?(): string };
|
|
175
|
+
}): string | undefined {
|
|
176
|
+
try {
|
|
177
|
+
return ctx.sessionManager?.getSessionId?.() || undefined;
|
|
178
|
+
} catch {
|
|
179
|
+
return undefined;
|
|
182
180
|
}
|
|
183
|
-
const rendered = renderQuotaSegment(doc, model.provider, ui.theme, model.id);
|
|
184
|
-
ui.setStatus(QUOTA_STATUS_KEY, rendered ?? undefined);
|
|
185
181
|
}
|
|
186
182
|
|
|
187
183
|
/**
|
|
@@ -231,6 +227,14 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
|
|
|
231
227
|
setLogSink(ctx.hasUI ? ctx.ui : null);
|
|
232
228
|
});
|
|
233
229
|
|
|
230
|
+
// `latest/*` never serves a session: switch to the concrete model it
|
|
231
|
+
// resolves to, so the session records (and on resume keeps) that version.
|
|
232
|
+
// Registered after the log sink so an unresolved alias warns in the UI, and
|
|
233
|
+
// in headless runs too, where agent definitions select models.
|
|
234
|
+
// A stale catalogue is revalidated (bounded) before an alias is pinned.
|
|
235
|
+
let ensureAliasesFresh: (() => Promise<void>) | undefined;
|
|
236
|
+
registerAliasPin(pi, { beforePin: () => ensureAliasesFresh?.() ?? Promise.resolve() });
|
|
237
|
+
|
|
234
238
|
const cfg = loadConfig();
|
|
235
239
|
const resolvedKey = resolveConfigValue(cfg.proxy.apiKey);
|
|
236
240
|
if (!resolvedKey) {
|
|
@@ -246,8 +250,13 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
|
|
|
246
250
|
for (const c of conflicts) log.warn(`conflict (${c.kind}): ${c.detail}`);
|
|
247
251
|
}
|
|
248
252
|
|
|
253
|
+
const refresher = createDiscoveryRefresher(() =>
|
|
254
|
+
revalidateDiscovery(pi, cfg, resolvedKey),
|
|
255
|
+
);
|
|
256
|
+
ensureAliasesFresh = refresher.ensureAliasesFresh;
|
|
257
|
+
|
|
249
258
|
try {
|
|
250
|
-
const cached = readDiscoveryCache();
|
|
259
|
+
const cached = readDiscoveryCache(discoveryNamespace(cfg, resolvedKey));
|
|
251
260
|
if (cached) {
|
|
252
261
|
// Serve the last good discovery instantly so Pi startup never blocks on
|
|
253
262
|
// the ~5s proxy round-trip, then revalidate over the network in the
|
|
@@ -255,18 +264,32 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
|
|
|
255
264
|
log.info(
|
|
256
265
|
`discovery from cache (age ${Math.round(cached.ageMs / 1000)}s): ${cached.discovery.builtinProviders.length} builtin, ${cached.discovery.customPool.length} custom`,
|
|
257
266
|
);
|
|
258
|
-
await applyAll(pi, cfg, cached.discovery
|
|
267
|
+
await applyAll(pi, cfg, cached.discovery, {
|
|
268
|
+
fetchedAt: Date.now() - cached.ageMs,
|
|
269
|
+
});
|
|
259
270
|
if (!headless) {
|
|
260
271
|
// Revalidate in the background, but bind the work to the session
|
|
261
272
|
// that started it: pi invalidates the extension handle when the
|
|
262
273
|
// session is replaced or reloaded, and using a captured handle
|
|
263
|
-
// afterwards throws.
|
|
264
|
-
|
|
274
|
+
// afterwards throws. An alias pin on a stale catalogue awaits this
|
|
275
|
+
// same refresh (bounded) instead of starting another.
|
|
276
|
+
void refresher.start();
|
|
265
277
|
}
|
|
278
|
+
// Headless runs stay off the network with a fresh cache; a stale one
|
|
279
|
+
// is refreshed only if a `latest/*` model is about to be pinned.
|
|
266
280
|
} else if (headless) {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
281
|
+
// Nothing cached: a subagent asking for `latest/*` (or any model of
|
|
282
|
+
// ours) would fail to resolve before any handler runs, so wait for
|
|
283
|
+
// the catalogue — bounded, since Pi awaits this factory.
|
|
284
|
+
const ok = await Promise.race([
|
|
285
|
+
refresher.start(),
|
|
286
|
+
delay(ALIAS_REFRESH_WAIT_MS).then(() => false),
|
|
287
|
+
]);
|
|
288
|
+
if (!ok) {
|
|
289
|
+
log.warn(
|
|
290
|
+
"discovery cache missing and the catalogue could not be fetched in time — no providers registered",
|
|
291
|
+
);
|
|
292
|
+
}
|
|
270
293
|
} else {
|
|
271
294
|
const discovery = await fetchDiscovery(cfg, resolvedKey);
|
|
272
295
|
await applyAll(pi, cfg, discovery);
|
|
@@ -306,39 +329,93 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
|
|
|
306
329
|
: resolveConfigValue(cfg.proxy.usageKey);
|
|
307
330
|
// Quota is available through the pi-bridge plugin (ordinary API key) or the
|
|
308
331
|
// legacy sidecar (separate usage key), so either credential enables it.
|
|
309
|
-
|
|
332
|
+
// Headless (JSON/print) runs have no footer, so they register no quota
|
|
333
|
+
// handlers at all.
|
|
334
|
+
if (headless) {
|
|
335
|
+
log.debug("headless run — quota status segment disabled");
|
|
336
|
+
} else if (resolvedUsageKey || cfg.proxy.apiKey) {
|
|
310
337
|
let lastTurnFetchMs = 0;
|
|
338
|
+
const footer = createQuotaFooter(sharedCacheSource(cfg, resolvedUsageKey));
|
|
339
|
+
// Pi awaits these handlers, and an alias pin runs inside model_select:
|
|
340
|
+
// each one paints from the cache and leaves the network to the
|
|
341
|
+
// background (see quota-footer.ts). None of them may throw.
|
|
342
|
+
const targetOf = (ctx: {
|
|
343
|
+
ui: QuotaTarget["ui"];
|
|
344
|
+
model?: QuotaTarget["model"];
|
|
345
|
+
sessionManager?: { getSessionId?(): string };
|
|
346
|
+
}): QuotaTarget => ({
|
|
347
|
+
ui: ctx.ui,
|
|
348
|
+
model: ctx.model,
|
|
349
|
+
sessionId: sessionIdOf(ctx),
|
|
350
|
+
});
|
|
351
|
+
const update = (
|
|
352
|
+
ctx: Parameters<typeof targetOf>[0] & { hasUI: boolean },
|
|
353
|
+
fetch: boolean,
|
|
354
|
+
): Promise<void> | undefined => {
|
|
355
|
+
try {
|
|
356
|
+
if (!ctx.hasUI) return undefined;
|
|
357
|
+
return footer.update(targetOf(ctx), { fetch });
|
|
358
|
+
} catch (err) {
|
|
359
|
+
log.debug("quota update failed:", (err as Error).message);
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
};
|
|
311
363
|
|
|
312
|
-
//
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
364
|
+
// The countdown and pace move while the session is idle too: repaint on a
|
|
365
|
+
// timer. A tick refreshes over the network only when the cache (or this
|
|
366
|
+
// session's binding) is older than the binding TTL, which also keeps
|
|
367
|
+
// the binding from expiring while idle.
|
|
368
|
+
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
369
|
+
const stopTicker = () => {
|
|
370
|
+
if (ticker !== undefined) clearInterval(ticker);
|
|
371
|
+
ticker = undefined;
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
pi.on("session_start", (_event, ctx) => {
|
|
375
|
+
stopTicker();
|
|
376
|
+
if (ctx.hasUI) {
|
|
377
|
+
ticker = setInterval(() => {
|
|
378
|
+
try {
|
|
379
|
+
void footer.update(targetOf(ctx), {
|
|
380
|
+
fetch: true,
|
|
381
|
+
staleAfterMs: SESSION_BINDING_TTL_MS,
|
|
382
|
+
unlessBusy: true,
|
|
383
|
+
});
|
|
384
|
+
} catch (err) {
|
|
385
|
+
log.debug("quota tick failed:", (err as Error).message);
|
|
386
|
+
}
|
|
387
|
+
}, QUOTA_TICK_MS);
|
|
388
|
+
(ticker as { unref?: () => void }).unref?.();
|
|
389
|
+
}
|
|
390
|
+
const pending = update(ctx, true);
|
|
391
|
+
void pending?.then(() => {
|
|
392
|
+
try {
|
|
393
|
+
warnIfLegacyUsageSource(ctx.ui);
|
|
394
|
+
} catch {
|
|
395
|
+
// The session may be gone by now.
|
|
396
|
+
}
|
|
397
|
+
});
|
|
317
398
|
});
|
|
318
399
|
|
|
319
|
-
// model_select:
|
|
320
|
-
//
|
|
321
|
-
pi.on("model_select",
|
|
322
|
-
|
|
323
|
-
await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model);
|
|
400
|
+
// model_select: repaint for the new model at once; never wait on the
|
|
401
|
+
// bridge, and a result for the previous model is discarded.
|
|
402
|
+
pi.on("model_select", (_event, ctx) => {
|
|
403
|
+
void update(ctx, true);
|
|
324
404
|
});
|
|
325
405
|
|
|
326
|
-
// turn_end: after an LLM response the quota has changed.
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
pi.on("turn_end",
|
|
330
|
-
if (!ctx.hasUI) return;
|
|
406
|
+
// turn_end: after an LLM response the quota has changed. Refresh (if the
|
|
407
|
+
// shared cache is stale) but debounce to avoid burst-fetching on rapid
|
|
408
|
+
// consecutive turns; within the window, repaint from cache only.
|
|
409
|
+
pi.on("turn_end", (_event, ctx) => {
|
|
331
410
|
const now = Date.now();
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
lastTurnFetchMs = now;
|
|
341
|
-
await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model);
|
|
411
|
+
const fetch = now - lastTurnFetchMs >= TURN_FETCH_DEBOUNCE_MS;
|
|
412
|
+
if (fetch) lastTurnFetchMs = now;
|
|
413
|
+
void update(ctx, fetch);
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
pi.on("session_shutdown", () => {
|
|
417
|
+
stopTicker();
|
|
418
|
+
footer.reset();
|
|
342
419
|
});
|
|
343
420
|
} else {
|
|
344
421
|
log.debug("usageKey not configured — quota status segment disabled");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-cliproxyapi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Pi extension for corporate management of model providers via a single CliProxyAPI endpoint",
|
|
6
6
|
"license": "MIT",
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
],
|
|
26
26
|
"scripts": {
|
|
27
27
|
"typecheck": "tsc --noEmit",
|
|
28
|
+
"test": "for f in tests/*.test.ts; do node --disable-warning=ExperimentalWarning --experimental-strip-types \"$f\" || exit 1; done",
|
|
28
29
|
"check:migration": "node --disable-warning=ExperimentalWarning --experimental-strip-types scripts/check-config-migration.ts",
|
|
29
30
|
"check:child": "node --disable-warning=ExperimentalWarning --experimental-strip-types tests/headless-child.ts"
|
|
30
31
|
},
|