pi-opencode-go-provider 1.1.20 → 1.1.22
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 +1 -0
- package/CHANGELOG.md +8 -0
- package/README.md +25 -2
- package/config.ts +9 -0
- package/index.ts +38 -12
- package/models.json +28 -0
- package/package.json +5 -4
- package/sync-policy.ts +309 -0
- package/tests/multiprovider.test.ts +19 -1
- package/tests/quiet-startup-sync.test.ts +267 -0
- package/tests/sync-policy.test.ts +259 -0
- package/tests/usage-sync.test.ts +146 -0
- package/tsconfig.json +4 -1
- package/tsconfig.vitest.json +10 -0
- package/usage-controller.ts +109 -1
- package/vitest.config.ts +11 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "./tsconfig.json",
|
|
3
|
+
"exclude": [],
|
|
4
|
+
"compilerOptions": {
|
|
5
|
+
"module": "ESNext",
|
|
6
|
+
"moduleResolution": "Bundler",
|
|
7
|
+
"noUncheckedIndexedAccess": false
|
|
8
|
+
},
|
|
9
|
+
"include": ["tests/sync-policy.test.ts", "tests/quiet-startup-sync.test.ts", "tests/usage-sync.test.ts"]
|
|
10
|
+
}
|
package/usage-controller.ts
CHANGED
|
@@ -4,10 +4,20 @@
|
|
|
4
4
|
* Mirrors the pi-better-openai usage controller: one snapshot per session,
|
|
5
5
|
* polled on a timer plus after each turn, pushed into the extension widget
|
|
6
6
|
* (favoured) or the footer status line when no terminal UI is available.
|
|
7
|
+
*
|
|
8
|
+
* Quiet startup sync: polling is skipped entirely without a UI (print/JSON mode,
|
|
9
|
+
* fan-out child agents) and without credentials. Background polls (session
|
|
10
|
+
* start, timer, turn/model events) are deduped across pi processes through
|
|
11
|
+
* sync-policy.ts: one process polls per USAGE_SYNC_TTL_MS and writes the
|
|
12
|
+
* snapshot to `<agentDir>/cache/opencode-go-usage.json`; the others render that
|
|
13
|
+
* file. `/opencode-go-usage` (notify) always polls.
|
|
7
14
|
*/
|
|
8
15
|
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import path from "node:path";
|
|
9
18
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
-
import { PROVIDER_ID, configPath, type UsageConfig } from "./config.ts";
|
|
19
|
+
import { PROVIDER_ID, configPath, usageCachePath, type UsageConfig } from "./config.ts";
|
|
20
|
+
import { acquireModelSync, keyFingerprint, writeFileAtomic, type SkipReason } from "./sync-policy.ts";
|
|
11
21
|
import { getActiveMultiproviderService } from "./multiprovider.ts";
|
|
12
22
|
import {
|
|
13
23
|
USAGE_LIMITS_NOTE,
|
|
@@ -20,6 +30,43 @@ import {
|
|
|
20
30
|
} from "./usage.ts";
|
|
21
31
|
|
|
22
32
|
const REQUEST_TIMEOUT_MS = 10_000;
|
|
33
|
+
/**
|
|
34
|
+
* Cross-process freshness window for the shared usage snapshot: half the
|
|
35
|
+
* default 60s poll interval. Each process's widget is at most ~30s behind a
|
|
36
|
+
* direct poll, while any number of pi processes collapse to about one usage
|
|
37
|
+
* request per 30s. Fixed (PI_PROVIDER_SYNC_TTL_MS tunes the model catalog only).
|
|
38
|
+
*/
|
|
39
|
+
export const USAGE_SYNC_TTL_MS = 30_000;
|
|
40
|
+
|
|
41
|
+
/** On-disk shape of the shared usage snapshot (never contains the key). */
|
|
42
|
+
interface SharedUsage {
|
|
43
|
+
version: 1;
|
|
44
|
+
keyFingerprint: string;
|
|
45
|
+
fetchedAt: number;
|
|
46
|
+
snapshot: UsageSnapshot;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The shared snapshot, only when it was polled with this same key. */
|
|
50
|
+
function readSharedUsage(cachePath: string, apiKey: string): SharedUsage | undefined {
|
|
51
|
+
try {
|
|
52
|
+
const data = JSON.parse(fs.readFileSync(cachePath, "utf8")) as Partial<SharedUsage> | null;
|
|
53
|
+
if (!data || data.keyFingerprint !== keyFingerprint(apiKey)) return undefined;
|
|
54
|
+
if (typeof data.fetchedAt !== "number" || !Array.isArray(data.snapshot?.windows)) return undefined;
|
|
55
|
+
return data as SharedUsage;
|
|
56
|
+
} catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function writeSharedUsage(cachePath: string, apiKey: string, snapshot: UsageSnapshot, fetchedAt: number): void {
|
|
62
|
+
try {
|
|
63
|
+
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
|
|
64
|
+
const shared: SharedUsage = { version: 1, keyFingerprint: keyFingerprint(apiKey), fetchedAt, snapshot };
|
|
65
|
+
writeFileAtomic(cachePath, JSON.stringify(shared) + "\n");
|
|
66
|
+
} catch {
|
|
67
|
+
// Non-fatal: other processes just poll themselves.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
23
70
|
const STALE_CONTEXT_MESSAGE = "This extension ctx is stale";
|
|
24
71
|
const MISSING_KEY_MESSAGE =
|
|
25
72
|
"no opencode-go API key. Set OPENCODE_API_KEY or add \"opencode-go\" to ~/.pi/agent/auth.json.";
|
|
@@ -42,6 +89,7 @@ export class UsageController {
|
|
|
42
89
|
private usageUpdatedAt: number | undefined;
|
|
43
90
|
private usageError: string | undefined;
|
|
44
91
|
private usageLastFetchAt: number | undefined;
|
|
92
|
+
private usageSource: "network" | "shared cache" | undefined;
|
|
45
93
|
private usageTimer: ReturnType<typeof setInterval> | undefined;
|
|
46
94
|
private usageRefreshInFlight = false;
|
|
47
95
|
private queuedRefresh: QueuedRefresh | undefined;
|
|
@@ -125,6 +173,8 @@ export class UsageController {
|
|
|
125
173
|
`Last fetch: ${this.usageLastFetchAt ? new Date(this.usageLastFetchAt).toLocaleTimeString() : "never"}`,
|
|
126
174
|
`Last success: ${this.usageUpdatedAt ? new Date(this.usageUpdatedAt).toLocaleTimeString() : "never"}`,
|
|
127
175
|
`Last error: ${this.usageError ?? "none"}`,
|
|
176
|
+
`Last source: ${this.usageSource ?? "none"}`,
|
|
177
|
+
`Shared snapshot: ${usageCachePath()} (fresh for ${USAGE_SYNC_TTL_MS / 1000}s)`,
|
|
128
178
|
`Windows: ${this.usageSnapshot?.windows.map((window) => `${window.label}=${window.remainingPercent}% left`).join(" ") ?? "none"}`,
|
|
129
179
|
`Endpoint: ${USAGE_URL}`,
|
|
130
180
|
`Config file: ${configPath()}`,
|
|
@@ -189,6 +239,15 @@ export class UsageController {
|
|
|
189
239
|
return envKey ? envKey : undefined;
|
|
190
240
|
}
|
|
191
241
|
|
|
242
|
+
/**
|
|
243
|
+
* Whether this context can render usage at all. Print/JSON mode and child
|
|
244
|
+
* agents run without a UI, so polling there would only spend requests.
|
|
245
|
+
* Throws the stale-context error like any other ctx access.
|
|
246
|
+
*/
|
|
247
|
+
private hasUI(ctx: ExtensionContext): boolean {
|
|
248
|
+
return ctx.hasUI !== false;
|
|
249
|
+
}
|
|
250
|
+
|
|
192
251
|
private fail(ctx: ExtensionContext, message: string, options?: UsageRefreshOptions): void {
|
|
193
252
|
this.usageError = message;
|
|
194
253
|
this.onUpdate(ctx);
|
|
@@ -202,6 +261,16 @@ export class UsageController {
|
|
|
202
261
|
): Promise<void> {
|
|
203
262
|
if (!this.isCurrent(generation)) return;
|
|
204
263
|
|
|
264
|
+
// Background polls never run without a UI; an explicit command (notify) still does.
|
|
265
|
+
if (!options?.notify) {
|
|
266
|
+
try {
|
|
267
|
+
if (!this.hasUI(ctx)) return;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (isStaleContextError(error)) this.deactivate(generation);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
205
274
|
const config = this.getConfig();
|
|
206
275
|
if (!config.enabled) {
|
|
207
276
|
this.usageSnapshot = undefined;
|
|
@@ -248,6 +317,8 @@ export class UsageController {
|
|
|
248
317
|
}
|
|
249
318
|
|
|
250
319
|
this.usageRefreshInFlight = true;
|
|
320
|
+
let lease: ReturnType<typeof acquireModelSync> = null;
|
|
321
|
+
let outcome: "fetched" | "failed" | "aborted" = "failed";
|
|
251
322
|
try {
|
|
252
323
|
const apiKey = await this.resolveApiKey(ctx);
|
|
253
324
|
if (!this.isCurrent(generation)) return;
|
|
@@ -259,6 +330,33 @@ export class UsageController {
|
|
|
259
330
|
}
|
|
260
331
|
|
|
261
332
|
this.usageLastFetchAt = Date.now();
|
|
333
|
+
|
|
334
|
+
// Cross-process dedupe: one process polls per USAGE_SYNC_TTL_MS, the rest
|
|
335
|
+
// render its snapshot. An explicit refresh (notify) bypasses the window and
|
|
336
|
+
// polls even while another process holds the lock. If the cache dir is
|
|
337
|
+
// unusable we fail open to polling (still throttled per process).
|
|
338
|
+
const cachePath = usageCachePath();
|
|
339
|
+
let skipReason: SkipReason | undefined;
|
|
340
|
+
lease = acquireModelSync({
|
|
341
|
+
cachePath,
|
|
342
|
+
apiKey,
|
|
343
|
+
force: options?.notify === true,
|
|
344
|
+
ttlMs: USAGE_SYNC_TTL_MS,
|
|
345
|
+
isValidCache: (d) => d != null,
|
|
346
|
+
onSkip: (reason) => { skipReason = reason; },
|
|
347
|
+
});
|
|
348
|
+
if (!lease && !options?.notify && skipReason !== "unwritable") {
|
|
349
|
+
const shared = readSharedUsage(cachePath, apiKey);
|
|
350
|
+
if (shared) {
|
|
351
|
+
this.usageSnapshot = shared.snapshot;
|
|
352
|
+
this.usageUpdatedAt = shared.fetchedAt;
|
|
353
|
+
this.usageError = undefined;
|
|
354
|
+
this.usageSource = "shared cache";
|
|
355
|
+
}
|
|
356
|
+
this.onUpdate(ctx);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
|
|
262
360
|
this.usageAbortController = new AbortController();
|
|
263
361
|
const response = await fetch(USAGE_URL, {
|
|
264
362
|
headers: { accept: "application/json", authorization: `Bearer ${apiKey}` },
|
|
@@ -286,6 +384,9 @@ export class UsageController {
|
|
|
286
384
|
this.usageSnapshot = snapshot;
|
|
287
385
|
this.usageUpdatedAt = Date.now();
|
|
288
386
|
this.usageError = undefined;
|
|
387
|
+
this.usageSource = "network";
|
|
388
|
+
if (lease) writeSharedUsage(cachePath, apiKey, snapshot, this.usageUpdatedAt);
|
|
389
|
+
outcome = "fetched";
|
|
289
390
|
this.onUpdate(ctx);
|
|
290
391
|
if (options?.notify) this.notify(ctx, this.formatStatus(ctx), "info");
|
|
291
392
|
} catch (error) {
|
|
@@ -297,6 +398,8 @@ export class UsageController {
|
|
|
297
398
|
const message = error instanceof Error ? error.message : String(error);
|
|
298
399
|
this.fail(ctx, message, options);
|
|
299
400
|
} finally {
|
|
401
|
+
if (outcome !== "fetched" && !this.isCurrent(generation)) outcome = "aborted";
|
|
402
|
+
lease?.release(outcome);
|
|
300
403
|
this.usageAbortController = undefined;
|
|
301
404
|
this.usageRefreshInFlight = false;
|
|
302
405
|
const next = this.queuedRefresh;
|
|
@@ -320,6 +423,11 @@ export class UsageController {
|
|
|
320
423
|
this.shuttingDown = false;
|
|
321
424
|
|
|
322
425
|
if (!this.getConfig().enabled) return;
|
|
426
|
+
try {
|
|
427
|
+
if (!this.hasUI(ctx)) return; // nothing to render: no startup poll, no timer
|
|
428
|
+
} catch {
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
323
431
|
void this.refresh(ctx, { force: true }, generation);
|
|
324
432
|
this.usageTimer = setInterval(() => {
|
|
325
433
|
if (!this.isCurrent(generation)) return;
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineConfig } from "vitest/config";
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
test: {
|
|
5
|
+
environment: "node",
|
|
6
|
+
// The other tests/*.test.ts files are node:test suites run by `node --test`.
|
|
7
|
+
include: ["tests/sync-policy.test.ts", "tests/quiet-startup-sync.test.ts", "tests/usage-sync.test.ts"],
|
|
8
|
+
clearMocks: true,
|
|
9
|
+
restoreMocks: true,
|
|
10
|
+
},
|
|
11
|
+
});
|