@bismawy/pi-arnative 0.16.0 → 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.
Files changed (47) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +130 -158
  18. package/{extensions → lib/features}/timestamps.ts +132 -131
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/CHANGELOG.md +0 -678
  40. package/extensions/animations.ts +0 -242
  41. package/extensions/footer.ts +0 -2580
  42. package/extensions/tools.ts +0 -2231
  43. package/extensions/ui-render-tweaks.ts +0 -1005
  44. package/extensions/usage-export.ts +0 -283
  45. package/extensions/usage.ts +0 -1406
  46. package/lib/check.ts +0 -21
  47. package/themes/gen-themes.mjs +0 -715
@@ -1,283 +0,0 @@
1
- /**
2
- * Prometheus textfile export — the agent's spend lands in Grafana without this package ever
3
- * opening a socket: a textfile collector that already runs on the host (`node_exporter
4
- * --collector.textfile.directory=…`, or any other textfile collector) scrapes
5
- * `<agent dir>/arnative/usage.prom` and the gauges show up next to the infra metrics.
6
- *
7
- * {@link renderProm} is pure — summary in, exposition text out — so it is the unit under test;
8
- * this module only does the I/O. The write happens on `turn_end`, at most once per
9
- * {@link EXPORT_THROTTLE_MS} and only when the rendered text differs from the last one written,
10
- * so an idle session never touches the file (the scan-timestamp gauge only moves when the data
11
- * does). The file is replaced atomically — temp file + rename, with the Windows `EPERM`
12
- * in-place fallback `lib/preset-store.ts` uses — and a failed export is swallowed: it must
13
- * never disturb the session. `PI_ARNATIVE_EXPORT=0` turns the export off.
14
- */
15
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
17
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
18
- import { tmpdir } from "node:os";
19
- import { join } from "node:path";
20
- import { assert, isMain } from "../lib/check.ts";
21
- import { writeAtomicSync } from "../lib/preset-store.ts";
22
- import { collectUsageSummary, resetUsageCache, type UsageSummary } from "../lib/usage-store.ts";
23
-
24
- /** At most one write per minute, whatever the turn rate. */
25
- export const EXPORT_THROTTLE_MS = 60_000;
26
- /** `PI_ARNATIVE_EXPORT=0` disables the export (a local file with no network, so it ships on). */
27
- export const EXPORT_ENV = "PI_ARNATIVE_EXPORT";
28
-
29
- // Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
30
- /** The textfile a collector scrapes: `<agent dir>/arnative/usage.prom`. */
31
- export function promFilePath(): string {
32
- return join(getAgentDir(), "arnative", "usage.prom");
33
- }
34
-
35
- /** Escape a label value per the exposition format: backslash first, then quote, then newline. */
36
- const escapeLabel = (v: string): string => v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
37
-
38
- /**
39
- * Render the exposition text for one summary. Pure and deterministic: the same summary and
40
- * `now` always produce byte-identical output. `now` is the scan time in ms (the caller decides
41
- * what "last scan" means), rendered as seconds in `arnative_usage_last_change_timestamp_seconds`.
42
- */
43
- export function renderProm(summary: UsageSummary, now: number): string {
44
- const lines: string[] = [];
45
- /** One sample line: `name{label="value",…} value`. */
46
- const sample = (name: string, labels: [string, string][], value: number): string =>
47
- `${name}${labels.length > 0 ? `{${labels.map(([k, v]) => `${k}="${escapeLabel(v)}"`).join(",")}}` : ""} ${value}`;
48
- /** One gauge family: its `# HELP` and `# TYPE` lines, then a single sample. */
49
- const gauge = (name: string, help: string, value: number): void => {
50
- lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} gauge`, sample(name, [], value));
51
- };
52
-
53
- const t = summary.totals;
54
- gauge("arnative_cost_billed_total", "Provider-billed cost in USD across all sessions (totalFromProvider; estimates never mixed in).", t.cost);
55
- gauge("arnative_cost_estimated_total", "Catalog-estimated cost in USD from models.json rates; never billed.", t.estimatedCost);
56
- gauge("arnative_cost_today", "Provider-billed cost in USD in the current UTC day (the day buckets).", t.today?.cost ?? 0);
57
- gauge("arnative_cost_30d", "Provider-billed cost in USD over the last 30 UTC days (the day buckets).", t.last30d?.cost ?? 0);
58
- lines.push("# HELP arnative_tokens_total Token usage by provider, model and kind.", "# TYPE arnative_tokens_total gauge");
59
- for (const p of summary.providers) {
60
- for (const m of p.models) {
61
- for (const [kind, value] of [["input", m.input], ["output", m.output], ["cache_read", m.cacheRead], ["cache_write", m.cacheWrite]] as const) {
62
- const labels: [string, string][] = [
63
- ["provider", p.name],
64
- ["model", m.name],
65
- ["kind", kind],
66
- ];
67
- lines.push(sample("arnative_tokens_total", labels, value));
68
- }
69
- }
70
- }
71
- gauge("arnative_sessions_total", "Distinct Pi session files scanned.", t.sessions);
72
- gauge("arnative_usage_last_change_timestamp_seconds", "Unix time this process last saw the usage data change (not the last scrape).", now / 1000);
73
- return `${lines.join("\n")}\n`;
74
- }
75
-
76
- /** Write the exposition atomically: temp file + rename, so a collector never reads a half-written
77
- * file. A rename refused with `EPERM`/`EBUSY`/`EXDEV` (Windows: a running pi session holds the
78
- * target open) falls back to an in-place write and removes its temp file — the
79
- * `lib/preset-store.ts` pattern. */
80
- export function writePromFile(text: string, path: string, rename: (from: string, to: string) => void = renameSync): void {
81
- writeAtomicSync(path, text, rename);
82
- }
83
-
84
- let lastExportMs = 0;
85
- let lastExportText = "";
86
- let lastSummaryJson = "";
87
- let lastScanAt = 0;
88
-
89
- /**
90
- * One export attempt: throttled to one write per {@link EXPORT_THROTTLE_MS}, skipped when the
91
- * rendered text matches the last one written, disabled by `PI_ARNATIVE_EXPORT=0`, and never
92
- * throwing. Returns true when the file was written. `path` defaults to {@link promFilePath};
93
- * the self-check points it at a temp dir.
94
- */
95
- export function exportProm(now: number, path: string = promFilePath()): boolean {
96
- try {
97
- if (process.env[EXPORT_ENV] === "0") return false;
98
- if (now - lastExportMs < EXPORT_THROTTLE_MS) return false;
99
- // Force the scan: the memo can be up to 5s old, and the turn that just ended is exactly
100
- // the one this export is for. The stamp moves here, not after the write, so a skipped
101
- // write (unchanged text, unwritable folder) cannot force a scan on every later turn.
102
- lastExportMs = now;
103
- const summary = collectUsageSummary(true);
104
- // The scan timestamp only moves when the data does, so an idle session renders
105
- // byte-identical text and the diff below skips the write.
106
- const key = JSON.stringify(summary);
107
- if (key !== lastSummaryJson) {
108
- lastSummaryJson = key;
109
- lastScanAt = now;
110
- }
111
- const text = renderProm(summary, lastScanAt);
112
- if (text === lastExportText) return false;
113
- writePromFile(text, path);
114
- lastExportText = text;
115
- return true;
116
- } catch {
117
- // A failed export must not disturb the session.
118
- return false;
119
- }
120
- }
121
-
122
- export default function registerUsageExport(pi: ExtensionAPI): void {
123
- pi.on("turn_end", () => {
124
- exportProm(Date.now());
125
- });
126
- // The throttle must not swallow the last turns of a session: reset it and flush once, so a
127
- // quit does not leave the file reporting an hour-old total.
128
- pi.on("session_shutdown", () => {
129
- lastExportMs = 0;
130
- exportProm(Date.now());
131
- });
132
- }
133
-
134
- // Self-check: `node extensions/usage-export.ts`
135
- if (isMain(import.meta.url)) {
136
- const NL = String.fromCharCode(10);
137
-
138
- // ---- the renderer: pure, no agent dir involved ----
139
- const emptySummary: UsageSummary = {
140
- providers: [],
141
- projects: [],
142
- totals: { sessions: 0, msgs: 0, input: 0, output: 0, cacheRead: 0, totalTokens: 0, cost: 0, reportedCost: 0, estimatedCost: 0 },
143
- };
144
- const empty = renderProm(emptySummary, 1_700_000_000_000);
145
- assert(
146
- empty ===
147
- [
148
- "# HELP arnative_cost_billed_total Provider-billed cost in USD across all sessions (totalFromProvider; estimates never mixed in).",
149
- "# TYPE arnative_cost_billed_total gauge",
150
- "arnative_cost_billed_total 0",
151
- "# HELP arnative_cost_estimated_total Catalog-estimated cost in USD from models.json rates; never billed.",
152
- "# TYPE arnative_cost_estimated_total gauge",
153
- "arnative_cost_estimated_total 0",
154
- "# HELP arnative_cost_today Provider-billed cost in USD in the current UTC day (the day buckets).",
155
- "# TYPE arnative_cost_today gauge",
156
- "arnative_cost_today 0",
157
- "# HELP arnative_cost_30d Provider-billed cost in USD over the last 30 UTC days (the day buckets).",
158
- "# TYPE arnative_cost_30d gauge",
159
- "arnative_cost_30d 0",
160
- "# HELP arnative_tokens_total Token usage by provider, model and kind.",
161
- "# TYPE arnative_tokens_total gauge",
162
- "# HELP arnative_sessions_total Distinct Pi session files scanned.",
163
- "# TYPE arnative_sessions_total gauge",
164
- "arnative_sessions_total 0",
165
- "# HELP arnative_usage_last_change_timestamp_seconds Unix time this process last saw the usage data change (not the last scrape).",
166
- "# TYPE arnative_usage_last_change_timestamp_seconds gauge",
167
- "arnative_usage_last_change_timestamp_seconds 1700000000",
168
- ].join(NL) + NL,
169
- "an empty summary renders the pinned exposition, zeros included: " + JSON.stringify(empty),
170
- );
171
-
172
- const full: UsageSummary = {
173
- providers: [
174
- {
175
- name: 'pro"v\\x',
176
- sessions: 1,
177
- msgs: 1,
178
- input: 10,
179
- output: 5,
180
- cacheRead: 2,
181
- cacheWrite: 4,
182
- totalTokens: 15,
183
- cost: 0.02,
184
- estimatedCost: 0.01,
185
- models: [{ name: "m\n1", sessions: 1, msgs: 1, input: 10, output: 5, cacheRead: 2, cacheWrite: 4, totalTokens: 15, cost: 0.02, estimatedCost: 0.01 }],
186
- },
187
- ],
188
- projects: [],
189
- totals: {
190
- sessions: 1,
191
- msgs: 1,
192
- input: 10,
193
- output: 5,
194
- cacheRead: 2,
195
- totalTokens: 15,
196
- cost: 0.02,
197
- reportedCost: 0.02,
198
- estimatedCost: 0.01,
199
- today: { cost: 0.02, estimated: 0, input: 10, output: 5, cacheRead: 2 },
200
- last30d: { cost: 0.02, estimated: 0, input: 10, output: 5, cacheRead: 2 },
201
- },
202
- };
203
- const text = renderProm(full, 1_700_000_000_000);
204
- assert(text === renderProm(full, 1_700_000_000_000), "two renders of the same summary are byte-identical");
205
- for (const line of text.trimEnd().split(NL)) {
206
- if (line.startsWith("#")) continue;
207
- const m = /^([a-z_0-9]+)(\{[^}]*\})? (\S+)$/.exec(line);
208
- assert(m !== null && Number.isFinite(Number(m[3])), "a sample line parses as name{labels} value: " + JSON.stringify(line));
209
- }
210
- assert(text.includes('arnative_tokens_total{provider="pro\\"v\\\\x",model="m\\n1",kind="input"} 10'), "label values escape backslash, quote and newline: " + JSON.stringify(text));
211
- assert(text.includes('arnative_tokens_total{provider="pro\\"v\\\\x",model="m\\n1",kind="output"} 5'), "the output kind is labelled: " + text);
212
- assert(text.includes('arnative_tokens_total{provider="pro\\"v\\\\x",model="m\\n1",kind="cache_read"} 2'), "the cache_read kind is labelled: " + text);
213
- assert(text.includes("arnative_cost_billed_total 0.02\n"), "billed cost is its own metric: " + text);
214
- assert(text.includes("arnative_cost_estimated_total 0.01\n"), "the estimate is never folded into the billed _total: " + text);
215
- assert(text.includes("arnative_cost_today 0.02\n") && text.includes("arnative_cost_30d 0.02\n"), "the today/30d buckets render: " + text);
216
- assert(text.includes("arnative_sessions_total 1\n"), "the session count renders: " + text);
217
-
218
- // ---- the writer: pointed at a temp dir, never at the real agent dir ----
219
- const fixture = mkdtempSync(join(tmpdir(), "arnative-export-"));
220
- const prevDir = process.env.PI_CODING_AGENT_DIR;
221
- process.env.PI_CODING_AGENT_DIR = fixture;
222
- resetUsageCache();
223
- assert(promFilePath() === join(fixture, "arnative", "usage.prom"), "the default target is <agent dir>/arnative/usage.prom");
224
-
225
- mkdirSync(join(fixture, "sessions", "p"), { recursive: true });
226
- const sessionFile = join(fixture, "sessions", "p", "s.jsonl");
227
- const asst = (input: number, cost: number) =>
228
- JSON.stringify({
229
- message: { role: "assistant", provider: "google", model: "m1", timestamp: Date.now(), usage: { input, output: 5, cacheRead: 1, cacheWrite: 2, cost: { total: cost, totalFromProvider: true } } },
230
- });
231
- writeFileSync(sessionFile, asst(100, 0.5) + NL);
232
- const path = join(fixture, "usage.prom");
233
- // Epoch-scale `now` values, so the throttle (which starts at 0) lets the first call through.
234
- const T0 = 1_700_000_000_000;
235
-
236
- assert(exportProm(T0, path) === true, "the first export writes");
237
- const first = readFileSync(path, "utf8");
238
- assert(first.includes("arnative_cost_billed_total 0.5\n"), "the file carries the billed cost: " + first);
239
- assert(first.includes('arnative_tokens_total{provider="google",model="m1",kind="input"} 100\n'), "the file carries the token rows: " + first);
240
- assert(first.includes("arnative_usage_last_change_timestamp_seconds 1700000000\n"), "the scan timestamp is the export time in seconds: " + first);
241
- assert(exportProm(T0 + 2_000, path) === false, "throttled: no second write within 60s");
242
- assert(readFileSync(path, "utf8") === first, "the throttled attempt did not touch the file");
243
- assert(exportProm(T0 + 61_000, path) === false, "past the throttle but unchanged data: the diff skips the write");
244
- assert(readFileSync(path, "utf8") === first, "an idle session does not touch the file");
245
-
246
- writeFileSync(sessionFile, asst(50, 0.25) + NL, { flag: "a" });
247
- resetUsageCache();
248
- assert(exportProm(T0 + 122_000, path) === true, "changed data past the throttle writes again");
249
- const second = readFileSync(path, "utf8");
250
- assert(
251
- second.includes("arnative_cost_billed_total 0.75\n") && second.includes('kind="input"} 150\n') && second.includes("arnative_usage_last_change_timestamp_seconds 1700000122\n"),
252
- "the new spend, tokens and scan time land: " + second,
253
- );
254
-
255
- process.env[EXPORT_ENV] = "0";
256
- writeFileSync(sessionFile, asst(1, 0.125) + NL, { flag: "a" });
257
- resetUsageCache();
258
- assert(exportProm(T0 + 200_000, path) === false, `${EXPORT_ENV}=0 disables the export`);
259
- assert(readFileSync(path, "utf8") === second, "the disabled export did not touch the file");
260
- delete process.env[EXPORT_ENV];
261
- assert(exportProm(T0 + 261_000) === true, "re-enabled past the throttle, it writes to the default path");
262
- assert(existsSync(join(fixture, "arnative", "usage.prom")), "the default path is <agent dir>/arnative/usage.prom");
263
-
264
- writeFileSync(sessionFile, asst(1, 0.0625) + NL, { flag: "a" });
265
- resetUsageCache();
266
- writeFileSync(join(fixture, "blocked"), "not a directory", "utf8");
267
- assert(exportProm(T0 + 400_000, join(fixture, "blocked", "usage.prom")) === false, "an unwritable target is swallowed, not thrown");
268
-
269
- // Windows: a rename refused with EPERM falls back to an in-place write (the rename seam).
270
- const seamPath = join(fixture, "seam", "usage.prom");
271
- const locked = (): never => {
272
- throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
273
- };
274
- writePromFile("seamed\n", seamPath, locked);
275
- assert(readFileSync(seamPath, "utf8") === "seamed\n", "a refused rename still writes the file in place");
276
- assert(!existsSync(`${seamPath}.${process.pid}.tmp`), "no temp file is left behind after the fallback");
277
-
278
- rmSync(fixture, { recursive: true, force: true });
279
- if (prevDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
280
- else process.env.PI_CODING_AGENT_DIR = prevDir;
281
- resetUsageCache();
282
- console.log("usage-export.ts self-check OK");
283
- }