pi-cliproxyapi 0.3.2 → 0.3.4

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/index.ts CHANGED
@@ -8,6 +8,7 @@
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.
@@ -16,11 +17,94 @@
16
17
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
17
18
 
18
19
  import { applyAll } from "./src/apply.ts";
20
+ import { readDiscoveryCache } from "./src/cache.ts";
19
21
  import { registerCommands } from "./src/commands.ts";
20
22
  import { loadConfig, resolveConfigValue } from "./src/config.ts";
21
23
  import { detectConflicts } from "./src/conflicts.ts";
22
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";
23
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
+ }
24
108
 
25
109
  export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
26
110
  registerCommands(pi);
@@ -39,8 +123,31 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
39
123
  for (const c of conflicts) log.warn(`conflict (${c.kind}): ${c.detail}`);
40
124
 
41
125
  try {
42
- const discovery = await fetchDiscovery(cfg, resolvedKey);
43
- await applyAll(pi, cfg, discovery);
126
+ const cached = readDiscoveryCache();
127
+ if (cached) {
128
+ // Serve the last good discovery instantly so Pi startup never blocks on
129
+ // the ~5s proxy round-trip, then revalidate over the network in the
130
+ // background (applyAll is idempotent — it just re-registers providers).
131
+ log.info(
132
+ `discovery from cache (age ${Math.round(cached.ageMs / 1000)}s): ${cached.discovery.builtinProviders.length} builtin, ${cached.discovery.customPool.length} custom`,
133
+ );
134
+ await applyAll(pi, cfg, cached.discovery);
135
+ void (async () => {
136
+ try {
137
+ const fresh = await fetchDiscovery(cfg, resolvedKey);
138
+ await applyAll(pi, cfg, fresh);
139
+ log.debug("discovery revalidated from network");
140
+ } catch (e) {
141
+ log.warn(
142
+ "background discovery revalidate failed:",
143
+ (e as Error).message,
144
+ );
145
+ }
146
+ })();
147
+ } else {
148
+ const discovery = await fetchDiscovery(cfg, resolvedKey);
149
+ await applyAll(pi, cfg, discovery);
150
+ }
44
151
  } catch (err) {
45
152
  log.error("initial apply failed:", (err as Error).message);
46
153
  // Commands stay registered; user can open /cliproxy and press r to refresh.
@@ -64,4 +171,48 @@ export default async function cliproxyapi(pi: ExtensionAPI): Promise<void> {
64
171
  }, ms);
65
172
  log.info(`background refresh every ${cfg.refreshIntervalMinutes}m`);
66
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
+ }
67
218
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cliproxyapi",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "type": "module",
5
5
  "description": "Pi extension for corporate management of model providers via a single CliProxyAPI endpoint",
6
6
  "license": "MIT",
package/src/cache.ts ADDED
@@ -0,0 +1,58 @@
1
+ // Disk cache for Discovery — stale-while-revalidate.
2
+ //
3
+ // The well-known/v1-models round-trip costs ~5s on every Pi startup (the proxy
4
+ // answers /.well-known/pi slowly), and Pi re-spawns the agent for every
5
+ // provider-feature probe, so that cost is paid constantly. We persist the last
6
+ // good Discovery and serve it instantly on boot, then revalidate over the
7
+ // network in the background.
8
+
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+
12
+ import { CONFIG_DIR } from "./config.ts";
13
+ import type { Discovery } from "./fetch-models.ts";
14
+ import { log } from "./log.ts";
15
+
16
+ export const DISCOVERY_CACHE_PATH = join(CONFIG_DIR, "discovery-cache.json");
17
+
18
+ interface CacheEnvelope {
19
+ savedAt: number;
20
+ discovery: Discovery;
21
+ }
22
+
23
+ export interface CachedDiscovery {
24
+ discovery: Discovery;
25
+ ageMs: number;
26
+ }
27
+
28
+ export function readDiscoveryCache(): CachedDiscovery | null {
29
+ if (!existsSync(DISCOVERY_CACHE_PATH)) return null;
30
+ try {
31
+ const env = JSON.parse(
32
+ readFileSync(DISCOVERY_CACHE_PATH, "utf8"),
33
+ ) as CacheEnvelope;
34
+ if (
35
+ !env ||
36
+ typeof env.savedAt !== "number" ||
37
+ !env.discovery ||
38
+ !Array.isArray(env.discovery.builtinProviders) ||
39
+ !Array.isArray(env.discovery.customPool)
40
+ ) {
41
+ return null;
42
+ }
43
+ return { discovery: env.discovery, ageMs: Date.now() - env.savedAt };
44
+ } catch (err) {
45
+ log.warn("failed to read discovery cache:", (err as Error).message);
46
+ return null;
47
+ }
48
+ }
49
+
50
+ export function writeDiscoveryCache(discovery: Discovery): void {
51
+ try {
52
+ mkdirSync(dirname(DISCOVERY_CACHE_PATH), { recursive: true });
53
+ const env: CacheEnvelope = { savedAt: Date.now(), discovery };
54
+ writeFileSync(DISCOVERY_CACHE_PATH, JSON.stringify(env), "utf8");
55
+ } catch (err) {
56
+ log.warn("failed to write discovery cache:", (err as Error).message);
57
+ }
58
+ }
@@ -17,10 +17,11 @@ import {
17
17
  normalizeSuggestedProvider,
18
18
  reasoningFromId,
19
19
  } from "./compat.ts";
20
+ import { writeDiscoveryCache } from "./cache.ts";
20
21
  import type { ProxyConfig } from "./config.ts";
21
22
  import { log } from "./log.ts";
22
23
 
23
- export const PLUGIN_USER_AGENT = "pi-cliproxyapi/0.3.2";
24
+ export const PLUGIN_USER_AGENT = "pi-cliproxyapi/0.3.3";
24
25
  const REQUEST_TIMEOUT_MS = 5_000;
25
26
 
26
27
  export interface DiscoveryModelEntry {
@@ -308,6 +309,7 @@ export async function fetchDiscovery(
308
309
  log.info(
309
310
  `discovery via /.well-known/pi: ${wk.builtinProviders.length} builtin, ${wk.customPool.length} custom`,
310
311
  );
312
+ writeDiscoveryCache(wk);
311
313
  return wk;
312
314
  }
313
315
  if (!resolvedKey) {
@@ -320,6 +322,7 @@ export async function fetchDiscovery(
320
322
  log.info(
321
323
  `discovery via /v1/models: ${d.builtinProviders.length} builtin, ${d.customPool.length} custom`,
322
324
  );
325
+ writeDiscoveryCache(d);
323
326
  return d;
324
327
  }
325
328
 
@@ -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
+ }
@@ -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
+ }