@herbertgao/pi-extensions 2026.11.19 → 2026.11.20

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.
Files changed (30) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +2 -2
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/node_modules/pi-typesafe/README.md +1 -1
  5. package/node_modules/pi-typesafe/dist/ask.js +6 -3
  6. package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
  7. package/node_modules/pi-typesafe/dist/auth.js +159 -55
  8. package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
  9. package/node_modules/pi-typesafe/dist/batch.js +62 -22
  10. package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
  11. package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
  12. package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
  13. package/node_modules/pi-typesafe/dist/client.js +67 -27
  14. package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
  15. package/node_modules/pi-typesafe/dist/errors.js +105 -2
  16. package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
  17. package/node_modules/pi-typesafe/dist/extension.js +206 -106
  18. package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
  19. package/node_modules/pi-typesafe/dist/index.js +3 -3
  20. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
  21. package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
  22. package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
  23. package/node_modules/pi-typesafe/dist/login.js +167 -13
  24. package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
  25. package/node_modules/pi-typesafe/dist/schema.js +47 -13
  26. package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
  27. package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
  28. package/node_modules/pi-typesafe/dist/usage.js +79 -40
  29. package/node_modules/pi-typesafe/package.json +3 -3
  30. package/package.json +2 -2
@@ -1,9 +1,113 @@
1
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
1
3
  import { noul } from "@typesafe-ai/sdk";
4
+ import { authStatePath } from "./auth.js";
2
5
  import { DEFAULT_BACKEND, resolveBackend } from "./backends.js";
3
6
  import { createTypeSafe } from "./client.js";
4
7
  import { keySituation, normalizeApiKey, storeApiKey } from "./credentials.js";
5
8
  import { TypeSafeIntegrationError } from "./errors.js";
6
9
  import { promptForApiKey } from "./key-prompt.js";
