@bismawy/pi-arnative 0.16.1 → 0.18.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/README.md +25 -16
- package/extensions/index.ts +41 -0
- package/lib/active-clock.ts +91 -0
- package/lib/ansi.ts +40 -78
- package/lib/box.ts +49 -68
- package/lib/chatbox.ts +371 -0
- package/lib/color.ts +3 -31
- package/lib/compat.ts +0 -60
- package/lib/edit-diff.ts +199 -0
- package/{extensions → lib/features}/arnative.ts +96 -423
- package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
- package/{extensions → lib/features}/budget.ts +17 -242
- package/lib/features/footer.ts +2232 -0
- package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
- package/{extensions → lib/features}/model-heal.ts +5 -28
- package/lib/features/progress-group.ts +1557 -0
- package/{extensions → lib/features}/render-cache.ts +113 -161
- package/{extensions → lib/features}/timestamps.ts +18 -94
- package/{extensions → lib/features}/todos.ts +44 -158
- package/lib/features/tools.ts +1202 -0
- package/lib/features/ui-render-tweaks.ts +606 -0
- package/lib/features/usage.ts +786 -0
- package/lib/format.ts +22 -4
- package/lib/git-status.ts +164 -0
- package/lib/list-picker.ts +1 -127
- package/lib/model-heal.ts +70 -162
- package/lib/patch.ts +0 -63
- package/lib/preset-store.ts +17 -133
- package/lib/provider-store.ts +573 -0
- package/lib/provider.ts +52 -851
- package/lib/runtime.ts +209 -0
- package/lib/shortcuts.ts +8 -58
- package/lib/spinner.ts +88 -162
- package/lib/status-widget.ts +4 -30
- package/lib/todos.ts +20 -143
- package/lib/usage-pricing.ts +143 -0
- package/lib/usage-store.ts +44 -378
- package/package.json +5 -6
- package/themes/arnative-blossom.json +0 -0
- package/themes/arnative-crimson.json +0 -0
- package/themes/arnative-cyberpunk.json +0 -0
- package/themes/arnative-dracula.json +0 -0
- package/themes/arnative-earthy.json +0 -0
- package/themes/arnative-garden.json +0 -0
- package/themes/arnative-gruvbox.json +0 -0
- package/themes/arnative-lemonade.json +0 -0
- package/themes/arnative-magical.json +0 -0
- package/themes/arnative-matrix.json +0 -0
- package/themes/arnative-neutral.json +0 -0
- package/themes/arnative-nord.json +0 -0
- package/themes/arnative-zinc.json +0 -0
- package/themes/arnative.json +0 -0
- package/CHANGELOG.md +0 -683
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2617
- package/extensions/tools.ts +0 -2231
- package/extensions/ui-render-tweaks.ts +0 -1005
- package/extensions/usage-export.ts +0 -283
- package/extensions/usage.ts +0 -1406
- package/lib/check.ts +0 -21
- package/themes/gen-themes.mjs +0 -715
package/lib/usage-store.ts
CHANGED
|
@@ -15,12 +15,36 @@
|
|
|
15
15
|
* rollup per file, so earlier messages stop counting in every view while the session
|
|
16
16
|
* files stay untouched (see {@link resetUsageStats}).
|
|
17
17
|
*/
|
|
18
|
-
import { closeSync, existsSync, fstatSync, mkdirSync,
|
|
19
|
-
import { tmpdir } from "node:os";
|
|
18
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
|
|
20
19
|
import { join, relative } from "node:path";
|
|
21
20
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
22
|
-
import { assert, isMain } from "./check.ts";
|
|
23
21
|
import { writeAtomicSync } from "./preset-store.ts";
|
|
22
|
+
import {
|
|
23
|
+
USAGE_RANGES,
|
|
24
|
+
dayKey,
|
|
25
|
+
estimateCost,
|
|
26
|
+
formatTokens,
|
|
27
|
+
hasPrice,
|
|
28
|
+
loadPriceTable,
|
|
29
|
+
rangeStart,
|
|
30
|
+
resetPriceMemo,
|
|
31
|
+
type ModelPrices,
|
|
32
|
+
type PriceTable,
|
|
33
|
+
type UsageRange,
|
|
34
|
+
} from "./usage-pricing.ts";
|
|
35
|
+
|
|
36
|
+
export {
|
|
37
|
+
USAGE_RANGES,
|
|
38
|
+
dayKey,
|
|
39
|
+
estimateCost,
|
|
40
|
+
formatTokens,
|
|
41
|
+
hasPrice,
|
|
42
|
+
loadPriceTable,
|
|
43
|
+
rangeStart,
|
|
44
|
+
type ModelPrices,
|
|
45
|
+
type PriceTable,
|
|
46
|
+
type UsageRange,
|
|
47
|
+
};
|
|
24
48
|
|
|
25
49
|
interface UsageEntry {
|
|
26
50
|
provider: string;
|
|
@@ -88,31 +112,6 @@ function addToRollup(r: Rollup, e: UsageEntry): void {
|
|
|
88
112
|
r.billed += e.billed ? e.cost : 0;
|
|
89
113
|
}
|
|
90
114
|
|
|
91
|
-
/** A time window the dashboard can show. `all` is the whole history. */
|
|
92
|
-
export type UsageRange = "all" | "today" | "7d" | "30d";
|
|
93
|
-
|
|
94
|
-
/** Tab order of the range bar. */
|
|
95
|
-
export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d"];
|
|
96
|
-
|
|
97
|
-
/** UTC day bucket key (`YYYY-MM-DD`) of a timestamp. UTC on purpose: local time would make the
|
|
98
|
-
* on-disk cache depend on the timezone of the machine that wrote it, so a restore elsewhere
|
|
99
|
-
* would re-bucket every entry. Exported for the range bar, whose windows share the buckets. */
|
|
100
|
-
export function dayKey(ms: number): string {
|
|
101
|
-
return new Date(ms > 0 ? ms : 0).toISOString().slice(0, 10);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** UTC midnight where `range` starts: today, 7 or 30 calendar days back.
|
|
105
|
-
* `undefined` for `all`, which has no floor. UTC to match the day buckets: a local-midnight
|
|
106
|
-
* floor would cut a UTC+7 "today" at 7am local and drop the morning's spend. */
|
|
107
|
-
export function rangeStart(range: UsageRange, now = Date.now()): number | undefined {
|
|
108
|
-
if (range === "all") return undefined;
|
|
109
|
-
const d = new Date(now);
|
|
110
|
-
d.setUTCHours(0, 0, 0, 0);
|
|
111
|
-
if (range === "today") return d.getTime();
|
|
112
|
-
d.setUTCDate(d.getUTCDate() - (range === "7d" ? 6 : 29));
|
|
113
|
-
return d.getTime();
|
|
114
|
-
}
|
|
115
|
-
|
|
116
115
|
/** Fold entries into an existing file rollup, updating provider, provider+model and day keys
|
|
117
116
|
* together in one pass over the entries. */
|
|
118
117
|
function foldInto(rollup: FileRollup, entries: UsageEntry[]): void {
|
|
@@ -218,124 +217,6 @@ export interface UsageSummary {
|
|
|
218
217
|
};
|
|
219
218
|
}
|
|
220
219
|
|
|
221
|
-
export type ModelPrices = Record<string, { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }>;
|
|
222
|
-
export type PriceTable = Record<string, ModelPrices>;
|
|
223
|
-
|
|
224
|
-
const modelsFilePath = (): string => join(getAgentDir(), "models.json");
|
|
225
|
-
|
|
226
|
-
type ModelsJsonCost = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
|
|
227
|
-
|
|
228
|
-
/** Memo of the last price-table read, keyed by the models.json path + mtimeMs + size: one
|
|
229
|
-
* `statSync` per call instead of a `readFileSync` on every footer frame. Cleared by
|
|
230
|
-
* `resetUsageCache()` so the self-checks see a cold read after changing the fixture. */
|
|
231
|
-
let priceMemo: { key: string; table: PriceTable } | null = null;
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Rates declared automatically in pi's `models.json` (`providers.<name>.models[].cost`).
|
|
235
|
-
* Keyed by provider to reconstruct estimates for historical or 0-cost rows. Memoized on the
|
|
236
|
-
* file's stat, so an unchanged file is parsed once, not once per caller.
|
|
237
|
-
*/
|
|
238
|
-
export function loadPriceTable(): PriceTable {
|
|
239
|
-
const path = modelsFilePath();
|
|
240
|
-
let key: string;
|
|
241
|
-
try {
|
|
242
|
-
const st = statSync(path);
|
|
243
|
-
key = `${path}\u0000${st.mtimeMs}\u0000${st.size}`;
|
|
244
|
-
} catch {
|
|
245
|
-
key = `${path}\u0000absent`;
|
|
246
|
-
}
|
|
247
|
-
if (priceMemo && priceMemo.key === key) return priceMemo.table;
|
|
248
|
-
const table: PriceTable = {};
|
|
249
|
-
try {
|
|
250
|
-
const raw = JSON.parse(readFileSync(path, "utf8")) as {
|
|
251
|
-
providers?: Record<string, { models?: { id?: string; cost?: ModelsJsonCost }[] }>;
|
|
252
|
-
};
|
|
253
|
-
for (const [provider, cfg] of Object.entries(raw.providers ?? {})) {
|
|
254
|
-
const models: ModelPrices = {};
|
|
255
|
-
for (const m of cfg?.models ?? []) {
|
|
256
|
-
const c = m?.cost;
|
|
257
|
-
if (!m?.id || !c || typeof c.input !== "number" || typeof c.output !== "number") continue;
|
|
258
|
-
models[m.id] = {
|
|
259
|
-
input: c.input,
|
|
260
|
-
output: c.output,
|
|
261
|
-
cacheRead: typeof c.cacheRead === "number" ? c.cacheRead : 0,
|
|
262
|
-
cacheWrite: typeof c.cacheWrite === "number" ? c.cacheWrite : 0,
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
if (Object.keys(models).length > 0) table[provider] = models;
|
|
266
|
-
}
|
|
267
|
-
} catch {
|
|
268
|
-
// Malformed or absent models.json means no declared rates.
|
|
269
|
-
}
|
|
270
|
-
priceMemo = { key, table };
|
|
271
|
-
return table;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/** True when this provider+model has a usable input+output price (cacheRead/cacheWrite are optional). */
|
|
275
|
-
export function hasPrice(provider: string, modelId: string, table: PriceTable = loadPriceTable()): boolean {
|
|
276
|
-
return findPrice(provider, modelId, table) !== null;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** Rates for one provider+model. The provider's own entry wins over the `*` fallback. */
|
|
280
|
-
function findPrice(
|
|
281
|
-
provider: string,
|
|
282
|
-
modelId: string,
|
|
283
|
-
table: PriceTable,
|
|
284
|
-
): { input: number; output: number; cacheRead: number; cacheWrite: number } | null {
|
|
285
|
-
return rateFor(table[provider], modelId) ?? rateFor(table["*"], modelId);
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function rateFor(
|
|
289
|
-
entries: ModelPrices | undefined,
|
|
290
|
-
modelId: string,
|
|
291
|
-
): { input: number; output: number; cacheRead: number; cacheWrite: number } | null {
|
|
292
|
-
if (!entries || typeof entries !== "object") return null;
|
|
293
|
-
const lower = modelId.toLowerCase();
|
|
294
|
-
const keys = Object.keys(entries).filter((k) => !k.startsWith("_"));
|
|
295
|
-
const key =
|
|
296
|
-
keys.find((k) => k.toLowerCase() === lower) ??
|
|
297
|
-
keys.find((k) => lower.endsWith("/" + k.toLowerCase()) || k.toLowerCase().endsWith("/" + lower));
|
|
298
|
-
if (!key) return null;
|
|
299
|
-
const p = entries[key]!;
|
|
300
|
-
if (typeof p.input !== "number" || typeof p.output !== "number") return null;
|
|
301
|
-
return {
|
|
302
|
-
input: p.input,
|
|
303
|
-
output: p.output,
|
|
304
|
-
cacheRead: typeof p.cacheRead === "number" ? p.cacheRead : 0,
|
|
305
|
-
cacheWrite: typeof p.cacheWrite === "number" ? p.cacheWrite : 0,
|
|
306
|
-
};
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/** Cost of one provider+model's token counts from the price table, or null when unpriced. */
|
|
310
|
-
export function estimateCost(
|
|
311
|
-
input: number,
|
|
312
|
-
output: number,
|
|
313
|
-
cacheRead: number,
|
|
314
|
-
cacheWrite: number,
|
|
315
|
-
modelId: string,
|
|
316
|
-
provider: string,
|
|
317
|
-
table: PriceTable = loadPriceTable(),
|
|
318
|
-
): number | null {
|
|
319
|
-
const p = findPrice(provider, modelId, table);
|
|
320
|
-
if (!p) return null;
|
|
321
|
-
return (input / 1e6) * p.input + (output / 1e6) * p.output + (cacheRead / 1e6) * p.cacheRead + (cacheWrite / 1e6) * p.cacheWrite;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/** Scaled value with 1 decimal ("2.5k"); a value that rounds up to the next unit is promoted (999,999 -> "1M", not "1000k"). */
|
|
325
|
-
const fmtUnit = (v: number, unit: string, next: string): string => {
|
|
326
|
-
const s = v.toFixed(1).replace(/\.0$/, "");
|
|
327
|
-
return s === "1000" ? `1${next}` : `${s}${unit}`;
|
|
328
|
-
};
|
|
329
|
-
|
|
330
|
-
/** Token count with k/M/B units; 0 or negative = "-". */
|
|
331
|
-
export function formatTokens(n: number): string {
|
|
332
|
-
if (!n || n <= 0) return "-";
|
|
333
|
-
if (n < 1000) return String(n);
|
|
334
|
-
if (n < 1_000_000) return fmtUnit(n / 1000, "k", "M");
|
|
335
|
-
if (n < 1_000_000_000) return fmtUnit(n / 1_000_000, "M", "B");
|
|
336
|
-
return fmtUnit(n / 1_000_000_000, "B", "T");
|
|
337
|
-
}
|
|
338
|
-
|
|
339
220
|
// Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
|
|
340
221
|
// Everything pi-arnative writes lives in one folder (agent dir/arnative); the cache moved
|
|
341
222
|
// there from a flat arnative-usage-cache.json, which is migrated in on first read.
|
|
@@ -727,6 +608,14 @@ function readTail(filePath: string, fromByte: number): Buffer | null {
|
|
|
727
608
|
let cachedSummary: UsageSummary | null = null;
|
|
728
609
|
let cachedRange: UsageRange | null = null;
|
|
729
610
|
let lastScanMs = 0;
|
|
611
|
+
let usageGen = 0;
|
|
612
|
+
let lastScanGen = -1;
|
|
613
|
+
|
|
614
|
+
/** Mark the cached usage summary stale after a turn or session switch so the next
|
|
615
|
+
* non-forced read (`budget`, footer) scans once without forcing redundant rescans. */
|
|
616
|
+
export function markUsageDirty(): void {
|
|
617
|
+
usageGen++;
|
|
618
|
+
}
|
|
730
619
|
|
|
731
620
|
/** Drop every in-memory memo so the next scan reads the cache file and the session files
|
|
732
621
|
* again. The self-check needs this: `forceScan` skips the 5s summary cache but still
|
|
@@ -734,11 +623,12 @@ let lastScanMs = 0;
|
|
|
734
623
|
* against itself and can never fail. */
|
|
735
624
|
export function resetUsageCache(): void {
|
|
736
625
|
diskMemo = null;
|
|
737
|
-
|
|
626
|
+
resetPriceMemo();
|
|
738
627
|
baselineMemo = null;
|
|
739
628
|
cachedSummary = null;
|
|
740
629
|
cachedRange = null;
|
|
741
630
|
lastScanMs = 0;
|
|
631
|
+
lastScanGen = -1;
|
|
742
632
|
}
|
|
743
633
|
|
|
744
634
|
// =============================================================================
|
|
@@ -961,7 +851,8 @@ function effectiveProviders(rollup: FileRollup, baseline: FileRollup | undefined
|
|
|
961
851
|
|
|
962
852
|
export function collectUsageSummary(forceScan = false, range: UsageRange = "all"): UsageSummary {
|
|
963
853
|
const now = Date.now();
|
|
964
|
-
|
|
854
|
+
const scanGen = usageGen;
|
|
855
|
+
if (!forceScan && cachedSummary && cachedRange === range && lastScanGen === scanGen && now - lastScanMs < 5000) {
|
|
965
856
|
return cachedSummary;
|
|
966
857
|
}
|
|
967
858
|
|
|
@@ -1183,6 +1074,7 @@ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"
|
|
|
1183
1074
|
cachedSummary = { providers, projects, totals };
|
|
1184
1075
|
cachedRange = range;
|
|
1185
1076
|
lastScanMs = now;
|
|
1077
|
+
lastScanGen = scanGen;
|
|
1186
1078
|
return cachedSummary;
|
|
1187
1079
|
}
|
|
1188
1080
|
|
|
@@ -1226,233 +1118,7 @@ export function getModelAllTimeUsage(modelId?: string): { input: number; output:
|
|
|
1226
1118
|
return { input: inp, output: out, cacheRead: read };
|
|
1227
1119
|
}
|
|
1228
1120
|
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
1234
|
-
const asst = (model: string, input: number, ts: number, cost = 0.02) =>
|
|
1235
|
-
JSON.stringify({
|
|
1236
|
-
message: {
|
|
1237
|
-
role: "assistant",
|
|
1238
|
-
provider: "google",
|
|
1239
|
-
model,
|
|
1240
|
-
timestamp: ts,
|
|
1241
|
-
usage: { input, output: 5, cacheRead: 1, cacheWrite: 2, cost: { total: cost, totalFromProvider: true } },
|
|
1242
|
-
},
|
|
1243
|
-
});
|
|
1244
|
-
const header = (cwd: string) => JSON.stringify({ type: "session", cwd });
|
|
1245
|
-
const tsToday = Date.now();
|
|
1246
|
-
const tsYesterday = Date.now() - 86_400_000;
|
|
1247
|
-
const today = new Date(tsToday).toISOString().slice(0, 10);
|
|
1248
|
-
const yesterday = new Date(tsYesterday).toISOString().slice(0, 10);
|
|
1249
|
-
|
|
1250
|
-
mkdirSync(join(fixture, "sessions", "proj-a"), { recursive: true });
|
|
1251
|
-
mkdirSync(join(fixture, "sessions", "proj-b"), { recursive: true });
|
|
1252
|
-
// proj-a carries a session header (cwd); proj-b has none, so it must land in "unknown".
|
|
1253
|
-
const fileA = join(fixture, "sessions", "proj-a", "a.jsonl");
|
|
1254
|
-
writeFileSync(fileA, [header("/repo/alpha"), asst("m1", 100, tsToday), asst("m1", 50, tsYesterday)].join(NL) + NL);
|
|
1255
|
-
writeFileSync(join(fixture, "sessions", "proj-b", "b.jsonl"), asst("m2", 7, tsToday) + NL);
|
|
1256
|
-
|
|
1257
|
-
const summary = collectUsageSummary(true);
|
|
1258
|
-
assert(summary.projects.length === 2, "one project per cwd plus unknown");
|
|
1259
|
-
const alpha = summary.projects.find((p) => p.name === "/repo/alpha")!;
|
|
1260
|
-
const unknown = summary.projects.find((p) => p.name === "unknown")!;
|
|
1261
|
-
assert(alpha.msgs === 2 && alpha.input === 150 && Math.abs(alpha.cost - 0.04) < 1e-9, "a project row carries its files' totals");
|
|
1262
|
-
assert(unknown.msgs === 1 && unknown.input === 7, "a file with no cwd lands in unknown");
|
|
1263
|
-
assert(alpha.providers.length === 1 && alpha.providers[0]!.name === "google" && alpha.providers[0]!.models[0]!.name === "m1", "a project trees into its providers and models");
|
|
1264
|
-
const sumOf = (f: (p: (typeof summary.projects)[number]) => number) => summary.projects.reduce((n, p) => n + f(p), 0);
|
|
1265
|
-
assert(
|
|
1266
|
-
sumOf((p) => p.msgs) === summary.totals.msgs &&
|
|
1267
|
-
sumOf((p) => p.input) === summary.totals.input &&
|
|
1268
|
-
sumOf((p) => p.output) === summary.totals.output &&
|
|
1269
|
-
Math.abs(sumOf((p) => p.cost) - summary.totals.cost) < 1e-9,
|
|
1270
|
-
"projects totals equal totals",
|
|
1271
|
-
);
|
|
1272
|
-
|
|
1273
|
-
// Day buckets: windows come from them, and on disk they sum to the file total.
|
|
1274
|
-
assert(summary.totals.today !== undefined && summary.totals.last7d !== undefined && summary.totals.last30d !== undefined, "day buckets produce the today/7d/30d windows");
|
|
1275
|
-
assert(summary.totals.today.input === 107 && Math.abs(summary.totals.today.cost - 0.04) < 1e-9, "today sums only today's bucket");
|
|
1276
|
-
assert(summary.totals.last7d.input === 157 && Math.abs(summary.totals.last7d.cost - 0.06) < 1e-9, "last7d includes yesterday");
|
|
1277
|
-
assert(summary.totals.last30d.input === 157, "last30d includes yesterday too");
|
|
1278
|
-
const cachePath = join(fixture, "arnative", "usage-cache.json");
|
|
1279
|
-
const disk = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { r: Record<string, number[]>; d?: Record<string, number[]>; w?: string }>;
|
|
1280
|
-
const relA = join("proj-a", "a.jsonl");
|
|
1281
|
-
const msgsOf = (rows: Record<string, number[]>) => Object.values(rows).reduce((n, a) => n + a[0]!, 0);
|
|
1282
|
-
assert(disk[relA]!.w === "/repo/alpha", "v8 stores the session cwd in w");
|
|
1283
|
-
assert(disk[relA]!.d !== undefined && msgsOf(disk[relA]!.d!) === msgsOf(disk[relA]!.r), "day buckets sum to the file total on disk");
|
|
1284
|
-
const rowA = disk[relA]!.r["google\u0000m1"]!;
|
|
1285
|
-
assert(rowA.length === 7 && rowA[4] === 4, "v8 rows carry cacheWrite (two entries x 2)");
|
|
1286
|
-
assert(Math.abs(rowA[6]! - 0.04) < 1e-9, "v8 rows carry the billed split of the cost");
|
|
1287
|
-
assert(
|
|
1288
|
-
Object.keys(disk[relA]!.d!).every((k) => k.startsWith(`${today}\u0000`) || k.startsWith(`${yesterday}\u0000`)) && disk[relA]!.d![`${today}\u0000google\u0000m1`] !== undefined,
|
|
1289
|
-
"day keys are the UTC day + provider + model",
|
|
1290
|
-
);
|
|
1291
|
-
assert(disk[join("proj-b", "b.jsonl")]!.w === "", "a file with no cwd stores the empty marker (it reads as unknown)");
|
|
1292
|
-
|
|
1293
|
-
// A grown file tail-folds: the cwd stays the cached one (the head is not re-read) and the
|
|
1294
|
-
// new entry lands in its day bucket.
|
|
1295
|
-
writeFileSync(fileA, asst("m1", 1000, tsToday) + NL, { flag: "a" });
|
|
1296
|
-
const grown = collectUsageSummary(true);
|
|
1297
|
-
assert(grown.totals.msgs === 4, "an appended record is folded from the tail");
|
|
1298
|
-
assert(grown.projects.find((p) => p.name === "/repo/alpha")!.input === 1150, "the tail fold keeps the cached cwd (the project is unchanged)");
|
|
1299
|
-
assert(grown.totals.today!.input === 1107, "the appended entry lands in today's bucket");
|
|
1300
|
-
const grownDisk = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { w?: string }>;
|
|
1301
|
-
assert(grownDisk[relA]!.w === "/repo/alpha", "the cwd survives a tail fold on disk too");
|
|
1302
|
-
|
|
1303
|
-
// A pre-v8 (v5 compact, no `d`) cache item is re-parsed once from its file — not trusted —
|
|
1304
|
-
// and re-saved as v8 with its days, cwd, cache writes, billed split and tool-result spend.
|
|
1305
|
-
const fileC = join(fixture, "sessions", "proj-b", "c.jsonl");
|
|
1306
|
-
writeFileSync(fileC, asst("m2", 11, tsToday) + NL);
|
|
1307
|
-
const cStat = statSync(fileC);
|
|
1308
|
-
writeFileSync(
|
|
1309
|
-
cachePath,
|
|
1310
|
-
JSON.stringify({ [join("proj-b", "c.jsonl")]: { m: cStat.mtimeMs, s: cStat.size, c: cStat.size, r: { "google\u0000m2": [99, 999, 1, 1, 9] } } }),
|
|
1311
|
-
);
|
|
1312
|
-
resetUsageCache();
|
|
1313
|
-
const reparsed = collectUsageSummary(true);
|
|
1314
|
-
assert(reparsed.totals.msgs === 5 && reparsed.totals.input === 1168, "a v5 cache item is re-parsed from the file (the stale 99 is not counted)");
|
|
1315
|
-
const afterDisk = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { d?: Record<string, number[]>; w?: string }>;
|
|
1316
|
-
const relC = join("proj-b", "c.jsonl");
|
|
1317
|
-
assert(afterDisk[relC]!.d !== undefined && msgsOf(afterDisk[relC]!.d!) === 1, "the re-parsed item is re-saved as v8 with day buckets");
|
|
1318
|
-
|
|
1319
|
-
// A v6 item (day buckets but 5-number rows) is also re-parsed once: its rows carry neither
|
|
1320
|
-
// cacheWrite nor the billed split, so it is stamped 6 and not trusted.
|
|
1321
|
-
const fileD = join(fixture, "sessions", "proj-b", "d.jsonl");
|
|
1322
|
-
writeFileSync(fileD, asst("m2", 13, tsToday) + NL);
|
|
1323
|
-
const dStat = statSync(fileD);
|
|
1324
|
-
writeFileSync(
|
|
1325
|
-
cachePath,
|
|
1326
|
-
JSON.stringify({
|
|
1327
|
-
[join("proj-b", "d.jsonl")]: {
|
|
1328
|
-
m: dStat.mtimeMs,
|
|
1329
|
-
s: dStat.size,
|
|
1330
|
-
c: dStat.size,
|
|
1331
|
-
r: { "google\u0000m2": [99, 999, 1, 1, 9] },
|
|
1332
|
-
d: { [`${today}\u0000google\u0000m2`]: [99, 999, 1, 1, 9] },
|
|
1333
|
-
},
|
|
1334
|
-
}),
|
|
1335
|
-
);
|
|
1336
|
-
resetUsageCache();
|
|
1337
|
-
const reparsed6 = collectUsageSummary(true);
|
|
1338
|
-
assert(reparsed6.totals.msgs === 6 && reparsed6.totals.input === 1181, "a v6 cache item is re-parsed from its file (the stale 99 is not counted)");
|
|
1339
|
-
|
|
1340
|
-
// Child spend: pi attaches it to the tool result, but the child also writes its own session
|
|
1341
|
-
// file, so the store must not read the tool result — that counts the same tokens twice.
|
|
1342
|
-
// Its own fixture, so the totals above stay untouched.
|
|
1343
|
-
assert(TOOL_PROVIDER === "tool", "child spend is attributed to the synthetic `tool` provider");
|
|
1344
|
-
const toolFixture = mkdtempSync(join(tmpdir(), "arnative-tool-"));
|
|
1345
|
-
process.env.PI_CODING_AGENT_DIR = toolFixture;
|
|
1346
|
-
resetUsageCache();
|
|
1347
|
-
mkdirSync(join(toolFixture, "sessions", "p"), { recursive: true });
|
|
1348
|
-
const toolFile = join(toolFixture, "sessions", "p", "t.jsonl");
|
|
1349
|
-
const toolResult = (toolName: string, usage?: object) =>
|
|
1350
|
-
JSON.stringify({
|
|
1351
|
-
message: { role: "toolResult", toolCallId: "c1", toolName, content: [], isError: false, timestamp: tsToday, ...(usage ? { usage } : {}) },
|
|
1352
|
-
});
|
|
1353
|
-
writeFileSync(
|
|
1354
|
-
toolFile,
|
|
1355
|
-
[
|
|
1356
|
-
header("/repo/alpha"),
|
|
1357
|
-
asst("m1", 100, tsToday),
|
|
1358
|
-
toolResult("subagent", { input: 40, output: 6, cacheRead: 2, cacheWrite: 1, cost: { total: 0.01, totalFromProvider: true } }),
|
|
1359
|
-
toolResult("bash"), // no usage at all
|
|
1360
|
-
].join(NL) + NL,
|
|
1361
|
-
);
|
|
1362
|
-
const parentOnly = collectUsageSummary(true);
|
|
1363
|
-
assert(parentOnly.totals.msgs === 1 && parentOnly.totals.input === 100, "a tool result's usage is not read: the child's own session file carries it");
|
|
1364
|
-
assert(parentOnly.providers.every((p) => p.name !== TOOL_PROVIDER), "no synthetic `tool` row: /usage never sees child spend twice");
|
|
1365
|
-
|
|
1366
|
-
// A subagent run writes <project>/<parent id>/<run id>/run-N/session.jsonl, and its
|
|
1367
|
-
// transcript under <project>/subagent-artifacts/: the child session is real spend, the
|
|
1368
|
-
// transcript is the same messages again.
|
|
1369
|
-
const childDir = join(toolFixture, "sessions", "p", "parent-1", "run-1", "run-0");
|
|
1370
|
-
mkdirSync(childDir, { recursive: true });
|
|
1371
|
-
writeFileSync(join(childDir, "session.jsonl"), [header("/repo/alpha"), asst("m1", 40, tsToday)].join(NL) + NL);
|
|
1372
|
-
mkdirSync(join(toolFixture, "sessions", "p", SUBAGENT_ARTIFACTS_DIR), { recursive: true });
|
|
1373
|
-
writeFileSync(
|
|
1374
|
-
join(toolFixture, "sessions", "p", SUBAGENT_ARTIFACTS_DIR, "x_transcript.jsonl"),
|
|
1375
|
-
[header("/repo/alpha"), asst("m1", 7, tsToday)].join(NL) + NL,
|
|
1376
|
-
);
|
|
1377
|
-
resetUsageCache();
|
|
1378
|
-
const nested = collectUsageSummary(true);
|
|
1379
|
-
assert(nested.totals.msgs === 2 && nested.totals.input === 140, "a child session is counted once (40), its transcript not at all (7)");
|
|
1380
|
-
assert(nested.totals.sessions === 2, "the parent session and the child session, not the transcript");
|
|
1381
|
-
|
|
1382
|
-
// A v7 item (7-number rows with day buckets, no `t`) is re-parsed once from its file — not
|
|
1383
|
-
// trusted — and re-saved as v8.
|
|
1384
|
-
const tStat = statSync(toolFile);
|
|
1385
|
-
writeFileSync(
|
|
1386
|
-
join(toolFixture, "arnative", "usage-cache.json"),
|
|
1387
|
-
JSON.stringify({
|
|
1388
|
-
[join("p", "t.jsonl")]: {
|
|
1389
|
-
m: tStat.mtimeMs,
|
|
1390
|
-
s: tStat.size,
|
|
1391
|
-
c: tStat.size,
|
|
1392
|
-
r: { "google\u0000m1": [99, 999, 1, 1, 1, 9, 9] },
|
|
1393
|
-
d: { [`${today}\u0000google\u0000m1`]: [99, 999, 1, 1, 1, 9, 9] },
|
|
1394
|
-
},
|
|
1395
|
-
}),
|
|
1396
|
-
);
|
|
1397
|
-
resetUsageCache();
|
|
1398
|
-
const reparsed7 = collectUsageSummary(true);
|
|
1399
|
-
assert(reparsed7.totals.msgs === 2 && reparsed7.totals.input === 140, "a v7 cache item is re-parsed from its file (the stale 99 is not counted)");
|
|
1400
|
-
const after7 = JSON.parse(readFileSync(join(toolFixture, "arnative", "usage-cache.json"), "utf8")) as Record<string, { t?: number }>;
|
|
1401
|
-
assert(after7[join("p", "t.jsonl")]!.t === CACHE_VERSION, "the re-parsed item is re-saved as the current version");
|
|
1402
|
-
|
|
1403
|
-
// A cache written by the build that also stored tool-result rows is stamped `t: 8`: it must
|
|
1404
|
-
// be re-parsed, or the child spend it holds is counted a second time next to the child's file.
|
|
1405
|
-
const staleDisk = JSON.parse(readFileSync(join(toolFixture, "arnative", "usage-cache.json"), "utf8")) as Record<string, unknown>;
|
|
1406
|
-
staleDisk[join("p", "t.jsonl")] = {
|
|
1407
|
-
m: tStat.mtimeMs,
|
|
1408
|
-
s: tStat.size,
|
|
1409
|
-
c: tStat.size,
|
|
1410
|
-
t: 8,
|
|
1411
|
-
r: { [`${TOOL_PROVIDER}\u0000subagent`]: [1, 40, 6, 2, 1, 0.01, 0.01], "google\u0000m1": [1, 100, 5, 1, 0, 0.02, 0.02] },
|
|
1412
|
-
};
|
|
1413
|
-
writeFileSync(join(toolFixture, "arnative", "usage-cache.json"), JSON.stringify(staleDisk));
|
|
1414
|
-
resetUsageCache();
|
|
1415
|
-
const afterStale = collectUsageSummary(true);
|
|
1416
|
-
assert(afterStale.providers.every((p) => p.name !== TOOL_PROVIDER), "a `t: 8` item's tool rows are dropped: the item is re-parsed");
|
|
1417
|
-
assert(afterStale.totals.input === 140, "the re-parsed item keeps the parent and the child, once each");
|
|
1418
|
-
|
|
1419
|
-
// An empty session (no assistant message) writes `r: {}`: that is a current item, not a
|
|
1420
|
-
// pre-v7 one — `some` over an empty map is false, and treating it as old would re-read that
|
|
1421
|
-
// file on every start. A tampered row proves the item is trusted rather than re-parsed.
|
|
1422
|
-
const emptyFile = join(toolFixture, "sessions", "p", "empty.jsonl");
|
|
1423
|
-
writeFileSync(emptyFile, header("/repo/alpha") + NL);
|
|
1424
|
-
resetUsageCache();
|
|
1425
|
-
collectUsageSummary(true);
|
|
1426
|
-
const emptyCachePath = join(toolFixture, "arnative", "usage-cache.json");
|
|
1427
|
-
const emptyDisk = JSON.parse(readFileSync(emptyCachePath, "utf8")) as Record<string, { r: Record<string, number[]> }>;
|
|
1428
|
-
assert(emptyDisk[join("p", "empty.jsonl")] !== undefined, "an empty session is cached");
|
|
1429
|
-
emptyDisk[join("p", "empty.jsonl")]!.r = { "google\u0000m9": [5, 500, 0, 0, 0, 0, 0] };
|
|
1430
|
-
writeFileSync(emptyCachePath, JSON.stringify(emptyDisk));
|
|
1431
|
-
resetUsageCache();
|
|
1432
|
-
assert(collectUsageSummary(true).totals.input === 640, "an empty `r` item is trusted, not re-read on every start");
|
|
1433
|
-
rmSync(toolFixture, { recursive: true, force: true });
|
|
1434
|
-
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
1435
|
-
resetUsageCache();
|
|
1436
|
-
|
|
1437
|
-
// Price table: cacheWrite is priced like the other three, and an unchanged models.json is
|
|
1438
|
-
// read once — two loadPriceTable() calls return the same memo object.
|
|
1439
|
-
writeFileSync(
|
|
1440
|
-
join(fixture, "models.json"),
|
|
1441
|
-
JSON.stringify({ providers: { google: { models: [{ id: "m1", cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 3 } }] } } }),
|
|
1442
|
-
);
|
|
1443
|
-
const table1 = loadPriceTable();
|
|
1444
|
-
assert(table1 === loadPriceTable(), "two loadPriceTable() calls with an unchanged file read it once (memo identity)");
|
|
1445
|
-
assert(estimateCost(1_000_000, 0, 0, 0, "m1", "google") === 1, "input keeps its own rate");
|
|
1446
|
-
assert(estimateCost(0, 0, 0, 1_000_000, "m1", "google") === 3, "cache writes use their own rate");
|
|
1447
|
-
assert(Math.abs(estimateCost(0, 0, 1_000_000, 1_000_000, "m1", "google")! - 3.1) < 1e-9, "cache read and cache write add up");
|
|
1448
|
-
await new Promise((r) => setTimeout(r, 5)); // mtime granularity: a rewrite must change the memo key
|
|
1449
|
-
writeFileSync(
|
|
1450
|
-
join(fixture, "models.json"),
|
|
1451
|
-
JSON.stringify({ providers: { google: { models: [{ id: "m1", cost: { input: 10, output: 2, cacheRead: 0.1, cacheWrite: 3 } }] } } }),
|
|
1452
|
-
);
|
|
1453
|
-
const table2 = loadPriceTable();
|
|
1454
|
-
assert(table2 !== table1 && estimateCost(1_000_000, 0, 0, 0, "m1", "google") === 10, "a changed models.json is re-read");
|
|
1455
|
-
|
|
1456
|
-
rmSync(fixture, { recursive: true, force: true });
|
|
1457
|
-
console.log("usage-store.ts self-check OK");
|
|
1458
|
-
}
|
|
1121
|
+
export const __test = {
|
|
1122
|
+
CACHE_VERSION,
|
|
1123
|
+
SUBAGENT_ARTIFACTS_DIR,
|
|
1124
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bismawy/pi-arnative",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -20,15 +20,14 @@
|
|
|
20
20
|
"files": [
|
|
21
21
|
"extensions",
|
|
22
22
|
"lib",
|
|
23
|
-
"themes",
|
|
24
|
-
"CHANGELOG.md",
|
|
23
|
+
"themes/*.json",
|
|
25
24
|
"LICENSE",
|
|
26
25
|
"README.md"
|
|
27
26
|
],
|
|
28
27
|
"pi": {
|
|
29
28
|
"image": "https://raw.githubusercontent.com/bismawy/pi-arnative/main/assets/banner.webp",
|
|
30
29
|
"extensions": [
|
|
31
|
-
"./extensions
|
|
30
|
+
"./extensions/index.ts"
|
|
32
31
|
],
|
|
33
32
|
"themes": [
|
|
34
33
|
"./themes/*.json"
|
|
@@ -40,8 +39,8 @@
|
|
|
40
39
|
"@earendil-works/pi-tui": "*"
|
|
41
40
|
},
|
|
42
41
|
"scripts": {
|
|
43
|
-
"dev": "pi --extension ./extensions/
|
|
44
|
-
"test": "node
|
|
42
|
+
"dev": "pi --extension ./extensions/index.ts",
|
|
43
|
+
"test": "node themes/gen-themes.mjs --check && node scripts/reporter.mjs --self-check && node --test --test-reporter=./scripts/reporter.mjs",
|
|
45
44
|
"preview": "node scripts/preview.mjs",
|
|
46
45
|
"overlay": "node scripts/overlay.mjs",
|
|
47
46
|
"themes": "node themes/gen-themes.mjs",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/themes/arnative.json
CHANGED
|
File without changes
|