pi-cliproxyapi 0.3.3 → 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/README.md +5 -5
- package/index.ts +128 -1
- package/package.json +3 -2
- package/src/config.ts +62 -8
- package/src/fetch-models.ts +1 -1
- package/src/status-quota.ts +162 -0
- package/src/ui-setup.ts +1 -1
- package/src/usage-shared-cache.ts +131 -0
package/README.md
CHANGED
|
@@ -83,15 +83,15 @@ Then run `/cliproxy-setup` to configure your proxy endpoint.
|
|
|
83
83
|
|
|
84
84
|
## Config
|
|
85
85
|
|
|
86
|
-
`~/.
|
|
86
|
+
`~/.pi/agent/pi-cliproxyapi/config.json` — created by `/cliproxy-setup`, editable by hand. If only the legacy `~/.config/pi-cliproxyapi/config.json` exists, an installed plugin moves it here once; a local checkout copies it and retains the legacy file.
|
|
87
87
|
|
|
88
88
|
```jsonc
|
|
89
89
|
{
|
|
90
90
|
"proxy": {
|
|
91
91
|
"endpoint": "https://proxy.example.com/v1",
|
|
92
|
-
"apiKey": "!cat ~/.
|
|
92
|
+
"apiKey": "!cat ~/.pi/agent/pi-cliproxyapi/key",
|
|
93
93
|
"providerPrefix": "corp",
|
|
94
|
-
"usageKey": "!cat ~/.
|
|
94
|
+
"usageKey": "!cat ~/.pi/agent/pi-cliproxyapi/usage-key"
|
|
95
95
|
},
|
|
96
96
|
"builtinProviders": {
|
|
97
97
|
"anthropic": { "enabled": true, "models": ["claude-opus-4-7"] },
|
|
@@ -106,7 +106,7 @@ Then run `/cliproxy-setup` to configure your proxy endpoint.
|
|
|
106
106
|
}
|
|
107
107
|
```
|
|
108
108
|
|
|
109
|
-
Values support `!command` (shell exec), `$ENV_VAR`, `~/path`
|
|
109
|
+
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.
|
|
110
110
|
|
|
111
111
|
## Discovery
|
|
112
112
|
|
|
@@ -191,7 +191,7 @@ The sidecar is **optional for basic usage** — without it the plugin falls back
|
|
|
191
191
|
```
|
|
192
192
|
index.ts ExtensionFactory entry point
|
|
193
193
|
src/
|
|
194
|
-
config.ts ~/.
|
|
194
|
+
config.ts ~/.pi/agent/pi-cliproxyapi/config.json
|
|
195
195
|
commands.ts 2 slash commands (hub + setup)
|
|
196
196
|
apply.ts pi.registerProvider calls
|
|
197
197
|
fetch-models.ts well-known + /v1/models fallback
|
package/index.ts
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
* CliProxyAPI endpoint with one corporate key.
|
|
4
4
|
*
|
|
5
5
|
* On factory boot we:
|
|
6
|
-
* 1. load ~/.
|
|
6
|
+
* 1. load ~/.pi/agent/pi-cliproxyapi/config.json (migrates legacy config; defaults if missing)
|
|
7
7
|
* 2. fetch discovery (well-known → fall back to /v1/models)
|
|
8
8
|
* 3. call pi.registerProvider for each enabled built-in + custom provider
|
|
9
9
|
* 4. register slash commands /cliproxy and /cliproxy-setup
|
|
10
10
|
* (refresh, usage, and diagnostics are tabs/actions inside the hub)
|
|
11
|
+
* 5. register status-line quota segment (shared file cache, see usage-shared-cache)
|
|
11
12
|
*
|
|
12
13
|
* All discovery + apply errors are logged but never abort extension load —
|
|
13
14
|
* a missing/broken proxy must not prevent Pi from starting.
|
|
@@ -21,7 +22,89 @@ import { registerCommands } from "./src/commands.ts";
|
|
|
21
22
|
import { loadConfig, resolveConfigValue } from "./src/config.ts";
|
|
22
23
|
import { detectConflicts } from "./src/conflicts.ts";
|
|
23
24
|
import { fetchDiscovery } from "./src/fetch-models.ts";
|
|
25
|
+
import type { ProxyConfig } from "./src/config.ts";
|
|
26
|
+
import type { UsageDocument } from "./src/fetch-usage.ts";
|
|
27
|
+
import { fetchUsage } from "./src/fetch-usage.ts";
|
|
24
28
|
import { log } from "./src/log.ts";
|
|
29
|
+
import {
|
|
30
|
+
isUsageFresh,
|
|
31
|
+
readUsageCache,
|
|
32
|
+
releaseUsageLock,
|
|
33
|
+
tryAcquireUsageLock,
|
|
34
|
+
writeUsageCache,
|
|
35
|
+
} from "./src/usage-shared-cache.ts";
|
|
36
|
+
import { renderQuotaSegment } from "./src/status-quota.ts";
|
|
37
|
+
|
|
38
|
+
/** Status-line key. The leading "0" makes it sort before alphabetic keys so
|
|
39
|
+
* the quota segment appears first on the footer's extension-status line. */
|
|
40
|
+
const QUOTA_STATUS_KEY = "0quota";
|
|
41
|
+
/** Minimum gap between network fetches triggered by turn_end, even if the
|
|
42
|
+
* shared file cache is stale (prevents burst fetches during rapid turns). */
|
|
43
|
+
const TURN_FETCH_DEBOUNCE_MS = 5_000;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Fetch usage data through the shared file cache: if the on-disk cache is
|
|
47
|
+
* fresh (within TTL), return it without any network call; otherwise acquire
|
|
48
|
+
* a cross-process lock and fetch at most once. Returns the best available
|
|
49
|
+
* doc (possibly stale) or null on failure.
|
|
50
|
+
*/
|
|
51
|
+
async function loadUsageCached(
|
|
52
|
+
cfg: ProxyConfig,
|
|
53
|
+
resolvedUsageKey: string,
|
|
54
|
+
opts: { readOnly?: boolean } = {},
|
|
55
|
+
): Promise<UsageDocument | null> {
|
|
56
|
+
const cached = readUsageCache();
|
|
57
|
+
if (cached && isUsageFresh(cached.ageMs)) return cached.doc;
|
|
58
|
+
// readOnly mode (debounce path): never fetch, serve stale cache if available.
|
|
59
|
+
if (opts.readOnly) return cached?.doc ?? null;
|
|
60
|
+
// Stale or missing — try to become the fetcher.
|
|
61
|
+
const token = tryAcquireUsageLock();
|
|
62
|
+
if (!token) {
|
|
63
|
+
// Another instance is fetching; serve stale data if we have it.
|
|
64
|
+
return cached?.doc ?? null;
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
const doc = await fetchUsage(cfg, resolvedUsageKey, { force: true });
|
|
68
|
+
writeUsageCache(doc);
|
|
69
|
+
return doc;
|
|
70
|
+
} catch (e) {
|
|
71
|
+
log.debug("usage fetch failed in shared cache:", (e as Error).message);
|
|
72
|
+
return cached?.doc ?? null;
|
|
73
|
+
} finally {
|
|
74
|
+
releaseUsageLock(token);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Update the quota status segment for the current model. No-op if the model
|
|
79
|
+
* has no quota windows (e.g. a custom provider) or if usage is unavailable. */
|
|
80
|
+
async function refreshQuotaStatus(
|
|
81
|
+
cfg: ProxyConfig,
|
|
82
|
+
resolvedUsageKey: string,
|
|
83
|
+
ui: {
|
|
84
|
+
theme: {
|
|
85
|
+
fg(color: "success" | "warning" | "error" | "dim", text: string): string;
|
|
86
|
+
};
|
|
87
|
+
setStatus(key: string, text: string | undefined): void;
|
|
88
|
+
},
|
|
89
|
+
model: { provider: string } | undefined,
|
|
90
|
+
opts: { readOnly?: boolean } = {},
|
|
91
|
+
): Promise<void> {
|
|
92
|
+
if (!model) {
|
|
93
|
+
ui.setStatus(QUOTA_STATUS_KEY, undefined);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (!resolvedUsageKey) {
|
|
97
|
+
ui.setStatus(QUOTA_STATUS_KEY, undefined);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const doc = await loadUsageCached(cfg, resolvedUsageKey, opts);
|
|
101
|
+
if (!doc) {
|
|
102
|
+
ui.setStatus(QUOTA_STATUS_KEY, undefined);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const rendered = renderQuotaSegment(doc, model.provider, ui.theme);
|
|
106
|
+
ui.setStatus(QUOTA_STATUS_KEY, rendered ?? undefined);
|
|
107
|
+
}
|
|
25
108
|
|
|
26
109
|
export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
|
|
27
110
|
registerCommands(pi);
|
|
@@ -88,4 +171,48 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
|
|
|
88
171
|
}, ms);
|
|
89
172
|
log.info(`background refresh every ${cfg.refreshIntervalMinutes}m`);
|
|
90
173
|
}
|
|
174
|
+
|
|
175
|
+
// -------- status-line quota segment
|
|
176
|
+
//
|
|
177
|
+
// The segment is context-aware: it shows 5h/7d windows for the current
|
|
178
|
+
// model's provider only (anthropic→claude, openai→codex, custom→hidden).
|
|
179
|
+
// The shared file cache ensures multiple Pi instances don't fetch more than
|
|
180
|
+
// once every 2 minutes.
|
|
181
|
+
const resolvedUsageKey = resolveConfigValue(cfg.proxy.usageKey);
|
|
182
|
+
if (resolvedUsageKey) {
|
|
183
|
+
let lastTurnFetchMs = 0;
|
|
184
|
+
|
|
185
|
+
// session_start: render immediately from cache (no fetch needed if fresh).
|
|
186
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
187
|
+
if (!ctx.hasUI) return;
|
|
188
|
+
await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// model_select: re-render for the new provider. Read from cache so the
|
|
192
|
+
// segment updates instantly on model switch without a network round-trip.
|
|
193
|
+
pi.on("model_select", async (_event, ctx) => {
|
|
194
|
+
if (!ctx.hasUI) return;
|
|
195
|
+
await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// turn_end: after an LLM response the quota has changed. Trigger a fetch
|
|
199
|
+
// (if the shared cache is stale) but debounce to avoid burst-fetching on
|
|
200
|
+
// rapid consecutive turns.
|
|
201
|
+
pi.on("turn_end", async (_event, ctx) => {
|
|
202
|
+
if (!ctx.hasUI) return;
|
|
203
|
+
const now = Date.now();
|
|
204
|
+
if (now - lastTurnFetchMs < TURN_FETCH_DEBOUNCE_MS) {
|
|
205
|
+
// Within debounce window — re-render from cache only (no fetch), so
|
|
206
|
+
// rapid consecutive turns never trigger burst /api/usage calls.
|
|
207
|
+
await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model, {
|
|
208
|
+
readOnly: true,
|
|
209
|
+
});
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
lastTurnFetchMs = now;
|
|
213
|
+
await refreshQuotaStatus(cfg, resolvedUsageKey, ctx.ui, ctx.model);
|
|
214
|
+
});
|
|
215
|
+
} else {
|
|
216
|
+
log.debug("usageKey not configured — quota status segment disabled");
|
|
217
|
+
}
|
|
91
218
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-cliproxyapi",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
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,7 +25,8 @@
|
|
|
25
25
|
"cliproxyapi"
|
|
26
26
|
],
|
|
27
27
|
"scripts": {
|
|
28
|
-
"typecheck": "tsc --noEmit"
|
|
28
|
+
"typecheck": "tsc --noEmit",
|
|
29
|
+
"check:migration": "node --disable-warning=ExperimentalWarning --experimental-strip-types scripts/check-config-migration.ts"
|
|
29
30
|
},
|
|
30
31
|
"peerDependencies": {
|
|
31
32
|
"@earendil-works/pi-ai": "*",
|
package/src/config.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
// ~/.
|
|
1
|
+
// ~/.pi/agent/pi-cliproxyapi/config.json — migrate, load, validate, persist.
|
|
2
2
|
//
|
|
3
3
|
// Schema:
|
|
4
4
|
//
|
|
5
5
|
// {
|
|
6
6
|
// "proxy": {
|
|
7
7
|
// "endpoint": "https://your-proxy.example.com/v1",
|
|
8
|
-
// "apiKey": "!cat ~/.
|
|
8
|
+
// "apiKey": "!cat ~/.pi/agent/pi-cliproxyapi/key",
|
|
9
9
|
// "providerPrefix": "myproxy",
|
|
10
|
-
// "usageKey": "!cat ~/.
|
|
10
|
+
// "usageKey": "!cat ~/.pi/agent/pi-cliproxyapi/usage-key"
|
|
11
11
|
// },
|
|
12
12
|
// "builtinProviders": {
|
|
13
13
|
// "openai": { "enabled": true, "apiOverride": null, "models": ["gpt-5.2"] },
|
|
@@ -26,16 +26,71 @@
|
|
|
26
26
|
// }
|
|
27
27
|
|
|
28
28
|
import { execSync } from "node:child_process";
|
|
29
|
-
import {
|
|
29
|
+
import { randomUUID } from "node:crypto";
|
|
30
|
+
import {
|
|
31
|
+
constants,
|
|
32
|
+
copyFileSync,
|
|
33
|
+
existsSync,
|
|
34
|
+
linkSync,
|
|
35
|
+
mkdirSync,
|
|
36
|
+
readFileSync,
|
|
37
|
+
rmSync,
|
|
38
|
+
unlinkSync,
|
|
39
|
+
writeFileSync,
|
|
40
|
+
} from "node:fs";
|
|
30
41
|
import { homedir } from "node:os";
|
|
31
42
|
import { dirname, join } from "node:path";
|
|
43
|
+
import { fileURLToPath } from "node:url";
|
|
32
44
|
|
|
33
45
|
import type { Api } from "@earendil-works/pi-ai";
|
|
34
46
|
|
|
35
47
|
import { log } from "./log.ts";
|
|
36
48
|
|
|
37
|
-
export const CONFIG_DIR = join(homedir(), ".
|
|
49
|
+
export const CONFIG_DIR = join(homedir(), ".pi", "agent", "pi-cliproxyapi");
|
|
38
50
|
export const CONFIG_PATH = join(CONFIG_DIR, "config.json");
|
|
51
|
+
const LEGACY_CONFIG_PATH = join(
|
|
52
|
+
homedir(),
|
|
53
|
+
".config",
|
|
54
|
+
"pi-cliproxyapi",
|
|
55
|
+
"config.json",
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
export function isLocalCheckout(): boolean {
|
|
59
|
+
return existsSync(
|
|
60
|
+
join(dirname(fileURLToPath(import.meta.url)), "..", ".git"),
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function migrateLegacyConfig(
|
|
65
|
+
legacyPath = LEGACY_CONFIG_PATH,
|
|
66
|
+
configPath = CONFIG_PATH,
|
|
67
|
+
localCheckout = isLocalCheckout(),
|
|
68
|
+
): void {
|
|
69
|
+
if (existsSync(configPath) || !existsSync(legacyPath)) return;
|
|
70
|
+
let temporaryPath: string | undefined;
|
|
71
|
+
try {
|
|
72
|
+
mkdirSync(dirname(configPath), { recursive: true });
|
|
73
|
+
temporaryPath = `${configPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
74
|
+
copyFileSync(legacyPath, temporaryPath, constants.COPYFILE_EXCL);
|
|
75
|
+
linkSync(temporaryPath, configPath);
|
|
76
|
+
rmSync(temporaryPath);
|
|
77
|
+
temporaryPath = undefined;
|
|
78
|
+
if (!localCheckout) unlinkSync(legacyPath);
|
|
79
|
+
log.info(
|
|
80
|
+
localCheckout ? "legacy config copied to" : "legacy config moved to",
|
|
81
|
+
configPath,
|
|
82
|
+
);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
if (temporaryPath) {
|
|
85
|
+
try {
|
|
86
|
+
rmSync(temporaryPath, { force: true });
|
|
87
|
+
} catch (cleanupErr) {
|
|
88
|
+
log.warn("failed to clean temporary config:", cleanupErr);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
log.warn("failed to migrate legacy config:", err);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
39
94
|
|
|
40
95
|
export interface BuiltinProviderConfig {
|
|
41
96
|
enabled: boolean;
|
|
@@ -92,6 +147,7 @@ const DEFAULT_CONFIG: ProxyConfig = {
|
|
|
92
147
|
};
|
|
93
148
|
|
|
94
149
|
export function loadConfig(): ProxyConfig {
|
|
150
|
+
migrateLegacyConfig();
|
|
95
151
|
if (!existsSync(CONFIG_PATH)) {
|
|
96
152
|
log.info("config not found, using defaults at", CONFIG_PATH);
|
|
97
153
|
return structuredClone(DEFAULT_CONFIG);
|
|
@@ -115,9 +171,7 @@ function normalizeConfig(raw: unknown): ProxyConfig {
|
|
|
115
171
|
if (!raw || typeof raw !== "object") return structuredClone(DEFAULT_CONFIG);
|
|
116
172
|
const r = raw as Record<string, unknown>;
|
|
117
173
|
const merged = structuredClone(DEFAULT_CONFIG);
|
|
118
|
-
const proxyBlock =
|
|
119
|
-
(r.proxy as Record<string, unknown> | undefined) ??
|
|
120
|
-
{};
|
|
174
|
+
const proxyBlock = (r.proxy as Record<string, unknown> | undefined) ?? {};
|
|
121
175
|
merged.proxy.endpoint =
|
|
122
176
|
typeof proxyBlock.endpoint === "string"
|
|
123
177
|
? proxyBlock.endpoint
|
package/src/fetch-models.ts
CHANGED
|
@@ -21,7 +21,7 @@ import { writeDiscoveryCache } from "./cache.ts";
|
|
|
21
21
|
import type { ProxyConfig } from "./config.ts";
|
|
22
22
|
import { log } from "./log.ts";
|
|
23
23
|
|
|
24
|
-
export const PLUGIN_USER_AGENT = "pi-cliproxyapi/0.3.
|
|
24
|
+
export const PLUGIN_USER_AGENT = "pi-cliproxyapi/0.3.5";
|
|
25
25
|
const REQUEST_TIMEOUT_MS = 5_000;
|
|
26
26
|
|
|
27
27
|
export interface DiscoveryModelEntry {
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Status-line quota renderer: produces the compact segment shown in the footer.
|
|
2
|
+
//
|
|
3
|
+
// Format: <gauge-icon> <braille-5h><braille-7d> <5h%>/<7d%>
|
|
4
|
+
// Example: ⣷⣤ 83/23 (claude: 5h=83% green, 7d=23% yellow)
|
|
5
|
+
//
|
|
6
|
+
// Context-aware: only the windows of the CURRENT model's provider are shown.
|
|
7
|
+
// Provider mapping (Pi provider → usage-API provider):
|
|
8
|
+
// anthropic → claude (5h Session / 7d Weekly)
|
|
9
|
+
// openai → codex (5h Window / 7d Window)
|
|
10
|
+
// custom → (hidden, no quota windows)
|
|
11
|
+
//
|
|
12
|
+
// Aggregation: MAX remaining fraction across live accounts (not disabled,
|
|
13
|
+
// not unavailable) for each 5h/7d window label.
|
|
14
|
+
//
|
|
15
|
+
// Colors: green ≥70% · yellow 30–69% · red <30%
|
|
16
|
+
|
|
17
|
+
// The renderer accepts a structural theme type (anything with fg()) so it
|
|
18
|
+
// stays decoupled from Pi's internal Theme class.
|
|
19
|
+
|
|
20
|
+
import type { UsageAccount, UsageDocument, UsageGroup } from "./fetch-usage.ts";
|
|
21
|
+
|
|
22
|
+
/** nf-md-gauge (Nerd Font Material Design speedometer). */
|
|
23
|
+
const GAUGE_ICON = "\u{F0627}";
|
|
24
|
+
|
|
25
|
+
/** Braille fill chars, 8 levels (empty → full). */
|
|
26
|
+
const BRAILLE = ["⡀", "⠂", "⣀", "⣄", "⣤", "⣶", "⣷", "⣾"];
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Map a Pi provider name to the provider key used by the usage API.
|
|
30
|
+
* Returns null for providers without quota windows (custom providers).
|
|
31
|
+
*/
|
|
32
|
+
export function providerToUsageKey(piProvider: string): string | null {
|
|
33
|
+
if (piProvider === "anthropic") return "claude";
|
|
34
|
+
if (piProvider === "openai") return "codex";
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Is an account "live" — usable and contributing quota? */
|
|
39
|
+
function isLiveAccount(a: UsageAccount): boolean {
|
|
40
|
+
return (
|
|
41
|
+
!a.disabled &&
|
|
42
|
+
!a.unavailable &&
|
|
43
|
+
a.supported &&
|
|
44
|
+
Array.isArray(a.groups) &&
|
|
45
|
+
a.groups.length > 0
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Does a group label refer to a 5-hour window? */
|
|
50
|
+
function is5hGroup(g: UsageGroup): boolean {
|
|
51
|
+
const s = `${g.id} ${g.label ?? ""}`.toLowerCase();
|
|
52
|
+
return s.includes("5h") || s.includes("five-hour") || s.includes("five hour");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Does a group label refer to a 7-day window? */
|
|
56
|
+
function is7dGroup(g: UsageGroup): boolean {
|
|
57
|
+
const s = `${g.id} ${g.label ?? ""}`.toLowerCase();
|
|
58
|
+
return s.includes("7d") || s.includes("seven-day") || s.includes("seven day");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface WindowAggregate {
|
|
62
|
+
fraction: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Aggregate a window period across live accounts.
|
|
67
|
+
*
|
|
68
|
+
* Semantics: within each account, take the MIN remaining among matching
|
|
69
|
+
* windows (the account's bottleneck for that period — e.g. claude has both
|
|
70
|
+
* a general "7d Weekly" and a model-specific "7d Sonnet" window; the tighter
|
|
71
|
+
* one governs). Then take the MAX across accounts (the router will dispatch
|
|
72
|
+
* to the account with the most headroom).
|
|
73
|
+
*/
|
|
74
|
+
function aggregateWindow(
|
|
75
|
+
accounts: UsageAccount[],
|
|
76
|
+
predicate: (g: UsageGroup) => boolean,
|
|
77
|
+
): WindowAggregate | null {
|
|
78
|
+
let maxAcross = -1;
|
|
79
|
+
for (const a of accounts) {
|
|
80
|
+
if (!isLiveAccount(a)) continue;
|
|
81
|
+
let minWithin = Infinity;
|
|
82
|
+
for (const g of a.groups ?? []) {
|
|
83
|
+
if (predicate(g)) {
|
|
84
|
+
if (g.remainingFraction < minWithin) minWithin = g.remainingFraction;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (minWithin !== Infinity && minWithin > maxAcross) {
|
|
88
|
+
maxAcross = minWithin;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (maxAcross < 0) return null;
|
|
92
|
+
return { fraction: clamp(maxAcross) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function clamp(f: number): number {
|
|
96
|
+
return Math.max(0, Math.min(1, f));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Braille fill char for a given fraction (8 levels). */
|
|
100
|
+
function brailleFor(fraction: number): string {
|
|
101
|
+
const idx = Math.min(
|
|
102
|
+
BRAILLE.length - 1,
|
|
103
|
+
Math.floor(fraction * BRAILLE.length),
|
|
104
|
+
);
|
|
105
|
+
return BRAILLE[idx]!;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Theme color name for a given remaining fraction. */
|
|
109
|
+
function colorForFraction(fraction: number): "success" | "warning" | "error" {
|
|
110
|
+
if (fraction >= 0.7) return "success";
|
|
111
|
+
if (fraction >= 0.3) return "warning";
|
|
112
|
+
return "error";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Percent as integer string (0–100). */
|
|
116
|
+
function pct(fraction: number): number {
|
|
117
|
+
return Math.round(fraction * 100);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Render the quota status segment for the current provider, or null if the
|
|
122
|
+
* provider has no quota windows (segment should be hidden).
|
|
123
|
+
*
|
|
124
|
+
* @param doc - usage document from /api/usage
|
|
125
|
+
* @param piProvider - Pi provider name of the current model (e.g. "anthropic")
|
|
126
|
+
* @param theme - Pi theme for coloring (from ctx.ui.theme)
|
|
127
|
+
*/
|
|
128
|
+
export function renderQuotaSegment(
|
|
129
|
+
doc: UsageDocument,
|
|
130
|
+
piProvider: string,
|
|
131
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
132
|
+
theme: {
|
|
133
|
+
fg(color: "success" | "warning" | "error" | "dim", text: string): string;
|
|
134
|
+
},
|
|
135
|
+
): string | null {
|
|
136
|
+
const usageKey = providerToUsageKey(piProvider);
|
|
137
|
+
if (!usageKey) return null;
|
|
138
|
+
|
|
139
|
+
const accounts = doc.accounts.filter((a) => a.provider === usageKey);
|
|
140
|
+
if (accounts.length === 0) return null;
|
|
141
|
+
|
|
142
|
+
const w5 = aggregateWindow(accounts, is5hGroup);
|
|
143
|
+
const w7 = aggregateWindow(accounts, is7dGroup);
|
|
144
|
+
|
|
145
|
+
// No 5h/7d windows found → hide the segment entirely
|
|
146
|
+
if (!w5 && !w7) return null;
|
|
147
|
+
|
|
148
|
+
const parts: string[] = [theme.fg("dim", GAUGE_ICON)];
|
|
149
|
+
|
|
150
|
+
if (w5) {
|
|
151
|
+
parts.push(
|
|
152
|
+
`${theme.fg("dim", "5h")} ${theme.fg(colorForFraction(w5.fraction), brailleFor(w5.fraction))} ${theme.fg(colorForFraction(w5.fraction), String(pct(w5.fraction)))}`,
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (w7) {
|
|
156
|
+
parts.push(
|
|
157
|
+
`${theme.fg("dim", "7d")} ${theme.fg(colorForFraction(w7.fraction), brailleFor(w7.fraction))} ${theme.fg(colorForFraction(w7.fraction), String(pct(w7.fraction)))}`,
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return parts.join(" ");
|
|
162
|
+
}
|
package/src/ui-setup.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// First-run setup wizard: collects endpoint + apiKey + providerPrefix + (optional) usageKey
|
|
2
|
-
// and writes them to ~/.
|
|
2
|
+
// and writes them to ~/.pi/agent/pi-cliproxyapi/config.json.
|
|
3
3
|
//
|
|
4
4
|
// All three fields support the same "!cmd" / "$ENV" / literal semantics as
|
|
5
5
|
// the rest of the config (see resolveConfigValue). For convenience the wizard
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// File-based shared cache for /api/usage — multiple Pi instances read the same
|
|
2
|
+
// file, and a file lock prevents thundering-herd fetches.
|
|
3
|
+
//
|
|
4
|
+
// Flow (per Pi instance):
|
|
5
|
+
// 1. readUsageCache() → { doc, ageMs } | null
|
|
6
|
+
// 2. if fresh (ageMs < TTL_MS) → use doc, no network
|
|
7
|
+
// 3. if stale or missing → tryAcquireLock()
|
|
8
|
+
// a. lock acquired → fetchUsage(force) → writeUsageCache → releaseLock
|
|
9
|
+
// b. lock NOT acquired (another instance fetching) → use stale doc or null
|
|
10
|
+
//
|
|
11
|
+
// Lock: O_EXCL create (atomic on POSIX). Contains pid + timestamp. Stale locks
|
|
12
|
+
// (older than LOCK_STALE_MS) are removed to recover from crashed processes.
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
existsSync,
|
|
16
|
+
mkdirSync,
|
|
17
|
+
readFileSync,
|
|
18
|
+
statSync,
|
|
19
|
+
unlinkSync,
|
|
20
|
+
writeFileSync,
|
|
21
|
+
} from "node:fs";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
|
|
24
|
+
import { CONFIG_DIR } from "./config.ts";
|
|
25
|
+
import type { UsageDocument } from "./fetch-usage.ts";
|
|
26
|
+
import { log } from "./log.ts";
|
|
27
|
+
|
|
28
|
+
export const USAGE_CACHE_PATH = join(CONFIG_DIR, "usage-cache.json");
|
|
29
|
+
export const USAGE_LOCK_PATH = join(CONFIG_DIR, "usage-cache.lock");
|
|
30
|
+
|
|
31
|
+
/** Minimum interval between network fetches, shared across all Pi instances. */
|
|
32
|
+
export const USAGE_CACHE_TTL_MS = 120_000; // 2 minutes
|
|
33
|
+
/** A lock file older than this is considered stale (process crashed). */
|
|
34
|
+
const LOCK_STALE_MS = 30_000;
|
|
35
|
+
|
|
36
|
+
interface CacheEnvelope {
|
|
37
|
+
fetchedAt: number; // epoch ms
|
|
38
|
+
doc: UsageDocument;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface CachedUsage {
|
|
42
|
+
doc: UsageDocument;
|
|
43
|
+
ageMs: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Read the shared cache file. Returns null if missing/corrupt. */
|
|
47
|
+
export function readUsageCache(): CachedUsage | null {
|
|
48
|
+
if (!existsSync(USAGE_CACHE_PATH)) return null;
|
|
49
|
+
try {
|
|
50
|
+
const env = JSON.parse(
|
|
51
|
+
readFileSync(USAGE_CACHE_PATH, "utf8"),
|
|
52
|
+
) as CacheEnvelope;
|
|
53
|
+
if (
|
|
54
|
+
!env ||
|
|
55
|
+
typeof env.fetchedAt !== "number" ||
|
|
56
|
+
!env.doc ||
|
|
57
|
+
!Array.isArray(env.doc.accounts)
|
|
58
|
+
) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
return { doc: env.doc, ageMs: Date.now() - env.fetchedAt };
|
|
62
|
+
} catch (err) {
|
|
63
|
+
log.warn("failed to read usage cache:", (err as Error).message);
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Is the cached data fresh enough to skip a network fetch? */
|
|
69
|
+
export function isUsageFresh(ageMs: number): boolean {
|
|
70
|
+
return ageMs < USAGE_CACHE_TTL_MS;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Write fresh usage data + timestamp to the shared cache file. */
|
|
74
|
+
export function writeUsageCache(doc: UsageDocument): void {
|
|
75
|
+
try {
|
|
76
|
+
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
77
|
+
const env: CacheEnvelope = { fetchedAt: Date.now(), doc };
|
|
78
|
+
writeFileSync(USAGE_CACHE_PATH, JSON.stringify(env), "utf8");
|
|
79
|
+
} catch (err) {
|
|
80
|
+
log.warn("failed to write usage cache:", (err as Error).message);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Try to acquire an exclusive lock for fetching usage.
|
|
86
|
+
* Returns the lock token if this instance should fetch, null if another is
|
|
87
|
+
* already doing so. Stale locks (crashed process) are cleaned up automatically.
|
|
88
|
+
* The token must be passed to {@link releaseUsageLock} so we only remove a
|
|
89
|
+
* lock we still own.
|
|
90
|
+
*/
|
|
91
|
+
export function tryAcquireUsageLock(): string | null {
|
|
92
|
+
const token = `${process.pid}@${Date.now()}`;
|
|
93
|
+
// Clean up stale lock from a crashed process
|
|
94
|
+
if (existsSync(USAGE_LOCK_PATH)) {
|
|
95
|
+
try {
|
|
96
|
+
const stat = statSync(USAGE_LOCK_PATH);
|
|
97
|
+
if (Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
|
|
98
|
+
log.debug("removing stale usage lock");
|
|
99
|
+
unlinkSync(USAGE_LOCK_PATH);
|
|
100
|
+
} else {
|
|
101
|
+
return null; // someone else holds a live lock
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
// stat/unlink race — treat as locked to be safe
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// O_EXCL ("wx") — atomically creates only if the file does not exist
|
|
109
|
+
try {
|
|
110
|
+
writeFileSync(USAGE_LOCK_PATH, token, { flag: "wx" });
|
|
111
|
+
return token;
|
|
112
|
+
} catch {
|
|
113
|
+
// race: another instance created the lock between our check and create
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function releaseUsageLock(ourToken: string): boolean {
|
|
119
|
+
try {
|
|
120
|
+
const content = readFileSync(USAGE_LOCK_PATH, "utf8").trim();
|
|
121
|
+
// Only remove the lock if it still belongs to us. If another process
|
|
122
|
+
// acquired it after our stale-cleanup, leave it alone.
|
|
123
|
+
if (content === ourToken) {
|
|
124
|
+
unlinkSync(USAGE_LOCK_PATH);
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|