10
+ import { emptyTotals, localDay } from "./usage.js";
11
+ /** Single stage transition writer for interactive login; out-of-order moves fail loudly instead of skipping verification. */
12
+ export function transitionLogin(state, event) {
13
+ if (event.type === "failed") {
14
+ if (state.stage === "cancelled" || state.stage === "verified" || state.stage === "failed") {
15
+ throw new Error(`Invalid login transition: ${event.type} from ${state.stage}`);
16
+ }
17
+ return { stage: "failed", error: event.error };
18
+ }
19
+ switch (state.stage) {
20
+ case "precheck":
21
+ if (event.type === "precheck_passed")
22
+ return { stage: "prompting", spec: state.spec, config: state.config };
23
+ break;
24
+ case "prompting":
25
+ if (event.type === "prompt_cancelled")
26
+ return { stage: "cancelled" };
27
+ if (event.type === "prompt_submitted")
28
+ return { stage: "validating", spec: state.spec, config: state.config, entered: event.entered };
29
+ break;
30
+ case "validating":
31
+ if (event.type === "key_validated") {
32
+ return {
33
+ stage: "probing",
34
+ spec: state.spec,
35
+ config: state.config,
36
+ key: event.key,
37
+ mode: state.config.modelsVerifyKey ? "models_list" : "judge_probe",
38
+ };
39
+ }
40
+ break;
41
+ case "probing":
42
+ if (event.type === "probe_succeeded") {
43
+ return {
44
+ stage: "storing",
45
+ spec: state.spec,
46
+ config: state.config,
47
+ key: state.key,
48
+ ...(event.models === undefined ? {} : { models: event.models }),
49
+ };
50
+ }
51
+ break;
52
+ case "storing":
53
+ if (event.type === "stored") {
54
+ const result = state.models === undefined ? { path: event.path } : { path: event.path, models: state.models };
55
+ return { stage: "verified", result };
56
+ }
57
+ break;
58
+ case "cancelled":
59
+ case "verified":
60
+ case "failed":
61
+ break;
62
+ }
63
+ throw new Error(`Invalid login transition: ${event.type} from ${state.stage}`);
64
+ }
65
+ /** Isolated ledger for login probes so key verification neither mutates usage.json nor trips daily spend caps. */
66
+ function createProbeLedger() {
67
+ return {
68
+ path: "",
69
+ usdPerMTok: 0,
70
+ today: () => ({ ...emptyTotals(), day: localDay(), estimatedUsd: 0 }),
71
+ recordStart: () => { },
72
+ recordSuccess: () => { },
73
+ recordFailure: () => { },
74
+ blocked: () => undefined,
75
+ describe: () => "login probe",
76
+ };
77
+ }
78
+ function snapshotFile(path) {
79
+ try {
80
+ return { kind: "present", content: readFileSync(path) };
81
+ }
82
+ catch (error) {
83
+ return error.code === "ENOENT" ? { kind: "absent" } : { kind: "unreadable" };
84
+ }
85
+ }
86
+ /** Restore auth-state.json after a rejected candidate key so a failed login never poisons the active key's record. */
87
+ function restoreFile(path, snapshot) {
88
+ if (snapshot.kind === "unreadable")
89
+ return;
90
+ if (snapshot.kind === "absent") {
91
+ try {
92
+ rmSync(path, { force: true });
93
+ }
94
+ catch { /* best-effort cleanup only */ }
95
+ return;
96
+ }
97
+ const temporary = `${path}.${process.pid}.restore.tmp`;
98
+ try {
99
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
100
+ writeFileSync(temporary, snapshot.content, { mode: 0o600, flag: "w" });
101
+ chmodSync(temporary, 0o600);
102
+ renameSync(temporary, path);
103
+ }
104
+ catch {
105
+ try {
106
+ rmSync(temporary, { force: true });
107
+ }
108
+ catch { /* best-effort cleanup only */ }
109
+ }
110
+ }
7
111
  /**
8
112
  * Prompt for one backend's key (hidden input), prove it before saving, and store it for every pi-typesafe consumer.
9
113
  * A backend whose model list is public is proved with one judge question instead, because that list accepts any key.
@@ -13,24 +117,74 @@ import { promptForApiKey } from "./key-prompt.js";
13
117
  export async function loginWithPrompt(ctx, options = {}) {
14
118
  const spec = options.backend ?? DEFAULT_BACKEND;
15
119
  const config = resolveBackend(spec);
120
+ let state = { stage: "precheck", spec, config };
121
+ const advance = (event) => {
122
+ state = transitionLogin(state, event);
123
+ return state;
124
+ };
16
125
  if (process.env[config.keyEnv]?.trim()) {
17
- throw new TypeSafeIntegrationError("configuration", `${config.keyEnv} is set in the environment and takes precedence over a stored key. Unset it before logging in interactively.`);
126
+ const error = new TypeSafeIntegrationError("configuration", `${config.keyEnv} is set in the environment and takes precedence over a stored key. Unset it before logging in interactively.`);
127
+ advance({ type: "failed", error });
128
+ throw error;
18
129
  }
19
130
  if (!ctx.hasUI) {
20
- throw new TypeSafeIntegrationError("configuration", `Logging in needs an interactive session. Set ${config.keyEnv} in the environment instead.`);
131
+ const error = new TypeSafeIntegrationError("configuration", `Logging in needs an interactive session. Set ${config.keyEnv} in the environment instead.`);
132
+ advance({ type: "failed", error });
133
+ throw error;
134
+ }
135
+ advance({ type: "precheck_passed" });
136
+ let entered;
137
+ try {
138
+ entered = await promptForApiKey(ctx, config.label);
21
139
  }
22
- const entered = await promptForApiKey(ctx, config.label);
23
- if (entered === undefined)
140
+ catch (error) {
141
+ advance({ type: "failed", error });
142
+ throw error;
143
+ }
144
+ if (entered === undefined) {
145
+ advance({ type: "prompt_cancelled" });
24
146
  return undefined;
25
- const key = normalizeApiKey(entered);
26
- const client = createTypeSafe({ apiKey: key, backend: spec });
27
- if (config.modelsVerifyKey) {
28
- const models = await client.listModels();
29
- return { path: storeApiKey(key, spec), models: models.length };
30
- }
31
- // A public model list accepts any key; one judge question proves this one.
32
- await client.evaluate({ state: "login", questions: { key: noul("Is this key accepted?") } });
33
- return { path: storeApiKey(key, spec) };
147
+ }
148
+ advance({ type: "prompt_submitted", entered });
149
+ let key;
150
+ try {
151
+ key = normalizeApiKey(entered);
152
+ }
153
+ catch (error) {
154
+ advance({ type: "failed", error });
155
+ throw error;
156
+ }
157
+ const probing = advance({ type: "key_validated", key });
158
+ if (probing.stage !== "probing")
159
+ throw new Error(`Unexpected login stage: ${probing.stage}`);
160
+ const authFile = authStatePath();
161
+ const authSnapshot = snapshotFile(authFile);
162
+ try {
163
+ const client = createTypeSafe({
164
+ apiKey: probing.key,
165
+ backend: probing.spec,
166
+ ledger: createProbeLedger(),
167
+ });
168
+ if (probing.mode === "models_list") {
169
+ const models = await client.listModels();
170
+ advance({ type: "probe_succeeded", models: models.length });
171
+ }
172
+ else {
173
+ // A public model list accepts any key; one judge question proves this one without touching usage.json.
174
+ await client.evaluate({ state: "login", questions: { key: noul("Is this key accepted?") } });
175
+ advance({ type: "probe_succeeded" });
176
+ }
177
+ const storedPath = storeApiKey(probing.key, probing.spec);
178
+ const done = advance({ type: "stored", path: storedPath });
179
+ if (done.stage !== "verified")
180
+ throw new Error(`Unexpected login stage: ${done.stage}`);
181
+ return done.result;
182
+ }
183
+ catch (error) {
184
+ restoreFile(authFile, authSnapshot);
185
+ advance({ type: "failed", error });
186
+ throw error;
187
+ }
34
188
  }
35
189
  /**
36
190
  * Use the configured key for the backend if there is one; otherwise run the login prompt. `undefined` means the user
@@ -38,6 +38,9 @@ export declare const evaluationSchema: Type.TObject<{
38
38
  }>]>>;
39
39
  model: Type.TOptional<Type.TString>;
40
40
  }>;
41
+ /** Canonical request admission stages, in strict precedence order. */
42
+ export declare const ADMISSION_STAGES: readonly ["normalize", "json_safe", "supported_shape", "schema", "backend_limits", "byte_budget"];
43
+ export type AdmissionStage = (typeof ADMISSION_STAGES)[number];
41
44
  /** Validate without including submitted content in validation errors. Prefer prepareEvaluationRequest(), which also accepts near-misses and enforces the byte budget. */
