pi-usage-hub 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ import type { UsageProvider, UsageReport } from "../types";
2
+
3
+ export function bar(pct: number, width = 24): string {
4
+ const filled = Math.round((pct / 100) * width);
5
+ const empty = width - filled;
6
+ const color = pct < 70 ? "32" : pct < 90 ? "33" : "31";
7
+ const blocks = "\u2588".repeat(filled) + "\u2591".repeat(empty);
8
+ return `\x1b[${color}m${blocks}\x1b[0m`;
9
+ }
10
+
11
+ export function shortReport(report: UsageReport, provider: UsageProvider): string {
12
+ if (report.error) {
13
+ const authError = /not logged in|session expired/i.test(report.error);
14
+ return `${provider.shortLabel} ${authError ? "login required" : "error"}`;
15
+ }
16
+ if (report.displayText) return `${provider.shortLabel} ${report.displayText}`;
17
+
18
+ const primary = report.session ?? report.weekly ?? report.monthly;
19
+ if (!primary) return provider.shortLabel;
20
+
21
+ const resetStr = primary.resetsIn ? ` · ↻ ${primary.resetsIn}` : "";
22
+ let text = `${primary.pct.toFixed(0)}%${resetStr}`;
23
+
24
+ const secondary: string[] = [];
25
+ if (report.session != null) {
26
+ if (report.weekly != null) secondary.push(`W${report.weekly.pct.toFixed(0)}%`);
27
+ if (report.monthly != null) secondary.push(`M${report.monthly.pct.toFixed(0)}%`);
28
+ } else if (report.weekly != null && report.monthly != null) {
29
+ secondary.push(`M${report.monthly.pct.toFixed(0)}%`);
30
+ }
31
+ if (secondary.length > 0) text += ` / ${secondary.join(" ")}`;
32
+
33
+ return `${provider.shortLabel} ${text}`;
34
+ }
35
+
36
+ export function fullReport(report: UsageReport, provider: UsageProvider): string {
37
+ const lines: string[] = [];
38
+ lines.push(`\x1b[1m${provider.label}\x1b[0m`);
39
+
40
+ if (report.displayText) {
41
+ const match = report.displayText.match(/[\d,.]+/);
42
+ const amount = match ? parseFloat(match[0].replace(/,/g, "")) : 0;
43
+ const color = amount >= 20 ? "32" : amount >= 10 ? "33" : "31";
44
+ lines.push(` Balance: \x1b[${color}m${report.displayText}\x1b[0m`);
45
+ return lines.join("\n");
46
+ }
47
+
48
+ if (report.error) {
49
+ lines.push(` \x1b[31m\u2716 ${report.error}\x1b[0m`);
50
+ return lines.join("\n");
51
+ }
52
+
53
+ if (report.session) {
54
+ const r = report.session.resetsIn ? ` \u23F1 ${report.session.resetsIn}` : "";
55
+ lines.push(` Rolling: ${bar(report.session.pct)} ${report.session.pct.toFixed(1)}%${r}`);
56
+ }
57
+ if (report.weekly) {
58
+ const r = report.weekly.resetsIn ? ` \u23F1 ${report.weekly.resetsIn}` : "";
59
+ lines.push(` Weekly: ${bar(report.weekly.pct)} ${report.weekly.pct.toFixed(1)}%${r}`);
60
+ }
61
+ if (report.monthly) {
62
+ const r = report.monthly.resetsIn ? ` \u23F1 ${report.monthly.resetsIn}` : "";
63
+ lines.push(` Monthly: ${bar(report.monthly.pct)} ${report.monthly.pct.toFixed(1)}%${r}`);
64
+ }
65
+
66
+ return lines.join("\n");
67
+ }
package/ui/format.ts ADDED
@@ -0,0 +1,92 @@
1
+ // Shared display/formatting helpers used by the usage overlay and its panels.
2
+
3
+ const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
4
+
5
+ export function visibleWidth(text: string): number {
6
+ return text.replace(ANSI_RE, "").length;
7
+ }
8
+
9
+ export function truncateToWidth(text: string, width: number): string {
10
+ let out = "";
11
+ let used = 0;
12
+ for (let i = 0; i < text.length; ) {
13
+ if (text[i] === "\x1b") {
14
+ const match = text.slice(i).match(/^\x1b\[[0-?]*[ -/]*[@-~]/);
15
+ if (match) {
16
+ out += match[0];
17
+ i += match[0].length;
18
+ continue;
19
+ }
20
+ }
21
+ const char = text[i]!;
22
+ if (used + 1 > width) break;
23
+ out += char;
24
+ used++;
25
+ i++;
26
+ }
27
+ return out;
28
+ }
29
+
30
+ function matchesKittyKey(data: string, codepoint: number, modifier = 0): boolean {
31
+ const match = data.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?(?:;(\d+))?(?::\d+)?u$/);
32
+ if (!match) return false;
33
+ const keyCodepoint = Number(match[1]);
34
+ const keyModifier = Number(match[2] ?? "1") - 1;
35
+ return keyCodepoint === codepoint && keyModifier === modifier;
36
+ }
37
+
38
+ function matchesModifyOtherKey(data: string, codepoint: number, modifier = 0): boolean {
39
+ const match = data.match(/^\x1b\[27;(\d+);(\d+)~$/);
40
+ if (!match) return false;
41
+ const keyModifier = Number(match[1]) - 1;
42
+ const keyCodepoint = Number(match[2]);
43
+ return keyCodepoint === codepoint && keyModifier === modifier;
44
+ }
45
+
46
+ export function isCloseKey(data: string): boolean {
47
+ return data === "\x1b"
48
+ || data === "\x03"
49
+ || data === "q"
50
+ || data === "Q"
51
+ || matchesKittyKey(data, 27)
52
+ || matchesModifyOtherKey(data, 27)
53
+ || matchesKittyKey(data, 113)
54
+ || matchesKittyKey(data, 81)
55
+ || matchesKittyKey(data, 99, 4)
56
+ || matchesModifyOtherKey(data, 99, 4);
57
+ }
58
+
59
+ export function formatMoney(value: number): string {
60
+ if (value === 0) return "$0";
61
+ if (value < 0.01) return `$${value.toFixed(4)}`;
62
+ if (value < 10) return `$${value.toFixed(2)}`;
63
+ if (value < 100) return `$${value.toFixed(1)}`;
64
+ return `$${Math.round(value)}`;
65
+ }
66
+
67
+ export function formatTokens(value: number): string {
68
+ if (value === 0) return "-";
69
+ if (value < 1000) return String(value);
70
+ if (value < 10_000) return `${(value / 1000).toFixed(1)}k`;
71
+ if (value < 1_000_000) return `${Math.round(value / 1000)}k`;
72
+ if (value < 10_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
73
+ return `${Math.round(value / 1_000_000)}M`;
74
+ }
75
+
76
+ export function formatNumber(value: number): string {
77
+ return value === 0 ? "-" : value.toLocaleString();
78
+ }
79
+
80
+ export function clip(s: string, w: number): string {
81
+ return s.length > w ? `${s.slice(0, w - 1)}…` : s;
82
+ }
83
+
84
+ export function padR(s: string, w: number): string {
85
+ const c = clip(s, w);
86
+ return c + " ".repeat(Math.max(0, w - c.length));
87
+ }
88
+
89
+ export function padL(s: string, w: number): string {
90
+ const c = clip(s, w);
91
+ return " ".repeat(Math.max(0, w - c.length)) + c;
92
+ }
@@ -0,0 +1,178 @@
1
+ // Session usage panel: local session-history stats with period/provider
2
+ // navigation and per-provider model breakdown. Owns all session-tab state,
3
+ // input handling, and rendering so index.ts only wires it into the overlay.
4
+
5
+ import type { Theme } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ collectSessionUsage,
8
+ type ProviderSessionUsage,
9
+ type SessionUsagePeriod,
10
+ type SessionUsageSummary,
11
+ } from "../session/collect";
12
+ import { formatMoney, formatNumber, formatTokens, padL, padR } from "./format";
13
+
14
+ const PERIODS: { key: keyof SessionUsageSummary; label: string }[] = [
15
+ { key: "today", label: "Today" },
16
+ { key: "thisWeek", label: "This Week" },
17
+ { key: "thisMonth", label: "This Month" },
18
+ { key: "allTime", label: "All Time" },
19
+ ];
20
+
21
+ const MAX_PROVIDERS = 5;
22
+
23
+ // Column widths shared by period, provider and model rows.
24
+ const nameW = 18;
25
+ const costW = 7;
26
+ const tokW = 8;
27
+ const inW = 8;
28
+ const outW = 7;
29
+ const cacheW = 8;
30
+ const msgW = 7;
31
+ const sesW = 5;
32
+
33
+ // Model rows are indented 3 extra spaces, so their name field is narrower to
34
+ // keep every numeric column aligned with the provider rows above.
35
+ // Column order: Name Sessions Msgs ↑In ↓Out Cache Tokens Cost
36
+ function cols(n: string, s: string, m: string, i: string, o: string, ca: string, t: string, c: string, nw = nameW): string {
37
+ return `${padR(n, nw)}${padL(s, sesW)}${padL(m, msgW)}${padL(i, inW)}${padL(o, outW)}${padL(ca, cacheW)}${padL(t, tokW)}${padL(c, costW)}`;
38
+ }
39
+
40
+ function statCols(name: string, t: { sessions: number; messages: number; cost: number; tokens: { total: number; input: number; output: number; cacheRead: number; cacheWrite: number } }, nw = nameW): string {
41
+ return cols(
42
+ name,
43
+ formatNumber(t.sessions),
44
+ formatNumber(t.messages),
45
+ formatTokens(t.tokens.input + t.tokens.cacheWrite),
46
+ formatTokens(t.tokens.output),
47
+ formatTokens(t.tokens.cacheRead + t.tokens.cacheWrite),
48
+ formatTokens(t.tokens.total),
49
+ formatMoney(t.cost),
50
+ nw,
51
+ );
52
+ }
53
+
54
+ export class SessionPanel {
55
+ private loading = false;
56
+ private usage: SessionUsageSummary | null = null;
57
+ private error = "";
58
+ private load: Promise<void> | null = null;
59
+ private periodIndex = 0;
60
+ private providerIndex = 0;
61
+ private expanded = new Set<string>();
62
+
63
+ constructor(private requestRender: () => void) {}
64
+
65
+ ensureLoaded(): void {
66
+ if (this.usage || this.load) return;
67
+ this.loading = true;
68
+ this.error = "";
69
+ this.load = collectSessionUsage()
70
+ .then(usage => {
71
+ this.usage = usage;
72
+ })
73
+ .catch(err => {
74
+ this.error = err?.message ?? String(err);
75
+ })
76
+ .finally(() => {
77
+ this.loading = false;
78
+ this.load = null;
79
+ this.requestRender();
80
+ });
81
+ }
82
+
83
+ /** Handle a key. Returns true if the panel consumed it. */
84
+ handleInput(data: string): boolean {
85
+ // Left/right: switch period tab
86
+ if (data === "\x1b[C" || data === "\x1b[D") {
87
+ const delta = data === "\x1b[C" ? 1 : -1;
88
+ this.periodIndex = (this.periodIndex + delta + PERIODS.length) % PERIODS.length;
89
+ this.providerIndex = 0;
90
+ this.expanded.clear();
91
+ this.requestRender();
92
+ return true;
93
+ }
94
+
95
+ // Up/down: navigate provider rows
96
+ if (data === "\x1b[A" || data === "\x1b[B") {
97
+ const delta = data === "\x1b[A" ? -1 : 1;
98
+ const n = this.providers().length;
99
+ if (n > 0) this.providerIndex = (this.providerIndex + delta + n) % n;
100
+ this.requestRender();
101
+ return true;
102
+ }
103
+
104
+ // Space/Enter: expand selected provider
105
+ if (data === " " || data === "\r") {
106
+ const name = this.providers()[this.providerIndex]?.provider;
107
+ if (name) {
108
+ if (this.expanded.has(name)) this.expanded.delete(name);
109
+ else this.expanded.add(name);
110
+ this.requestRender();
111
+ }
112
+ return true;
113
+ }
114
+
115
+ return false;
116
+ }
117
+
118
+ private currentPeriod(): SessionUsagePeriod | null {
119
+ return this.usage ? this.usage[PERIODS[this.periodIndex]!.key] : null;
120
+ }
121
+
122
+ private providers(): ProviderSessionUsage[] {
123
+ return this.currentPeriod()?.providers.slice(0, MAX_PROVIDERS) ?? [];
124
+ }
125
+
126
+ render(theme: Theme): string[] {
127
+ const th = theme;
128
+ if (this.loading) return [` ${th.fg("muted", "Loading local session usage...")}`];
129
+ if (this.error) return [` ${th.fg("warning", this.error)}`];
130
+ if (!this.usage) return [` ${th.fg("muted", "Loading...")}`];
131
+
132
+ const lines: string[] = [];
133
+
134
+ // ── Period tab bar (2nd-level, row 1) ──
135
+ const tabParts = PERIODS.map(({ label }, i) => {
136
+ const selected = i === this.periodIndex;
137
+ return selected
138
+ ? th.fg("accent", `[${label}]`)
139
+ : th.fg("dim", ` ${label} `);
140
+ });
141
+ lines.push(` ${tabParts.join(th.fg("borderMuted", "│"))}`);
142
+ lines.push(th.fg("borderMuted", " " + "─".repeat(72)));
143
+
144
+ // ── Provider table (always MAX_PROVIDERS rows tall for fixed height) ──
145
+ const providers = this.providers();
146
+ lines.push(th.fg("muted", ` ${cols("Provider", "Sess", "Msgs", "↑In", "↓Out", "Cache", "Tokens", "Cost")}`));
147
+
148
+ for (let i = 0; i < MAX_PROVIDERS; i++) {
149
+ const p = providers[i];
150
+ if (!p) {
151
+ lines.push(""); // empty row to hold fixed height
152
+ continue;
153
+ }
154
+ const selected = i === this.providerIndex;
155
+ const isExpanded = this.expanded.has(p.provider);
156
+ const prefix = selected ? (isExpanded ? " ▾ " : " ▸ ") : " ";
157
+ const text = `${prefix}${statCols(p.provider, p)}`;
158
+ lines.push(selected ? th.fg("accent", text) : th.fg("dim", text));
159
+
160
+ if (isExpanded) {
161
+ for (const m of p.models) {
162
+ lines.push(th.fg("dim", ` └ ${statCols(m.model, m, nameW - 2)}`));
163
+ }
164
+ }
165
+ }
166
+
167
+ // ── Period summary (single row) at bottom ──
168
+ const period = PERIODS[this.periodIndex]!;
169
+ const totals = this.usage[period.key].totals;
170
+ lines.push("");
171
+ lines.push(th.fg("borderMuted", " " + "─".repeat(72)));
172
+ lines.push(th.fg("accent", ` ${statCols("Total:", totals)}`));
173
+
174
+ lines.push("");
175
+ lines.push(` ${th.fg("dim", `←→ period · ↑↓ provider · Space expand · Tab switch · Esc close`)}`);
176
+ return lines;
177
+ }
178
+ }
@@ -0,0 +1,132 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import type { UsageProvider, UsageReport } from "../types";
3
+ import { fullReport } from "./format-report";
4
+ import { SessionPanel } from "./session-panel";
5
+ import { isCloseKey, truncateToWidth, visibleWidth } from "./format";
6
+
7
+ export class UsageWindow {
8
+ private mode: "quota" | "session";
9
+ private loading = true;
10
+ /** Fixed display order (config/registry order). */
11
+ private orderedProviders: UsageProvider[] = [];
12
+ private reports = new Map<UsageProvider, UsageReport>();
13
+ private message = "Fetching usage data...";
14
+ private session: SessionPanel;
15
+
16
+ constructor(
17
+ private theme: Theme,
18
+ private done: () => void,
19
+ private requestRender: () => void,
20
+ private unsubscribeInput?: () => void,
21
+ initialMode: "quota" | "session" = "quota",
22
+ private ensureQuotaLoaded?: () => void,
23
+ ) {
24
+ this.mode = initialMode;
25
+ this.session = new SessionPanel(requestRender);
26
+ if (initialMode === "session") this.session.ensureLoaded();
27
+ }
28
+
29
+ setPendingProviders(pendingProviders: UsageProvider[]): void {
30
+ this.orderedProviders = pendingProviders;
31
+ this.reports.clear();
32
+ this.message = "";
33
+ this.invalidate();
34
+ }
35
+
36
+ addReport(provider: UsageProvider, report: UsageReport): void {
37
+ this.reports.set(provider, report);
38
+ this.invalidate();
39
+ }
40
+
41
+ finishLoading(): void {
42
+ this.loading = false;
43
+ this.message = this.reports.size === 0 ? "No supported usage provider detected" : "";
44
+ this.invalidate();
45
+ }
46
+
47
+ setError(error: string): void {
48
+ this.loading = false;
49
+ this.orderedProviders = [];
50
+ this.reports.clear();
51
+ this.message = error;
52
+ this.invalidate();
53
+ }
54
+
55
+ handleInput(data: string): void {
56
+ if (isCloseKey(data)) {
57
+ this.done();
58
+ return;
59
+ }
60
+ if (data === "\t") {
61
+ this.mode = this.mode === "quota" ? "session" : "quota";
62
+ if (this.mode === "session") this.session.ensureLoaded();
63
+ if (this.mode === "quota") this.ensureQuotaLoaded?.();
64
+ this.requestRender();
65
+ return;
66
+ }
67
+ if (this.mode === "session") this.session.handleInput(data);
68
+ }
69
+
70
+ render(width: number): string[] {
71
+ const w = Math.max(32, width);
72
+ const innerW = Math.max(1, w - 2);
73
+ const bodyW = Math.max(1, innerW - 2);
74
+ const th = this.theme;
75
+
76
+ const pad = (s: string) => s + " ".repeat(Math.max(0, bodyW - visibleWidth(s)));
77
+ const row = (content = "") =>
78
+ th.fg("border", "│") + " " + pad(truncateToWidth(content, bodyW)) + " " + th.fg("border", "│");
79
+
80
+ const active = this.mode === "quota"
81
+ ? `${th.fg("accent", "[Quota]")} ${th.fg("dim", "[Session]")}`
82
+ : `${th.fg("dim", "[Quota]")} ${th.fg("accent", "[Session]")}`;
83
+ const content = this.mode === "quota" ? this.renderQuotaLines() : this.session.render(th);
84
+
85
+ const lines: string[] = [];
86
+ lines.push(th.fg("border", `╭${"─".repeat(innerW)}╮`));
87
+ lines.push(row(` ${th.fg("accent", th.bold("Estimated Usage"))} ${active}`));
88
+ lines.push(row(th.fg("borderMuted", "─".repeat(innerW))));
89
+ for (const line of content) lines.push(row(line));
90
+ if (this.mode === "quota") {
91
+ lines.push(row());
92
+ lines.push(row(` ${th.fg("dim", "←→/u switch view · Esc/q close")}`));
93
+ }
94
+ lines.push(th.fg("border", `╰${"─".repeat(innerW)}╯`));
95
+ return lines;
96
+ }
97
+
98
+ private renderQuotaLines(): string[] {
99
+ const th = this.theme;
100
+ const lines: string[] = [];
101
+
102
+ if (this.message) {
103
+ const text = this.message.startsWith("No ")
104
+ ? th.fg("muted", this.message)
105
+ : th.fg("warning", this.message);
106
+ lines.push(` ${text}`);
107
+ }
108
+
109
+ for (let i = 0; i < this.orderedProviders.length; i++) {
110
+ if (i > 0) lines.push("");
111
+ const provider = this.orderedProviders[i]!;
112
+ const report = this.reports.get(provider);
113
+ if (report) {
114
+ for (const line of fullReport(report, provider).split("\n")) {
115
+ lines.push(` ${line}`);
116
+ }
117
+ } else {
118
+ lines.push(` ${th.fg("accent", th.bold(provider.label))}`);
119
+ lines.push(` ${th.fg("muted", "Loading...")}`);
120
+ }
121
+ }
122
+
123
+ return lines;
124
+ }
125
+
126
+ invalidate(): void {}
127
+
128
+ dispose(): void {
129
+ this.unsubscribeInput?.();
130
+ this.unsubscribeInput = undefined;
131
+ }
132
+ }
@@ -0,0 +1,96 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { copyFileSync, existsSync, unlinkSync, mkdtempSync } from "node:fs";
3
+ import { pbkdf2Sync, createDecipheriv } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+
7
+ const CHROME_COOKIE_DB = join(
8
+ process.env.HOME ?? "~",
9
+ "Library",
10
+ "Application Support",
11
+ "Google",
12
+ "Chrome",
13
+ "Default",
14
+ "Cookies",
15
+ );
16
+ const CHROME_EPOCH_OFFSET = 11_644_473_600;
17
+
18
+ export interface CookieRow {
19
+ hostKey: string;
20
+ name: string;
21
+ value: string;
22
+ }
23
+
24
+ let cachedKey: Buffer | null = null;
25
+
26
+ function getChromeKey(): Buffer {
27
+ if (cachedKey) return cachedKey;
28
+ const password = execFileSync("security", [
29
+ "find-generic-password", "-w", "-s", "Chrome Safe Storage",
30
+ ], { encoding: "utf8", timeout: 5000 }).trim();
31
+ cachedKey = pbkdf2Sync(Buffer.from(password), "saltysalt", 1003, 16, "sha1");
32
+ return cachedKey;
33
+ }
34
+
35
+ function decryptCookie(blob: Buffer, key: Buffer): string | null {
36
+ if (!blob.subarray(0, 3).equals(Buffer.from("v10"))) {
37
+ try { return blob.toString("utf-8"); } catch { return null; }
38
+ }
39
+ const ct = blob.subarray(3);
40
+ const iv = Buffer.alloc(16, 0x20);
41
+ try {
42
+ const decipher = createDecipheriv("aes-128-cbc", key, iv);
43
+ const plain = Buffer.concat([decipher.update(ct), decipher.final()]);
44
+ return plain.subarray(32).toString("utf-8");
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /** Read cookies from Chrome for domains matching `likePattern` (SQL LIKE). macOS only. */
51
+ export function readChromeCookies(likePattern: string, validDomains: string[]): CookieRow[] {
52
+ if (process.platform !== "darwin") return [];
53
+ if (!existsSync(CHROME_COOKIE_DB)) return [];
54
+
55
+ const tmpDir = mkdtempSync(join(tmpdir(), "pi-cookies-"));
56
+ const tmpDb = join(tmpDir, "Cookies");
57
+ try {
58
+ copyFileSync(CHROME_COOKIE_DB, tmpDb);
59
+ } catch {
60
+ return [];
61
+ }
62
+
63
+ const key = getChromeKey();
64
+ const nowChrome = (Date.now() / 1000 + CHROME_EPOCH_OFFSET) * 1_000_000;
65
+
66
+ try {
67
+ const stdout = execFileSync("sqlite3", [
68
+ "-separator", "|",
69
+ "-noheader",
70
+ tmpDb,
71
+ `SELECT host_key, name, hex(encrypted_value), expires_utc\n FROM cookies WHERE host_key LIKE '${likePattern.replace(/'/g, "''")}'`,
72
+ ], { encoding: "utf8", timeout: 5000 });
73
+
74
+ const rows: CookieRow[] = [];
75
+ for (const line of stdout.trim().split("\n")) {
76
+ if (!line) continue;
77
+ const [hostKey, name, encHex, expiresUtcStr] = line.split("|");
78
+ const expiresUtc = Number(expiresUtcStr);
79
+ if (!hostKey || !name || !encHex) continue;
80
+ if (expiresUtc && expiresUtc < nowChrome) continue;
81
+ if (!validDomains.includes(hostKey)) continue;
82
+
83
+ const value = decryptCookie(Buffer.from(encHex, "hex"), key);
84
+ if (value == null) continue;
85
+
86
+ try { Buffer.from(value, "latin1"); } catch { continue; }
87
+
88
+ rows.push({ hostKey, name, value });
89
+ }
90
+ return rows;
91
+ } catch {
92
+ return [];
93
+ } finally {
94
+ try { unlinkSync(tmpDb); } catch { /* ignore */ }
95
+ }
96
+ }
@@ -0,0 +1,17 @@
1
+ /** Format a positive duration in seconds as a short human string. */
2
+ export function formatDurationSeconds(seconds: number): string {
3
+ if (!Number.isFinite(seconds) || seconds <= 0) return "now";
4
+ const d = Math.floor(seconds / 86400);
5
+ const h = Math.floor((seconds % 86400) / 3600);
6
+ const m = Math.floor((seconds % 3600) / 60);
7
+ if (d > 0 && h > 0) return `${d}d ${h}h`;
8
+ if (d > 0) return `${d}d`;
9
+ if (h > 0 && m > 0) return `${h}h ${m}m`;
10
+ if (h > 0) return `${h}h`;
11
+ if (m > 0) return `${m}m`;
12
+ return "<1m";
13
+ }
14
+
15
+ export function formatDurationMs(ms: number): string {
16
+ return formatDurationSeconds(ms / 1000);
17
+ }