@llblab/pi-codex-usage 0.10.1 → 0.12.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/AGENTS.md +9 -6
- package/BACKLOG.md +2 -1
- package/CHANGELOG.md +12 -1
- package/README.md +75 -17
- package/index.ts +8 -1602
- package/lib/extension.ts +25 -0
- package/lib/fast.ts +23 -0
- package/lib/query.ts +368 -0
- package/lib/status-format.ts +347 -0
- package/lib/status.ts +435 -0
- package/lib/telegram.ts +45 -0
- package/lib/usage-store.ts +229 -0
- package/lib/usage.ts +425 -0
- package/package.json +11 -6
package/lib/status.ts
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
/** Domain: status lifecycle. Owns: local refresh, terminal redraw and optional Telegram row. Excludes: /fast command and request hook. */
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { isFastEnabled, isFastEligibleModel } from "./fast.ts";
|
|
5
|
+
import { claimRefresh, isRefreshDue, nextRefreshAt, ownsRefreshClaim, publishRefresh, readState, type SharedState, MIN_ATTEMPT_GAP_MS } from "./usage-store.ts";
|
|
6
|
+
import { canReuseCachedReport, isFullyAvailableReport, isOpenAICodexModel, isUsageUnavailable, type CodexUsageModel, type CodexUsageReport } from "./usage.ts";
|
|
7
|
+
import { appendFastStatus, formatReportBar, formatStatuslineLoading, formatStatuslineProblem, formatCodexUsageStatusValue, formatCodexUsageStatusline, nextResetCountdownDelayMs } from "./status-format.ts";
|
|
8
|
+
import { queryUsage, type QueryUsageResult } from "./query.ts";
|
|
9
|
+
import { registerCodexUsageTelegramStatusLine } from "./telegram.ts";
|
|
10
|
+
|
|
11
|
+
const DEFAULT_STATUS_LABEL_TEXT = "codex";
|
|
12
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
13
|
+
const SECOND_MS = 1000;
|
|
14
|
+
const MINUTE_MS = 60 * SECOND_MS;
|
|
15
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
16
|
+
const MAX_TICK_MS = 30 * SECOND_MS;
|
|
17
|
+
const MIN_TICK_MS = SECOND_MS;
|
|
18
|
+
const TAKEOVER_JITTER_MS = 2 * SECOND_MS;
|
|
19
|
+
const STALE_REPORT_MAX_AGE_MS = HOUR_MS;
|
|
20
|
+
const PROVISIONAL_RETRY_MS = SECOND_MS;
|
|
21
|
+
const FULL_AVAILABILITY_CONFIRMATION_MS = 15 * SECOND_MS;
|
|
22
|
+
const LOADING_FRAME_MS = 30;
|
|
23
|
+
const REDRAW_BLINK_MS = 150;
|
|
24
|
+
const STATUS_KEY = "aa-codex-usage";
|
|
25
|
+
const DUAL_BAR_WIDTH = 10;
|
|
26
|
+
|
|
27
|
+
type TimeoutHandle = ReturnType<typeof setTimeout> & { unref?: () => void };
|
|
28
|
+
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
29
|
+
type CodexSharedState = SharedState<CodexUsageReport>;
|
|
30
|
+
|
|
31
|
+
export function createCodexUsageStatus(pi: ExtensionAPI) {
|
|
32
|
+
const instanceId = `${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
|
|
33
|
+
const stateDir = join(getAgentDir(), "tmp", "pi-codex-usage");
|
|
34
|
+
let lastAttemptAt = 0;
|
|
35
|
+
let inFlightRefresh: Promise<void> | undefined;
|
|
36
|
+
let shown: { key?: string; report?: CodexUsageReport; updatedAt?: number } = {};
|
|
37
|
+
let statuslineBlinkTimer: TimeoutHandle | undefined;
|
|
38
|
+
let statuslineCountdownTimer: TimeoutHandle | undefined;
|
|
39
|
+
let statuslineLoadingTimer: TimeoutHandle | undefined;
|
|
40
|
+
let statuslineRefreshTimer: TimeoutHandle | undefined;
|
|
41
|
+
let statuslineLoadingFrame = 0;
|
|
42
|
+
let statuslineRequestId = 0;
|
|
43
|
+
let unregisterTelegramStatusLine: (() => void) | undefined;
|
|
44
|
+
let telegramStatusLineRegistration: Promise<void> | undefined;
|
|
45
|
+
let fastModelId: string | undefined;
|
|
46
|
+
let fastEnabled = false;
|
|
47
|
+
let lastStatusText: string | undefined;
|
|
48
|
+
let loadingModel: CodexUsageModel | undefined;
|
|
49
|
+
|
|
50
|
+
const syncFast = (model: PiModel | undefined, ctx: ExtensionContext) => {
|
|
51
|
+
fastModelId = isFastEligibleModel(model) ? model.id : undefined;
|
|
52
|
+
fastEnabled = fastModelId !== undefined && isFastEnabled(fastModelId);
|
|
53
|
+
};
|
|
54
|
+
const setCodexStatus = (ctx: ExtensionContext, text: string | undefined, model?: CodexUsageModel) => {
|
|
55
|
+
lastStatusText = text;
|
|
56
|
+
ctx.ui.setStatus(STATUS_KEY, text === undefined ? undefined : appendFastStatus(
|
|
57
|
+
ctx, text,
|
|
58
|
+
fastEnabled && model?.id === fastModelId,
|
|
59
|
+
));
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const loadState = () => readState<CodexUsageReport>(stateDir);
|
|
63
|
+
|
|
64
|
+
const ensureTelegramStatusLineRegistered = () => {
|
|
65
|
+
if (unregisterTelegramStatusLine || telegramStatusLineRegistration) return;
|
|
66
|
+
telegramStatusLineRegistration = registerCodexUsageTelegramStatusLine(
|
|
67
|
+
({ activeModel }) => {
|
|
68
|
+
if (!isOpenAICodexModel(activeModel)) return undefined;
|
|
69
|
+
if (!shown.report) return undefined;
|
|
70
|
+
const value = formatCodexUsageStatusValue(shown.report, activeModel);
|
|
71
|
+
return value
|
|
72
|
+
? { label: DEFAULT_STATUS_LABEL_TEXT, value }
|
|
73
|
+
: undefined;
|
|
74
|
+
},
|
|
75
|
+
)
|
|
76
|
+
.then((unregister) => {
|
|
77
|
+
unregisterTelegramStatusLine = unregister;
|
|
78
|
+
})
|
|
79
|
+
.finally(() => {
|
|
80
|
+
telegramStatusLineRegistration = undefined;
|
|
81
|
+
});
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const clearStatuslineTimers = () => {
|
|
85
|
+
if (statuslineBlinkTimer) clearTimeout(statuslineBlinkTimer);
|
|
86
|
+
if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
|
|
87
|
+
if (statuslineLoadingTimer) clearTimeout(statuslineLoadingTimer);
|
|
88
|
+
if (statuslineRefreshTimer) clearTimeout(statuslineRefreshTimer);
|
|
89
|
+
statuslineBlinkTimer = undefined;
|
|
90
|
+
statuslineCountdownTimer = undefined;
|
|
91
|
+
statuslineLoadingTimer = undefined;
|
|
92
|
+
statuslineRefreshTimer = undefined;
|
|
93
|
+
loadingModel = undefined;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const stopStatuslineLoading = () => {
|
|
97
|
+
if (statuslineLoadingTimer) clearTimeout(statuslineLoadingTimer);
|
|
98
|
+
statuslineLoadingTimer = undefined;
|
|
99
|
+
loadingModel = undefined;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const startStatuslineLoading = (
|
|
103
|
+
ctx: ExtensionContext,
|
|
104
|
+
model: CodexUsageModel | undefined,
|
|
105
|
+
) => {
|
|
106
|
+
const modelChanged = loadingModel?.id !== model?.id;
|
|
107
|
+
loadingModel = model;
|
|
108
|
+
if (statuslineLoadingTimer) {
|
|
109
|
+
if (modelChanged && lastStatusText !== undefined) setCodexStatus(ctx, lastStatusText, model);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
statuslineLoadingFrame = Math.random() < 0.5 ? 0 : DUAL_BAR_WIDTH * 2 - 1;
|
|
113
|
+
const drawNextFrame = () => {
|
|
114
|
+
try {
|
|
115
|
+
setCodexStatus(ctx, formatStatuslineLoading(ctx, statuslineLoadingFrame, loadingModel), loadingModel);
|
|
116
|
+
statuslineLoadingFrame += 1;
|
|
117
|
+
statuslineLoadingTimer = setTimeout(
|
|
118
|
+
drawNextFrame,
|
|
119
|
+
LOADING_FRAME_MS,
|
|
120
|
+
) as TimeoutHandle;
|
|
121
|
+
statuslineLoadingTimer.unref?.();
|
|
122
|
+
} catch (error) {
|
|
123
|
+
statuslineLoadingTimer = undefined;
|
|
124
|
+
handleTimerError(error);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
drawNextFrame();
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const clearUsageStatusline = (ctx: ExtensionContext) => {
|
|
131
|
+
statuslineRequestId += 1;
|
|
132
|
+
clearStatuslineTimers();
|
|
133
|
+
shown = {};
|
|
134
|
+
setCodexStatus(ctx, undefined);
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const scheduleStatuslineRefresh = (ctx: ExtensionContext, delayMs: number) => {
|
|
138
|
+
if (statuslineRefreshTimer) clearTimeout(statuslineRefreshTimer);
|
|
139
|
+
statuslineRefreshTimer = setTimeout(() => {
|
|
140
|
+
void refreshCurrentCodexUsageStatusline(ctx, false).catch(
|
|
141
|
+
handleAsyncTimerError,
|
|
142
|
+
);
|
|
143
|
+
}, delayMs) as TimeoutHandle;
|
|
144
|
+
statuslineRefreshTimer.unref?.();
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const scheduleStatuslineCountdown = (
|
|
148
|
+
ctx: ExtensionContext,
|
|
149
|
+
report: CodexUsageReport,
|
|
150
|
+
model: CodexUsageModel | undefined,
|
|
151
|
+
) => {
|
|
152
|
+
if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
|
|
153
|
+
const delayMs = nextResetCountdownDelayMs(report, Date.now(), model);
|
|
154
|
+
if (delayMs === undefined) {
|
|
155
|
+
statuslineCountdownTimer = undefined;
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
statuslineCountdownTimer = setTimeout(() => {
|
|
159
|
+
try {
|
|
160
|
+
if (isOpenAICodexModel(ctx.model)) {
|
|
161
|
+
setCodexStatus(ctx, formatCodexUsageStatusline(report, ctx, model), model);
|
|
162
|
+
scheduleStatuslineCountdown(ctx, report, model);
|
|
163
|
+
}
|
|
164
|
+
} catch (error) {
|
|
165
|
+
handleTimerError(error);
|
|
166
|
+
}
|
|
167
|
+
}, delayMs) as TimeoutHandle;
|
|
168
|
+
statuslineCountdownTimer.unref?.();
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const setUsageStatusline = (
|
|
172
|
+
ctx: ExtensionContext,
|
|
173
|
+
report: CodexUsageReport,
|
|
174
|
+
options: { blink: boolean; model: CodexUsageModel | undefined },
|
|
175
|
+
) => {
|
|
176
|
+
if (statuslineBlinkTimer) clearTimeout(statuslineBlinkTimer);
|
|
177
|
+
if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
|
|
178
|
+
stopStatuslineLoading();
|
|
179
|
+
statuslineBlinkTimer = undefined;
|
|
180
|
+
statuslineCountdownTimer = undefined;
|
|
181
|
+
const text = formatCodexUsageStatusline(report, ctx, options.model);
|
|
182
|
+
if (options.blink) {
|
|
183
|
+
setCodexStatus(ctx, formatStatuslineLoading(ctx, statuslineLoadingFrame, options.model), options.model);
|
|
184
|
+
statuslineBlinkTimer = setTimeout(() => {
|
|
185
|
+
try {
|
|
186
|
+
setCodexStatus(ctx, text, options.model);
|
|
187
|
+
scheduleStatuslineCountdown(ctx, report, options.model);
|
|
188
|
+
statuslineBlinkTimer = undefined;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
handleTimerError(error);
|
|
191
|
+
}
|
|
192
|
+
}, REDRAW_BLINK_MS) as TimeoutHandle;
|
|
193
|
+
statuslineBlinkTimer.unref?.();
|
|
194
|
+
} else {
|
|
195
|
+
setCodexStatus(ctx, text, options.model);
|
|
196
|
+
scheduleStatuslineCountdown(ctx, report, options.model);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** Draws the shared state; skips redraws when nothing changed. */
|
|
201
|
+
const renderState = (
|
|
202
|
+
ctx: ExtensionContext,
|
|
203
|
+
state: CodexSharedState | undefined,
|
|
204
|
+
model: CodexUsageModel | undefined,
|
|
205
|
+
force: boolean,
|
|
206
|
+
) => {
|
|
207
|
+
// Cached display data is not permission to query when the file is unreadable.
|
|
208
|
+
if (!state && shown.report && Date.now() - (shown.updatedAt ?? 0) < STALE_REPORT_MAX_AGE_MS) {
|
|
209
|
+
if (force) setUsageStatusline(ctx, shown.report, { blink: false, model });
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const usable =
|
|
213
|
+
state?.report &&
|
|
214
|
+
state.updatedAt !== undefined &&
|
|
215
|
+
Date.now() - state.updatedAt < STALE_REPORT_MAX_AGE_MS &&
|
|
216
|
+
canReuseCachedReport(state.report, model)
|
|
217
|
+
? state.report
|
|
218
|
+
: undefined;
|
|
219
|
+
if (usable) {
|
|
220
|
+
const key = `report:${state?.updatedAt}`;
|
|
221
|
+
if (!force && shown.key === key) return;
|
|
222
|
+
const blink = shown.report
|
|
223
|
+
? formatReportBar(shown.report, model) !== formatReportBar(usable, model)
|
|
224
|
+
: false;
|
|
225
|
+
shown = { key, report: usable, updatedAt: state?.updatedAt };
|
|
226
|
+
setUsageStatusline(ctx, usable, { blink, model });
|
|
227
|
+
} else if (state?.error) {
|
|
228
|
+
const key = `error:${state.error}`;
|
|
229
|
+
if (!force && shown.key === key) return;
|
|
230
|
+
shown = { key };
|
|
231
|
+
clearStatuslineTimers();
|
|
232
|
+
setCodexStatus(ctx, formatStatuslineProblem(ctx, state.unavailable === true, model), model);
|
|
233
|
+
} else {
|
|
234
|
+
shown = { key: "loading" };
|
|
235
|
+
startStatuslineLoading(ctx, model);
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* When this instance is due (leader after 1 minute, anyone after 90 seconds) it
|
|
241
|
+
* claims leadership under the lock (owner and timestamp, so no other
|
|
242
|
+
* instance is due), then fetches, then stamps the outcome. Failures are
|
|
243
|
+
* published with a backoff so other instances do not pile on.
|
|
244
|
+
*/
|
|
245
|
+
const refreshSharedState = (
|
|
246
|
+
ctx: ExtensionContext,
|
|
247
|
+
model: CodexUsageModel | undefined,
|
|
248
|
+
) => {
|
|
249
|
+
if (inFlightRefresh) return inFlightRefresh;
|
|
250
|
+
const promise = (async () => {
|
|
251
|
+
const claim = claimRefresh(stateDir, instanceId);
|
|
252
|
+
if (!claim) return;
|
|
253
|
+
lastAttemptAt = Date.now();
|
|
254
|
+
const result = await queryConfirmedUsage(
|
|
255
|
+
ctx,
|
|
256
|
+
model,
|
|
257
|
+
loadState()?.report,
|
|
258
|
+
() => ownsRefreshClaim(stateDir, claim),
|
|
259
|
+
);
|
|
260
|
+
if (!result) return;
|
|
261
|
+
if (result.ok) {
|
|
262
|
+
publishRefresh(stateDir, claim, result);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (result.errors.some((error) => isStaleExtensionContextError(error.cause)))
|
|
266
|
+
return;
|
|
267
|
+
publishRefresh(stateDir, claim, {
|
|
268
|
+
ok: false,
|
|
269
|
+
error: result.errors.map((error) => error.message).join("; "),
|
|
270
|
+
unavailable: isUsageUnavailable(result.errors),
|
|
271
|
+
rateLimited: result.errors.some((error) =>
|
|
272
|
+
error.message.includes("returned 429"),
|
|
273
|
+
),
|
|
274
|
+
});
|
|
275
|
+
})().finally(() => {
|
|
276
|
+
if (inFlightRefresh === promise) inFlightRefresh = undefined;
|
|
277
|
+
});
|
|
278
|
+
inFlightRefresh = promise;
|
|
279
|
+
return promise;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Queries the usage. A first report claiming every window is completely
|
|
284
|
+
* unused is provisional (providers can briefly emit zeroed windows while
|
|
285
|
+
* initializing), so the claiming leader re-queries it every second for up to
|
|
286
|
+
* 15 seconds before publishing.
|
|
287
|
+
*/
|
|
288
|
+
const queryConfirmedUsage = async (
|
|
289
|
+
ctx: ExtensionContext,
|
|
290
|
+
model: CodexUsageModel | undefined,
|
|
291
|
+
previous: CodexUsageReport | undefined,
|
|
292
|
+
mayQuery: () => boolean,
|
|
293
|
+
): Promise<QueryUsageResult | undefined> => {
|
|
294
|
+
const startedAt = Date.now();
|
|
295
|
+
let result = await queryUsage(
|
|
296
|
+
ctx,
|
|
297
|
+
{ timeoutMs: DEFAULT_TIMEOUT_MS },
|
|
298
|
+
model,
|
|
299
|
+
mayQuery,
|
|
300
|
+
);
|
|
301
|
+
if (previous && isFullyAvailableReport(previous, model)) return result;
|
|
302
|
+
while (
|
|
303
|
+
result?.ok &&
|
|
304
|
+
isFullyAvailableReport(result.report, model) &&
|
|
305
|
+
Date.now() - startedAt < FULL_AVAILABILITY_CONFIRMATION_MS
|
|
306
|
+
) {
|
|
307
|
+
await new Promise((resolve) => setTimeout(resolve, PROVISIONAL_RETRY_MS));
|
|
308
|
+
const retry = await queryUsage(
|
|
309
|
+
ctx,
|
|
310
|
+
{ timeoutMs: DEFAULT_TIMEOUT_MS },
|
|
311
|
+
model,
|
|
312
|
+
mayQuery,
|
|
313
|
+
);
|
|
314
|
+
if (!retry) return undefined;
|
|
315
|
+
if (!retry.ok) break;
|
|
316
|
+
result = retry;
|
|
317
|
+
}
|
|
318
|
+
return result;
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
const nextTickDelayMs = (state: CodexSharedState | undefined) => {
|
|
322
|
+
// Nothing to show yet (e.g. a claimed fetch is in flight): poll quickly.
|
|
323
|
+
if (shown.key === "loading") return MIN_TICK_MS;
|
|
324
|
+
const now = Date.now();
|
|
325
|
+
const dueAt = Math.max(
|
|
326
|
+
nextRefreshAt(state, instanceId, now),
|
|
327
|
+
lastAttemptAt + MIN_ATTEMPT_GAP_MS,
|
|
328
|
+
);
|
|
329
|
+
const jitter =
|
|
330
|
+
state?.owner === instanceId ? 0 : Math.random() * TAKEOVER_JITTER_MS;
|
|
331
|
+
return Math.min(MAX_TICK_MS, Math.max(MIN_TICK_MS, dueAt - now + jitter));
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
const refreshCurrentCodexUsageStatusline = async (
|
|
335
|
+
ctx: ExtensionContext,
|
|
336
|
+
forceRender: boolean,
|
|
337
|
+
model?: PiModel,
|
|
338
|
+
) => {
|
|
339
|
+
try {
|
|
340
|
+
const activeModel = model ?? ctx.model;
|
|
341
|
+
const previousFast = fastEnabled;
|
|
342
|
+
syncFast(activeModel, ctx);
|
|
343
|
+
forceRender ||= previousFast !== fastEnabled;
|
|
344
|
+
if (!isOpenAICodexModel(activeModel)) {
|
|
345
|
+
clearUsageStatusline(ctx);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const requestId = statuslineRequestId + 1;
|
|
350
|
+
statuslineRequestId = requestId;
|
|
351
|
+
let state = loadState();
|
|
352
|
+
renderState(ctx, state, activeModel, forceRender);
|
|
353
|
+
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
if (
|
|
356
|
+
isRefreshDue(state, instanceId, now) &&
|
|
357
|
+
now - lastAttemptAt >= MIN_ATTEMPT_GAP_MS
|
|
358
|
+
) {
|
|
359
|
+
await refreshSharedState(ctx, activeModel);
|
|
360
|
+
if (requestId !== statuslineRequestId) return;
|
|
361
|
+
if (!isOpenAICodexModel(ctx.model)) {
|
|
362
|
+
clearUsageStatusline(ctx);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
state = loadState();
|
|
366
|
+
renderState(ctx, state, activeModel, false);
|
|
367
|
+
}
|
|
368
|
+
scheduleStatuslineRefresh(ctx, nextTickDelayMs(state));
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (isStaleExtensionContextError(error)) {
|
|
371
|
+
clearStatuslineTimers();
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
ensureTelegramStatusLineRegistered();
|
|
379
|
+
|
|
380
|
+
pi.on("session_start", (_event, ctx) => {
|
|
381
|
+
syncFast(ctx.model, ctx);
|
|
382
|
+
ensureTelegramStatusLineRegistered();
|
|
383
|
+
if (isOpenAICodexModel(ctx.model))
|
|
384
|
+
void refreshCurrentCodexUsageStatusline(ctx, true).catch(
|
|
385
|
+
handleAsyncTimerError,
|
|
386
|
+
);
|
|
387
|
+
else clearUsageStatusline(ctx);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
391
|
+
if (isOpenAICodexModel(ctx.model))
|
|
392
|
+
void refreshCurrentCodexUsageStatusline(ctx, true).catch(
|
|
393
|
+
handleAsyncTimerError,
|
|
394
|
+
);
|
|
395
|
+
else clearUsageStatusline(ctx);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
pi.on("model_select", (event, ctx) => {
|
|
399
|
+
syncFast(event.model, ctx);
|
|
400
|
+
if (isOpenAICodexModel(event.model)) {
|
|
401
|
+
void refreshCurrentCodexUsageStatusline(ctx, true, event.model).catch(
|
|
402
|
+
handleAsyncTimerError,
|
|
403
|
+
);
|
|
404
|
+
} else {
|
|
405
|
+
clearUsageStatusline(ctx);
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
410
|
+
clearUsageStatusline(ctx);
|
|
411
|
+
unregisterTelegramStatusLine?.();
|
|
412
|
+
unregisterTelegramStatusLine = undefined;
|
|
413
|
+
});
|
|
414
|
+
return {
|
|
415
|
+
fastChanged(ctx: ExtensionContext, model: PiModel) {
|
|
416
|
+
syncFast(model, ctx);
|
|
417
|
+
if (lastStatusText !== undefined) setCodexStatus(ctx, lastStatusText, model);
|
|
418
|
+
renderState(ctx, loadState(), model, true);
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
function handleAsyncTimerError(error: unknown): void {
|
|
425
|
+
handleTimerError(error);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function handleTimerError(error: unknown): void {
|
|
429
|
+
if (isStaleExtensionContextError(error)) return;
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function isStaleExtensionContextError(error: unknown): boolean {
|
|
434
|
+
return error instanceof Error && error.message.includes("ctx is stale");
|
|
435
|
+
}
|
package/lib/telegram.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Domain: Telegram adapter. Owns: optional provider registration. Excludes: quota state and terminal formatting. */
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
const CODEX_USAGE_EXTENSION_ID = "@llblab/pi-codex-usage";
|
|
4
|
+
const TELEGRAM_STATUS_IMPORT_SPECIFIERS = [
|
|
5
|
+
"@llblab/pi-telegram/status",
|
|
6
|
+
new URL("../../pi-telegram/api/status.ts", import.meta.url).href,
|
|
7
|
+
];
|
|
8
|
+
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
9
|
+
type CodexUsageTelegramStatusModel = Pick<PiModel, "id" | "name" | "provider">;
|
|
10
|
+
type TelegramStatusLineProviderResult =
|
|
11
|
+
{ label: string; value: string } | undefined;
|
|
12
|
+
type TelegramStatusLineProvider = (ctx: {
|
|
13
|
+
activeModel?: CodexUsageTelegramStatusModel;
|
|
14
|
+
}) => TelegramStatusLineProviderResult;
|
|
15
|
+
type TelegramStatusLineModule = {
|
|
16
|
+
registerTelegramStatusLineProvider?: (
|
|
17
|
+
provider: TelegramStatusLineProvider,
|
|
18
|
+
options: { id: string },
|
|
19
|
+
) => () => void;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
async function importTelegramStatusLineModule(): Promise<
|
|
23
|
+
TelegramStatusLineModule | undefined
|
|
24
|
+
> {
|
|
25
|
+
for (const specifier of TELEGRAM_STATUS_IMPORT_SPECIFIERS) {
|
|
26
|
+
try {
|
|
27
|
+
const imported = (await import(specifier)) as TelegramStatusLineModule;
|
|
28
|
+
if (typeof imported.registerTelegramStatusLineProvider === "function") {
|
|
29
|
+
return imported;
|
|
30
|
+
}
|
|
31
|
+
} catch {
|
|
32
|
+
// pi-telegram is optional; absence just disables the Telegram status line.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function registerCodexUsageTelegramStatusLine(
|
|
39
|
+
provider: TelegramStatusLineProvider,
|
|
40
|
+
): Promise<(() => void) | undefined> {
|
|
41
|
+
const telegramStatus = await importTelegramStatusLineModule();
|
|
42
|
+
return telegramStatus?.registerTelegramStatusLineProvider?.(provider, {
|
|
43
|
+
id: CODEX_USAGE_EXTENSION_ID,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/** Domain: shared refresh. Owns: quota file, leadership claims and SQLite mutex. Excludes: request transport and UI. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { DatabaseSync } from "node:sqlite";
|
|
6
|
+
|
|
7
|
+
// --- Shared Refresh ---
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Cross-instance coordination for quota polling. Every Pi instance reads one
|
|
11
|
+
* JSON file; a single "leader"
|
|
12
|
+
* refreshes it every `LEADER_INTERVAL_MS`. Any other instance may take over once
|
|
13
|
+
* the file is `TAKEOVER_AFTER_MS` old: it first claims leadership (owner and
|
|
14
|
+
* timestamp) so nobody else is due, then fetches, then stamps the result. The
|
|
15
|
+
* file is the only authority for requests and fenced publication. Writes are
|
|
16
|
+
* atomic renames; short critical sections use an OS-backed SQLite mutex.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export const LEADER_INTERVAL_MS = 60_000;
|
|
20
|
+
/** The leader is considered gone after missing its slot by 30 seconds. */
|
|
21
|
+
export const TAKEOVER_AFTER_MS = LEADER_INTERVAL_MS + 30_000;
|
|
22
|
+
/** Minimum pause between two fetch attempts of the same instance. */
|
|
23
|
+
export const MIN_ATTEMPT_GAP_MS = 60_000;
|
|
24
|
+
|
|
25
|
+
const STATE_FILE = "usage.json";
|
|
26
|
+
const LOCK_FILE = "mutex.sqlite";
|
|
27
|
+
|
|
28
|
+
export type SharedState<Report = unknown> = {
|
|
29
|
+
report?: Report;
|
|
30
|
+
/** When `report` was last fetched successfully. */
|
|
31
|
+
updatedAt?: number;
|
|
32
|
+
/**
|
|
33
|
+
* When the leader last touched the file: written when it claims a refresh,
|
|
34
|
+
* before fetching, and again when the fetch finishes.
|
|
35
|
+
*/
|
|
36
|
+
claimedAt?: number;
|
|
37
|
+
/** Instance id of the current leader (the last instance to claim). */
|
|
38
|
+
owner?: string;
|
|
39
|
+
/** Unique generation for this refresh, including renewals by the same owner. */
|
|
40
|
+
claimId?: string;
|
|
41
|
+
/** Last failure message; cleared by the next success. */
|
|
42
|
+
error?: string;
|
|
43
|
+
/** The failure means "no quota available" (n/a), not a runtime error. */
|
|
44
|
+
unavailable?: boolean;
|
|
45
|
+
failures?: number;
|
|
46
|
+
/** No instance should fetch before this time. */
|
|
47
|
+
retryNotBefore?: number;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export function readState<Report>(
|
|
51
|
+
dir: string,
|
|
52
|
+
): SharedState<Report> | undefined {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(
|
|
55
|
+
readFileSync(join(dir, STATE_FILE), "utf8"),
|
|
56
|
+
) as unknown;
|
|
57
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
58
|
+
? (parsed as SharedState<Report>)
|
|
59
|
+
: undefined;
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function writeState<Report>(
|
|
66
|
+
dir: string,
|
|
67
|
+
state: SharedState<Report>,
|
|
68
|
+
): boolean {
|
|
69
|
+
try {
|
|
70
|
+
mkdirSync(dir, { recursive: true });
|
|
71
|
+
const temp = join(dir, `${STATE_FILE}.${process.pid}.tmp`);
|
|
72
|
+
writeFileSync(temp, JSON.stringify(state), { mode: 0o600 });
|
|
73
|
+
renameSync(temp, join(dir, STATE_FILE));
|
|
74
|
+
return true;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type RefreshClaim = { owner: string; claimId: string };
|
|
81
|
+
|
|
82
|
+
export type RefreshOutcome<Report> =
|
|
83
|
+
| { ok: true; report: Report }
|
|
84
|
+
| {
|
|
85
|
+
ok: false;
|
|
86
|
+
error: string;
|
|
87
|
+
unavailable?: boolean;
|
|
88
|
+
rateLimited: boolean;
|
|
89
|
+
retryAfterMs?: number;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/** Read, decide and claim under the lock; never authorize an unwritten claim. */
|
|
93
|
+
export function claimRefresh(
|
|
94
|
+
dir: string,
|
|
95
|
+
owner: string,
|
|
96
|
+
now?: number,
|
|
97
|
+
): RefreshClaim | undefined {
|
|
98
|
+
const release = tryAcquireLock(dir);
|
|
99
|
+
if (!release) return undefined;
|
|
100
|
+
try {
|
|
101
|
+
const current = readState(dir);
|
|
102
|
+
const at = now ?? Date.now();
|
|
103
|
+
if (!isRefreshDue(current, owner, at)) return undefined;
|
|
104
|
+
const claim = { owner, claimId: randomUUID() };
|
|
105
|
+
return writeState(dir, { ...current, ...claim, claimedAt: at })
|
|
106
|
+
? claim
|
|
107
|
+
: undefined;
|
|
108
|
+
} finally {
|
|
109
|
+
release();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function matchesClaim(
|
|
114
|
+
state: SharedState | undefined,
|
|
115
|
+
claim: RefreshClaim,
|
|
116
|
+
now: number,
|
|
117
|
+
): boolean {
|
|
118
|
+
return (
|
|
119
|
+
state?.owner === claim.owner &&
|
|
120
|
+
state.claimId === claim.claimId &&
|
|
121
|
+
typeof state.claimedAt === "number" &&
|
|
122
|
+
now - state.claimedAt < TAKEOVER_AFTER_MS
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Each admission check reads the file, not a remembered leadership flag. */
|
|
127
|
+
export function ownsRefreshClaim(
|
|
128
|
+
dir: string,
|
|
129
|
+
claim: RefreshClaim,
|
|
130
|
+
now?: number,
|
|
131
|
+
): boolean {
|
|
132
|
+
const current = readState(dir);
|
|
133
|
+
return matchesClaim(current, claim, now ?? Date.now());
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A late success OR failure must not overwrite a successor's state. */
|
|
137
|
+
export function publishRefresh<Report>(
|
|
138
|
+
dir: string,
|
|
139
|
+
claim: RefreshClaim,
|
|
140
|
+
outcome: RefreshOutcome<Report>,
|
|
141
|
+
now?: number,
|
|
142
|
+
): boolean {
|
|
143
|
+
const release = tryAcquireLock(dir);
|
|
144
|
+
if (!release) return false;
|
|
145
|
+
try {
|
|
146
|
+
const current = readState<Report>(dir);
|
|
147
|
+
const at = now ?? Date.now();
|
|
148
|
+
if (!matchesClaim(current, claim, at)) return false;
|
|
149
|
+
if (outcome.ok) {
|
|
150
|
+
return writeState(dir, {
|
|
151
|
+
...claim,
|
|
152
|
+
claimedAt: at,
|
|
153
|
+
updatedAt: at,
|
|
154
|
+
report: outcome.report,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const failures = (current?.failures ?? 0) + 1;
|
|
158
|
+
return writeState(dir, {
|
|
159
|
+
...current,
|
|
160
|
+
...claim,
|
|
161
|
+
claimedAt: at,
|
|
162
|
+
error: outcome.error,
|
|
163
|
+
unavailable: outcome.unavailable,
|
|
164
|
+
failures,
|
|
165
|
+
retryNotBefore: at + failureBackoffMs(failures, outcome),
|
|
166
|
+
});
|
|
167
|
+
} finally {
|
|
168
|
+
release();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Earliest time at which `owner` should try to refresh the state. */
|
|
173
|
+
export function nextRefreshAt(
|
|
174
|
+
state: SharedState<unknown> | undefined,
|
|
175
|
+
owner: string,
|
|
176
|
+
now: number,
|
|
177
|
+
): number {
|
|
178
|
+
const hold = state?.retryNotBefore ?? 0;
|
|
179
|
+
const touchedAt = Math.max(
|
|
180
|
+
state?.updatedAt ?? -Infinity,
|
|
181
|
+
state?.claimedAt ?? -Infinity,
|
|
182
|
+
);
|
|
183
|
+
if (touchedAt === -Infinity) return Math.max(now, hold);
|
|
184
|
+
const interval =
|
|
185
|
+
state?.owner === owner ? LEADER_INTERVAL_MS : TAKEOVER_AFTER_MS;
|
|
186
|
+
return Math.max(touchedAt + interval, hold);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function isRefreshDue(
|
|
190
|
+
state: SharedState<unknown> | undefined,
|
|
191
|
+
owner: string,
|
|
192
|
+
now: number,
|
|
193
|
+
): boolean {
|
|
194
|
+
return nextRefreshAt(state, owner, now) <= now;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Exponential failure backoff; HTTP 429 gets a longer base and cap. */
|
|
198
|
+
export function failureBackoffMs(
|
|
199
|
+
failures: number,
|
|
200
|
+
options: { rateLimited: boolean; retryAfterMs?: number },
|
|
201
|
+
): number {
|
|
202
|
+
const base = options.rateLimited ? 5 * 60_000 : 60_000;
|
|
203
|
+
const cap = options.rateLimited ? 30 * 60_000 : 5 * 60_000;
|
|
204
|
+
const exponential = Math.min(cap, base * 2 ** Math.max(0, failures - 1));
|
|
205
|
+
return Math.max(options.retryAfterMs ?? 0, exponential);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* An empty SQLite transaction is a non-waiting, OS-backed mutex, not storage
|
|
210
|
+
* for quota or leadership. Close or process death releases it; a paused live
|
|
211
|
+
* holder cannot be evicted. Never unlink/replace mutex.sqlite while in use.
|
|
212
|
+
*/
|
|
213
|
+
export function tryAcquireLock(dir: string): (() => void) | undefined {
|
|
214
|
+
let database: DatabaseSync | undefined;
|
|
215
|
+
try {
|
|
216
|
+
mkdirSync(dir, { recursive: true });
|
|
217
|
+
database = new DatabaseSync(join(dir, LOCK_FILE));
|
|
218
|
+
// Contention must not wait on Pi's TUI thread; PRAGMA also works on Node 22.
|
|
219
|
+
database.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE");
|
|
220
|
+
} catch {
|
|
221
|
+
database?.close();
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
return () => {
|
|
225
|
+
const held = database;
|
|
226
|
+
database = undefined;
|
|
227
|
+
held?.close();
|
|
228
|
+
};
|
|
229
|
+
}
|