42
45
  export declare function parseEvaluationRequest(value: unknown): SystemOneRequest;
43
46
  /** Accept common near-misses from language models without loosening the schema itself. Prefer prepareEvaluationRequest(), which applies this before validating. */
@@ -83,16 +83,54 @@ function describeSchemaErrors(value) {
83
83
  }
84
84
  return details.join("; ");
85
85
  }
86
- /** Validate without including submitted content in validation errors. Prefer prepareEvaluationRequest(), which also accepts near-misses and enforces the byte budget. */
87
- export function parseEvaluationRequest(value) {
88
- if (value !== null && typeof value === "object" && !Array.isArray(value) && !isJsonSafe(value)) {
89
- throw new TypeSafeIntegrationError("validation", `Invalid evaluation request: state and questions must be plain JSON. ${usage}`);
86
+ /** Canonical request admission stages, in strict precedence order. */
87
+ export const ADMISSION_STAGES = [
88
+ "normalize",
89
+ "json_safe",
90
+ "supported_shape",
91
+ "schema",
92
+ "backend_limits",
93
+ "byte_budget",
94
+ ];
95
+ const PARSE_STAGE_SET = new Set(["json_safe", "supported_shape", "schema"]);
96
+ // Derive parse stages from ADMISSION_STAGES so stage ordering is declared once.
97
+ const PARSE_STAGES = ADMISSION_STAGES.filter(stage => PARSE_STAGE_SET.has(stage));
98
+ function runAdmissionStage(stage, value, options) {
99
+ switch (stage) {
100
+ case "normalize":
101
+ return normalizeEvaluationRequest(value);
102
+ case "json_safe":
103
+ if (value !== null && typeof value === "object" && !Array.isArray(value) && !isJsonSafe(value)) {
104
+ throw new TypeSafeIntegrationError("validation", `Invalid evaluation request: state and questions must be plain JSON. ${usage}`);
105
+ }
106
+ return value;
107
+ case "supported_shape":
108
+ refuseUnsupported(value);
109
+ return value;
110
+ case "schema":
111
+ if (!Check(evaluationSchema, value)) {
112
+ throw new TypeSafeIntegrationError("validation", `Invalid evaluation request at ${describeSchemaErrors(value)}. ${usage}`);
113
+ }
114
+ return value;
115
+ case "backend_limits":
116
+ if (options.limits !== undefined)
117
+ assertWithinBackendLimits(value, options.limits);
118
+ return value;
119
+ case "byte_budget":
120
+ assertWithinByteLimit(JSON.stringify(value), options.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES);
121
+ return value;
90
122
  }
91
- refuseUnsupported(value);
92
- if (!Check(evaluationSchema, value)) {
93
- throw new TypeSafeIntegrationError("validation", `Invalid evaluation request at ${describeSchemaErrors(value)}. ${usage}`);
123
+ }
124
+ function admitEvaluationRequest(value, stages, options = {}) {
125
+ let current = value;
126
+ for (const stage of stages) {
127
+ current = runAdmissionStage(stage, current, options);
94
128
  }
95
- return value;
129
+ return current;
130
+ }
131
+ /** Validate without including submitted content in validation errors. Prefer prepareEvaluationRequest(), which also accepts near-misses and enforces the byte budget. */
132
+ export function parseEvaluationRequest(value) {
133
+ return admitEvaluationRequest(value, PARSE_STAGES);
96
134
  }
97
135
  function isJsonSafe(value) {
98
136
  try {
@@ -198,9 +236,5 @@ export function assertWithinByteLimit(text, maxInputBytes) {
198
236
  * pass through here, so what one accepts the others accept.
199
237
  */
200
238
  export function prepareEvaluationRequest(value, options = {}) {
201
- const validated = parseEvaluationRequest(normalizeEvaluationRequest(value));
202
- if (options.limits !== undefined)
203
- assertWithinBackendLimits(validated, options.limits);
204
- assertWithinByteLimit(JSON.stringify(validated), options.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES);
205
- return validated;
239
+ return admitEvaluationRequest(value, ADMISSION_STAGES, options);
206
240
  }
@@ -1,3 +1,4 @@
1
1
  export { promptForApiKey } from "./key-prompt.js";
2
+ export type { KeyPromptEvent, KeyPromptState, KeyPromptTransition } from "./key-prompt.js";
2
3
  export { loginWithPrompt, ensureApiKey } from "./login.js";
3
- export type { LoginResult, EnsureApiKeyResult } from "./login.js";
4
+ export type { LoginEvent, LoginProbeMode, LoginResult, LoginState, EnsureApiKeyResult } from "./login.js";
@@ -34,6 +34,15 @@ export interface BlockedCap {
34
34
  readonly used: number;
35
35
  readonly day: string;
36
36
  }
37
+ /**
38
+ * One stored day. `costUsd` is the cost recorded request by request, at each request's own price, and
39
+ * `costedInputTokens` the input tokens it covers. A day written before costs were recorded has neither, so all of its
40
+ * input tokens are estimated at the ledger's rate.
41
+ */
42
+ interface DayRecord extends UsageTotals {
43
+ readonly costUsd?: number;
44
+ readonly costedInputTokens?: number;
45
+ }
37
46
  export declare function localDay(now?: Date): string;
38
47
  /** The stored ledger. Alongside the key store so one directory holds every pi-typesafe file. */
39
48
  export declare function usagePath(): string;
@@ -44,6 +53,49 @@ export declare function emptyTotals(): UsageTotals;
44
53
  export declare const LOCK_WAIT_MS = 200;
45
54
  /** A lock this old belongs to a process that died while holding it; the next update takes it over. */
46
55
  export declare const LOCK_STALE_MS = 5000;
56
+ /** Single attempt to acquire the exclusive lock file. */
57
+ export type LockProbe = {
58
+ readonly status: "acquired";
59
+ readonly release: () => void;
60
+ } | {
61
+ readonly status: "contended_stale";
62
+ } | {
63
+ readonly status: "contended_active";
64
+ } | {
65
+ readonly status: "unavailable";
66
+ };
67
+ /** Final result of waiting up to LOCK_WAIT_MS for the ledger lock. */
68
+ export type LockOutcome = {
69
+ readonly status: "acquired";
70
+ readonly release: () => void;
71
+ } | {
72
+ readonly status: "timed_out";
73
+ } | {
74
+ readonly status: "unavailable";
75
+ };
76
+ /** In-process delta buffer state keyed by local day so held-back deltas survive contention and midnight rollover. */
77
+ export type DeltaBufferState = {
78
+ readonly status: "synced";
79
+ } | {
80
+ readonly status: "buffered";
81
+ readonly pending: Readonly<Record<string, DayRecord>>;
82
+ };
83
+ export type DeltaBufferEvent = {
84
+ readonly type: "record";
85
+ readonly day: string;
86
+ readonly delta: DayRecord;
87
+ } | {
88
+ readonly type: "flushed";
89
+ };
90
+ /** Single-writer transition helper for the in-process usage delta buffer. */
91
+ export declare function transitionDeltaBuffer(state: DeltaBufferState, event: DeltaBufferEvent): DeltaBufferState;
92
+ /** One non-blocking probe of the lock file; unlinks a lock older than LOCK_STALE_MS before signaling retry. */
93
+ export declare function probeLock(lock: string, nowMs: number): LockProbe;
94
+ /**
95
+ * Take the lock file next to the ledger, created exclusively. Waits at most LOCK_WAIT_MS; a lock older than
96
+ * LOCK_STALE_MS is taken over.
97
+ */
98
+ export declare function takeLock(lock: string): LockOutcome;
47
99
  /** The caps a headless run may set without code: `PI_TYPESAFE_MAX_USD_PER_DAY` and its siblings. */
48
100
  export declare function capsFromEnvironment(env?: NodeJS.ProcessEnv): SpendCaps;
49
101
  /** Environment first for day caps, then the explicit option; a cap is never raised by the environment. */
@@ -81,3 +133,4 @@ export interface UsageLedger {
81
133
  flush?(): void;
82
134
  }
83
135
  export declare function openUsageLedger(options?: UsageLedgerOptions): UsageLedger;
136
+ export {};
@@ -123,45 +123,83 @@ function writeDays(path, days) {
123
123
  function pause(ms) {
124
124
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
125
125
  }
126
- /**
127
- * Take the lock file next to the ledger, created exclusively. Waits at most LOCK_WAIT_MS; a lock older than
128
- * LOCK_STALE_MS is taken over. Returns the release function, or undefined when the lock could not be taken.
129
- */
130
- function takeLock(lock) {
131
- const deadline = Date.now() + LOCK_WAIT_MS;
126
+ /** Single-writer transition helper for the in-process usage delta buffer. */
127
+ export function transitionDeltaBuffer(state, event) {
128
+ switch (event.type) {
129
+ case "record": {
130
+ const base = state.status === "buffered" ? state.pending : {};
131
+ const existing = base[event.day] ?? emptyTotals();
132
+ return {
133
+ status: "buffered",
134
+ pending: { ...base, [event.day]: addDay(existing, event.delta) },
135
+ };
136
+ }
137
+ case "flushed":
138
+ return { status: "synced" };
139
+ }
140
+ }
141
+ /** One non-blocking probe of the lock file; unlinks a lock older than LOCK_STALE_MS before signaling retry. */
142
+ export function probeLock(lock, nowMs) {
132
143
  try {
133
- mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
134
- for (;;) {
135
- try {
136
- closeSync(openSync(lock, "wx", 0o600));
137
- return () => { try {
138
- unlinkSync(lock);
139
- }
140
- catch { /* already gone */ } };
141
- }
142
- catch (error) {
143
- if (error.code !== "EEXIST")
144
- return undefined;
144
+ closeSync(openSync(lock, "wx", 0o600));
145
+ return { status: "acquired", release: () => { try {
146
+ unlinkSync(lock);
145
147
  }
148
+ catch { /* already gone */ } } };
149
+ }
150
+ catch (error) {
151
+ if (error.code !== "EEXIST")
152
+ return { status: "unavailable" };
153
+ }
154
+ try {
155
+ if (nowMs - statSync(lock).mtimeMs > LOCK_STALE_MS) {
146
156
  try {
147
- if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
148
- unlinkSync(lock);
149
- continue;
150
- }
157
+ unlinkSync(lock);
151
158
  }
152
159
  catch (error) {
153
- // The holder released it, or another process took it over, between our open and our stat.
154
160
  if (error.code !== "ENOENT")
155
- return undefined;
156
- continue;
161
+ return { status: "unavailable" };
157
162
  }
158
- if (Date.now() >= deadline)
159
- return undefined;
160
- pause(LOCK_RETRY_MS);
163
+ return { status: "contended_stale" };
161
164
  }
162
165
  }
166
+ catch (error) {
167
+ // The holder released it, or another process took it over, between our open and our stat.
168
+ if (error.code !== "ENOENT")
169
+ return { status: "unavailable" };
170
+ return { status: "contended_stale" };
171
+ }
172
+ return { status: "contended_active" };
173
+ }
174
+ /**
175
+ * Take the lock file next to the ledger, created exclusively. Waits at most LOCK_WAIT_MS; a lock older than
176
+ * LOCK_STALE_MS is taken over.
177
+ */
178
+ export function takeLock(lock) {
179
+ const deadline = Date.now() + LOCK_WAIT_MS;
180
+ try {
181
+ mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
182
+ }
163
183
  catch {
164
- return undefined;
184
+ return { status: "unavailable" };
185
+ }
186
+ for (;;) {
187
+ const probe = probeLock(lock, Date.now());
188
+ switch (probe.status) {
189
+ case "acquired":
190
+ case "unavailable":
191
+ return probe;
192
+ case "contended_stale":
193
+ // Stale or just-released lock: retry without sleeping, still bounded by deadline.
194
+ if (Date.now() >= deadline)
195
+ return { status: "timed_out" };
196
+ continue;
197
+ case "contended_active":
198
+ if (Date.now() >= deadline)
199
+ return { status: "timed_out" };
200
+ pause(LOCK_RETRY_MS);
201
+ continue;
202
+ }
165
203
  }
166
204
  }
167
205
  /** The caps a headless run may set without code: `PI_TYPESAFE_MAX_USD_PER_DAY` and its siblings. */
@@ -200,8 +238,7 @@ export function openUsageLedger(options = {}) {
200
238
  const lock = `${path}.lock`;
201
239
  const now = options.now ?? (() => new Date());
202
240
  const usdPerMTok = options.usdPerMTok !== undefined && Number.isFinite(options.usdPerMTok) && options.usdPerMTok >= 0 ? options.usdPerMTok : DEFAULT_USD_PER_MTOK;
203
- /** Deltas this process has recorded and the file does not hold yet, by day. */
204
- let pending = {};
241
+ let buffer = { status: "synced" };
205
242
  /** Recorded costs plus an estimate for the input tokens that have none. */
206
243
  const costOf = (value) => Math.round(((value.costUsd ?? 0) + estimateUsd(Math.max(0, value.inputTokens - (value.costedInputTokens ?? 0)), usdPerMTok)) * 1e6) / 1e6;
207
244
  const report = (value, name) => ({
@@ -217,14 +254,15 @@ export function openUsageLedger(options = {}) {
217
254
  const current = () => {
218
255
  const day = localDay(now());
219
256
  const stored = readDays(path)?.[day] ?? emptyTotals();
220
- return { day, totals: pending[day] === undefined ? stored : addDay(stored, pending[day]) };
257
+ const pendingDay = buffer.status === "buffered" ? buffer.pending[day] : undefined;
258
+ return { day, totals: pendingDay === undefined ? stored : addDay(stored, pendingDay) };
221
259
  };
222
260
  const flush = () => {
223
- const owed = Object.entries(pending);
224
- if (owed.length === 0)
261
+ if (buffer.status === "synced")
225
262
  return;
226
- const release = takeLock(lock);
227
- if (!release)
263
+ const owed = Object.entries(buffer.pending);
264
+ const outcome = takeLock(lock);
265
+ if (outcome.status !== "acquired")
228
266
  return;
229
267
  try {
230
268
  const stored = readDays(path);
@@ -232,16 +270,17 @@ export function openUsageLedger(options = {}) {
232
270
  return;
233
271
  for (const [name, delta] of owed)
234
272
  stored[name] = addDay(stored[name] ?? emptyTotals(), delta);
235
- if (writeDays(path, keepRecent(stored, localDay(now()))))
236
- pending = {};
273
+ if (writeDays(path, keepRecent(stored, localDay(now())))) {
274
+ buffer = transitionDeltaBuffer(buffer, { type: "flushed" });
275
+ }
237
276
  }
238
277
  finally {
239
- release();
278
+ outcome.release();
240
279
  }
241
280
  };
242
281
  const add = (delta) => {
243
282
  const day = localDay(now());
244
- pending[day] = addDay(pending[day] ?? emptyTotals(), { ...emptyTotals(), ...delta });
283
+ buffer = transitionDeltaBuffer(buffer, { type: "record", day, delta: { ...emptyTotals(), ...delta } });
245
284
  flush();
246
285
  };
247
286
  return {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-typesafe",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "description": "TypeSafe AI (Jev) decisions for Pi: batched Choice/Score/Noul evaluation tool, terminal playground, and a typed API other extensions build on.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -80,8 +80,8 @@
80
80
  }
81
81
  },
82
82
  "devDependencies": {
83
- "@earendil-works/pi-coding-agent": "0.86.1",
84
- "@earendil-works/pi-tui": "^0.86.1",
83
+ "@earendil-works/pi-coding-agent": "1.4.0",
84
+ "@earendil-works/pi-tui": "1.4.0",
85
85
  "@types/node": "^22.0.0",
86
86
  "tsx": "^4.23.13",
87
87
  "typebox": "^1.3.31",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-extensions",
3
- "version": "2026.11.19",
3
+ "version": "2026.11.20",
4
4
  "description": "Aggregate installer for HerbertGao-maintained Pi extensions.",
5
5
  "keywords": [
6
6
  "extensions",
@@ -81,7 +81,7 @@
81
81
  "pi-lens": "4.5.1",
82
82
  "pi-next-cue": "1.0.8",
83
83
  "pi-provider-qoder": "0.6.13",
84
- "pi-typesafe": "0.14.0",
84
+ "pi-typesafe": "0.15.1",
85
85
  "pi-web-access": "0.48.0",
86
86
  "pidusage": "^4.0.1",
87
87
  "promise.try": "^2.0.1",