repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

perf: defer extension startup work

d909bc7639a580bfc243c806bbb9446636628427

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (28)

extensions/angel/index.ts

Modified
14 14 import * as fs from "node:fs/promises";
15 15 import * as path from "node:path";
16 16 import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai";
17 -import { complete } from "@earendil-works/pi-ai/compat";
18 17 import type {
19 18 ExtensionAPI,
20 19 ExtensionContext,
444 443 auth: { apiKey?: string; headers?: ProviderHeaders },
445 444 signal?: AbortSignal,
446 445 ): Promise<AngelResult> {
446 + const { complete } = await import("@earendil-works/pi-ai/compat");
447 447 const res = await complete(
448 448 binding.advisor,

extensions/cmprss/index.ts

Modified
537 537 export default function cmprssExtension(pi: ExtensionAPI) {
538 - let runtime = createRuntime(settingsFrom(), (event) =>
538 + let runtime = createRuntime(DEFAULT_CONFIG, (event) =>
539 539 pi.appendEntry(ENTRY_TYPE, event),

extensions/cost/__tests__/harness.test.ts

Modified
1 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
1 4 import { afterEach, describe, expect, it } from "vitest";
2 5 import { createTestSession, type TestSession } from "../../../test/harness";
3 6 import costExtension, { __test } from "../index.ts";
5 8 describe("cost pi-test-harness", () => {
6 9 let t: TestSession | undefined;
10 + let root: string | undefined;
8 12 afterEach(() => {
9 13 t?.dispose();
14 + if (root) rmSync(root, { recursive: true, force: true });
10 15 t = undefined;
16 + root = undefined;
13 19 it("loads in real Pi extension runtime", async () => {
16 22 expect(t.session.extensionRunner.extensions).toHaveLength(1);
25 + it("scans monthly session costs asynchronously", async () => {
26 + root = mkdtempSync(path.join(tmpdir(), "pi-cost-test-"));
27 + const sessionDir = path.join(root, "project");
28 + mkdirSync(sessionDir);
29 + const now = new Date();
30 + const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
31 + writeFileSync(
32 + path.join(sessionDir, `${month}-session.jsonl`),
33 + JSON.stringify({
34 + type: "message",
35 + message: {
36 + role: "assistant",
37 + usage: { cost: { total: 1.25 } },
38 + },
39 + }),
40 + "utf8",
41 + );
43 + await expect(__test.calculateMonthlyCost(sessionDir)).resolves.toBe(1.25);
44 + await expect(
45 + __test.calculateMonthlyCost(sessionDir, () => false),
46 + ).resolves.toBeUndefined();
47 + });
19 49 it("formats cached token usage compactly", () => {
20 50 expect(
21 51 __test.tokenLabel({

extensions/cost/index.ts

Modified
6 6 * - cost: turn/session/monthly spend when non-zero
9 -import { type Dirent, readdirSync, readFileSync } from "node:fs";
9 +import type { Dirent } from "node:fs";
10 +import { readdir, readFile } from "node:fs/promises";
10 11 import { dirname, join } from "node:path";
11 12 import type {
12 13 ExtensionAPI,
191 192 // ── Session file scan ─────────────────────────────────────────────────────
193 -function safeReadDir(path: string): Dirent[] {
194 +async function safeReadDir(path: string): Promise<Dirent[]> {
195 - return readdirSync(path, { withFileTypes: true });
196 + return await readdir(path, { withFileTypes: true });
196 197 } catch {
197 198 return [];
218 -function sessionFilesForMonth(sessionDir: string, month: string): string[] {
219 +async function sessionFilesForMonth(
220 + sessionDir: string,
221 + month: string,
222 + isCurrent: () => boolean,
223 +): Promise<string[] | undefined> {
219 224 const root = dirname(sessionDir);
220 225 const files: string[] = [];
222 - for (const entry of safeReadDir(root)) {
227 + for (const entry of await safeReadDir(root)) {
228 + if (!isCurrent()) return undefined;
223 229 if (entry.isFile() && isSessionFileForMonth(entry, month)) {
224 230 files.push(join(root, entry.name));
225 231 continue;
228 234 if (!entry.isDirectory()) continue;
229 235 const childDir = join(root, entry.name);
230 - for (const file of safeReadDir(childDir)) {
236 + for (const file of await safeReadDir(childDir)) {
237 + if (!isCurrent()) return undefined;
231 238 if (isSessionFileForMonth(file, month))
232 239 files.push(join(childDir, file.name));
236 243 return files;
239 -function sumFileCosts(filePath: string): number {
246 +async function sumFileCosts(filePath: string): Promise<number> {
241 248 return sumMessageCosts(
242 - parseSessionEntries(readFileSync(filePath, "utf-8")),
249 + parseSessionEntries(await readFile(filePath, "utf-8")),
244 251 } catch {
245 252 return 0;
249 -async function calculateMonthlyCost(sessionDir: string): Promise<number> {
256 +async function calculateMonthlyCost(
257 + sessionDir: string,
258 + isCurrent: () => boolean = () => true,
259 +): Promise<number | undefined> {
260 + const files = await sessionFilesForMonth(
261 + sessionDir,
262 + currentMonthKey(),
263 + isCurrent,
264 + );
265 + if (!files) return undefined;
250 266 let total = 0;
251 - for (const file of sessionFilesForMonth(sessionDir, currentMonthKey())) {
252 - total += sumFileCosts(file);
267 + for (const file of files) {
268 + if (!isCurrent()) return undefined;
269 + total += await sumFileCosts(file);
254 - return total;
271 + return isCurrent() ? total : undefined;
257 274 // ── Formatting ────────────────────────────────────────────────────────────
421 438 const sessionDir = ctx.sessionManager.getSessionDir();
422 439 setTimeout(() => {
423 440 void (async () => {
424 - const total = await calculateMonthlyCost(sessionDir);
425 - if (ticket !== generation) return;
441 + const total = await calculateMonthlyCost(
442 + sessionDir,
443 + () => ticket === generation,
444 + );
445 + if (total === undefined) return;
426 446 monthlyCost = total;
427 447 lastSignature = "";
428 448 await syncBestEffort(ctx);
452 -export const __test = { tokenLabel };
472 +export const __test = { calculateMonthlyCost, tokenLabel };

extensions/devil/index.ts

Modified
32 32 import { join } from "node:path";
33 33 import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
34 34 import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai";
35 -import { complete } from "@earendil-works/pi-ai/compat";
36 35 import type {
37 36 ExtensionAPI,
38 37 ExtensionContext,
741 740 roleTimeoutMs,
742 741 signal,
743 742 async (timeoutSignal) =>
744 - complete(
743 + (await import("@earendil-works/pi-ai/compat")).complete(
745 744 model,
747 746 systemPrompt: SYNTHESIS_SYSTEM_PROMPT,
933 932 // ── Extension entry ───────────────────────────────────────────────────
935 934 export default async function (pi: ExtensionAPI) {
936 - gcEphemeralForks();
937 935 const devilSettings = readDevilSettings();
938 936 const activeControllers = new Set<AbortController>();
937 + let garbageCollected = false;
940 939 // ── Flags ─────────────────────────────────────────────────────────
963 962 pi.registerCommand("devil", {
964 963 description: "Start an interactive devil's advocate debate",
965 964 handler: async (args, ctx) => {
965 + if (!garbageCollected) {
966 + gcEphemeralForks();
967 + garbageCollected = true;
966 969 const idea = args.trim();
967 970 if (!idea) {
968 971 ctx.ui?.notify("Usage: /devil <your idea>", "error");

extensions/fast/index.ts

Modified
48 48 return projectFast.enable ?? globalFast.enable ?? false;
51 +function isStaleContextError(error: unknown): boolean {
52 + return (
53 + error instanceof Error &&
54 + error.message.includes("ctx is stale after session replacement or reload")
55 + );
51 58 function hasFooter(): boolean {
52 59 const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
53 60 return footer?.loaded === true && (footer.version ?? 0) >= 1;
63 70 export default function fast(pi: ExtensionAPI): void {
64 - let enabled = readEnabled(process.cwd());
71 + let currentCwd = process.cwd();
72 + let enabled: boolean | undefined;
73 + let generation = 0;
66 - function refresh(cwd: string): void {
67 - enabled = readEnabled(cwd);
75 + function ensureEnabled(): boolean {
76 + if (enabled === undefined) enabled = readEnabled(currentCwd);
77 + return enabled;
70 80 function clear(ctx?: ExtensionContext): void {
75 85 function publish(ctx: ExtensionContext): void {
76 86 if (!ctx.hasUI) return;
77 - if (!fastActive(ctx, enabled)) {
87 + if (!fastActive(ctx, enabled ?? false)) {
78 88 clear(ctx);
79 89 return;
102 112 context: Context,
103 113 options?: SimpleStreamOptions,
105 - if (!enabled)
115 + if (!ensureEnabled())
106 116 return streamSimpleOpenAICodexResponses(
107 117 model as Model<typeof API>,
108 118 context,
126 - pi.on("session_start", (_event, ctx) => {
127 - refresh(ctx.cwd);
128 - publish(ctx);
136 + function scheduleRefresh(ctx: ExtensionContext): void {
137 + const ticket = ++generation;
138 + currentCwd = ctx.cwd;
139 + enabled = undefined;
140 + const timer = setTimeout(() => {
141 + if (ticket !== generation) return;
142 + ensureEnabled();
143 + try {
144 + publish(ctx);
145 + } catch (error) {
146 + if (!isStaleContextError(error)) throw error;
148 + }, 0);
149 + timer.unref?.();
152 + pi.on("session_start", (_event, ctx) => scheduleRefresh(ctx));
153 + pi.on("model_select", (_event, ctx) => scheduleRefresh(ctx));
154 + pi.on("session_shutdown", (_event, ctx) => {
155 + generation++;
156 + enabled = undefined;
157 + clear(ctx);
130 - pi.on("model_select", (_event, ctx) => {
131 - refresh(ctx.cwd);
132 - publish(ctx);
133 - });
134 - pi.on("session_shutdown", (_event, ctx) => clear(ctx));
137 161 export const _test = { fastActive, parseFastSettings };

extensions/goal/index.ts

Modified
1 1 import { StringEnum } from "@earendil-works/pi-ai";
2 -import { complete as piComplete } from "@earendil-works/pi-ai/compat";
3 2 import {
4 3 createAgentSession,
5 4 DefaultResourceLoader,
19 18 } from "@earendil-works/pi-tui";
20 19 import { Type } from "typebox";
22 -type JudgeComplete = typeof piComplete;
21 +type JudgeComplete = typeof import("@earendil-works/pi-ai/compat").complete;
22 +const defaultJudgeComplete: JudgeComplete = async (...args) =>
23 + (await import("@earendil-works/pi-ai/compat")).complete(...args);
23 24 const JUDGE_COMPLETE_FOR_TEST = Symbol.for(
24 25 "@bugabinga/pi-ext-goal/completeJudge",
33 34 function judgeComplete(): JudgeComplete {
34 - return (globalThis as GoalTestGlobals)[JUDGE_COMPLETE_FOR_TEST] ?? piComplete;
35 + return (
36 + (globalThis as GoalTestGlobals)[JUDGE_COMPLETE_FOR_TEST] ??
37 + defaultJudgeComplete
38 + );
37 41 type GoalStatus = "active" | "paused" | "complete" | "blocked";
2695 2699 let piRetryDeferrals = 0;
2696 2700 let removeTerminalInput: (() => void) | undefined;
2701 + let generation = 0;
2697 2702 let promptTemplates: GoalPromptTemplate[] = [];
2703 + let promptTemplatesLoad:
2704 + | { generation: number; promise: Promise<GoalPromptTemplate[]> }
2705 + | undefined;
2698 2706 let probe: ProbeState | undefined;
2699 2707 let lastTurnEvidence: TurnEvidence | undefined;
2700 2708 let liveUiInterval: ReturnType<typeof setInterval> | undefined;
2735 2743 const syncUpdateGoalTool = () =>
2736 2744 setToolActive(pi, "update_goal", canUseUpdateGoal(state));
2745 + const ensurePromptTemplates = (
2746 + ctx: ExtensionContext,
2747 + ): Promise<GoalPromptTemplate[]> => {
2748 + if (promptTemplatesLoad?.generation !== generation) {
2749 + const ticket = generation;
2750 + const promise = loadGoalPromptTemplates(ctx)
2751 + .then((templates) => {
2752 + if (ticket === generation) promptTemplates = templates;
2753 + return ticket === generation ? templates : [];
2754 + })
2755 + .catch((error) => {
2756 + if (ticket === generation)
2757 + console.error("goal prompt template load failed:", error);
2758 + return [];
2759 + });
2760 + promptTemplatesLoad = { generation: ticket, promise };
2762 + return promptTemplatesLoad.promise;
2763 + };
2738 2765 pi.registerShortcut("alt+g", {
2739 2766 description: "Toggle /goal widget compact/expanded",
2748 - pi.on("session_start", async (_event, ctx) => {
2749 - promptTemplates = await loadGoalPromptTemplates(ctx);
2775 + pi.on("session_start", (_event, ctx) => {
2776 + generation++;
2777 + promptTemplates = [];
2778 + promptTemplatesLoad = undefined;
2779 + void ensurePromptTemplates(ctx);
2750 2780 state = latestGoalState(ctx);
2751 2781 if (state && state.status === "active") ensureDossier(pi, ctx, state);
2752 2782 continuation.queued = false;
2864 2894 pi.on("session_shutdown", (_event, ctx) => {
2895 + generation++;
2896 + promptTemplatesLoad = undefined;
2865 2897 stopLiveUiTicker();
2866 2898 continuation.queued = false;
2867 2899 continuation.scheduled = false;

extensions/model-info/index.ts

Modified
83 83 export default function modelInfoExtension(pi: ExtensionAPI): void {
84 84 function refresh(ctx: ExtensionContext, thinking?: string): void {
85 85 if (!ctx.hasUI) return;
86 - publish(pi, ctx, thinking);
86 + publish(pi, ctx, thinking ?? ctx.thinkingLevel);
89 89 pi.on("session_start", (_event, ctx) => refresh(ctx));

extensions/pulse/index.ts

Modified
5 5 * Pulse - Living documentation sync
7 7 * Run /pulse help for usage.
10 -import { execFile, execFileSync } from "node:child_process";
10 +import { execFile } from "node:child_process";
11 11 import { createHash } from "node:crypto";
12 12 import * as fs from "node:fs";
13 13 import * as path from "node:path";
678 678 const execFileAsync = promisify(execFile);
680 -function gitFingerprint(cwd: string): string | null {
681 - try {
682 - return execFileSync(
683 - "git",
684 - ["status", "--porcelain=v1", "-z", "--untracked-files=all"],
686 - cwd,
687 - encoding: "utf-8",
688 - stdio: ["ignore", "pipe", "ignore"],
689 - },
690 - );
691 - } catch {
692 - return null;
696 -async function gitFingerprintAsync(
680 +async function gitFingerprint(
697 681 cwd: string,
698 682 signal: AbortSignal,
699 683 ): Promise<string | null> {
798 782 // Dirty state
799 783 // ------------------------------------------------------------------------
801 - function markWorkspaceDirty(fingerprint = gitFingerprint(state.cwd)): void {
802 - state.workspaceDirty = true;
803 - state.lastMutationAt = Date.now();
804 - state.lastGitFingerprint = fingerprint;
785 + async function readGitFingerprint(
786 + cwd: string,
787 + ticket: number,
788 + ): Promise<string | null | undefined> {
789 + fingerprintAbort?.abort();
790 + const abort = new AbortController();
791 + fingerprintAbort = abort;
792 + const fingerprint = await gitFingerprint(cwd, abort.signal);
793 + if (fingerprintAbort === abort) fingerprintAbort = undefined;
794 + if (ticket !== generation || abort.signal.aborted) return undefined;
795 + return fingerprint;
807 - function reconcileMaybeDirty(): void {
808 - if (!state.maybeWorkspaceDirty) return;
798 + function markWorkspaceDirty(): void {
799 + state.workspaceDirty = true;
800 + state.lastMutationAt = Date.now();
803 + async function reconcileMaybeDirty(ticket: number): Promise<boolean> {
804 + if (!state.maybeWorkspaceDirty) return ticket === generation;
809 805 state.maybeWorkspaceDirty = false;
810 - const next = gitFingerprint(state.cwd);
811 - if (next === null || next !== state.lastGitFingerprint) {
812 - markWorkspaceDirty(next);
813 - return;
806 + const next = await readGitFingerprint(state.cwd, ticket);
807 + if (next === undefined) return false;
808 + if (next === null || next !== state.lastGitFingerprint)
809 + markWorkspaceDirty();
815 810 state.lastGitFingerprint = next;
811 + return true;
818 814 // ------------------------------------------------------------------------
1023 - state.lastGitFingerprint = gitFingerprint(runCwd);
1019 + const fingerprint = await readGitFingerprint(runCwd, ticket);
1020 + if (fingerprint === undefined) return;
1021 + state.lastGitFingerprint = fingerprint;
1024 1022 state.lastUpdateTime = Date.now();
1025 1023 state.lastRunAt = state.lastUpdateTime;
1026 1024 if (!failed) {
1097 - reconcileMaybeDirty();
1095 + if (!(await reconcileMaybeDirty(ticket))) return;
1098 1096 const now = Date.now();
1099 1097 const dirtyReady =
1100 1098 state.workspaceDirty &&
1606 1604 state.lastMutationAt = 0;
1607 1605 state.lastGitFingerprint = null;
1608 1606 setTimeout(() => {
1609 - if (ticket !== generation) return;
1610 - fingerprintAbort?.abort();
1611 - const abort = new AbortController();
1612 - fingerprintAbort = abort;
1613 - void gitFingerprintAsync(state.cwd, abort.signal).then((fingerprint) => {
1614 - if (ticket !== generation || abort.signal.aborted) return;
1615 - state.lastGitFingerprint = fingerprint;
1607 + if (
1608 + ticket !== generation ||
1609 + state.workspaceDirty ||
1610 + state.maybeWorkspaceDirty ||
1611 + state.isChecking
1613 + return;
1614 + void readGitFingerprint(state.cwd, ticket).then((fingerprint) => {
1615 + if (fingerprint !== undefined) state.lastGitFingerprint = fingerprint;
1618 1618 state.isPaused = false;

extensions/rtk/__tests__/rtk.test.ts

Modified
121 121 expect(fx.notes).toEqual([]);
124 - test("starts the availability probe after session_start returns", async () => {
124 + test("defers the availability probe until the first bash call", async () => {
125 125 const fx = fakePi(async () => ({ code: 127, stdout: "" }));
126 126 rtkExtension(fx.pi as never);
127 127 const result = fx.handlers.session_start?.[0]?.({}, fx.ctx);
128 128 expect(result).toBeUndefined();
129 + await new Promise((resolve) => setTimeout(resolve, 0));
129 130 expect(fx.pi.exec).not.toHaveBeenCalled();
130 - await vi.waitFor(() => expect(fx.pi.exec).toHaveBeenCalled());
131 + expect(await emit(fx as never, "ps aux")).toBe("ps aux");
131 132 expect(fx.notes).toEqual([["rtk disabled: not found on PATH", "warning"]]);

extensions/rtk/index.ts

Modified
289 289 return support;
292 - pi.on("session_start", (_event, ctx) => {
293 - const ticket = ++generation;
292 + pi.on("session_start", () => {
293 + generation++;
294 294 announced = false;
295 295 initialization = undefined;
296 - const timer = setTimeout(() => {
297 - if (ticket === generation)
298 - void ensureInitialized(ctx).catch((error) =>
299 - console.error("rtk initialization failed:", error),
300 - );
301 - }, 0);
302 - timer.unref?.();
304 297 pi.on("session_shutdown", () => {
305 298 generation++;

extensions/runtime/index.ts

Modified
178 178 name: "nodejs",
179 179 icon: "",
180 180 files: RUNTIME_FILES.nodejs,
181 - version: () => exactVersion("node", ["--version"]),
181 + version: () => Promise.resolve(process.version),
184 184 name: "python",

extensions/session-rename/index.ts

Modified
8 8 * - Names are 1–3 words.
11 -import { completeSimple } from "@earendil-works/pi-ai/compat";
12 11 import type {
13 12 ExtensionAPI,
14 13 ExtensionContext,
28 27 summary?: string;
29 28 message?: { role?: string; content?: unknown; toolName?: string };
31 -type Model = Parameters<typeof completeSimple>[0];
30 +type CompleteSimple =
31 + typeof import("@earendil-works/pi-ai/compat").completeSimple;
32 +type Model = Parameters<CompleteSimple>[0];
32 33 type RenameReason = "load" | "turn" | "manual";
34 35 type MarkerData = {
336 337 transcript +
337 338 "\n</session>";
340 + const { completeSimple } = await import("@earendil-works/pi-ai/compat");
339 341 const response = await completeSimple(
340 342 model,

extensions/split-fork/__tests__/harness.test.ts

Modified
1 +import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
1 4 import { afterEach, describe, expect, it } from "vitest";
2 5 import { createTestSession, type TestSession } from "../../../test/harness";
3 6 import splitForkExtension, { __test } from "../index";
5 8 let t: TestSession | undefined;
9 +let fakeBin: string | undefined;
7 11 afterEach(() => {
8 12 t?.dispose();
13 + if (fakeBin) rmSync(fakeBin, { recursive: true, force: true });
9 14 t = undefined;
15 + fakeBin = undefined;
12 18 describe("split-fork extension", () => {
16 22 expect(t.session.extensionRunner.extensions).toHaveLength(1);
25 + it("finds osascript through native PATH access", () => {
26 + fakeBin = mkdtempSync(path.join(tmpdir(), "pi-split-fork-bin-"));
27 + copyFileSync(process.execPath, path.join(fakeBin, "osascript"));
29 + expect(__test.hasOsascript({ Path: fakeBin })).toBe(true);
30 + expect(__test.hasOsascript({ PATH: path.join(fakeBin, "missing") })).toBe(
31 + false,
32 + );
33 + });
19 35 it("shell quotes prompt-safe command parts", () => {
20 36 expect(__test.shellQuote("can't")).toBe("'can'\"'\"'t'");
21 37 expect(__test.shellQuote("")).toBe("''");

extensions/split-fork/index.ts

Modified
1 -import { spawnSync } from "node:child_process";
2 1 import { randomUUID } from "node:crypto";
3 -import { existsSync, promises as fs } from "node:fs";
2 +import { accessSync, constants, existsSync, promises as fs } from "node:fs";
4 3 import path from "node:path";
5 4 import type {
6 5 ExtensionAPI,
55 54 return `${commandParts.map(shellQuote).join(" ")}\n`;
58 -function hasOsascript(): boolean {
59 - const result = spawnSync("osascript", ["-e", "return 1"], {
60 - stdio: "ignore",
61 - });
62 - return !result.error && result.status === 0;
57 +function hasOsascript(env = process.env): boolean {
58 + const pathKey = Object.keys(env).find((key) => key.toLowerCase() === "path");
59 + for (const directory of (pathKey ? env[pathKey] : "")?.split(
60 + path.delimiter,
61 + ) ?? []) {
62 + try {
63 + accessSync(
64 + path.join(directory.replace(/^"|"$/gu, ""), "osascript"),
65 + constants.X_OK,
66 + );
67 + return true;
68 + } catch {}
69 + }
70 + return false;
65 73 async function createForkedSession(
95 103 return newSessionFile;
98 -export const __test = { buildPiStartupInput, shellQuote };
106 +export const __test = { buildPiStartupInput, hasOsascript, shellQuote };
100 108 export default function splitForkExtension(pi: ExtensionAPI) {
101 109 pi.on("session_start", (_event, ctx) => {

extensions/the-system/index.ts

Modified
3 3 import {
4 4 type ExtensionAPI,
5 5 type ExtensionContext,
6 6 isToolCallEventType,
7 7 } from "@earendil-works/pi-coding-agent";
8 -import { createMockupTool } from "./mockup.js";
8 +import { createMockupTool } from "./mockup-tool.js";
9 9 import { systemArgumentCompletions } from "./system-command-meta.js";
11 11 function isStaleContextError(error: unknown): boolean {
47 47 notified = false;
49 49 pi.on("before_agent_start", async (event, ctx) => {
50 - await notifyOnce(ctx, generation);
50 + void notifyOnce(ctx, generation).catch((error) =>
51 + console.error("The System startup check failed:", error),
52 + );
51 53 const { composeSystemPrompt } = await import("./system.js");
52 54 return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };

extensions/the-system/mockup-tool.ts

Added
new file mode 100644
1 +import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
2 +import { Text } from "@earendil-works/pi-tui";
3 +import { Type } from "typebox";
4 +import type { MockupResult } from "./mockup.js";
6 +const DESCRIPTION =
7 + "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.";
9 +const parameters = Type.Object({
10 + title: Type.String({
11 + description: "Short browser page title for this visual decision.",
12 + }),
13 + question: Type.String({
14 + description: "The exact visual question the human should answer.",
15 + }),
16 + options: Type.Array(
17 + Type.Object({
18 + id: Type.String({
19 + description:
20 + "Stable option id. Letters, numbers, dot, underscore, dash only.",
21 + }),
22 + label: Type.String({ description: "Human-visible option label." }),
23 + description: Type.Optional(
24 + Type.String({
25 + description: "One short sentence explaining the option.",
26 + }),
27 + ),
28 + html: Type.String({
29 + description:
30 + "HTML fragment for this mockup option. Do not include <!doctype>, <html>, <head>, or <body>. Scripts are allowed.",
31 + }),
32 + }),
33 + {
34 + minItems: 1,
35 + maxItems: 4,
36 + description:
37 + "One to four mockup options. One option is valid for reviewing a single screen.",
38 + },
39 + ),
40 + multi: Type.Optional(
41 + Type.Boolean({
42 + default: false,
43 + description: "Allow selecting multiple options.",
44 + }),
45 + ),
46 +});
48 +export function createMockupTool() {
49 + return defineTool({
50 + name: "mockup",
51 + label: "Mockup",
52 + description: DESCRIPTION,
53 + promptSnippet: DESCRIPTION,
54 + promptGuidelines: [
55 + "Use mockup for visual UI/layout/style choices when seeing options beats reading descriptions.",
56 + "Pass only HTML fragments in options[].html; never pass <!doctype>, <html>, <head>, or <body>.",
57 + "Create 1-4 options. One option is valid for review of a single screen.",
58 + "The tool owns browser communication, selection, notes, annotations, Accept, and Iterate. Do not ask the user to repeat browser feedback in chat.",
59 + "After an iterate result, revise the fragments and call mockup again. After accept, continue the design unless notes require another iteration.",
60 + ],
61 + parameters,
62 + renderCall(args, theme, context) {
63 + const title = theme.fg("toolTitle", theme.bold("mockup"));
64 + const optionCount = Array.isArray(args.options) ? args.options.length : 0;
65 + const lines = [
66 + title,
67 + theme.fg(
68 + "dim",
69 + `${args.title ?? "untitled"} · ${optionCount} option${optionCount === 1 ? "" : "s"}`,
70 + ),
71 + ];
72 + if (context.expanded && Array.isArray(args.options)) {
73 + for (const option of args.options)
74 + lines.push(theme.fg("muted", `- ${String(option.id)}`));
75 + } else {
76 + lines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
77 + }
78 + return new Text(lines.join("\n"), 0, 0);
79 + },
80 + renderResult(result, context, theme) {
81 + const details = result.details as Partial<MockupResult> | undefined;
82 + if (!details) return new Text("", 0, 0);
83 + const annotations = details.annotations ?? [];
84 + const summary = `${details.action ?? "submitted"} · ${(details.selected ?? []).join(", ") || "none"} · ${annotations.length} annotation${annotations.length === 1 ? "" : "s"}`;
85 + if (!context.expanded) return new Text(theme.fg("dim", summary), 0, 0);
86 + return new Text(
87 + [
88 + theme.fg("dim", summary),
89 + details.notes ? `notes: ${details.notes}` : "notes: ",
90 + ].join("\n"),
91 + 0,
92 + );
93 + },
94 + async execute(_toolCallId, params, signal, _onUpdate, ctx) {
95 + return (await import("./mockup.js")).executeMockup(params, signal, ctx);
96 + },
97 + });

extensions/the-system/mockup.ts

Modified
6 6 type Server,
7 7 type ServerResponse,
8 8 } from "node:http";
9 -import {
10 - defineTool,
11 - keyHint,
12 - type ToolDefinition,
13 -} from "@earendil-works/pi-coding-agent";
14 -import { Text } from "@earendil-works/pi-tui";
15 -import { Type } from "typebox";
17 10 export type MockupOption = {
18 11 id: string;
48 41 const DEFAULT_TIMEOUT_MS = 3_600_000;
49 42 const ID_RE = /^[a-zA-Z0-9._-]+$/;
51 -export const MOCKUP_DESCRIPTION =
52 - "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.";
54 44 export function MOCKUP_FULL_DOCUMENT_ERROR(path: string): string {
55 45 return `${path} must be an HTML fragment, not a full document. Remove <!doctype>, <html>, <head>, <body>; keep only content for the card.`;
58 -export function createMockupTool(): ToolDefinition {
59 - return defineTool({
60 - name: "mockup",
61 - label: "Mockup",
62 - description: MOCKUP_DESCRIPTION,
63 - promptSnippet: MOCKUP_DESCRIPTION,
64 - promptGuidelines: [
65 - "Use mockup for visual UI/layout/style choices when seeing options beats reading descriptions.",
66 - "Pass only HTML fragments in options[].html; never pass <!doctype>, <html>, <head>, or <body>.",
67 - "Create 1-4 options. One option is valid for review of a single screen.",
68 - "The tool owns browser communication, selection, notes, annotations, Accept, and Iterate. Do not ask the user to repeat browser feedback in chat.",
69 - "After an iterate result, revise the fragments and call mockup again. After accept, continue the design unless notes require another iteration.",
70 - ],
71 - parameters: mockupParameters,
72 - renderCall(args, theme, context) {
73 - const title = theme.fg("toolTitle", theme.bold("mockup"));
74 - const optionCount = Array.isArray(args.options) ? args.options.length : 0;
75 - const lines = [
76 - title,
77 - theme.fg(
78 - "dim",
79 - `${args.title ?? "untitled"} · ${optionCount} option${optionCount === 1 ? "" : "s"}`,
80 - ),
81 - ];
82 - if (context.expanded && Array.isArray(args.options)) {
83 - for (const option of args.options) {
84 - if (option && typeof option === "object" && "id" in option) {
85 - lines.push(theme.fg("muted", `- ${String(option.id)}`));
86 - }
87 - }
88 - } else {
89 - lines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
90 - }
91 - return new Text(lines.join("\n"), 0, 0);
92 - },
93 - renderResult(result, context, theme) {
94 - const details = result.details as Partial<MockupResult> | undefined;
95 - if (!details) return new Text("", 0, 0);
96 - const summary = `${details.action ?? "submitted"} · ${(details.selected ?? []).join(", ") || "none"} · ${(details.annotations ?? []).length} annotation${(details.annotations ?? []).length === 1 ? "" : "s"}`;
97 - if (!context.expanded) return new Text(theme.fg("dim", summary), 0, 0);
98 - return new Text(
99 - [
100 - theme.fg("dim", summary),
101 - details.notes ? `notes: ${details.notes}` : "notes: ",
102 - ].join("\n"),
103 - 0,
104 - );
105 - },
106 - async execute(_toolCallId, params, signal, _onUpdate, ctx) {
107 - const request = validateMockupRequest(params);
108 - const server = await startMockupServer(request, {
109 - openBrowser: process.env.PI_MOCKUP_NO_OPEN !== "1",
110 - });
111 - if (ctx.hasUI) {
112 - ctx.ui.notify(`Mockup open: ${server.url}`, "info");
113 - }
114 - try {
115 - const result = await abortable(server.result, signal, () =>
116 - server.close("aborted"),
117 - );
118 - return {
119 - content: [
120 - {
121 - type: "text" as const,
122 - text: JSON.stringify(result),
123 - },
124 - ],
125 - details: result,
126 - };
127 - } finally {
128 - server.close("done");
129 - }
130 - },
48 +export async function executeMockup(
49 + params: unknown,
50 + signal: AbortSignal | undefined,
51 + ctx: { hasUI: boolean; ui: { notify(message: string, level: "info"): void } },
52 +) {
53 + const request = validateMockupRequest(params);
54 + const server = await startMockupServer(request, {
55 + openBrowser: process.env.PI_MOCKUP_NO_OPEN !== "1",
57 + if (ctx.hasUI) ctx.ui.notify(`Mockup open: ${server.url}`, "info");
58 + try {
59 + const result = await abortable(server.result, signal, () =>
60 + server.close("aborted"),
61 + );
62 + return {
63 + content: [{ type: "text" as const, text: JSON.stringify(result) }],
64 + details: result,
65 + };
66 + } finally {
67 + server.close("done");
68 + }
134 71 export function validateMockupRequest(value: unknown): MockupRequest {
568 505 return JSON.stringify(value).replaceAll("<", "\\u003c");
571 -const mockupParameters = Type.Object({
572 - title: Type.String({
573 - description: "Short browser page title for this visual decision.",
574 - }),
575 - question: Type.String({
576 - description: "The exact visual question the human should answer.",
577 - }),
578 - options: Type.Array(
579 - Type.Object({
580 - id: Type.String({
581 - description:
582 - "Stable option id. Letters, numbers, dot, underscore, dash only.",
583 - }),
584 - label: Type.String({ description: "Human-visible option label." }),
585 - description: Type.Optional(
586 - Type.String({
587 - description: "One short sentence explaining the option.",
588 - }),
589 - ),
590 - html: Type.String({
591 - description:
592 - "HTML fragment for this mockup option. Do not include <!doctype>, <html>, <head>, or <body>. Scripts are allowed.",
593 - }),
594 - }),
595 - {
596 - minItems: 1,
597 - maxItems: 4,
598 - description:
599 - "One to four mockup options. One option is valid for reviewing a single screen.",
600 - },
601 - ),
602 - multi: Type.Optional(
603 - Type.Boolean({
604 - default: false,
605 - description: "Allow selecting multiple options.",
606 - }),
607 - ),
608 -});
610 508 const FRAME_CSS = String.raw`
611 509 :root { color-scheme: dark light; --bg:#101010; --panel:#181818; --text:#ededed; --muted:#9a9a9a; --line:#ededed; --soft:#2a2a2a; --accent:#d86dd8; --bad:#ff6b6b; font:14px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
612 510 @media (prefers-color-scheme: light) { :root { --bg:#f4f0f4; --panel:#fff; --text:#151515; --muted:#666; --line:#151515; --soft:#e4dfe4; --accent:#a900a9; } }

extensions/tldr/index.ts

Modified
3 3 import type {
4 4 Model,
5 5 ProviderHeaders,
6 6 UserMessage,
7 7 } from "@earendil-works/pi-ai";
8 -import { complete } from "@earendil-works/pi-ai/compat";
9 8 import {
10 9 type ExtensionAPI,
11 10 type ExtensionContext,
19 18 clearTimeout(handle: unknown): void;
22 -type GenerateTldr = typeof complete;
21 +type GenerateTldr = typeof import("@earendil-works/pi-ai/compat").complete;
23 +const generateTldr: GenerateTldr = async (...args) =>
24 + (await import("@earendil-works/pi-ai/compat")).complete(...args);
24 26 type TldrPriority = "immediate" | "normal" | "final";
460 462 constructor(options: TldrEngineOptions) {
461 463 this.facts = options.facts;
462 - this.generate = options.generate ?? complete;
464 + this.generate = options.generate ?? generateTldr;
463 465 this.scheduler = options.scheduler ?? defaultScheduler;
464 466 this.configuredModelRef = options.configuredModelRef;

extensions/usage/__tests__/harness.test.ts

Modified
16 16 expect(t.session.extensionRunner.extensions).toHaveLength(1);
19 + it("loads the dashboard implementation on first command use", async () => {
20 + t = await createTestSession({ extensionFactories: [usageExtension] });
21 + const command =
22 + t.session.extensionRunner.extensions[0].commands.get("usage");
24 + await expect(command.handler("", { hasUI: false } as never)).resolves.toBe(
25 + undefined,
26 + );
27 + });

extensions/usage/implementation.ts

Added
new file mode 100644
1 +/**
2 + * /usage — Usage statistics dashboard
3 + *
4 + * Aggregated usage across all sessions parsed from local JSONL files.
5 + * Tab cycles: Today → This Week → Last Week → All Time.
6 + * Toggle insights view with 'v' for cost optimization tips.
7 + *
8 + * Based on tmustier/pi-extensions (usage-extension).
9 + * MIT License — https://github.com/tmustier/pi-extensions
10 + */
12 +import { readdir, readFile } from "node:fs/promises";
13 +import { dirname, join } from "node:path";
14 +import type {
15 + ExtensionCommandContext,
16 + Theme,
17 +} from "@earendil-works/pi-coding-agent";
18 +import { DynamicBorder } from "@earendil-works/pi-coding-agent";
19 +import {
20 + CancellableLoader,
21 + Container,
22 + matchesKey,
23 + Spacer,
24 + truncateToWidth,
25 + visibleWidth,
26 + wrapTextWithAnsi,
27 +} from "@earendil-works/pi-tui";
29 +// ── Types ──────────────────────────────────────────────────────────────────
31 +interface TokenStats {
32 + total: number;
33 + input: number;
34 + output: number;
35 + cacheRead: number;
36 + cacheWrite: number;
38 +interface BaseStats {
39 + messages: number;
40 + cost: number;
41 + tokens: TokenStats;
43 +interface ModelStats extends BaseStats {
44 + sessions: Set<string>;
46 +interface ProviderStats extends BaseStats {
47 + sessions: Set<string>;
48 + models: Map<string, ModelStats>;
50 +interface TotalStats extends BaseStats {
51 + sessions: number;
53 +interface Insight {
54 + percent: number;
55 + headline: string;
56 + advice: string;
58 +interface PeriodInsights {
59 + insights: Insight[];
61 +interface RawMessage {
62 + sessionId: string;
63 + timestamp: number;
64 + cost: number;
65 + input: number;
66 + cacheRead: number;
67 + cacheWrite: number;
70 +interface ParsedMessage {
71 + provider: string;
72 + model: string;
73 + cost: number;
74 + input: number;
75 + output: number;
76 + cacheRead: number;
77 + cacheWrite: number;
78 + timestamp: number;
81 +interface ParsedSession {
82 + sessionId: string;
83 + messages: ParsedMessage[];
85 +interface PeriodRawData {
86 + messages: RawMessage[];
87 + sessionCosts: Map<string, number>;
89 +interface GlobalSessionSpan {
90 + startMs: number;
91 + endMs: number;
93 +interface TimeFilteredStats {
94 + providers: Map<string, ProviderStats>;
95 + totals: TotalStats;
96 + insights: PeriodInsights;
98 +interface UsageData {
99 + today: TimeFilteredStats;
100 + thisWeek: TimeFilteredStats;
101 + lastWeek: TimeFilteredStats;
102 + allTime: TimeFilteredStats;
104 +type TabName = "today" | "thisWeek" | "lastWeek" | "allTime";
105 +type ViewMode = "table" | "insights";
107 +// ── Column config ──────────────────────────────────────────────────────────
109 +interface DataColumn {
110 + label: string;
111 + width: number;
112 + dimmed?: boolean;
113 + getValue: (stats: BaseStats & { sessions: Set<string> | number }) => string;
116 +const SESSIONS_COL: DataColumn = {
117 + label: "Sessions",
118 + width: 9,
119 + getValue: (s) =>
120 + formatNumber(typeof s.sessions === "number" ? s.sessions : s.sessions.size),
122 +const MSGS_COL: DataColumn = {
123 + label: "Msgs",
124 + width: 9,
125 + getValue: (s) => formatNumber(s.messages),
127 +const COST_COL: DataColumn = {
128 + label: "Cost",
129 + width: 9,
130 + getValue: (s) => formatCost(s.cost),
132 +const TOKENS_COL: DataColumn = {
133 + label: "Tokens",
134 + width: 9,
135 + getValue: (s) => formatTokens(s.tokens.total),
137 +const INPUT_COL: DataColumn = {
138 + label: "↑In",
139 + width: 8,
140 + dimmed: true,
141 + getValue: (s) => formatTokens(s.tokens.input + s.tokens.cacheWrite),
143 +const OUTPUT_COL: DataColumn = {
144 + label: "↓Out",
145 + width: 8,
146 + dimmed: true,
147 + getValue: (s) => formatTokens(s.tokens.output),
149 +const CACHE_COL: DataColumn = {
150 + label: "Cache",
151 + width: 8,
152 + dimmed: true,
153 + getValue: (s) => formatTokens(s.tokens.cacheRead + s.tokens.cacheWrite),
156 +const FULL_COLS: DataColumn[] = [
157 + SESSIONS_COL,
158 + MSGS_COL,
159 + COST_COL,
160 + TOKENS_COL,
161 + INPUT_COL,
162 + OUTPUT_COL,
163 + CACHE_COL,
166 +interface TableLayout {
167 + columns: DataColumn[];
168 + nameWidth: number;
169 + tableWidth: number;
170 + compact: boolean;
172 +const MAX_NAME_WIDTH = 26;
174 +function getTableLayout(width: number): TableLayout {
175 + const layouts: Array<{
176 + columns: DataColumn[];
177 + minName: number;
178 + compact?: boolean;
179 + }> = [
180 + { columns: FULL_COLS, minName: MAX_NAME_WIDTH },
182 + columns: [SESSIONS_COL, MSGS_COL, COST_COL, TOKENS_COL],
183 + minName: 14,
184 + compact: true,
185 + },
187 + columns: [SESSIONS_COL, COST_COL, TOKENS_COL],
188 + minName: 12,
189 + compact: true,
190 + },
191 + { columns: [COST_COL, TOKENS_COL], minName: 10, compact: true },
192 + { columns: [COST_COL], minName: 8, compact: true },
193 + ];
194 + for (const c of layouts) {
195 + const colsWidth = c.columns.reduce((s, col) => s + col.width, 0);
196 + const nameWidth = Math.min(MAX_NAME_WIDTH, Math.max(width - colsWidth, 0));
197 + if (nameWidth >= c.minName)
198 + return {
199 + columns: c.columns,
200 + nameWidth,
201 + tableWidth: nameWidth + colsWidth,
202 + compact: !!c.compact,
203 + };
205 + const fallback = layouts.at(-1);
206 + if (!fallback) throw new Error("usage layouts must not be empty");
207 + const fw = fallback.columns.reduce((s, col) => s + col.width, 0);
208 + return {
209 + columns: fallback.columns,
210 + nameWidth: Math.min(MAX_NAME_WIDTH, Math.max(width - fw, 0)),
211 + tableWidth: 0,
212 + compact: true,
213 + };
216 +// ── Data collection ────────────────────────────────────────────────────────
218 +async function collectSessionFiles(
219 + dir: string,
220 + files: string[],
221 + signal?: AbortSignal,
222 +): Promise<void> {
223 + try {
224 + const entries = await readdir(dir, { withFileTypes: true });
225 + for (const entry of entries) {
226 + if (signal?.aborted) return;
227 + const p = join(dir, entry.name);
228 + if (entry.isDirectory()) await collectSessionFiles(p, files, signal);
229 + else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(p);
231 + } catch {
232 + /* skip */
236 +const YIELD_EVERY_N_LINES = 500;
238 +async function parseSessionFile(
239 + filePath: string,
240 + seenHashes: Set<string>,
241 + signal?: AbortSignal,
242 +): Promise<ParsedSession | null> {
243 + try {
244 + const content = await readFile(filePath, "utf8");
245 + if (signal?.aborted) return null;
247 + const lines = content.trim().split("\n");
248 + const messages: ParsedMessage[] = [];
249 + let sessionId = "";
251 + for (let i = 0; i < lines.length; i++) {
252 + if (signal?.aborted) return null;
253 + if (i % YIELD_EVERY_N_LINES === 0)
254 + await new Promise<void>((r) => setImmediate(r));
256 + const line = lines[i];
257 + if (!line?.trim()) continue;
259 + const entry = parseJsonLine(line);
260 + if (!entry) continue;
262 + if (entry.type === "session") {
263 + sessionId = entry.id as string;
264 + } else if (
265 + entry.type === "message" &&
266 + (entry.message as any)?.role === "assistant"
267 + ) {
268 + const msg = extractUsageMessage(
269 + entry.message as Record<string, unknown>,
270 + );
271 + if (!msg) continue;
272 + const hash = `${msg.timestamp}:${msg.input + msg.output + msg.cacheRead + msg.cacheWrite}`;
273 + if (seenHashes.has(hash)) continue;
274 + seenHashes.add(hash);
275 + messages.push(msg);
278 + return sessionId ? { sessionId, messages } : null;
279 + } catch {
280 + return null;
284 +function parseJsonLine(line: string): Record<string, unknown> | null {
285 + try {
286 + return JSON.parse(line);
287 + } catch {
288 + return null;
292 +function extractUsageMessage(
293 + msg: Record<string, unknown>,
294 +): ParsedMessage | null {
295 + const usage = msg.usage as Record<string, number | undefined> | undefined;
296 + if (!usage || !msg.provider || !msg.model) return null;
298 + const input = usage.input ?? 0;
299 + const output = usage.output ?? 0;
300 + const cacheRead = usage.cacheRead ?? 0;
301 + const cacheWrite = usage.cacheWrite ?? 0;
302 + const cost = (usage.cost as Record<string, number> | undefined)?.total ?? 0;
304 + const fallbackTs = msg.timestamp
305 + ? new Date(msg.timestamp as string).getTime()
306 + : 0;
307 + const timestamp =
308 + (msg.timestamp as number) || (Number.isNaN(fallbackTs) ? 0 : fallbackTs);
310 + return {
311 + provider: msg.provider as string,
312 + model: msg.model as string,
313 + cost,
314 + input,
315 + output,
316 + cacheRead,
317 + cacheWrite,
318 + timestamp,
319 + };
322 +function accumulateStats(
323 + target: BaseStats & { sessions: Set<string> | number },
324 + sessionId: string,
325 + cost: number,
326 + tokens: TokenStats,
327 +): void {
328 + if (target.sessions instanceof Set) target.sessions.add(sessionId);
329 + target.messages++;
330 + target.cost += cost;
331 + target.tokens.total += tokens.total;
332 + target.tokens.input += tokens.input;
333 + target.tokens.output += tokens.output;
334 + target.tokens.cacheRead += tokens.cacheRead;
335 + target.tokens.cacheWrite += tokens.cacheWrite;
338 +function emptyTokens(): TokenStats {
339 + return { total: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
341 +function emptyTimeFiltered(): TimeFilteredStats {
342 + return {
343 + providers: new Map(),
344 + totals: { sessions: 0, messages: 0, cost: 0, tokens: emptyTokens() },
345 + insights: { insights: [] },
346 + };
348 +function emptyUsage(): UsageData {
349 + return {
350 + today: emptyTimeFiltered(),
351 + thisWeek: emptyTimeFiltered(),
352 + lastWeek: emptyTimeFiltered(),
353 + allTime: emptyTimeFiltered(),
354 + };
357 +const TAB_ORDER: TabName[] = ["today", "thisWeek", "lastWeek", "allTime"];
359 +function getPeriods(
360 + ts: number,
361 + todayMs: number,
362 + weekMs: number,
363 + lastWeekMs: number,
364 +): TabName[] {
365 + const periods: TabName[] = ["allTime"];
366 + if (ts >= todayMs) periods.push("today");
367 + if (ts >= weekMs) periods.push("thisWeek");
368 + else if (ts >= lastWeekMs) periods.push("lastWeek");
369 + return periods;
372 +async function collectUsageData(
373 + sessionDir: string,
374 + signal?: AbortSignal,
375 +): Promise<UsageData | null> {
376 + const startOfToday = new Date();
377 + startOfToday.setHours(0, 0, 0, 0);
378 + const todayMs = startOfToday.getTime();
379 + const startOfWeek = new Date();
380 + const dow = startOfWeek.getDay();
381 + startOfWeek.setDate(startOfWeek.getDate() - (dow === 0 ? 6 : dow - 1));
382 + startOfWeek.setHours(0, 0, 0, 0);
383 + const weekMs = startOfWeek.getTime();
384 + const startOfLastWeek = new Date(startOfWeek);
385 + startOfLastWeek.setDate(startOfLastWeek.getDate() - 7);
386 + const lastWeekMs = startOfLastWeek.getTime();
388 + const data = emptyUsage();
389 + const rawByPeriod: Record<TabName, PeriodRawData> = {
390 + today: { messages: [], sessionCosts: new Map() },
391 + thisWeek: { messages: [], sessionCosts: new Map() },
392 + lastWeek: { messages: [], sessionCosts: new Map() },
393 + allTime: { messages: [], sessionCosts: new Map() },
394 + };
395 + const globalSessionSpans = new Map<string, GlobalSessionSpan>();
397 + const files: string[] = [];
398 + // sessionDir is the per-project dir (<root>/<encoded-cwd>/).
399 + // Go up one level to get the root sessions dir so we scan ALL projects.
400 + await collectSessionFiles(dirname(sessionDir), files, signal);
401 + if (signal?.aborted) return null;
402 + const seenHashes = new Set<string>();
404 + for (const filePath of files) {
405 + if (signal?.aborted) return null;
406 + const parsed = await parseSessionFile(filePath, seenHashes, signal);
407 + if (!parsed) continue;
409 + for (const msg of parsed.messages) {
410 + if (msg.timestamp > 0) {
411 + const span = globalSessionSpans.get(parsed.sessionId);
412 + if (!span)
413 + globalSessionSpans.set(parsed.sessionId, {
414 + startMs: msg.timestamp,
415 + endMs: msg.timestamp,
416 + });
417 + else {
418 + if (msg.timestamp < span.startMs) span.startMs = msg.timestamp;
419 + if (msg.timestamp > span.endMs) span.endMs = msg.timestamp;
423 + const periods = getPeriods(msg.timestamp, todayMs, weekMs, lastWeekMs);
424 + const tokens = {
425 + total: msg.input + msg.output + msg.cacheWrite,
426 + input: msg.input,
427 + output: msg.output,
428 + cacheRead: msg.cacheRead,
429 + cacheWrite: msg.cacheWrite,
430 + };
432 + for (const period of periods) {
433 + const stats = data[period];
434 + let providerStats = stats.providers.get(msg.provider);
435 + if (!providerStats) {
436 + providerStats = {
437 + sessions: new Set(),
438 + messages: 0,
439 + cost: 0,
440 + tokens: emptyTokens(),
441 + models: new Map(),
442 + };
443 + stats.providers.set(msg.provider, providerStats);
445 + let modelStats = providerStats.models.get(msg.model);
446 + if (!modelStats) {
447 + modelStats = {
448 + sessions: new Set(),
449 + messages: 0,
450 + cost: 0,
451 + tokens: emptyTokens(),
452 + };
453 + providerStats.models.set(msg.model, modelStats);
456 + modelStats.sessions.add(parsed.sessionId);
457 + accumulateStats(modelStats, parsed.sessionId, msg.cost, tokens);
458 + accumulateStats(providerStats, parsed.sessionId, msg.cost, tokens);
459 + accumulateStats(stats.totals, parsed.sessionId, msg.cost, tokens);
460 + rawByPeriod[period].messages.push({
461 + sessionId: parsed.sessionId,
462 + timestamp: msg.timestamp,
463 + cost: msg.cost,
464 + input: msg.input,
465 + cacheRead: msg.cacheRead,
466 + cacheWrite: msg.cacheWrite,
467 + });
468 + rawByPeriod[period].sessionCosts.set(
469 + parsed.sessionId,
470 + (rawByPeriod[period].sessionCosts.get(parsed.sessionId) ?? 0) +
471 + msg.cost,
472 + );
475 + await new Promise<void>((r) => setImmediate(r));
478 + // Compute insights
479 + const longSessionIds = new Set<string>();
480 + for (const [id, span] of globalSessionSpans) {
481 + if (span.endMs - span.startMs >= LONG_SESSION_MS) longSessionIds.add(id);
483 + for (const period of TAB_ORDER)
484 + data[period].insights = computeInsights(
485 + rawByPeriod[period],
486 + longSessionIds,
487 + );
489 + return data;
492 +// ── Insights ───────────────────────────────────────────────────────────────
494 +const PARALLEL_WINDOW_MS = 2 * 60_000;
495 +const PARALLEL_THRESHOLD = 4;
496 +const LARGE_CONTEXT = 150_000;
497 +const LARGE_UNCACHED = 100_000;
498 +const LONG_SESSION_MS = 8 * 60 * 60 * 1000;
499 +const TOP_N = 5;
500 +const MIN_MSG_PARALLEL = 10;
502 +function computeInsights(
503 + raw: PeriodRawData,
504 + longSessionIds: Set<string>,
505 +): PeriodInsights {
506 + if (!raw.messages.length) return { insights: [] };
507 + const total = raw.messages.reduce((s, m) => s + m.cost, 0);
508 + if (total <= 0) return { insights: [] };
510 + const candidates: Insight[] = [];
512 + // Parallel
513 + const timed = raw.messages.filter((m) => m.timestamp > 0);
514 + if (
515 + timed.length >= MIN_MSG_PARALLEL &&
516 + new Set(timed.map((m) => m.sessionId)).size >= PARALLEL_THRESHOLD
517 + ) {
518 + const sorted = timed.slice().sort((a, b) => a.timestamp - b.timestamp);
519 + const sidCount = new Map<string, number>();
520 + let unique = 0,
521 + left = 0,
522 + right = 0,
523 + parallelCost = 0;
524 + for (const cur of sorted) {
525 + while (
526 + right < sorted.length &&
527 + sorted[right]?.timestamp <= cur.timestamp + PARALLEL_WINDOW_MS
528 + ) {
529 + const sid = sorted[right]?.sessionId;
530 + const n = (sidCount.get(sid) ?? 0) + 1;
531 + sidCount.set(sid, n);
532 + if (n === 1) unique++;
533 + right++;
535 + while (
536 + left < right &&
537 + sorted[left]?.timestamp < cur.timestamp - PARALLEL_WINDOW_MS
538 + ) {
539 + const sid = sorted[left]?.sessionId;
540 + const n = (sidCount.get(sid) ?? 0) - 1;
541 + if (!n) {
542 + sidCount.delete(sid);
543 + unique--;
544 + } else sidCount.set(sid, n);
545 + left++;
547 + if (unique >= PARALLEL_THRESHOLD) parallelCost += cur.cost;
549 + if (parallelCost > 0)
550 + candidates.push({
551 + percent: (parallelCost / total) * 100,
552 + headline: `of cost was while ${PARALLEL_THRESHOLD}+ sessions ran in parallel`,
553 + advice: "Queueing sessions uses capacity more evenly.",
554 + });
557 + // Large context
558 + const largeCtxW = raw.messages
559 + .filter((m) => m.input + m.cacheRead + m.cacheWrite > LARGE_CONTEXT)
560 + .reduce((s, m) => s + m.cost, 0);
561 + if (largeCtxW > 0)
562 + candidates.push({
563 + percent: (largeCtxW / total) * 100,
564 + headline: `of cost was at >${Math.round(LARGE_CONTEXT / 1000)}k context`,
565 + advice: "/compact mid-task, /clear when switching tasks.",
566 + });
568 + // Uncached
569 + const uncachedW = raw.messages
570 + .filter((m) => m.input + m.cacheWrite > LARGE_UNCACHED)
571 + .reduce((s, m) => s + m.cost, 0);
572 + if (uncachedW > 0)
573 + candidates.push({
574 + percent: (uncachedW / total) * 100,
575 + headline: `of cost came from >${Math.round(LARGE_UNCACHED / 1000)}k-token uncached prompts`,
576 + advice: "/compact before stepping away keeps the cold-start small.",
577 + });
579 + // Long sessions
580 + const longW = raw.messages
581 + .filter((m) => longSessionIds.has(m.sessionId))
582 + .reduce((s, m) => s + m.cost, 0);
583 + if (longW > 0)
584 + candidates.push({
585 + percent: (longW / total) * 100,
586 + headline: `of cost came from ${Math.round(LONG_SESSION_MS / 3600_000)}h+ sessions`,
587 + advice: "Continuous usage can add up quickly.",
588 + });
590 + // Top-N
591 + if (raw.sessionCosts.size > TOP_N) {
592 + const sorted = Array.from(raw.sessionCosts.values()).sort((a, b) => b - a);
593 + const topW = sorted.slice(0, TOP_N).reduce((s, c) => s + c, 0);
594 + candidates.push({
595 + percent: (topW / total) * 100,
596 + headline: `of cost from top ${TOP_N} sessions`,
597 + advice: "A small number of sessions drives most spend.",
598 + });
601 + return {
602 + insights: candidates
603 + .filter((i) => i.percent >= 1)
604 + .sort((a, b) => b.percent - a.percent),
605 + };
608 +// ── Formatting ─────────────────────────────────────────────────────────────
610 +function formatCost(c: number): string {
611 + if (c === 0) return "-";
612 + if (c < 0.01) return `$${c.toFixed(4)}`;
613 + if (c < 10) return `$${c.toFixed(2)}`;
614 + if (c < 100) return `$${c.toFixed(1)}`;
615 + return `$${Math.round(c)}`;
618 +function formatTokens(n: number): string {
619 + if (n === 0) return "-";
620 + if (n < 1_000) return n.toString();
621 + if (n < 10_000) return `${(n / 1_000).toFixed(1)}k`;
622 + if (n < 1_000_000) return `${Math.round(n / 1_000)}k`;
623 + if (n < 10_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
624 + return `${Math.round(n / 1_000_000)}M`;
627 +function formatNumber(n: number): string {
628 + return n === 0 ? "-" : n.toLocaleString();
631 +function padLeft(s: string, len: number): string {
632 + const v = visibleWidth(s);
633 + return v >= len ? s : " ".repeat(len - v) + s;
636 +function padRight(s: string, len: number): string {
637 + const v = visibleWidth(s);
638 + return v >= len ? s : s + " ".repeat(len - v);
641 +function fitCell(
642 + s: string,
643 + len: number,
644 + align: "left" | "right" = "left",
645 +): string {
646 + return align === "right"
647 + ? padLeft(truncateToWidth(s, len), len)
648 + : padRight(truncateToWidth(s, len), len);
651 +function pickFitting(w: number, variants: string[]): string {
652 + for (const v of variants) if (visibleWidth(v) <= w) return v;
653 + return variants[variants.length - 1] || "";
656 +function formatPct(p: number): string {
657 + return p >= 10 ? `${Math.round(p)}%` : `${Math.round(p * 10) / 10}%`;
660 +// ── Component ──────────────────────────────────────────────────────────────
662 +const TAB_LABELS: Record<TabName, string> = {
663 + today: "Today",
664 + thisWeek: "This Week",
665 + lastWeek: "Last Week",
666 + allTime: "All Time",
669 +class UsageComponent {
670 + private activeTab: TabName = "allTime";
671 + private viewMode: ViewMode = "table";
672 + private data: UsageData;
673 + private selectedIndex = 0;
674 + private expanded = new Set<string>();
675 + private providerOrder: string[] = [];
676 + private theme: Theme;
677 + private requestRender: () => void;
678 + private done: () => void;
680 + constructor(
681 + theme: Theme,
682 + data: UsageData,
683 + requestRender: () => void,
684 + done: () => void,
685 + ) {
686 + this.theme = theme;
687 + this.data = data;
688 + this.requestRender = requestRender;
689 + this.done = done;
690 + this.updateProviderOrder();
693 + private updateProviderOrder() {
694 + const stats = this.data[this.activeTab];
695 + this.providerOrder = Array.from(stats.providers.entries())
696 + .sort((a, b) => b[1].cost - a[1].cost)
697 + .map(([n]) => n);
698 + this.selectedIndex = Math.min(
699 + this.selectedIndex,
700 + Math.max(0, this.providerOrder.length - 1),
701 + );
704 + handleInput(data: string): void {
705 + if (matchesKey(data, "escape") || matchesKey(data, "q")) {
706 + this.done();
707 + return;
709 + if (matchesKey(data, "v")) {
710 + this.viewMode = this.viewMode === "table" ? "insights" : "table";
711 + this.requestRender();
712 + return;
714 + if (matchesKey(data, "tab") || matchesKey(data, "right")) {
715 + const idx = TAB_ORDER.indexOf(this.activeTab);
716 + this.activeTab =
717 + TAB_ORDER[(idx + 1) % TAB_ORDER.length] ?? this.activeTab;
718 + this.updateProviderOrder();
719 + this.requestRender();
720 + } else if (matchesKey(data, "shift+tab") || matchesKey(data, "left")) {
721 + const idx = TAB_ORDER.indexOf(this.activeTab);
722 + this.activeTab =
723 + TAB_ORDER[(idx - 1 + TAB_ORDER.length) % TAB_ORDER.length] ??
724 + this.activeTab;
725 + this.updateProviderOrder();
726 + this.requestRender();
727 + } else if (this.viewMode === "table" && matchesKey(data, "up")) {
728 + if (this.selectedIndex > 0) {
729 + this.selectedIndex--;
730 + this.requestRender();
732 + } else if (this.viewMode === "table" && matchesKey(data, "down")) {
733 + if (this.selectedIndex < this.providerOrder.length - 1) {
734 + this.selectedIndex++;
735 + this.requestRender();
737 + } else if (
738 + this.viewMode === "table" &&
739 + (matchesKey(data, "enter") || matchesKey(data, "space"))
740 + ) {
741 + const p = this.providerOrder[this.selectedIndex];
742 + if (p) {
743 + this.expanded.has(p) ? this.expanded.delete(p) : this.expanded.add(p);
744 + this.requestRender();
749 + render(width: number): string[] {
750 + return this.viewMode === "insights"
751 + ? this.renderInsightsView(width)
752 + : this.renderTableView(width);
755 + private renderInsightsView(width: number): string[] {
756 + const th = this.theme;
757 + const stats = this.data[this.activeTab];
758 + const lines: string[] = [];
759 + lines.push(th.fg("accent", th.bold("Usage Insights")), "");
760 + lines.push(
761 + th.fg(
762 + "dim",
763 + `What's contributing to your cost? ${TAB_LABELS[this.activeTab]} · weighted by USD`,
764 + ),
765 + "",
766 + );
767 + if (!stats.totals.messages) {
768 + lines.push(th.fg("dim", " No usage for this period."), "");
769 + } else if (!stats.totals.cost) {
770 + lines.push(th.fg("dim", " No cost data."), "");
771 + } else if (!stats.insights.insights.length) {
772 + lines.push(th.fg("dim", " No insights above 1%."), "");
773 + } else {
774 + for (const insight of stats.insights.insights) {
775 + lines.push(
776 + `${th.fg("accent", th.bold(formatPct(insight.percent)))} ${insight.headline}`,
777 + );
778 + for (const w of wrapTextWithAnsi(
779 + insight.advice,
780 + Math.max(width - 5, 30),
781 + ))
782 + lines.push(` ${th.fg("dim", w)}`);
783 + lines.push("");
786 + lines.push(
787 + th.fg(
788 + "dim",
789 + pickFitting(width, [
790 + "[Tab/←→] period [v] table [q] close",
791 + "[q] close",
792 + ]),
793 + ),
794 + );
795 + return lines.map((l) => truncateToWidth(l, width));
798 + private renderTableView(width: number): string[] {
799 + const th = this.theme;
800 + const stats = this.data[this.activeTab];
801 + const layout = getTableLayout(width);
802 + const lines: string[] = [];
804 + // Tabs
805 + const tabs = TAB_ORDER.map((t) =>
806 + t === this.activeTab
807 + ? th.fg("accent", `[${TAB_LABELS[t]}]`)
808 + : th.fg("dim", ` ${TAB_LABELS[t]} `),
809 + ).join(" ");
810 + lines.push(
811 + pickFitting(width, [
812 + tabs,
813 + th.fg("accent", `[${TAB_LABELS[this.activeTab]}]`),
814 + ]),
815 + );
816 + if (layout.compact)
817 + lines.push(
818 + ...wrapTextWithAnsi(
819 + th.fg("dim", "Compact view. Widen terminal for more columns."),
820 + Math.max(width, 1),
821 + ),
822 + );
823 + lines.push("");
825 + // Header
826 + let headerLine = fitCell("Provider / Model", layout.nameWidth);
827 + for (const col of layout.columns)
828 + headerLine += col.dimmed
829 + ? th.fg("dim", fitCell(col.label, col.width, "right"))
830 + : fitCell(col.label, col.width, "right");
831 + lines.push(th.fg("muted", headerLine));
832 + lines.push(th.fg("border", "─".repeat(layout.tableWidth)));
834 + // Rows
835 + if (!this.providerOrder.length) {
836 + lines.push(th.fg("dim", " No usage data"));
838 + for (let i = 0; i < this.providerOrder.length; i++) {
839 + const name = this.providerOrder[i];
840 + if (!name) continue;
841 + const prov = stats.providers.get(name);
842 + if (!prov) continue;
843 + const sel = i === this.selectedIndex;
844 + const exp = this.expanded.has(name);
845 + const arrow = sel
846 + ? th.fg("accent", `${exp ? "▾" : "▸"} `)
847 + : th.fg("dim", `${exp ? "▾" : "▸"} `);
848 + lines.push(
849 + this.row(name, prov, layout, { prefix: arrow, selected: sel }),
850 + );
851 + if (exp) {
852 + for (const [mn, ms] of Array.from(prov.models.entries()).sort(
853 + (a, b) => b[1].cost - a[1].cost,
854 + )) {
855 + lines.push(this.row(mn, ms, layout, { indent: 4, dimAll: true }));
860 + // Totals
861 + lines.push(th.fg("border", "─".repeat(layout.tableWidth)));
862 + let totalRow = fitCell(th.bold("Total"), layout.nameWidth);
863 + for (const col of layout.columns)
864 + totalRow += col.dimmed
865 + ? th.fg("dim", fitCell(col.getValue(stats.totals), col.width, "right"))
866 + : fitCell(col.getValue(stats.totals), col.width, "right");
867 + lines.push(totalRow);
868 + lines.push("");
870 + lines.push(
871 + th.fg(
872 + "dim",
873 + pickFitting(width, [
874 + "Tokens = In + Out + CacheWrite · ↑In = In + CacheWrite (v0.2.0+)",
875 + "Incl. CacheWrite (v0.2.0+)",
876 + ]),
877 + ),
878 + );
879 + lines.push(
880 + th.fg(
881 + "dim",
882 + pickFitting(width, [
883 + "[Tab/←→] period [↑↓] select [Enter] expand [v] insights [q] close",
884 + "[↑↓] select [v] insights [q] close",
885 + "[q] close",
886 + ]),
887 + ),
888 + );
889 + return lines.map((l) => truncateToWidth(l, width));
892 + private row(
893 + name: string,
894 + stats: BaseStats & { sessions: Set<string> | number },
895 + layout: TableLayout,
896 + opts: {
897 + prefix?: string;
898 + indent?: number;
899 + selected?: boolean;
900 + dimAll?: boolean;
901 + } = {},
902 + ): string {
903 + const th = this.theme;
904 + const { indent = 0, selected = false, dimAll = false } = opts;
905 + const rawPrefix = opts.prefix ?? " ".repeat(indent);
906 + const prefixW = visibleWidth(truncateToWidth(rawPrefix, layout.nameWidth));
907 + const innerW = Math.max(layout.nameWidth - prefixW, 0);
908 + const truncName = innerW > 0 ? truncateToWidth(name, innerW) : "";
909 + const styledName = selected
910 + ? th.fg("accent", truncName)
911 + : dimAll
912 + ? th.fg("dim", truncName)
913 + : truncName;
914 + let row = rawPrefix + (innerW > 0 ? padRight(styledName, innerW) : "");
915 + for (const col of layout.columns) {
916 + const v = fitCell(col.getValue(stats), col.width, "right");
917 + row += col.dimmed || dimAll ? th.fg("dim", v) : v;
919 + return row;
922 + invalidate(): void {}
923 + dispose(): void {}
926 +export async function showUsage(
927 + _args: string,
928 + ctx: ExtensionCommandContext,
929 +): Promise<void> {
930 + if (!ctx.hasUI) return;
932 + const data = await ctx.ui.custom<UsageData | null>(
933 + (tui, theme, _kb, done) => {
934 + const loader = new CancellableLoader(
935 + tui,
936 + (s) => theme.fg("accent", s),
937 + (s) => theme.fg("muted", s),
938 + "Loading Usage...",
939 + );
940 + let finished = false;
941 + const finish = (v: UsageData | null) => {
942 + if (finished) return;
943 + finished = true;
944 + loader.dispose();
945 + done(v);
946 + };
947 + loader.onAbort = () => finish(null);
948 + collectUsageData(ctx.sessionManager.getSessionDir(), loader.signal)
949 + .then(finish)
950 + .catch(() => finish(null));
951 + return loader;
952 + },
953 + );
955 + if (!data) return;
957 + await ctx.ui.custom<void>((tui, theme, _kb, done) => {
958 + const container = new Container();
959 + container.addChild(new Spacer(1));
960 + container.addChild(new DynamicBorder((s: string) => theme.fg("border", s)));
961 + container.addChild(new Spacer(1));
962 + const usage = new UsageComponent(
963 + theme,
964 + data,
965 + () => tui.requestRender(),
966 + () => done(),
967 + );
968 + return {
969 + render: (w: number) => {
970 + const border = container.render(w).map((l) => truncateToWidth(l, w));
971 + return [
972 + ...border,
973 + ...usage.render(w),
974 + "",
975 + theme.fg("border", "─".repeat(w)),
976 + ].map((l) => truncateToWidth(l, w));
977 + },
978 + invalidate: () => container.invalidate(),
979 + handleInput: (input: string) => usage.handleInput(input),
980 + dispose: () => {},
981 + };
982 + });

extensions/usage/index.ts

Modified
1 -/**
2 - * /usage — Usage statistics dashboard
3 - *
4 - * Aggregated usage across all sessions parsed from local JSONL files.
5 - * Tab cycles: Today → This Week → Last Week → All Time.
6 - * Toggle insights view with 'v' for cost optimization tips.
7 - *
8 - * Based on tmustier/pi-extensions (usage-extension).
9 - * MIT License — https://github.com/tmustier/pi-extensions
10 - */
1 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12 -import { readdir, readFile } from "node:fs/promises";
13 -import { dirname, join } from "node:path";
14 -import type {
15 - ExtensionAPI,
16 - ExtensionCommandContext,
17 - Theme,
18 -} from "@earendil-works/pi-coding-agent";
19 -import { DynamicBorder } from "@earendil-works/pi-coding-agent";
20 -import {
21 - CancellableLoader,
22 - Container,
23 - matchesKey,
24 - Spacer,
25 - truncateToWidth,
26 - visibleWidth,
27 - wrapTextWithAnsi,
28 -} from "@earendil-works/pi-tui";
30 -// ── Types ──────────────────────────────────────────────────────────────────
32 -interface TokenStats {
33 - total: number;
34 - input: number;
35 - output: number;
36 - cacheRead: number;
37 - cacheWrite: number;
39 -interface BaseStats {
40 - messages: number;
41 - cost: number;
42 - tokens: TokenStats;
44 -interface ModelStats extends BaseStats {
45 - sessions: Set<string>;
47 -interface ProviderStats extends BaseStats {
48 - sessions: Set<string>;
49 - models: Map<string, ModelStats>;
51 -interface TotalStats extends BaseStats {
52 - sessions: number;
54 -interface Insight {
55 - percent: number;
56 - headline: string;
57 - advice: string;
59 -interface PeriodInsights {
60 - insights: Insight[];
62 -interface RawMessage {
63 - sessionId: string;
64 - timestamp: number;
65 - cost: number;
66 - input: number;
67 - cacheRead: number;
68 - cacheWrite: number;
71 -interface ParsedMessage {
72 - provider: string;
73 - model: string;
74 - cost: number;
75 - input: number;
76 - output: number;
77 - cacheRead: number;
78 - cacheWrite: number;
79 - timestamp: number;
82 -interface ParsedSession {
83 - sessionId: string;
84 - messages: ParsedMessage[];
86 -interface PeriodRawData {
87 - messages: RawMessage[];
88 - sessionCosts: Map<string, number>;
90 -interface GlobalSessionSpan {
91 - startMs: number;
92 - endMs: number;
94 -interface TimeFilteredStats {
95 - providers: Map<string, ProviderStats>;
96 - totals: TotalStats;
97 - insights: PeriodInsights;
99 -interface UsageData {
100 - today: TimeFilteredStats;
101 - thisWeek: TimeFilteredStats;
102 - lastWeek: TimeFilteredStats;
103 - allTime: TimeFilteredStats;
105 -type TabName = "today" | "thisWeek" | "lastWeek" | "allTime";
106 -type ViewMode = "table" | "insights";
108 -// ── Column config ──────────────────────────────────────────────────────────
110 -interface DataColumn {
111 - label: string;
112 - width: number;
113 - dimmed?: boolean;
114 - getValue: (stats: BaseStats & { sessions: Set<string> | number }) => string;
117 -const SESSIONS_COL: DataColumn = {
118 - label: "Sessions",
119 - width: 9,
120 - getValue: (s) =>
121 - formatNumber(typeof s.sessions === "number" ? s.sessions : s.sessions.size),
122 -};
123 -const MSGS_COL: DataColumn = {
124 - label: "Msgs",
125 - width: 9,
126 - getValue: (s) => formatNumber(s.messages),
127 -};
128 -const COST_COL: DataColumn = {
129 - label: "Cost",
130 - width: 9,
131 - getValue: (s) => formatCost(s.cost),
132 -};
133 -const TOKENS_COL: DataColumn = {
134 - label: "Tokens",
135 - width: 9,
136 - getValue: (s) => formatTokens(s.tokens.total),
137 -};
138 -const INPUT_COL: DataColumn = {
139 - label: "↑In",
140 - width: 8,
141 - dimmed: true,
142 - getValue: (s) => formatTokens(s.tokens.input + s.tokens.cacheWrite),
143 -};
144 -const OUTPUT_COL: DataColumn = {
145 - label: "↓Out",
146 - width: 8,
147 - dimmed: true,
148 - getValue: (s) => formatTokens(s.tokens.output),
149 -};
150 -const CACHE_COL: DataColumn = {
151 - label: "Cache",
152 - width: 8,
153 - dimmed: true,
154 - getValue: (s) => formatTokens(s.tokens.cacheRead + s.tokens.cacheWrite),
155 -};
157 -const FULL_COLS: DataColumn[] = [
158 - SESSIONS_COL,
159 - MSGS_COL,
160 - COST_COL,
161 - TOKENS_COL,
162 - INPUT_COL,
163 - OUTPUT_COL,
164 - CACHE_COL,
165 -];
167 -interface TableLayout {
168 - columns: DataColumn[];
169 - nameWidth: number;
170 - tableWidth: number;
171 - compact: boolean;
173 -const MAX_NAME_WIDTH = 26;
175 -function getTableLayout(width: number): TableLayout {
176 - const layouts: Array<{
177 - columns: DataColumn[];
178 - minName: number;
179 - compact?: boolean;
180 - }> = [
181 - { columns: FULL_COLS, minName: MAX_NAME_WIDTH },
182 - {
183 - columns: [SESSIONS_COL, MSGS_COL, COST_COL, TOKENS_COL],
184 - minName: 14,
185 - compact: true,
186 - },
187 - {
188 - columns: [SESSIONS_COL, COST_COL, TOKENS_COL],
189 - minName: 12,
190 - compact: true,
191 - },
192 - { columns: [COST_COL, TOKENS_COL], minName: 10, compact: true },
193 - { columns: [COST_COL], minName: 8, compact: true },
194 - ];
195 - for (const c of layouts) {
196 - const colsWidth = c.columns.reduce((s, col) => s + col.width, 0);
197 - const nameWidth = Math.min(MAX_NAME_WIDTH, Math.max(width - colsWidth, 0));
198 - if (nameWidth >= c.minName)
199 - return {
200 - columns: c.columns,
201 - nameWidth,
202 - tableWidth: nameWidth + colsWidth,
203 - compact: !!c.compact,
204 - };
205 - }
206 - const fallback = layouts.at(-1);
207 - if (!fallback) throw new Error("usage layouts must not be empty");
208 - const fw = fallback.columns.reduce((s, col) => s + col.width, 0);
209 - return {
210 - columns: fallback.columns,
211 - nameWidth: Math.min(MAX_NAME_WIDTH, Math.max(width - fw, 0)),
212 - tableWidth: 0,
213 - compact: true,
214 - };
217 -// ── Data collection ────────────────────────────────────────────────────────
219 -async function collectSessionFiles(
220 - dir: string,
221 - files: string[],
222 - signal?: AbortSignal,
223 -): Promise<void> {
224 - try {
225 - const entries = await readdir(dir, { withFileTypes: true });
226 - for (const entry of entries) {
227 - if (signal?.aborted) return;
228 - const p = join(dir, entry.name);
229 - if (entry.isDirectory()) await collectSessionFiles(p, files, signal);
230 - else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(p);
231 - }
232 - } catch {
233 - /* skip */
234 - }
237 -const YIELD_EVERY_N_LINES = 500;
239 -async function parseSessionFile(
240 - filePath: string,
241 - seenHashes: Set<string>,
242 - signal?: AbortSignal,
243 -): Promise<ParsedSession | null> {
244 - try {
245 - const content = await readFile(filePath, "utf8");
246 - if (signal?.aborted) return null;
248 - const lines = content.trim().split("\n");
249 - const messages: ParsedMessage[] = [];
250 - let sessionId = "";
252 - for (let i = 0; i < lines.length; i++) {
253 - if (signal?.aborted) return null;
254 - if (i % YIELD_EVERY_N_LINES === 0)
255 - await new Promise<void>((r) => setImmediate(r));
257 - const line = lines[i];
258 - if (!line?.trim()) continue;
260 - const entry = parseJsonLine(line);
261 - if (!entry) continue;
263 - if (entry.type === "session") {
264 - sessionId = entry.id as string;
265 - } else if (
266 - entry.type === "message" &&
267 - (entry.message as any)?.role === "assistant"
268 - ) {
269 - const msg = extractUsageMessage(
270 - entry.message as Record<string, unknown>,
271 - );
272 - if (!msg) continue;
273 - const hash = `${msg.timestamp}:${msg.input + msg.output + msg.cacheRead + msg.cacheWrite}`;
274 - if (seenHashes.has(hash)) continue;
275 - seenHashes.add(hash);
276 - messages.push(msg);
277 - }
278 - }
279 - return sessionId ? { sessionId, messages } : null;
280 - } catch {
281 - return null;
282 - }
285 -function parseJsonLine(line: string): Record<string, unknown> | null {
286 - try {
287 - return JSON.parse(line);
288 - } catch {
289 - return null;
290 - }
293 -function extractUsageMessage(
294 - msg: Record<string, unknown>,
295 -): ParsedMessage | null {
296 - const usage = msg.usage as Record<string, number | undefined> | undefined;
297 - if (!usage || !msg.provider || !msg.model) return null;
299 - const input = usage.input ?? 0;
300 - const output = usage.output ?? 0;
301 - const cacheRead = usage.cacheRead ?? 0;
302 - const cacheWrite = usage.cacheWrite ?? 0;
303 - const cost = (usage.cost as Record<string, number> | undefined)?.total ?? 0;
305 - const fallbackTs = msg.timestamp
306 - ? new Date(msg.timestamp as string).getTime()
307 - : 0;
308 - const timestamp =
309 - (msg.timestamp as number) || (Number.isNaN(fallbackTs) ? 0 : fallbackTs);
311 - return {
312 - provider: msg.provider as string,
313 - model: msg.model as string,
314 - cost,
315 - input,
316 - output,
317 - cacheRead,
318 - cacheWrite,
319 - timestamp,
320 - };
323 -function accumulateStats(
324 - target: BaseStats & { sessions: Set<string> | number },
325 - sessionId: string,
326 - cost: number,
327 - tokens: TokenStats,
328 -): void {
329 - if (target.sessions instanceof Set) target.sessions.add(sessionId);
330 - target.messages++;
331 - target.cost += cost;
332 - target.tokens.total += tokens.total;
333 - target.tokens.input += tokens.input;
334 - target.tokens.output += tokens.output;
335 - target.tokens.cacheRead += tokens.cacheRead;
336 - target.tokens.cacheWrite += tokens.cacheWrite;
339 -function emptyTokens(): TokenStats {
340 - return { total: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
342 -function emptyTimeFiltered(): TimeFilteredStats {
343 - return {
344 - providers: new Map(),
345 - totals: { sessions: 0, messages: 0, cost: 0, tokens: emptyTokens() },
346 - insights: { insights: [] },
347 - };
349 -function emptyUsage(): UsageData {
350 - return {
351 - today: emptyTimeFiltered(),
352 - thisWeek: emptyTimeFiltered(),
353 - lastWeek: emptyTimeFiltered(),
354 - allTime: emptyTimeFiltered(),
355 - };
358 -const TAB_ORDER: TabName[] = ["today", "thisWeek", "lastWeek", "allTime"];
360 -function getPeriods(
361 - ts: number,
362 - todayMs: number,
363 - weekMs: number,
364 - lastWeekMs: number,
365 -): TabName[] {
366 - const periods: TabName[] = ["allTime"];
367 - if (ts >= todayMs) periods.push("today");
368 - if (ts >= weekMs) periods.push("thisWeek");
369 - else if (ts >= lastWeekMs) periods.push("lastWeek");
370 - return periods;
373 -async function collectUsageData(
374 - sessionDir: string,
375 - signal?: AbortSignal,
376 -): Promise<UsageData | null> {
377 - const startOfToday = new Date();
378 - startOfToday.setHours(0, 0, 0, 0);
379 - const todayMs = startOfToday.getTime();
380 - const startOfWeek = new Date();
381 - const dow = startOfWeek.getDay();
382 - startOfWeek.setDate(startOfWeek.getDate() - (dow === 0 ? 6 : dow - 1));
383 - startOfWeek.setHours(0, 0, 0, 0);
384 - const weekMs = startOfWeek.getTime();
385 - const startOfLastWeek = new Date(startOfWeek);
386 - startOfLastWeek.setDate(startOfLastWeek.getDate() - 7);
387 - const lastWeekMs = startOfLastWeek.getTime();
389 - const data = emptyUsage();
390 - const rawByPeriod: Record<TabName, PeriodRawData> = {
391 - today: { messages: [], sessionCosts: new Map() },
392 - thisWeek: { messages: [], sessionCosts: new Map() },
393 - lastWeek: { messages: [], sessionCosts: new Map() },
394 - allTime: { messages: [], sessionCosts: new Map() },
395 - };
396 - const globalSessionSpans = new Map<string, GlobalSessionSpan>();
398 - const files: string[] = [];
399 - // sessionDir is the per-project dir (<root>/<encoded-cwd>/).
400 - // Go up one level to get the root sessions dir so we scan ALL projects.
401 - await collectSessionFiles(dirname(sessionDir), files, signal);
402 - if (signal?.aborted) return null;
403 - const seenHashes = new Set<string>();
405 - for (const filePath of files) {
406 - if (signal?.aborted) return null;
407 - const parsed = await parseSessionFile(filePath, seenHashes, signal);
408 - if (!parsed) continue;
410 - for (const msg of parsed.messages) {
411 - if (msg.timestamp > 0) {
412 - const span = globalSessionSpans.get(parsed.sessionId);
413 - if (!span)
414 - globalSessionSpans.set(parsed.sessionId, {
415 - startMs: msg.timestamp,
416 - endMs: msg.timestamp,
417 - });
418 - else {
419 - if (msg.timestamp < span.startMs) span.startMs = msg.timestamp;
420 - if (msg.timestamp > span.endMs) span.endMs = msg.timestamp;
421 - }
422 - }
424 - const periods = getPeriods(msg.timestamp, todayMs, weekMs, lastWeekMs);
425 - const tokens = {
426 - total: msg.input + msg.output + msg.cacheWrite,
427 - input: msg.input,
428 - output: msg.output,
429 - cacheRead: msg.cacheRead,
430 - cacheWrite: msg.cacheWrite,
431 - };
433 - for (const period of periods) {
434 - const stats = data[period];
435 - let providerStats = stats.providers.get(msg.provider);
436 - if (!providerStats) {
437 - providerStats = {
438 - sessions: new Set(),
439 - messages: 0,
440 - cost: 0,
441 - tokens: emptyTokens(),
442 - models: new Map(),
443 - };
444 - stats.providers.set(msg.provider, providerStats);
445 - }
446 - let modelStats = providerStats.models.get(msg.model);
447 - if (!modelStats) {
448 - modelStats = {
449 - sessions: new Set(),
450 - messages: 0,
451 - cost: 0,
452 - tokens: emptyTokens(),
453 - };
454 - providerStats.models.set(msg.model, modelStats);
455 - }
457 - modelStats.sessions.add(parsed.sessionId);
458 - accumulateStats(modelStats, parsed.sessionId, msg.cost, tokens);
459 - accumulateStats(providerStats, parsed.sessionId, msg.cost, tokens);
460 - accumulateStats(stats.totals, parsed.sessionId, msg.cost, tokens);
461 - rawByPeriod[period].messages.push({
462 - sessionId: parsed.sessionId,
463 - timestamp: msg.timestamp,
464 - cost: msg.cost,
465 - input: msg.input,
466 - cacheRead: msg.cacheRead,
467 - cacheWrite: msg.cacheWrite,
468 - });
469 - rawByPeriod[period].sessionCosts.set(
470 - parsed.sessionId,
471 - (rawByPeriod[period].sessionCosts.get(parsed.sessionId) ?? 0) +
472 - msg.cost,
473 - );
474 - }
475 - }
476 - await new Promise<void>((r) => setImmediate(r));
477 - }
479 - // Compute insights
480 - const longSessionIds = new Set<string>();
481 - for (const [id, span] of globalSessionSpans) {
482 - if (span.endMs - span.startMs >= LONG_SESSION_MS) longSessionIds.add(id);
483 - }
484 - for (const period of TAB_ORDER)
485 - data[period].insights = computeInsights(
486 - rawByPeriod[period],
487 - longSessionIds,
488 - );
490 - return data;
493 -// ── Insights ───────────────────────────────────────────────────────────────
495 -const PARALLEL_WINDOW_MS = 2 * 60_000;
496 -const PARALLEL_THRESHOLD = 4;
497 -const LARGE_CONTEXT = 150_000;
498 -const LARGE_UNCACHED = 100_000;
499 -const LONG_SESSION_MS = 8 * 60 * 60 * 1000;
500 -const TOP_N = 5;
501 -const MIN_MSG_PARALLEL = 10;
503 -function computeInsights(
504 - raw: PeriodRawData,
505 - longSessionIds: Set<string>,
506 -): PeriodInsights {
507 - if (!raw.messages.length) return { insights: [] };
508 - const total = raw.messages.reduce((s, m) => s + m.cost, 0);
509 - if (total <= 0) return { insights: [] };
511 - const candidates: Insight[] = [];
513 - // Parallel
514 - const timed = raw.messages.filter((m) => m.timestamp > 0);
515 - if (
516 - timed.length >= MIN_MSG_PARALLEL &&
517 - new Set(timed.map((m) => m.sessionId)).size >= PARALLEL_THRESHOLD
518 - ) {
519 - const sorted = timed.slice().sort((a, b) => a.timestamp - b.timestamp);
520 - const sidCount = new Map<string, number>();
521 - let unique = 0,
522 - left = 0,
523 - right = 0,
524 - parallelCost = 0;
525 - for (const cur of sorted) {
526 - while (
527 - right < sorted.length &&
528 - sorted[right]?.timestamp <= cur.timestamp + PARALLEL_WINDOW_MS
529 - ) {
530 - const sid = sorted[right]?.sessionId;
531 - const n = (sidCount.get(sid) ?? 0) + 1;
532 - sidCount.set(sid, n);
533 - if (n === 1) unique++;
534 - right++;
535 - }
536 - while (
537 - left < right &&
538 - sorted[left]?.timestamp < cur.timestamp - PARALLEL_WINDOW_MS
539 - ) {
540 - const sid = sorted[left]?.sessionId;
541 - const n = (sidCount.get(sid) ?? 0) - 1;
542 - if (!n) {
543 - sidCount.delete(sid);
544 - unique--;
545 - } else sidCount.set(sid, n);
546 - left++;
547 - }
548 - if (unique >= PARALLEL_THRESHOLD) parallelCost += cur.cost;
549 - }
550 - if (parallelCost > 0)
551 - candidates.push({
552 - percent: (parallelCost / total) * 100,
553 - headline: `of cost was while ${PARALLEL_THRESHOLD}+ sessions ran in parallel`,
554 - advice: "Queueing sessions uses capacity more evenly.",
555 - });
556 - }
558 - // Large context
559 - const largeCtxW = raw.messages
560 - .filter((m) => m.input + m.cacheRead + m.cacheWrite > LARGE_CONTEXT)
561 - .reduce((s, m) => s + m.cost, 0);
562 - if (largeCtxW > 0)
563 - candidates.push({
564 - percent: (largeCtxW / total) * 100,
565 - headline: `of cost was at >${Math.round(LARGE_CONTEXT / 1000)}k context`,
566 - advice: "/compact mid-task, /clear when switching tasks.",
567 - });
569 - // Uncached
570 - const uncachedW = raw.messages
571 - .filter((m) => m.input + m.cacheWrite > LARGE_UNCACHED)
572 - .reduce((s, m) => s + m.cost, 0);
573 - if (uncachedW > 0)
574 - candidates.push({
575 - percent: (uncachedW / total) * 100,
576 - headline: `of cost came from >${Math.round(LARGE_UNCACHED / 1000)}k-token uncached prompts`,
577 - advice: "/compact before stepping away keeps the cold-start small.",
578 - });
580 - // Long sessions
581 - const longW = raw.messages
582 - .filter((m) => longSessionIds.has(m.sessionId))
583 - .reduce((s, m) => s + m.cost, 0);
584 - if (longW > 0)
585 - candidates.push({
586 - percent: (longW / total) * 100,
587 - headline: `of cost came from ${Math.round(LONG_SESSION_MS / 3600_000)}h+ sessions`,
588 - advice: "Continuous usage can add up quickly.",
589 - });
591 - // Top-N
592 - if (raw.sessionCosts.size > TOP_N) {
593 - const sorted = Array.from(raw.sessionCosts.values()).sort((a, b) => b - a);
594 - const topW = sorted.slice(0, TOP_N).reduce((s, c) => s + c, 0);
595 - candidates.push({
596 - percent: (topW / total) * 100,
597 - headline: `of cost from top ${TOP_N} sessions`,
598 - advice: "A small number of sessions drives most spend.",
599 - });
600 - }
602 - return {
603 - insights: candidates
604 - .filter((i) => i.percent >= 1)
605 - .sort((a, b) => b.percent - a.percent),
606 - };
609 -// ── Formatting ─────────────────────────────────────────────────────────────
611 -function formatCost(c: number): string {
612 - if (c === 0) return "-";
613 - if (c < 0.01) return `$${c.toFixed(4)}`;
614 - if (c < 10) return `$${c.toFixed(2)}`;
615 - if (c < 100) return `$${c.toFixed(1)}`;
616 - return `$${Math.round(c)}`;
619 -function formatTokens(n: number): string {
620 - if (n === 0) return "-";
621 - if (n < 1_000) return n.toString();
622 - if (n < 10_000) return `${(n / 1_000).toFixed(1)}k`;
623 - if (n < 1_000_000) return `${Math.round(n / 1_000)}k`;
624 - if (n < 10_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
625 - return `${Math.round(n / 1_000_000)}M`;
628 -function formatNumber(n: number): string {
629 - return n === 0 ? "-" : n.toLocaleString();
632 -function padLeft(s: string, len: number): string {
633 - const v = visibleWidth(s);
634 - return v >= len ? s : " ".repeat(len - v) + s;
637 -function padRight(s: string, len: number): string {
638 - const v = visibleWidth(s);
639 - return v >= len ? s : s + " ".repeat(len - v);
642 -function fitCell(
643 - s: string,
644 - len: number,
645 - align: "left" | "right" = "left",
646 -): string {
647 - return align === "right"
648 - ? padLeft(truncateToWidth(s, len), len)
649 - : padRight(truncateToWidth(s, len), len);
652 -function pickFitting(w: number, variants: string[]): string {
653 - for (const v of variants) if (visibleWidth(v) <= w) return v;
654 - return variants[variants.length - 1] || "";
657 -function formatPct(p: number): string {
658 - return p >= 10 ? `${Math.round(p)}%` : `${Math.round(p * 10) / 10}%`;
661 -// ── Component ──────────────────────────────────────────────────────────────
663 -const TAB_LABELS: Record<TabName, string> = {
664 - today: "Today",
665 - thisWeek: "This Week",
666 - lastWeek: "Last Week",
667 - allTime: "All Time",
668 -};
670 -class UsageComponent {
671 - private activeTab: TabName = "allTime";
672 - private viewMode: ViewMode = "table";
673 - private data: UsageData;
674 - private selectedIndex = 0;
675 - private expanded = new Set<string>();
676 - private providerOrder: string[] = [];
677 - private theme: Theme;
678 - private requestRender: () => void;
679 - private done: () => void;
681 - constructor(
682 - theme: Theme,
683 - data: UsageData,
684 - requestRender: () => void,
685 - done: () => void,
686 - ) {
687 - this.theme = theme;
688 - this.data = data;
689 - this.requestRender = requestRender;
690 - this.done = done;
691 - this.updateProviderOrder();
692 - }
694 - private updateProviderOrder() {
695 - const stats = this.data[this.activeTab];
696 - this.providerOrder = Array.from(stats.providers.entries())
697 - .sort((a, b) => b[1].cost - a[1].cost)
698 - .map(([n]) => n);
699 - this.selectedIndex = Math.min(
700 - this.selectedIndex,
701 - Math.max(0, this.providerOrder.length - 1),
702 - );
703 - }
705 - handleInput(data: string): void {
706 - if (matchesKey(data, "escape") || matchesKey(data, "q")) {
707 - this.done();
708 - return;
709 - }
710 - if (matchesKey(data, "v")) {
711 - this.viewMode = this.viewMode === "table" ? "insights" : "table";
712 - this.requestRender();
713 - return;
714 - }
715 - if (matchesKey(data, "tab") || matchesKey(data, "right")) {
716 - const idx = TAB_ORDER.indexOf(this.activeTab);
717 - this.activeTab =
718 - TAB_ORDER[(idx + 1) % TAB_ORDER.length] ?? this.activeTab;
719 - this.updateProviderOrder();
720 - this.requestRender();
721 - } else if (matchesKey(data, "shift+tab") || matchesKey(data, "left")) {
722 - const idx = TAB_ORDER.indexOf(this.activeTab);
723 - this.activeTab =
724 - TAB_ORDER[(idx - 1 + TAB_ORDER.length) % TAB_ORDER.length] ??
725 - this.activeTab;
726 - this.updateProviderOrder();
727 - this.requestRender();
728 - } else if (this.viewMode === "table" && matchesKey(data, "up")) {
729 - if (this.selectedIndex > 0) {
730 - this.selectedIndex--;
731 - this.requestRender();
732 - }
733 - } else if (this.viewMode === "table" && matchesKey(data, "down")) {
734 - if (this.selectedIndex < this.providerOrder.length - 1) {
735 - this.selectedIndex++;
736 - this.requestRender();
737 - }
738 - } else if (
739 - this.viewMode === "table" &&
740 - (matchesKey(data, "enter") || matchesKey(data, "space"))
741 - ) {
742 - const p = this.providerOrder[this.selectedIndex];
743 - if (p) {
744 - this.expanded.has(p) ? this.expanded.delete(p) : this.expanded.add(p);
745 - this.requestRender();
746 - }
747 - }
748 - }
750 - render(width: number): string[] {
751 - return this.viewMode === "insights"
752 - ? this.renderInsightsView(width)
753 - : this.renderTableView(width);
754 - }
756 - private renderInsightsView(width: number): string[] {
757 - const th = this.theme;
758 - const stats = this.data[this.activeTab];
759 - const lines: string[] = [];
760 - lines.push(th.fg("accent", th.bold("Usage Insights")), "");
761 - lines.push(
762 - th.fg(
763 - "dim",
764 - `What's contributing to your cost? ${TAB_LABELS[this.activeTab]} · weighted by USD`,
765 - ),
766 - "",
767 - );
768 - if (!stats.totals.messages) {
769 - lines.push(th.fg("dim", " No usage for this period."), "");
770 - } else if (!stats.totals.cost) {
771 - lines.push(th.fg("dim", " No cost data."), "");
772 - } else if (!stats.insights.insights.length) {
773 - lines.push(th.fg("dim", " No insights above 1%."), "");
774 - } else {
775 - for (const insight of stats.insights.insights) {
776 - lines.push(
777 - `${th.fg("accent", th.bold(formatPct(insight.percent)))} ${insight.headline}`,
778 - );
779 - for (const w of wrapTextWithAnsi(
780 - insight.advice,
781 - Math.max(width - 5, 30),
782 - ))
783 - lines.push(` ${th.fg("dim", w)}`);
784 - lines.push("");
785 - }
786 - }
787 - lines.push(
788 - th.fg(
789 - "dim",
790 - pickFitting(width, [
791 - "[Tab/←→] period [v] table [q] close",
792 - "[q] close",
793 - ]),
794 - ),
795 - );
796 - return lines.map((l) => truncateToWidth(l, width));
797 - }
799 - private renderTableView(width: number): string[] {
800 - const th = this.theme;
801 - const stats = this.data[this.activeTab];
802 - const layout = getTableLayout(width);
803 - const lines: string[] = [];
805 - // Tabs
806 - const tabs = TAB_ORDER.map((t) =>
807 - t === this.activeTab
808 - ? th.fg("accent", `[${TAB_LABELS[t]}]`)
809 - : th.fg("dim", ` ${TAB_LABELS[t]} `),
810 - ).join(" ");
811 - lines.push(
812 - pickFitting(width, [
813 - tabs,
814 - th.fg("accent", `[${TAB_LABELS[this.activeTab]}]`),
815 - ]),
816 - );
817 - if (layout.compact)
818 - lines.push(
819 - ...wrapTextWithAnsi(
820 - th.fg("dim", "Compact view. Widen terminal for more columns."),
821 - Math.max(width, 1),
822 - ),
823 - );
824 - lines.push("");
826 - // Header
827 - let headerLine = fitCell("Provider / Model", layout.nameWidth);
828 - for (const col of layout.columns)
829 - headerLine += col.dimmed
830 - ? th.fg("dim", fitCell(col.label, col.width, "right"))
831 - : fitCell(col.label, col.width, "right");
832 - lines.push(th.fg("muted", headerLine));
833 - lines.push(th.fg("border", "─".repeat(layout.tableWidth)));
835 - // Rows
836 - if (!this.providerOrder.length) {
837 - lines.push(th.fg("dim", " No usage data"));
838 - }
839 - for (let i = 0; i < this.providerOrder.length; i++) {
840 - const name = this.providerOrder[i];
841 - if (!name) continue;
842 - const prov = stats.providers.get(name);
843 - if (!prov) continue;
844 - const sel = i === this.selectedIndex;
845 - const exp = this.expanded.has(name);
846 - const arrow = sel
847 - ? th.fg("accent", `${exp ? "▾" : "▸"} `)
848 - : th.fg("dim", `${exp ? "▾" : "▸"} `);
849 - lines.push(
850 - this.row(name, prov, layout, { prefix: arrow, selected: sel }),
851 - );
852 - if (exp) {
853 - for (const [mn, ms] of Array.from(prov.models.entries()).sort(
854 - (a, b) => b[1].cost - a[1].cost,
855 - )) {
856 - lines.push(this.row(mn, ms, layout, { indent: 4, dimAll: true }));
857 - }
858 - }
859 - }
861 - // Totals
862 - lines.push(th.fg("border", "─".repeat(layout.tableWidth)));
863 - let totalRow = fitCell(th.bold("Total"), layout.nameWidth);
864 - for (const col of layout.columns)
865 - totalRow += col.dimmed
866 - ? th.fg("dim", fitCell(col.getValue(stats.totals), col.width, "right"))
867 - : fitCell(col.getValue(stats.totals), col.width, "right");
868 - lines.push(totalRow);
869 - lines.push("");
871 - lines.push(
872 - th.fg(
873 - "dim",
874 - pickFitting(width, [
875 - "Tokens = In + Out + CacheWrite · ↑In = In + CacheWrite (v0.2.0+)",
876 - "Incl. CacheWrite (v0.2.0+)",
877 - ]),
878 - ),
879 - );
880 - lines.push(
881 - th.fg(
882 - "dim",
883 - pickFitting(width, [
884 - "[Tab/←→] period [↑↓] select [Enter] expand [v] insights [q] close",
885 - "[↑↓] select [v] insights [q] close",
886 - "[q] close",
887 - ]),
888 - ),
889 - );
890 - return lines.map((l) => truncateToWidth(l, width));
891 - }
893 - private row(
894 - name: string,
895 - stats: BaseStats & { sessions: Set<string> | number },
896 - layout: TableLayout,
897 - opts: {
898 - prefix?: string;
899 - indent?: number;
900 - selected?: boolean;
901 - dimAll?: boolean;
902 - } = {},
903 - ): string {
904 - const th = this.theme;
905 - const { indent = 0, selected = false, dimAll = false } = opts;
906 - const rawPrefix = opts.prefix ?? " ".repeat(indent);
907 - const prefixW = visibleWidth(truncateToWidth(rawPrefix, layout.nameWidth));
908 - const innerW = Math.max(layout.nameWidth - prefixW, 0);
909 - const truncName = innerW > 0 ? truncateToWidth(name, innerW) : "";
910 - const styledName = selected
911 - ? th.fg("accent", truncName)
912 - : dimAll
913 - ? th.fg("dim", truncName)
914 - : truncName;
915 - let row = rawPrefix + (innerW > 0 ? padRight(styledName, innerW) : "");
916 - for (const col of layout.columns) {
917 - const v = fitCell(col.getValue(stats), col.width, "right");
918 - row += col.dimmed || dimAll ? th.fg("dim", v) : v;
919 - }
920 - return row;
921 - }
923 - invalidate(): void {}
924 - dispose(): void {}
927 -// ── Extension ──────────────────────────────────────────────────────────────
929 -export default function (pi: ExtensionAPI) {
3 +export default function usageExtension(pi: ExtensionAPI): void {
930 4 pi.registerCommand("usage", {
931 5 description: "Show usage statistics dashboard",
932 - handler: async (_args: string, ctx: ExtensionCommandContext) => {
933 - if (!ctx.hasUI) return;
935 - const data = await ctx.ui.custom<UsageData | null>(
936 - (tui, theme, _kb, done) => {
937 - const loader = new CancellableLoader(
938 - tui,
939 - (s) => theme.fg("accent", s),
940 - (s) => theme.fg("muted", s),
941 - "Loading Usage...",
942 - );
943 - let finished = false;
944 - const finish = (v: UsageData | null) => {
945 - if (finished) return;
946 - finished = true;
947 - loader.dispose();
948 - done(v);
949 - };
950 - loader.onAbort = () => finish(null);
951 - collectUsageData(ctx.sessionManager.getSessionDir(), loader.signal)
952 - .then(finish)
953 - .catch(() => finish(null));
954 - return loader;
955 - },
956 - );
958 - if (!data) return;
960 - await ctx.ui.custom<void>((tui, theme, _kb, done) => {
961 - const container = new Container();
962 - container.addChild(new Spacer(1));
963 - container.addChild(
964 - new DynamicBorder((s: string) => theme.fg("border", s)),
965 - );
966 - container.addChild(new Spacer(1));
967 - const usage = new UsageComponent(
968 - theme,
969 - data,
970 - () => tui.requestRender(),
971 - () => done(),
972 - );
973 - return {
974 - render: (w: number) => {
975 - const border = container
976 - .render(w)
977 - .map((l) => truncateToWidth(l, w));
978 - return [
979 - ...border,
980 - ...usage.render(w),
981 - "",
982 - theme.fg("border", "─".repeat(w)),
983 - ].map((l) => truncateToWidth(l, w));
984 - },
985 - invalidate: () => container.invalidate(),
986 - handleInput: (input: string) => usage.handleInput(input),
987 - dispose: () => {},
988 - };
989 - });
990 - },
6 + handler: async (args, ctx) =>
7 + (await import("./implementation.js")).showUsage(args, ctx),

extensions/uv/__tests__/harness.test.ts

Modified
7 7 } from "node:fs";
8 8 import { tmpdir } from "node:os";
9 9 import { join } from "node:path";
10 -import { afterEach, describe, expect, it } from "vitest";
10 +import { afterEach, describe, expect, it, vi } from "vitest";
11 11 import { createTestSession, type TestSession } from "../../../test/harness";
12 12 import uvExtension, { __test } from "../index";
38 38 chmodSync(uv, 0o755);
41 + expect(await __test.uvInstalled({ PATH: fakeBin }, process.platform)).toBe(
42 + true,
43 + );
41 44 t = await createTestSession({
42 45 env: { PATH: fakeBin },
43 46 extensionFactories: [uvExtension],
53 56 extensionFactories: [uvExtension],
56 - expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
57 - "uv extension: uv not found on PATH",
58 - "warning",
59 - ]);
59 + await vi.waitFor(() =>
60 + expect(t?.events.uiCallsFor("notify").at(-1)?.args).toEqual([
61 + "uv extension: uv not found on PATH",
62 + "warning",
63 + ]),
64 + );
62 67 it("blocks pip-family commands with uv guidance", () => {

extensions/uv/index.ts

Modified
1 -import { accessSync, constants } from "node:fs";
1 +import { constants } from "node:fs";
2 +import { access } from "node:fs/promises";
2 3 import { delimiter, join } from "node:path";
3 4 import {
4 5 type BashSpawnContext,
11 12 "intercepted-commands",
14 -function uvInstalled(env = process.env, platform = process.platform): boolean {
15 +async function uvInstalled(
16 + env = process.env,
17 + platform = process.platform,
18 +): Promise<boolean> {
15 19 const names = platform === "win32" ? ["uv.exe", "uv.cmd", "uv.bat"] : ["uv"];
16 20 const mode = platform === "win32" ? constants.F_OK : constants.X_OK;
17 21 for (const directory of (env[pathEnvKey(env)] ?? "").split(delimiter)) {
18 22 for (const name of names) {
19 23 try {
20 - accessSync(join(directory.replace(/^"|"$/gu, ""), name), mode);
24 + await access(join(directory.replace(/^"|"$/gu, ""), name), mode);
21 25 return true;
22 26 } catch {}
122 126 export default function uvExtension(pi: ExtensionAPI) {
127 + let generation = 0;
123 129 pi.on("session_start", (_event, ctx) => {
124 - if (!uvInstalled() && ctx.hasUI) {
125 - ctx.ui.notify("uv extension: uv not found on PATH", "warning");
126 - }
130 + const ticket = ++generation;
131 + void uvInstalled().then((installed) => {
132 + if (ticket === generation && !installed && ctx.hasUI)
133 + ctx.ui.notify("uv extension: uv not found on PATH", "warning");
134 + });
135 + });
136 + pi.on("session_shutdown", () => {
137 + generation++;
129 140 pi.registerTool(

extensions/vcs-status/__tests__/vcs.test.ts

Modified
13 13 "# branch.head main",
14 14 "# branch.ab +2 -1",
15 + "# stash 1",
15 16 "1 M. N... 100644 100644 100644 a a file.ts",
16 17 "? new.ts",
17 18 ].join("\n"),
18 - true,
21 21 expect(__test.gitLabel(status)).toBe("main [$+?⇕]");

extensions/vcs-status/index.ts

Modified
211 -function parsePorcelain(stdout: string, hasStash: boolean): GitStatus {
211 +function parsePorcelain(stdout: string, hasStash = false): GitStatus {
212 212 const s = emptyGitStatus();
213 213 s.stashed = hasStash;
228 228 continue;
230 + if (line.startsWith("# stash ")) {
231 + s.stashed = Number(line.slice("# stash ".length).trim()) > 0;
232 + continue;
230 234 if (line.startsWith("#")) continue;
231 235 if (line.startsWith("? ")) {
232 236 s.untracked++;
252 256 async function readGitStatus(cwd: string, gitDir: string): Promise<GitStatus> {
253 257 const headBranch = await gitBranchFromHead(gitDir);
255 - const [{ stdout }, stash] = await Promise.all([
256 - execFileAsync("git", ["status", "--porcelain=2", "--branch"], {
259 + const { stdout } = await execFileAsync(
260 + "git",
261 + ["status", "--porcelain=2", "--branch", "--show-stash"],
258 264 timeout: COMMAND_TIMEOUT_MS,
259 - }),
260 - execFileAsync("git", ["rev-parse", "--verify", "--quiet", "refs/stash"], {
261 - cwd,
262 - timeout: COMMAND_TIMEOUT_MS,
263 - }).catch(() => ({ stdout: "" })),
264 - ]);
265 + },
266 + );
265 267 const status = parsePorcelain(
266 268 typeof stdout === "string" ? stdout : String(stdout),
267 - String(stash.stdout).trim().length > 0,
269 270 status.branch = headBranch ?? status.branch;
270 271 return status;

extensions/web/__tests__/web-fetch-contract.test.ts

Modified
182 182 extensionFactories: [webExtension],
183 183 env: pathEnv(emptyDir),
185 - await new Promise((resolve) => setTimeout(resolve, 0));
187 - const notify = t.events.uiCallsFor("notify");
188 - const calls = notify.map((call) => call.args);
189 - expect(calls).toEqual(
190 - expect.arrayContaining([
191 - expect.arrayContaining([expect.stringContaining("pandoc"), "warning"]),
185 + await vi.waitFor(() => {
186 + const calls = t?.events.uiCallsFor("notify").map((call) => call.args);
187 + expect(calls).toEqual(
192 188 expect.arrayContaining([
193 - expect.stringContaining("pdftotext"),
194 - "warning",
189 + expect.arrayContaining([
190 + expect.stringContaining("pandoc"),
191 + "warning",
192 + ]),
193 + expect.arrayContaining([
194 + expect.stringContaining("pdftotext"),
195 + "warning",
196 + ]),
196 - ]),
197 - );
198 - expect(calls).not.toEqual(
199 - expect.arrayContaining([
200 - expect.arrayContaining([expect.stringContaining("identify"), "info"]),
201 - expect.arrayContaining([expect.stringContaining("ffprobe"), "info"]),
202 - ]),
203 - );
198 + );
199 + expect(calls).not.toEqual(
200 + expect.arrayContaining([
201 + expect.arrayContaining([expect.stringContaining("identify"), "info"]),
202 + expect.arrayContaining([expect.stringContaining("ffprobe"), "info"]),
203 + ]),
204 + );
205 + });
206 208 it("throws search failures without duplicate notify", async () => {

extensions/web/index.ts

Modified
409 409 async function notifyMissingPlatformTools(
410 410 ctx: ExtensionContext,
411 + isCurrent: () => boolean,
411 412 ): Promise<void> {
412 413 if (!ctx.hasUI) return;
413 - for (const dep of PLATFORM_TOOL_DEPENDENCIES) {
414 - const hint = await checkToolAvailability(dep.cmd, dep.hint);
415 - if (hint) ctx.ui.notify(`web: ${dep.purpose}. ${hint}`, dep.level);
414 + const hints = await Promise.all(
415 + PLATFORM_TOOL_DEPENDENCIES.map(async (dep) => ({
416 + dep,
417 + hint: await checkToolAvailability(dep.cmd, dep.hint),
418 + })),
419 + );
420 + if (!isCurrent()) return;
421 + try {
422 + for (const { dep, hint } of hints)
423 + if (hint) ctx.ui.notify(`web: ${dep.purpose}. ${hint}`, dep.level);
424 + } catch (error) {
425 + if (
426 + !(error instanceof Error) ||
427 + !error.message.includes(
428 + "ctx is stale after session replacement or reload",
431 + throw error;
741 757 export default function webExtension(pi: ExtensionAPI) {
742 758 // ── Session-scoped spotlight markers ───────────────────────────────────
743 759 const spotlightMarkers: SpotlightMarkers = createMarkers();
760 + let generation = 0;
745 - pi.on("session_start", async (_event, ctx) => {
746 - await notifyMissingPlatformTools(ctx);
762 + pi.on("session_start", (_event, ctx) => {
763 + const ticket = ++generation;
764 + void notifyMissingPlatformTools(ctx, () => ticket === generation).catch(
765 + (error) => console.error("web platform tool check failed:", error),
766 + );
749 769 // ── Cleanup temp files on session shutdown ─────────────────────────────
751 771 pi.on("session_shutdown", async () => {
752 - for (const dir of tempDirs) {
753 - await rm(dir, { recursive: true, force: true }).catch(() => {});
772 + generation++;
773 + const ownedDirs = [...tempDirs];
755 774 tempDirs.clear();
775 + await Promise.all(
776 + ownedDirs.map((dir) =>
777 + rm(dir, { recursive: true, force: true }).catch(() => {}),
778 + ),
779 + );
758 782 // ── web_fetch ──────────────────────────────────────────────────────────