From 50740b4d08e3338b0f64d8c1eee3466e42b7343b Mon Sep 17 00:00:00 2001 From: catShark <1716967236@qq.com> Date: Wed, 18 Nov 2026 14:46:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20/usage=20=E7=94=A8=E9=87=8F=E9=9D=A2?= =?UTF-8?q?=E6=9D=BF=E4=B8=AD=E6=96=87=E5=8C=96=EF=BC=88=E4=B8=8A=E6=B8=B8?= =?UTF-8?q?=200.10.2=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 基于 @tmustier/pi-usage-extension 0.10.2(github.com/tmustier/pi-extensions 的 usage-extension/),仅改文案与 3 处中文宽度/排版补丁。 - zh-map.mjs:100 条词表(103 处替换),覆盖视图/周期/表头/快捷键/加载/洞察全部文案 - apply-zh.mjs:幂等应用器,上游改文案时报 MISS 而非静默漏译 - 本地补丁:x 轴日期改 ASCII M/D、分组横线用 visibleWidth、中文括号前不补空格 - 数据层:辅助用量伪渠道改 工具/摘要,CACHE_VERSION 6→7(名字会 intern 进缓存) - 保持英文:CSV 表头、JSON 键名、导出文件名,避免下游表格/脚本失配 - scripts/:渲染与数据/导出冒烟脚本 --- .gitignore | 4 + LICENSE | 21 + README.md | 56 + apply-zh.mjs | 97 ++ data.ts | 1898 ++++++++++++++++++++++++++++++++ export.ts | 146 +++ graph.ts | 413 +++++++ index.ts | 1009 +++++++++++++++++ package.json | 29 + scripts/usage-data-smoke.mjs | 61 + scripts/usage-render-smoke.mjs | 116 ++ zh-map.mjs | 241 ++++ 12 files changed, 4091 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 apply-zh.mjs create mode 100644 data.ts create mode 100644 export.ts create mode 100644 graph.ts create mode 100644 index.ts create mode 100644 package.json create mode 100644 scripts/usage-data-smoke.mjs create mode 100644 scripts/usage-render-smoke.mjs create mode 100644 zh-map.mjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..454261b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.log +.usage-cache-*.tmp +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..77dac72 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Thomas Mustier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..60bb3d1 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# /usage 用量面板(中文副本) + +中文界面副本,源自 `@tmustier/pi-usage-extension` **0.10.2**(上游 `github.com/tmustier/pi-extensions` 的 `usage-extension/`)。 +本目录被 pi 自动发现(`~/.pi/agent/extensions/*/package.json` 的 `pi.extensions` 或 `index.ts`),命令仍是 `/usage`。 + +## 文件 + +| 文件 | 说明 | +|---|---| +| `index.ts` `data.ts` `graph.ts` `export.ts` | 上游源码(仅改了文案与 3 处本地补丁) | +| `export.ts` | **未汉化**:CSV 表头保持英文(`provider,model,cost_usd,...`),避免下游表格/脚本失配 | +| `zh-map.mjs` | 汉化词表:`{文件: [[英文原文, 中文], ...]}` | +| `apply-zh.mjs` | 词表应用器 + 本地补丁(幂等,未命中即报错) | +| `package.json` | 本副本清单,`version: 0.10.2-zh.1` | +| `scripts/usage-render-smoke.mjs` | 渲染冒烟:三视图按指定宽度渲染为纯文本,报超宽行 | +| `scripts/usage-data-smoke.mjs` | 数据/导出冒烟:采集 + 洞察文案 + CSV/JSON 片段 | + +## 汉化覆盖 + +- 视图名 / 周期 Tab / 表头 / 合计行 / 底部快捷键提示 / 加载进度 / 导出回执 +- 图表模式行、指标名、分组名、图例 `合计` 与 `其他 (N)` +- 洞察页全部文案(标题、副标题、分组标题、6 类告警 + 5 类结构结论含 advice) +- 辅助用量伪渠道 `工具 / 摘要`(旧版为 `Tools / summaries`) + +保持英文:CSV 表头、JSON 键名(`period`/`totals`/`insights`…)、导出文件名(`usage-graph-allTime-…csv`)、模型名与思考等级等数据值。 + +## 本地补丁(与语言无关的宽度/排版修正) + +1. 图表 x 轴日期改 ASCII `M/D`:`renderChart` 用字符串长度算轴位,`toLocaleDateString` 在 zh-CN 下返回 `8月14日`(宽度 = 长度×2),会把末尾标签挤出并截断。 +2. 洞察分组横线长度改用 `visibleWidth(label)` 而不是 `label.length`,否则中文标签会让横线超出宽度、被截成 `…`。 +3. 告警标题里的 `(本期 x%)` 前不再补空格(英文 `(12% of this period)` 需要空格,中文不需要)。 + +## 数据层改动 + +`AUXILIARY_PROVIDER/AUXILIARY_MODEL` 改为中文并 **bump `CACHE_VERSION` 6 → 7**:这些名字会被 intern 进 `~/.pi/agent/usage-extension-cache.json`,不 bump 会出现中英混排。代价是首次 `/usage` 走一次"重建"(本机 312 个会话约 2s)。 + +## 升级上游 + +```bash +SRC=~/.pi/agent/npm/node_modules/@tmustier/pi-usage-extension +cp $SRC/{index.ts,data.ts,graph.ts,export.ts} ~/.pi/agent/extensions/usage-zh/ +cd ~/.pi/agent/extensions/usage-zh && node apply-zh.mjs # 报 MISS 即上游改了文案 +node scripts/usage-render-smoke.mjs --width 80 # 渲染冒烟 +node scripts/usage-data-smoke.mjs # 数据/导出冒烟 +``` + +冒烟脚本默认以仓库根为扩展目录,可用 `--dir` 指到别处;`PI_DIST` / `JITI` 环境变量可覆盖依赖路径。 + +`MISS` 条目按 `zh-map.mjs` 的英文原文更新后重跑;新增界面文案需自行补条目。 + +## 注意 + +- 仓库:`ssh://git@git.cat-shark.xyz:2222/cat-shark/usage-zh.git`;本目录即工作副本,`origin/main` +- **不要把 `npm:@tmustier/pi-usage-extension` 再加回 `settings.json`**:两个扩展都会注册 `/usage`,命令重复。同理也不要用 `pi install` 再装本仓库的 git 包 +- 上游 npm 版仍留在 `~/.pi/agent/npm/node_modules/`,用作 diff/升级参照,不影响加载 +- 改完后:`node apply-zh.mjs` → 冒烟通过 → `/reload` 生效 → commit/push diff --git a/apply-zh.mjs b/apply-zh.mjs new file mode 100644 index 0000000..35d2560 --- /dev/null +++ b/apply-zh.mjs @@ -0,0 +1,97 @@ +#!/usr/bin/env node +// 把 zh-map.mjs 的词表 + 本文件底部的本地补丁应用到扩展源码(默认就地替换)。 +// +// 用法: +// node apply-zh.mjs # 就地汉化(幂等:已汉化的条目记为 DONE) +// node apply-zh.mjs --dry # 只报告命中/未命中,不写文件 +// +// 升级上游时的流程: +// 1. 用新版 @tmustier/pi-usage-extension 的 index.ts/data.ts/graph.ts 覆盖本目录 +// 2. node apply-zh.mjs +// 3. 报 MISS 的条目说明上游改了文案 → 更新 zh-map.mjs / PATCHES 后重跑 + +import { readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { MAP } from "./zh-map.mjs"; + +// 中文环境下必须的本地补丁(与语言无关的宽度/排版修正)。 +// 键为文件,值为 [英文原文, 替换文本, 说明]。 +const PATCHES = { + "index.ts": [ + [ + 'return d.toLocaleDateString(undefined, { day: "numeric", month: "short" });\n\t\t};\n\n\t\tconst chartHeight = 12;', + [ + "\t\t\t// 图表 x 轴用 ASCII 月/日:renderChart 用字符串长度算轴位,", + '\t\t\t// 中文 locale 的 "8月14日" 显示宽度是长度的两倍,会把末尾标签挤掉。', + "\t\t\tconst mm = d.getMonth() + 1;", + "\t\t\tconst dd = d.getDate();", + '\t\t\treturn d.getFullYear() === new Date().getFullYear() ? `${mm}/${dd}` : `${String(d.getFullYear()).slice(2)}/${mm}/${dd}`;', + "\t\t};", + "", + "\t\tconst chartHeight = 12;", + ].join("\n"), + "x 轴日期改 ASCII,避免 CJK 宽度错位", + ], + [ + 'const rule = "─".repeat(Math.max(contentWidth - label.length - 1, 4));', + 'const rule = "─".repeat(Math.max(contentWidth - visibleWidth(label) - 1, 4));', + "分组横线按显示宽度计算(中文标签 width ≠ length)", + ], + [ + "const headline = match ? `${match[1]} ${th.fg(\"dim\", match[2]!)}` : insight.headline;", + "const headline = match ? `${match[1]}${th.fg(\"dim\", match[2]!)}` : insight.headline;", + "中文括号前不留空格", + ], + ], +}; + +const here = dirname(fileURLToPath(import.meta.url)); +const dry = process.argv.includes("--dry"); + +let missing = 0; +const misses = []; + +function applyPairs(src, pairs, file, kind) { + let done = 0; + let already = 0; + for (const [en, zh] of pairs) { + const count = src.split(en).length - 1; + if (count > 0) { + src = src.split(en).join(zh); + done += count; + continue; + } + if (zh && src.includes(zh)) { + already++; + continue; + } + misses.push(`[${file}/${kind}] ${en.slice(0, 100)}`); + } + return { src, done, already }; +} + +const files = new Set([...Object.keys(MAP), ...Object.keys(PATCHES)]); + +for (const file of files) { + const path = join(here, file); + let src = readFileSync(path, "utf8"); + + const t = applyPairs(src, MAP[file] ?? [], file, "词表"); + src = t.src; + const p = applyPairs(src, (PATCHES[file] ?? []).map(([en, zh]) => [en, zh]), file, "补丁"); + src = p.src; + + if (!dry) writeFileSync(path, src); + missing = misses.length; + console.log( + `[${file}] 词表命中 ${t.done} 处(已汉化 ${t.already}),补丁命中 ${p.done} 处(已应用 ${p.already})` + ); +} + +console.log(`\n未命中 ${missing} 条${dry ? "(dry-run,未写盘)" : ""}`); +for (const m of misses) console.log(" MISS " + m); +if (missing > 0) { + console.log("提示:MISS 多为上游文案变更;对照 zh-map.mjs / PATCHES 更新后重跑。"); + process.exitCode = 1; +} diff --git a/data.ts b/data.ts new file mode 100644 index 0000000..cb117ff --- /dev/null +++ b/data.ts @@ -0,0 +1,1898 @@ +/** + * Data collection, caching, and insights for the /usage dashboard. + * + * Performance model (see CHANGELOG 0.4.0): + * - Session JSONL files are scanned at the buffer level. Only lines relevant + * to assistant or auxiliary accounting are decoded and JSON.parsed. Ordinary + * multi-megabyte tool results are skipped; accounting-bearing large results + * use an allocation-safe byte parser for their small metadata fields. + * - Per-file extraction results are persisted to an on-disk cache keyed by + * (size, mtimeMs). Session files are append-only, so a warm load only + * re-parses files that changed since the last run. + */ + +import { readFileSync } from "node:fs"; +import { readdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; + +// ============================================================================= +// Types +// ============================================================================= + +export interface TokenStats { + total: number; + input: number; + output: number; + cacheRead: number; + cacheWrite: number; +} + +export interface BaseStats { + messages: number; + cost: number; + tokens: TokenStats; +} + +export interface ModelStats extends BaseStats { + sessions: Set; +} + +export interface ProviderStats extends BaseStats { + sessions: Set; + models: Map; +} + +export interface TotalStats extends BaseStats { + sessions: number; +} + +export interface Insight { + /** Structure insights always show; alarms fire only when material. */ + kind: "structure" | "alarm"; + /** Leading stat, already formatted (e.g. "34%", "$446", "1.4×"). */ + stat: string; + headline: string; + /** Dimmed follow-up line; empty string renders nothing. */ + advice: string; +} + +export interface PeriodInsights { + insights: Insight[]; +} + +interface CostCount { + cost: number; + messages: number; +} + +interface PeriodRawData { + /** All recorded cost, including usage reported by tools and summaries. */ + totalCost: number; + /** Cost attached to assistant messages, used as the turn-insight denominator. */ + assistantCost: number; + /** Usage reported by tool results, compactions, and branch summaries. */ + auxiliaryCost: number; + /** Messages at ≥ CTX_TAX_THRESHOLD context. */ + ctxHigh: CostCount; + /** Messages below CTX_LOW_THRESHOLD context (comparison group). */ + ctxLow: CostCount; + projectCosts: Map; + sessionCosts: Map; + /** Cost of each session's first-ever message falling in this period. */ + upfrontCost: number; + /** Cache misses after >TTL_GAP_MS idle — resuming after the cache expired. */ + ttlMissCost: number; + /** Cache misses right after a mid-session model switch (no idle gap). */ + modelSwitchMissCost: number; + /** Cache misses with no idle gap, compaction, or model switch — true prefix changes. */ + prefixMissCost: number; + reasoningTokens: number; + outputTokens: number; + cacheReadTokens: number; + freshTokens: number; +} + +/** Per-message adjacency info, computed on raw file order before dedupe. */ +interface MessageMeta { + /** Gap to the previous assistant message in the same file; -1 when unknown. */ + gapMs: number; + /** Context size of the previous assistant message in the same file; 0 when first. */ + prevCtx: number; + /** True when the provider/model differs from the previous assistant message. */ + modelSwitched: boolean; + /** True for the first deduped message of a session across all its files. */ + isSessionStart: boolean; +} + +export interface TrendInfo { + /** Cost over the last 7 calendar days including today. */ + last7Cost: number; + /** Average weekly cost over the prior 28 days. */ + priorWeeklyPace: number; +} + +export interface TimeFilteredStats { + providers: Map; + totals: TotalStats; + insights: PeriodInsights; +} + +/** + * One (provider, model, thinkingLevel) cell inside an hourly bucket. + * Powers the graph explorer; built post-dedupe so it matches table totals. + */ +export interface HourlyCell { + messages: number; + cost: number; + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + reasoning: number; +} + +/** Composite key: `${provider}\u0000${model}\u0000${thinkingLevel}` */ +export type HourlyKey = string; + +export const HOURLY_KEY_SEP = "\u0000"; + +export function makeHourlyKey(provider: string, model: string, thinkingLevel: string): HourlyKey { + return provider + HOURLY_KEY_SEP + model + HOURLY_KEY_SEP + thinkingLevel; +} + +export function splitHourlyKey(key: HourlyKey): { provider: string; model: string; thinkingLevel: string } { + const [provider = "", model = "", thinkingLevel = ""] = key.split(HOURLY_KEY_SEP); + return { provider, model, thinkingLevel }; +} + +export interface PeriodBounds { + todayMs: number; + weekStartMs: number; + lastWeekStartMs: number; + thisMonthStartMs: number; + last30DaysStartMs: number; + nowMs: number; +} + +export interface UsageData { + today: TimeFilteredStats; + thisWeek: TimeFilteredStats; + lastWeek: TimeFilteredStats; + thisMonth: TimeFilteredStats; + last30Days: TimeFilteredStats; + allTime: TimeFilteredStats; + /** Deduped usage bucketed by hour start (ms) → series key → metrics. */ + hourly: Map>; + bounds: PeriodBounds; +} + +export type TabName = "today" | "thisWeek" | "lastWeek" | "thisMonth" | "last30Days" | "allTime"; + +export const TAB_ORDER: TabName[] = ["today", "thisWeek", "lastWeek", "thisMonth", "last30Days", "allTime"]; + +export type UsageSource = "assistant" | "auxiliary"; + +/** Pi's own label for usage that cannot be attributed to a provider/model. */ +export const AUXILIARY_PROVIDER = "工具"; +export const AUXILIARY_MODEL = "摘要"; +export const AUXILIARY_THINKING_LEVEL = "工具/摘要"; + +export interface UsageAmount { + cost: number; + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + reasoning: number; +} + +export interface SessionMessage extends UsageAmount { + provider: string; + model: string; + /** Thinking level active when the message was produced; "" when unknown. */ + thinkingLevel: string; + /** Assistant response, or usage reported by a tool/summary entry. */ + source: UsageSource; + /** Session entry id used to dedupe copied auxiliary entries; empty for assistant messages. */ + sourceId: string; + timestamp: number; + /** The request followed a compaction or context edit that intentionally changed its prefix. */ + afterContextChange: boolean; +} + +export interface ChildToolUsage { + resultIndex: number; + /** Persisted child session path when the tool supplied one; empty otherwise. */ + sessionFile: string; + usage: UsageAmount; +} + +export interface ToolUsageRecord { + /** Parent tool-result entry id, stable across copied branch history. */ + sourceId: string; + timestamp: number; + /** Canonical Pi 0.81+ tool usage; null for legacy nested-agent results. */ + reportedUsage: UsageAmount | null; + /** Run id used to derive the standard nested-session path when needed. */ + runId: string; + /** Recognised per-child usage from nested-agent tool details. */ + children: ChildToolUsage[]; +} + +export interface ParsedSessionFile { + /** Empty string when the file has no session header — such files are ignored. */ + sessionId: string; + /** Working directory from the session header; "" when absent. */ + cwd: string; + /** Extracted assistant and summary usage records, pre-dedupe. */ + messages: SessionMessage[]; + /** Tool usage is reconciled against recursively scanned child sessions later. */ + toolUsages: ToolUsageRecord[]; +} + +// ============================================================================= +// Paths +// ============================================================================= + +export function getAgentDir(): string { + // Replicate Pi's logic: respect PI_CODING_AGENT_DIR env var + return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"); +} + +function sessionDirSetting(settingsPath: string): string | undefined { + try { + const { sessionDir } = JSON.parse(readFileSync(settingsPath, "utf8")); + return typeof sessionDir === "string" ? sessionDir : undefined; + } catch { + return undefined; // No settings file, or one Pi cannot read either. + } +} + +/** Where Pi keeps sessions: `--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, then `sessionDir` from project over global settings. */ +function getSessionsDir(): string { + const flag = process.argv.lastIndexOf("--session-dir"); + const configured = + (flag >= 0 ? process.argv[flag + 1] : undefined) || + process.env.PI_CODING_AGENT_SESSION_DIR || + sessionDirSetting(join(".pi", "settings.json")) || + sessionDirSetting(join(getAgentDir(), "settings.json")); + return configured ? resolve(configured.replace(/^~(?=\/|$)/, homedir())) : join(getAgentDir(), "sessions"); +} + +export function getDefaultCachePath(): string { + return join(getAgentDir(), "usage-extension-cache.json"); +} + +// ============================================================================= +// Session file discovery +// ============================================================================= + +async function collectSessionFilesRecursively(dir: string, files: string[], signal?: AbortSignal): Promise { + try { + const entries = await readdir(dir, { withFileTypes: true }); + if (signal?.aborted) return; + // Sibling directories are read concurrently; callers sort the result. + const subdirs: Promise[] = []; + for (const entry of entries) { + const entryPath = join(dir, entry.name); + if (entry.isDirectory()) { + subdirs.push(collectSessionFilesRecursively(entryPath, files, signal)); + } else if (entry.isFile() && entry.name.endsWith(".jsonl")) { + files.push(entryPath); + } + } + await Promise.all(subdirs); + } catch { + // Skip directories we can't read + } +} + +async function getAllSessionFiles(sessionsDir: string, signal?: AbortSignal): Promise { + const files: string[] = []; + await collectSessionFilesRecursively(sessionsDir, files, signal); + files.sort(); + return files; +} + +// ============================================================================= +// Session file parsing +// ============================================================================= + +const NEWLINE = 0x0a; + +// Relevance patterns for the buffer-level pre-filter. Pi writes compact JSON +// (`"role":"assistant"`), but imported/third-party session files have been seen +// with Python-style spaced JSON (`"role": "assistant"`), so both are matched. +// False positives (e.g. a tool result quoting one of these strings verbatim) +// only cost a wasted JSON.parse — the parsed entry is still shape-checked. +const PATTERN_ASSISTANT_COMPACT = Buffer.from('"role":"assistant"'); +const PATTERN_ASSISTANT_SPACED = Buffer.from('"role": "assistant"'); +const PATTERN_TOOL_RESULT_COMPACT = Buffer.from('"role":"toolResult"'); +const PATTERN_TOOL_RESULT_SPACED = Buffer.from('"role": "toolResult"'); +const PATTERN_USAGE_COMPACT = Buffer.from('"usage":{'); +const PATTERN_USAGE_SPACED = Buffer.from('"usage": {'); +const PATTERN_SESSION_COMPACT = Buffer.from('"type":"session"'); +const PATTERN_SESSION_SPACED = Buffer.from('"type": "session"'); +const PATTERN_THINKING_COMPACT = Buffer.from('"type":"thinking_level_change"'); +const PATTERN_THINKING_SPACED = Buffer.from('"type": "thinking_level_change"'); +const PATTERN_COMPACTION_COMPACT = Buffer.from('"type":"compaction"'); +const PATTERN_COMPACTION_SPACED = Buffer.from('"type": "compaction"'); +const PATTERN_CONTEXT_EDIT_COMPACT = Buffer.from('"type":"context_edit"'); +const PATTERN_CONTEXT_EDIT_SPACED = Buffer.from('"type": "context_edit"'); +const PATTERN_BRANCH_SUMMARY_COMPACT = Buffer.from('"type":"branch_summary"'); +const PATTERN_BRANCH_SUMMARY_SPACED = Buffer.from('"type": "branch_summary"'); +// pi-subagents versions predating Pi 0.81 persisted child usage in details but +// could not put it on the canonical tool-result usage field. Their tool names +// are near the start of the line, so we can recover those records without +// scanning every multi-megabyte tool result. +const PATTERN_SUBAGENT_TOOL_COMPACT = Buffer.from('"toolName":"subagent"'); +const PATTERN_SUBAGENT_TOOL_SPACED = Buffer.from('"toolName": "subagent"'); +const PATTERN_SUBAGENT_WAIT_TOOL_COMPACT = Buffer.from('"toolName":"subagent_wait"'); +const PATTERN_SUBAGENT_WAIT_TOOL_SPACED = Buffer.from('"toolName": "subagent_wait"'); + +const PARSE_YIELD_EVERY_LINES = 2000; + +function finiteNumber(value: unknown): number { + return typeof value === "number" && Number.isFinite(value) ? value : 0; +} + +function parseUsageAmount(value: unknown): UsageAmount | null { + if (!value || typeof value !== "object") return null; + const persisted = value as Record; + const costValue = persisted.cost; + const cost = + typeof costValue === "number" + ? finiteNumber(costValue) + : costValue && typeof costValue === "object" + ? finiteNumber((costValue as Record).total) + : 0; + const usage = { + cost, + input: finiteNumber(persisted.input), + output: finiteNumber(persisted.output), + cacheRead: finiteNumber(persisted.cacheRead), + cacheWrite: finiteNumber(persisted.cacheWrite), + reasoning: finiteNumber(persisted.reasoning), + }; + return usage.cost === 0 && usage.input === 0 && usage.output === 0 && usage.cacheRead === 0 && usage.cacheWrite === 0 + ? null + : usage; +} + +function parsedTimestamp(messageTimestamp: unknown, entryTimestamp: unknown): number { + const parsed = + typeof messageTimestamp === "number" + ? messageTimestamp + : new Date(String(messageTimestamp ?? entryTimestamp ?? "")).getTime(); + return Number.isFinite(parsed) ? parsed : 0; +} + +function auxiliaryMessage(usage: UsageAmount, timestamp: number, sourceId: string): SessionMessage { + return { + provider: AUXILIARY_PROVIDER, + model: AUXILIARY_MODEL, + thinkingLevel: AUXILIARY_THINKING_LEVEL, + source: "auxiliary", + sourceId, + ...usage, + timestamp, + afterContextChange: false, + }; +} + +function buildToolUsageRecord( + toolName: unknown, + detailsValue: unknown, + reportedValue: unknown, + sourceIdValue: unknown, + messageTimestamp: unknown, + entryTimestamp: unknown +): ToolUsageRecord | null { + const reportedUsage = parseUsageAmount(reportedValue); + const details = detailsValue && typeof detailsValue === "object" ? (detailsValue as Record) : null; + const totalChildUsage = parseUsageAmount(details?.totalChildUsage); + const knownNestedTool = toolName === "subagent" || toolName === "subagent_wait"; + const children: ChildToolUsage[] = []; + if (details && Array.isArray(details.results)) { + for (let resultIndex = 0; resultIndex < details.results.length; resultIndex++) { + const result = details.results[resultIndex]; + if (!result || typeof result !== "object") continue; + const child = result as Record; + const usage = parseUsageAmount(child.usage); + const sessionFile = typeof child.sessionFile === "string" ? child.sessionFile : ""; + // Legacy fallback is deliberately restricted to recognised nested-agent + // records. Generic Pi 0.81 tools remain canonical through reportedUsage. + if (usage && (knownNestedTool || totalChildUsage || (reportedUsage && sessionFile))) { + children.push({ resultIndex, sessionFile, usage }); + } + } + } + if (!reportedUsage && children.length === 0) return null; + return { + sourceId: typeof sourceIdValue === "string" ? sourceIdValue : "", + timestamp: parsedTimestamp(messageTimestamp, entryTimestamp), + reportedUsage, + runId: details && typeof details.runId === "string" ? details.runId : "", + children, + }; +} + +const LARGE_TOOL_RESULT_BYTES = 64 * 1024; +const PROPERTY_ID = Buffer.from('"id":'); +const PROPERTY_TIMESTAMP = Buffer.from('"timestamp":'); +const PROPERTY_MESSAGE = Buffer.from('"message":'); +const PROPERTY_TOOL_NAME = Buffer.from('"toolName":'); +const PROPERTY_DETAILS = Buffer.from('"details":'); +const PROPERTY_USAGE = Buffer.from('"usage":'); +const DIRECT_CHILD_PROPERTIES = new Set(["usage", "sessionFile"]); + +function skipJsonWhitespace(buffer: Buffer, offset: number, limit: number): number { + while (offset < limit && (buffer[offset] === 0x20 || buffer[offset] === 0x09 || buffer[offset] === 0x0a || buffer[offset] === 0x0d)) offset++; + return offset; +} + +/** Find one JSON value's end without decoding large strings or container bodies. */ +function jsonValueEnd(buffer: Buffer, offset: number, limit: number): number { + offset = skipJsonWhitespace(buffer, offset, limit); + if (offset >= limit) return offset; + const first = buffer[offset]; + if (first === 0x22) { + let escaped = false; + for (let i = offset + 1; i < limit; i++) { + const byte = buffer[i]; + if (escaped) escaped = false; + else if (byte === 0x5c) escaped = true; + else if (byte === 0x22) return i + 1; + } + return limit; + } + if (first === 0x7b || first === 0x5b) { + let depth = 0; + let inString = false; + let escaped = false; + for (let i = offset; i < limit; i++) { + const byte = buffer[i]; + if (inString) { + if (escaped) escaped = false; + else if (byte === 0x5c) escaped = true; + else if (byte === 0x22) inString = false; + continue; + } + if (byte === 0x22) inString = true; + else if (byte === 0x7b || byte === 0x5b) depth++; + else if (byte === 0x7d || byte === 0x5d) { + depth--; + if (depth === 0) return i + 1; + } + } + return limit; + } + let end = offset; + while (end < limit && buffer[end] !== 0x2c && buffer[end] !== 0x5d && buffer[end] !== 0x7d) end++; + return end; +} + +function parseJsonValueAt(buffer: Buffer, offset: number, limit: number): unknown { + const start = skipJsonWhitespace(buffer, offset, limit); + const end = jsonValueEnd(buffer, start, limit); + if (end <= start) return undefined; + try { + return JSON.parse(buffer.toString("utf8", start, end)); + } catch { + return undefined; + } +} + +function parsePropertyValue(buffer: Buffer, property: Buffer, from: number, to: number): unknown { + const propertyOffset = buffer.indexOf(property, from); + if (propertyOffset < 0 || propertyOffset >= to) return undefined; + return parseJsonValueAt(buffer, propertyOffset + property.length, to); +} + +function parseLastPropertyValue(buffer: Buffer, property: Buffer, from: number, to: number): unknown { + const propertyOffset = buffer.lastIndexOf(property, to - 1); + if (propertyOffset < from) return undefined; + return parseJsonValueAt(buffer, propertyOffset + property.length, to); +} + +interface DirectObjectScan { + end: number; + values: Map; +} + +/** Scan direct object properties while skipping nested values allocation-free. */ +function scanDirectObjectProperties(buffer: Buffer, objectStart: number, limit: number, wanted: Set): DirectObjectScan { + const values = new Map(); + let cursor = objectStart + 1; + while (cursor < limit) { + cursor = skipJsonWhitespace(buffer, cursor, limit); + if (buffer[cursor] === 0x7d) return { end: cursor + 1, values }; + if (buffer[cursor] === 0x2c) { + cursor++; + continue; + } + if (buffer[cursor] !== 0x22) return { end: jsonValueEnd(buffer, objectStart, limit), values }; + const keyEnd = jsonValueEnd(buffer, cursor, limit); + let colon = skipJsonWhitespace(buffer, keyEnd, limit); + if (buffer[colon] !== 0x3a) return { end: jsonValueEnd(buffer, objectStart, limit), values }; + const valueStart = skipJsonWhitespace(buffer, colon + 1, limit); + const valueEnd = jsonValueEnd(buffer, valueStart, limit); + const key = buffer.toString("utf8", cursor + 1, keyEnd - 1); + if (wanted.has(key)) values.set(key, [valueStart, valueEnd]); + if (valueEnd <= valueStart) return { end: limit, values }; + cursor = valueEnd; + } + return { end: limit, values }; +} + +function parseJsonRange(buffer: Buffer, range: [number, number] | undefined): unknown { + if (!range) return undefined; + try { + return JSON.parse(buffer.toString("utf8", range[0], range[1])); + } catch { + return undefined; + } +} + +interface ChildResultsScan { + end: number; + results: Array>; +} + +function scanChildResults(buffer: Buffer, arrayStart: number, limit: number): ChildResultsScan { + const results: Array> = []; + let cursor = arrayStart + 1; + while (cursor < limit) { + cursor = skipJsonWhitespace(buffer, cursor, limit); + if (buffer[cursor] === 0x5d) return { end: cursor + 1, results }; + if (buffer[cursor] === 0x2c) { + cursor++; + continue; + } + if (buffer[cursor] === 0x7b) { + const scanned = scanDirectObjectProperties(buffer, cursor, limit, DIRECT_CHILD_PROPERTIES); + results.push({ + usage: parseJsonRange(buffer, scanned.values.get("usage")), + sessionFile: parseJsonRange(buffer, scanned.values.get("sessionFile")), + }); + if (scanned.end <= cursor) return { end: limit, results }; + cursor = scanned.end; + continue; + } + const valueEnd = jsonValueEnd(buffer, cursor, limit); + if (valueEnd <= cursor) return { end: limit, results }; + cursor = valueEnd; + } + return { end: limit, results }; +} + +interface LargeDetailsScan { + end: number; + details: Record; +} + +/** Scan nested-agent details and its result metadata in a single byte pass. */ +function scanLargeDetails(buffer: Buffer, objectStart: number, limit: number): LargeDetailsScan { + const details: Record = { results: [] }; + let cursor = objectStart + 1; + while (cursor < limit) { + cursor = skipJsonWhitespace(buffer, cursor, limit); + if (buffer[cursor] === 0x7d) return { end: cursor + 1, details }; + if (buffer[cursor] === 0x2c) { + cursor++; + continue; + } + if (buffer[cursor] !== 0x22) return { end: jsonValueEnd(buffer, objectStart, limit), details }; + const keyEnd = jsonValueEnd(buffer, cursor, limit); + let colon = skipJsonWhitespace(buffer, keyEnd, limit); + if (buffer[colon] !== 0x3a) return { end: jsonValueEnd(buffer, objectStart, limit), details }; + const valueStart = skipJsonWhitespace(buffer, colon + 1, limit); + const key = buffer.toString("utf8", cursor + 1, keyEnd - 1); + let valueEnd: number; + if (key === "results" && buffer[valueStart] === 0x5b) { + const scanned = scanChildResults(buffer, valueStart, limit); + details.results = scanned.results; + valueEnd = scanned.end; + } else { + valueEnd = jsonValueEnd(buffer, valueStart, limit); + if (key === "runId" || key === "totalChildUsage") { + details[key] = parseJsonRange(buffer, [valueStart, valueEnd]); + } + } + if (valueEnd <= valueStart) return { end: limit, details }; + cursor = valueEnd; + } + return { end: limit, details }; +} + +/** + * Parse only the small accounting fields from a large tool-result line. This + * avoids UTF-8 decoding and JSON.parse allocation for multi-megabyte content. + */ +function parseLargeToolResultLine(line: Buffer): ToolUsageRecord | null { + const messageOffset = line.indexOf(PROPERTY_MESSAGE); + if (messageOffset < 0) return null; + const detailsOffset = line.indexOf(PROPERTY_DETAILS, messageOffset); + let detailsEnd = -1; + let details: Record | null = null; + if (detailsOffset >= 0) { + const detailsStart = skipJsonWhitespace(line, detailsOffset + PROPERTY_DETAILS.length, line.length); + if (line[detailsStart] === 0x7b) { + const scanned = scanLargeDetails(line, detailsStart, line.length); + detailsEnd = scanned.end; + details = scanned.details; + } + } + + const reportedUsage = detailsEnd >= 0 + ? parsePropertyValue(line, PROPERTY_USAGE, detailsEnd, line.length) + : parseLastPropertyValue(line, PROPERTY_USAGE, messageOffset, line.length); + const sourceId = parsePropertyValue(line, PROPERTY_ID, 0, messageOffset); + const entryTimestamp = parsePropertyValue(line, PROPERTY_TIMESTAMP, 0, messageOffset); + const messageTimestamp = parseLastPropertyValue(line, PROPERTY_TIMESTAMP, messageOffset, line.length); + const toolName = parsePropertyValue(line, PROPERTY_TOOL_NAME, messageOffset, detailsOffset >= 0 ? detailsOffset : line.length); + return buildToolUsageRecord(toolName, details, reportedUsage, sourceId, messageTimestamp, entryTimestamp); +} + +function lineMightBeRelevant(line: Buffer): boolean { + // Entry type/role fields are at the front of Pi's JSONL objects. Restrict + // those checks to a small prefix so multi-megabyte tool output is not scanned + // repeatedly for every possible entry shape. + const head = line.length > 1024 ? line.subarray(0, 1024) : line; + if (head.includes(PATTERN_ASSISTANT_COMPACT) || head.includes(PATTERN_ASSISTANT_SPACED)) return true; + + if (head.includes(PATTERN_TOOL_RESULT_COMPACT) || head.includes(PATTERN_TOOL_RESULT_SPACED)) { + if ( + head.includes(PATTERN_SUBAGENT_TOOL_COMPACT) || + head.includes(PATTERN_SUBAGENT_TOOL_SPACED) || + head.includes(PATTERN_SUBAGENT_WAIT_TOOL_COMPACT) || + head.includes(PATTERN_SUBAGENT_WAIT_TOOL_SPACED) + ) { + return true; + } + // Pi serializes optional tool usage after content/details and immediately + // before the small isError/timestamp suffix. Checking the tail preserves + // the fast path for ordinary tool results, which dominate session bytes. + const tail = line.length > 4096 ? line.subarray(line.length - 4096) : line; + return tail.includes(PATTERN_USAGE_COMPACT) || tail.includes(PATTERN_USAGE_SPACED); + } + + return ( + head.includes(PATTERN_SESSION_COMPACT) || + head.includes(PATTERN_THINKING_COMPACT) || + head.includes(PATTERN_COMPACTION_COMPACT) || + head.includes(PATTERN_CONTEXT_EDIT_COMPACT) || + head.includes(PATTERN_BRANCH_SUMMARY_COMPACT) || + head.includes(PATTERN_SESSION_SPACED) || + head.includes(PATTERN_THINKING_SPACED) || + head.includes(PATTERN_COMPACTION_SPACED) || + head.includes(PATTERN_CONTEXT_EDIT_SPACED) || + head.includes(PATTERN_BRANCH_SUMMARY_SPACED) + ); +} + +/** + * Extract the session id plus assistant/tool/summary usage from a JSONL buffer. + * Returns partial results when aborted — callers must check `signal.aborted` + * before caching or using the result. + */ +export async function parseSessionBuffer(buffer: Buffer, signal?: AbortSignal): Promise { + const messages: SessionMessage[] = []; + const toolUsages: ToolUsageRecord[] = []; + let sessionId = ""; + let cwd = ""; + // Assistant messages don't carry the thinking level; pi records it as separate + // thinking_level_change entries, always written before the first assistant + // message of a session. Replaying them in append order attributes each message + // to the level active when it was produced. + let thinkingLevel = ""; + let contextChangePending = false; + + let start = 0; + let lineNumber = 0; + + while (start < buffer.length) { + let end = buffer.indexOf(NEWLINE, start); + if (end === -1) end = buffer.length; + + lineNumber++; + if (lineNumber % PARSE_YIELD_EVERY_LINES === 0) { + await new Promise((resolve) => setImmediate(resolve)); + if (signal?.aborted) return { sessionId, cwd, messages, toolUsages }; + } + + const lineBuffer = buffer.subarray(start, end); + if (end > start && lineMightBeRelevant(lineBuffer)) { + const head = lineBuffer.subarray(0, Math.min(1024, lineBuffer.length)); + if (lineBuffer.length > LARGE_TOOL_RESULT_BYTES && head.includes(PATTERN_TOOL_RESULT_COMPACT)) { + const toolUsage = parseLargeToolResultLine(lineBuffer); + if (toolUsage) toolUsages.push(toolUsage); + start = end + 1; + continue; + } + try { + const entry = JSON.parse(buffer.toString("utf8", start, end)); + + if (entry.type === "session") { + sessionId = entry.id; + if (typeof entry.cwd === "string") cwd = entry.cwd; + } else if (entry.type === "thinking_level_change") { + if (typeof entry.thinkingLevel === "string") thinkingLevel = entry.thinkingLevel; + } else if (entry.type === "compaction") { + const usage = parseUsageAmount(entry.usage); + if (usage) messages.push(auxiliaryMessage(usage, parsedTimestamp(undefined, entry.timestamp), typeof entry.id === "string" ? entry.id : "")); + contextChangePending = true; + } else if (entry.type === "context_edit") { + contextChangePending = true; + } else if (entry.type === "branch_summary") { + const usage = parseUsageAmount(entry.usage); + if (usage) messages.push(auxiliaryMessage(usage, parsedTimestamp(undefined, entry.timestamp), typeof entry.id === "string" ? entry.id : "")); + } else if (entry.type === "message" && entry.message?.role === "assistant") { + const msg = entry.message; + if (msg.usage && msg.provider && msg.model) { + const fallbackTs = entry.timestamp ? new Date(entry.timestamp).getTime() : 0; + messages.push({ + provider: msg.provider, + model: msg.model, + thinkingLevel, + source: "assistant", + sourceId: "", + cost: msg.usage.cost?.total || 0, + input: msg.usage.input || 0, + output: msg.usage.output || 0, + cacheRead: msg.usage.cacheRead || 0, + cacheWrite: msg.usage.cacheWrite || 0, + reasoning: msg.usage.reasoning || 0, + timestamp: msg.timestamp || (Number.isNaN(fallbackTs) ? 0 : fallbackTs), + afterContextChange: contextChangePending, + }); + contextChangePending = false; + } + } else if (entry.type === "message" && entry.message?.role === "toolResult") { + const msg = entry.message; + const toolUsage = buildToolUsageRecord(msg.toolName, msg.details, msg.usage, entry.id, msg.timestamp, entry.timestamp); + if (toolUsage) toolUsages.push(toolUsage); + } + } catch { + // Skip malformed lines + } + } + + start = end + 1; + } + + return { sessionId, cwd, messages, toolUsages }; +} + +// ============================================================================= +// On-disk cache +// ============================================================================= + +const CACHE_VERSION = 7; + +type CachedMessageTuple = [ + providerIdx: number, + modelIdx: number, + cost: number, + input: number, + output: number, + cacheRead: number, + cacheWrite: number, + timestamp: number, + thinkingLevelIdx: number, + reasoning: number, + afterContextChange: 0 | 1, + auxiliary: 0 | 1, + sourceIdIdx: number, +]; + +type CachedUsageTuple = [ + cost: number, + input: number, + output: number, + cacheRead: number, + cacheWrite: number, + reasoning: number, +]; + +type CachedChildToolUsageTuple = [ + resultIndex: number, + sessionFileIdx: number, + usage: CachedUsageTuple, +]; + +type CachedToolUsageTuple = [ + sourceIdIdx: number, + timestamp: number, + reportedUsage: CachedUsageTuple | null, + runIdIdx: number, + children: CachedChildToolUsageTuple[], +]; + +interface CacheFileEntry { + size: number; + mtimeMs: number; + sessionId: string; + cwd: string; + messages: CachedMessageTuple[]; + toolUsages: CachedToolUsageTuple[]; +} + +export interface CachedFileState { + size: number; + mtimeMs: number; + parsed: ParsedSessionFile; +} + +export async function loadUsageCache(cachePath: string): Promise> { + const result = new Map(); + let raw: { version?: unknown; names?: unknown; files?: unknown }; + try { + raw = JSON.parse(await readFile(cachePath, "utf8")); + } catch { + return result; // Missing or corrupt cache — rebuild from scratch. + } + if (!raw || raw.version !== CACHE_VERSION || !Array.isArray(raw.names) || typeof raw.files !== "object" || raw.files === null) { + return result; + } + + const names = raw.names as unknown[]; + for (const [filePath, entry] of Object.entries(raw.files as Record)) { + if ( + !entry || + typeof entry.size !== "number" || + typeof entry.mtimeMs !== "number" || + typeof entry.sessionId !== "string" || + typeof entry.cwd !== "string" || + !Array.isArray(entry.messages) || + !Array.isArray(entry.toolUsages) + ) { + continue; + } + const messages: SessionMessage[] = []; + let valid = true; + for (const tuple of entry.messages) { + if (!Array.isArray(tuple) || tuple.length !== 13) { + valid = false; + break; + } + const provider = names[tuple[0]]; + const model = names[tuple[1]]; + const thinkingLevel = names[tuple[8]]; + const sourceId = names[tuple[12]]; + if ( + typeof provider !== "string" || + typeof model !== "string" || + typeof thinkingLevel !== "string" || + typeof sourceId !== "string" || + (tuple[11] !== 0 && tuple[11] !== 1) + ) { + valid = false; + break; + } + messages.push({ + provider, + model, + thinkingLevel, + source: tuple[11] === 1 ? "auxiliary" : "assistant", + sourceId, + cost: Number(tuple[2]) || 0, + input: Number(tuple[3]) || 0, + output: Number(tuple[4]) || 0, + cacheRead: Number(tuple[5]) || 0, + cacheWrite: Number(tuple[6]) || 0, + timestamp: Number(tuple[7]) || 0, + reasoning: Number(tuple[9]) || 0, + afterContextChange: tuple[10] === 1, + }); + } + if (!valid) continue; + const toolUsages: ToolUsageRecord[] = []; + for (const tuple of entry.toolUsages) { + if (!Array.isArray(tuple) || tuple.length !== 5 || !Array.isArray(tuple[4])) { + valid = false; + break; + } + const sourceId = names[tuple[0]]; + const runId = names[tuple[3]]; + const reportedUsage = cachedUsageAmount(tuple[2]); + if (typeof sourceId !== "string" || typeof runId !== "string" || (tuple[2] !== null && !reportedUsage)) { + valid = false; + break; + } + const children: ChildToolUsage[] = []; + for (const childTuple of tuple[4]) { + if (!Array.isArray(childTuple) || childTuple.length !== 3) { + valid = false; + break; + } + const sessionFile = names[childTuple[1]]; + const usage = cachedUsageAmount(childTuple[2]); + if (typeof childTuple[0] !== "number" || typeof sessionFile !== "string" || !usage) { + valid = false; + break; + } + children.push({ resultIndex: childTuple[0], sessionFile, usage }); + } + if (!valid) break; + toolUsages.push({ + sourceId, + timestamp: Number(tuple[1]) || 0, + reportedUsage, + runId, + children, + }); + } + if (!valid) continue; + result.set(filePath, { + size: entry.size, + mtimeMs: entry.mtimeMs, + parsed: { sessionId: entry.sessionId, cwd: entry.cwd, messages, toolUsages }, + }); + } + return result; +} + +function cachedUsageAmount(value: unknown): UsageAmount | null { + if (!Array.isArray(value) || value.length !== 6 || value.some((part) => typeof part !== "number" || !Number.isFinite(part))) { + return null; + } + return { + cost: value[0], + input: value[1], + output: value[2], + cacheRead: value[3], + cacheWrite: value[4], + reasoning: value[5], + }; +} + +function cacheUsageAmount(usage: UsageAmount): CachedUsageTuple { + return [usage.cost, usage.input, usage.output, usage.cacheRead, usage.cacheWrite, usage.reasoning]; +} + +export async function saveUsageCache(cachePath: string, states: Map): Promise { + const names: string[] = []; + const nameIndex = new Map(); + const intern = (name: string): number => { + let idx = nameIndex.get(name); + if (idx === undefined) { + idx = names.length; + names.push(name); + nameIndex.set(name, idx); + } + return idx; + }; + + const files: Record = {}; + for (const [filePath, state] of states) { + files[filePath] = { + size: state.size, + mtimeMs: state.mtimeMs, + sessionId: state.parsed.sessionId, + cwd: state.parsed.cwd, + messages: state.parsed.messages.map((m): CachedMessageTuple => [ + intern(m.provider), + intern(m.model), + m.cost, + m.input, + m.output, + m.cacheRead, + m.cacheWrite, + m.timestamp, + intern(m.thinkingLevel), + m.reasoning, + m.afterContextChange ? 1 : 0, + m.source === "auxiliary" ? 1 : 0, + intern(m.source === "auxiliary" ? m.sourceId : ""), + ]), + toolUsages: state.parsed.toolUsages.map((tool): CachedToolUsageTuple => [ + intern(tool.sourceId), + tool.timestamp, + tool.reportedUsage ? cacheUsageAmount(tool.reportedUsage) : null, + intern(tool.runId), + tool.children.map((child): CachedChildToolUsageTuple => [ + child.resultIndex, + intern(child.sessionFile), + cacheUsageAmount(child.usage), + ]), + ]), + }; + } + + const payload = JSON.stringify({ version: CACHE_VERSION, names, files }); + // Atomic-ish write: concurrent /usage runs race to a last-writer-wins rename + // instead of interleaving partial writes. + const tmpPath = join(dirname(cachePath), `.usage-cache-${process.pid}-${Date.now()}.tmp`); + await writeFile(tmpPath, payload, "utf8"); + await rename(tmpPath, cachePath); +} + +// ============================================================================= +// Aggregation +// ============================================================================= + +function emptyTokens(): TokenStats { + return { total: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }; +} + +function emptyModelStats(): ModelStats { + return { sessions: new Set(), messages: 0, cost: 0, tokens: emptyTokens() }; +} + +function emptyProviderStats(): ProviderStats { + return { sessions: new Set(), messages: 0, cost: 0, tokens: emptyTokens(), models: new Map() }; +} + +function emptyTimeFilteredStats(): TimeFilteredStats { + return { + providers: new Map(), + totals: { sessions: 0, messages: 0, cost: 0, tokens: emptyTokens() }, + insights: { insights: [] }, + }; +} + +function emptyPeriodRawData(): PeriodRawData { + return { + totalCost: 0, + assistantCost: 0, + auxiliaryCost: 0, + ctxHigh: { cost: 0, messages: 0 }, + ctxLow: { cost: 0, messages: 0 }, + projectCosts: new Map(), + sessionCosts: new Map(), + upfrontCost: 0, + ttlMissCost: 0, + modelSwitchMissCost: 0, + prefixMissCost: 0, + reasoningTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + freshTokens: 0, + }; +} + +/** + * Collapse a session cwd to a short, stable project label: `~` for the home + * directory, up to two path segments below home (worktrees collapse to their + * repository), absolute paths elsewhere. + */ +export function projectLabelFromCwd(cwd: string): string { + if (!cwd) return "(unknown)"; + // Normalize Windows separators so backslash paths (C:\Users\me\...) match the + // forward-slash forms compared below. Path text after the home prefix keeps + // its normalized forward slashes, which is what the label displays. + const normalized = cwd.replaceAll("\\", "/"); + // Collapse any home-directory prefix to "~", not just the current user's — + // session stores merged from other machines can carry a different username. + const home = homedir().replaceAll("\\", "/"); + let homePrefix: string | null = null; + if (normalized === home || normalized.startsWith(home + "/")) { + homePrefix = home; + } else { + const m = /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)(?=\/|$)/.exec(normalized); + if (m) homePrefix = m[1]!; + } + if (homePrefix !== null && normalized.length <= homePrefix.length) return "~"; + let rel = homePrefix !== null ? normalized.slice(homePrefix.length + 1) : normalized; + const wt = rel.indexOf("/.worktrees/"); + if (wt !== -1) rel = rel.slice(0, wt); + const parts = rel.split("/").filter(Boolean); + if (homePrefix !== null) return `~/${parts.slice(0, 2).join("/")}`; + // Windows drive paths outside a home (D:/work/repo/sub): drop the drive segment + // so the label keeps meaningful segments (work/repo) and stays slash-separated. + const segments = /^[A-Za-z]:$/.test(parts[0] ?? "") ? parts.slice(1) : parts; + const label = segments.slice(0, 2).join("/"); + if (/^[A-Za-z]:\//.test(normalized)) return label; + return `/${label}`; +} + +function emptyUsageData(bounds: PeriodBounds): UsageData { + return { + today: emptyTimeFilteredStats(), + thisWeek: emptyTimeFilteredStats(), + lastWeek: emptyTimeFilteredStats(), + thisMonth: emptyTimeFilteredStats(), + last30Days: emptyTimeFilteredStats(), + allTime: emptyTimeFilteredStats(), + hourly: new Map(), + bounds, + }; +} + +const HOUR_MS = 3_600_000; + +function addToHourlyBuckets(hourly: Map>, msg: SessionMessage): void { + if (msg.timestamp <= 0) return; // Unknown time can't be placed on a time axis. + const hour = Math.floor(msg.timestamp / HOUR_MS) * HOUR_MS; + let bucket = hourly.get(hour); + if (!bucket) { + bucket = new Map(); + hourly.set(hour, bucket); + } + const key = makeHourlyKey(msg.provider, msg.model, msg.thinkingLevel); + let cell = bucket.get(key); + if (!cell) { + cell = { messages: 0, cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }; + bucket.set(key, cell); + } + if (msg.source === "assistant") cell.messages++; + cell.cost += msg.cost; + cell.input += msg.input; + cell.output += msg.output; + cell.cacheRead += msg.cacheRead; + cell.cacheWrite += msg.cacheWrite; + cell.reasoning += msg.reasoning; +} + +// Helper to accumulate stats into a target +function accumulateStats( + target: BaseStats, + cost: number, + tokens: { total: number; input: number; output: number; cacheRead: number; cacheWrite: number }, + countMessage: boolean +): void { + if (countMessage) target.messages++; + target.cost += cost; + target.tokens.total += tokens.total; + target.tokens.input += tokens.input; + target.tokens.output += tokens.output; + target.tokens.cacheRead += tokens.cacheRead; + target.tokens.cacheWrite += tokens.cacheWrite; +} + +function getPeriodsForTimestamp( + timestamp: number, + todayMs: number, + weekStartMs: number, + lastWeekStartMs: number, + thisMonthStartMs: number, + last30DaysStartMs: number +): TabName[] { + const periods: TabName[] = ["allTime"]; + if (timestamp >= todayMs) periods.push("today"); + if (timestamp >= weekStartMs) { + periods.push("thisWeek"); + } else if (timestamp >= lastWeekStartMs) { + periods.push("lastWeek"); + } + if (timestamp >= thisMonthStartMs) periods.push("thisMonth"); + if (timestamp >= last30DaysStartMs) periods.push("last30Days"); + return periods; +} + +const DAY_MS = 24 * HOUR_MS; +const PROGRESS_REPORT_EVERY = 100; + +function addMessagesToUsageData( + data: UsageData, + sessionId: string, + project: string, + messages: SessionMessage[], + meta: MessageMeta[], + todayMs: number, + weekStartMs: number, + lastWeekStartMs: number, + thisMonthStartMs: number, + last30DaysStartMs: number, + rawByPeriod: Record, + costByDayIdx: Map +): void { + const sessionContributed = { today: false, thisWeek: false, lastWeek: false, thisMonth: false, last30Days: false, allTime: false }; + + for (let mi = 0; mi < messages.length; mi++) { + const msg = messages[mi]!; + const mm = meta[mi]!; + + // pi's built-in test providers never call a real API — keep them out of stats. + if (EXCLUDED_PROVIDERS.has(msg.provider)) continue; + + // Day-indexed cost totals power the burn-trend insight. + if (msg.timestamp > 0) { + const dayIdx = Math.floor((msg.timestamp - todayMs) / DAY_MS); + costByDayIdx.set(dayIdx, (costByDayIdx.get(dayIdx) ?? 0) + msg.cost); + } + + addToHourlyBuckets(data.hourly, msg); + + const periods = getPeriodsForTimestamp( + msg.timestamp, + todayMs, + weekStartMs, + lastWeekStartMs, + thisMonthStartMs, + last30DaysStartMs + ); + const tokens = { + // Count fresh tokens processed this turn. + // Include cacheWrite because those prompt tokens were newly written and billed. + // Exclude cacheRead because repeated cache hits would otherwise dominate totals. + total: msg.input + msg.output + msg.cacheWrite, + input: msg.input, + output: msg.output, + cacheRead: msg.cacheRead, + cacheWrite: msg.cacheWrite, + }; + + for (const period of periods) { + const stats = data[period]; + + let providerStats = stats.providers.get(msg.provider); + if (!providerStats) { + providerStats = emptyProviderStats(); + stats.providers.set(msg.provider, providerStats); + } + + let modelStats = providerStats.models.get(msg.model); + if (!modelStats) { + modelStats = emptyModelStats(); + providerStats.models.set(msg.model, modelStats); + } + + const isAssistant = msg.source === "assistant"; + modelStats.sessions.add(sessionId); + accumulateStats(modelStats, msg.cost, tokens, isAssistant); + + providerStats.sessions.add(sessionId); + accumulateStats(providerStats, msg.cost, tokens, isAssistant); + + accumulateStats(stats.totals, msg.cost, tokens, isAssistant); + sessionContributed[period] = true; + + const raw = rawByPeriod[period]; + raw.totalCost += msg.cost; + raw.projectCosts.set(project, (raw.projectCosts.get(project) ?? 0) + msg.cost); + raw.sessionCosts.set(sessionId, (raw.sessionCosts.get(sessionId) ?? 0) + msg.cost); + + // Auxiliary calls belong in accounting totals, project/session mix, and + // burn trend. They are not assistant turns, so do not let their synthetic + // model identity or nested context distort turn/cache insights. + if (!isAssistant) { + raw.auxiliaryCost += msg.cost; + continue; + } + raw.assistantCost += msg.cost; + + const ctx = msg.input + msg.cacheRead + msg.cacheWrite; + if (ctx >= CTX_TAX_THRESHOLD) { + raw.ctxHigh.cost += msg.cost; + raw.ctxHigh.messages++; + } else if (ctx < CTX_LOW_THRESHOLD) { + raw.ctxLow.cost += msg.cost; + raw.ctxLow.messages++; + } + if (mm.isSessionStart) raw.upfrontCost += msg.cost; + if ( + !msg.afterContextChange && + mm.prevCtx >= MISS_MIN_PREV_CONTEXT && + msg.cacheRead < Math.min(MISS_MAX_CACHE_READ, 0.3 * mm.prevCtx) + ) { + if (mm.gapMs > TTL_GAP_MS) raw.ttlMissCost += msg.cost; + else if (mm.gapMs >= 0 && mm.modelSwitched) raw.modelSwitchMissCost += msg.cost; + else if (mm.gapMs >= 0) raw.prefixMissCost += msg.cost; + } + raw.reasoningTokens += msg.reasoning; + raw.outputTokens += msg.output; + raw.cacheReadTokens += msg.cacheRead; + raw.freshTokens += msg.input + msg.cacheWrite; + } + } + + if (sessionContributed.today) data.today.totals.sessions++; + if (sessionContributed.thisWeek) data.thisWeek.totals.sessions++; + if (sessionContributed.lastWeek) data.lastWeek.totals.sessions++; + if (sessionContributed.thisMonth) data.thisMonth.totals.sessions++; + if (sessionContributed.last30Days) data.last30Days.totals.sessions++; + if (sessionContributed.allTime) data.allTime.totals.sessions++; +} + +// ============================================================================= +// Nested tool-usage accounting +// ============================================================================= + +// Recognised nested-agent tool results report usage for child runs that +// pi-subagents also persists as ordinary session files, which this scan +// already counts with full model attribution. When every child session file +// behind a report is part of the scan, the children speak for themselves and +// the parent's aggregate is skipped. Otherwise the aggregate (or, for pre-0.81 +// legacy entries, each unresolved child's reported usage) is counted under +// Tools / summaries. +// +// Copied branch history gets a new parent filename, so a copy's runId-derived +// child paths can dangle even though the original's resolve. Resolved child +// identities are therefore unioned across all copies of an entry before any +// emission, and identical emissions collapse in the sourceId dedupe. + +interface ScannedSessionIndex { + /** Resolved paths of scanned files that have a session header. */ + paths: Set; + /** Directory of each scanned file → number of scanned files inside it. */ + fileCountByDir: Map; +} + +function buildScannedSessionIndex(states: Map): ScannedSessionIndex { + const paths = new Set(); + const fileCountByDir = new Map(); + for (const [filePath, state] of states) { + if (!state.parsed.sessionId) continue; + const resolved = resolve(filePath); + paths.add(resolved); + const dir = dirname(resolved); + fileCountByDir.set(dir, (fileCountByDir.get(dir) ?? 0) + 1); + } + return { paths, fileCountByDir }; +} + +function childSessionScanned( + parentFilePath: string, + tool: ToolUsageRecord, + child: ChildToolUsage, + index: ScannedSessionIndex +): boolean { + if (child.sessionFile) { + const explicit = isAbsolute(child.sessionFile) + ? resolve(child.sessionFile) + : resolve(dirname(parentFilePath), child.sessionFile); + if (index.paths.has(explicit)) return true; + } + if (tool.runId) { + const runDir = resolve(dirname(parentFilePath), basename(parentFilePath, ".jsonl"), tool.runId, `run-${child.resultIndex}`); + // The run directory holds exactly one session per child run, so either the + // conventional name or a lone scanned file inside it identifies the child. + if (index.paths.has(join(runDir, "session.jsonl"))) return true; + if (index.fileCountByDir.get(runDir) === 1) return true; + } + return false; +} + +/** Identity of one child slot of one tool entry, stable across copied history. */ +function toolChildIdentity(tool: ToolUsageRecord, child: ChildToolUsage): string { + const fingerprint = child.usage.input + child.usage.output + child.usage.cacheRead + child.usage.cacheWrite; + return `${tool.sourceId}:${tool.timestamp}:${child.resultIndex}:${fingerprint}`; +} + +function resolvedToolChildIdentities(states: Map, index: ScannedSessionIndex): Set { + const resolved = new Set(); + for (const [filePath, state] of states) { + for (const tool of state.parsed.toolUsages) { + if (!tool.sourceId) continue; + for (const child of tool.children) { + if (childSessionScanned(filePath, tool, child, index)) resolved.add(toolChildIdentity(tool, child)); + } + } + } + return resolved; +} + +function toolUsageMessages( + parentFilePath: string, + tool: ToolUsageRecord, + index: ScannedSessionIndex, + resolvedChildren: Set +): SessionMessage[] { + const scanned = (child: ChildToolUsage) => + childSessionScanned(parentFilePath, tool, child, index) || + (tool.sourceId !== "" && resolvedChildren.has(toolChildIdentity(tool, child))); + if (tool.reportedUsage) { + if (tool.children.length > 0 && tool.children.every(scanned)) return []; + return [auxiliaryMessage(tool.reportedUsage, tool.timestamp, tool.sourceId)]; + } + // Before Pi 0.81, recognised nested-agent tools persisted per-child usage in + // details only. Count just the children whose sessions this scan cannot see. + return tool.children + .filter((child) => !scanned(child)) + .map((child) => auxiliaryMessage(child.usage, tool.timestamp, tool.sourceId ? `${tool.sourceId}:child:${child.resultIndex}` : "")); +} +// ============================================================================= +// Collection orchestration +// ============================================================================= + +const STAT_CONCURRENCY = 16; +const DEFAULT_PARSE_CONCURRENCY = 4; +const AGGREGATE_YIELD_EVERY_FILES = 200; + +export interface CollectProgress { + /** Why this pass needs to parse files. */ + mode: "first-run" | "rebuild" | "update"; + /** Session files that need parsing this pass (0 = fully warm). */ + filesToParse: number; + /** Files parsed so far; reported in coarse increments. */ + filesParsed: number; + /** Newest session activity already ingested (ms since epoch); null when starting fresh. */ + sinceMs: number | null; +} + +export interface CollectUsageOptions { + signal?: AbortSignal; + /** Called once before parsing begins and periodically while files are parsed. */ + onProgress?: (progress: CollectProgress) => void; + /** Defaults to the directory where Pi keeps sessions. */ + sessionsDir?: string; + /** Defaults to `/usage-extension-cache.json`. Pass `null` to disable the on-disk cache. */ + cachePath?: string | null; + /** Reference time for period bucketing. Defaults to `new Date()`. */ + now?: Date; + parseConcurrency?: number; +} + +export async function collectUsageData(options: CollectUsageOptions = {}): Promise { + const signal = options.signal; + const now = options.now ?? new Date(); + const sessionsDir = options.sessionsDir ?? getSessionsDir(); + const cachePath = options.cachePath === undefined ? getDefaultCachePath() : options.cachePath; + const parseConcurrency = Math.max(1, options.parseConcurrency ?? DEFAULT_PARSE_CONCURRENCY); + + const startOfToday = new Date(now); + startOfToday.setHours(0, 0, 0, 0); + const todayMs = startOfToday.getTime(); + + // Start of current week (Monday 00:00) + const startOfWeek = new Date(now); + const dayOfWeek = startOfWeek.getDay(); // 0 = Sunday, 1 = Monday, ... + const daysSinceMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1; + startOfWeek.setDate(startOfWeek.getDate() - daysSinceMonday); + startOfWeek.setHours(0, 0, 0, 0); + const weekStartMs = startOfWeek.getTime(); + + // Start of last week (previous Monday 00:00) + const startOfLastWeek = new Date(startOfWeek); + startOfLastWeek.setDate(startOfLastWeek.getDate() - 7); + const lastWeekStartMs = startOfLastWeek.getTime(); + + // Calendar month to date, from local midnight on the first. + const startOfThisMonth = new Date(now); + startOfThisMonth.setDate(1); + startOfThisMonth.setHours(0, 0, 0, 0); + const thisMonthStartMs = startOfThisMonth.getTime(); + + // Rolling 30-day window: the last 30 calendar days including today, + // i.e. from midnight 29 days before today. setDate handles DST correctly. + const startOfLast30Days = new Date(startOfToday); + startOfLast30Days.setDate(startOfLast30Days.getDate() - 29); + const last30DaysStartMs = startOfLast30Days.getTime(); + + // 1. Discover session files. The cache does not depend on discovery, so + // load it at the same time. + const cacheStatePromise = Promise.all([ + cachePath + ? stat(cachePath).then( + () => true, + () => false // No cache file yet — first run. + ) + : false, + cachePath ? loadUsageCache(cachePath) : new Map(), + ]); + const filePaths = await getAllSessionFiles(sessionsDir, signal); + if (signal?.aborted) return null; + + // 2. Stat them (batched) so cache freshness can be checked without reading contents. + const fileStats = new Map(); + { + let next = 0; + await Promise.all( + Array.from({ length: STAT_CONCURRENCY }, async () => { + while (next < filePaths.length) { + if (signal?.aborted) return; + const filePath = filePaths[next++]!; + try { + const st = await stat(filePath); + fileStats.set(filePath, { size: st.size, mtimeMs: st.mtimeMs }); + } catch { + // File vanished between listing and stat — skip it. + } + } + }) + ); + } + if (signal?.aborted) return null; + + // 3. Load the cache and decide which files actually need parsing. + const [cacheFileExists, previous] = await cacheStatePromise; + if (signal?.aborted) return null; + const current = new Map(); + const toParse: string[] = []; + for (const filePath of filePaths) { + const st = fileStats.get(filePath); + if (!st) continue; + const cached = previous.get(filePath); + if (cached && cached.size === st.size && cached.mtimeMs === st.mtimeMs) { + current.set(filePath, cached); + } else { + toParse.push(filePath); + } + } + let dirty = toParse.length > 0; + if (!dirty) { + for (const filePath of previous.keys()) { + if (!fileStats.has(filePath)) { + dirty = true; // A cached file was deleted — evict it by rewriting. + break; + } + } + } + + // Progress reporting: distinguish a true first run from a format-change + // rebuild (cache file present but unusable) and a routine incremental update. + const progressMode: CollectProgress["mode"] = + previous.size > 0 ? "update" : cacheFileExists ? "rebuild" : "first-run"; + let sinceMs: number | null = null; + if (progressMode === "update") { + for (const state of previous.values()) { + if (state.mtimeMs > (sinceMs ?? 0)) sinceMs = state.mtimeMs; + } + } + let filesParsed = 0; + const reportProgress = (): void => { + options.onProgress?.({ mode: progressMode, filesToParse: toParse.length, filesParsed, sinceMs }); + }; + reportProgress(); + + // 4. Parse new/changed files with bounded concurrency. + { + let next = 0; + await Promise.all( + Array.from({ length: parseConcurrency }, async () => { + while (next < toParse.length) { + if (signal?.aborted) return; + const filePath = toParse[next++]!; + const st = fileStats.get(filePath)!; + let buffer: Buffer; + try { + buffer = await readFile(filePath); + } catch { + filesParsed++; + continue; // File vanished — skip it. + } + const parsed = await parseSessionBuffer(buffer, signal); + if (signal?.aborted) return; // Never cache a partial parse. + current.set(filePath, { size: st.size, mtimeMs: st.mtimeMs, parsed }); + filesParsed++; + if (filesParsed % PROGRESS_REPORT_EVERY === 0 || filesParsed === toParse.length) { + reportProgress(); + } + } + }) + ); + } + + if (signal?.aborted) { + // Best effort: persist whatever finished so a cancelled cold build makes + // the next attempt cheaper. Keep old entries for files not processed yet — + // they are re-validated against size/mtime next run anyway. + if (cachePath && dirty && current.size > 0) { + const merged = new Map(previous); + for (const [filePath, state] of current) merged.set(filePath, state); + await saveUsageCache(cachePath, merged).catch(() => {}); + } + return null; + } + + // 5. Persist the refreshed cache (also evicts entries for deleted files). + if (cachePath && dirty) { + await saveUsageCache(cachePath, current).catch(() => { + // Cache write failures must never break /usage. + }); + } + + // 6. Aggregate in sorted path order with cross-file dedupe. + const data = emptyUsageData({ + todayMs, + weekStartMs, + lastWeekStartMs, + thisMonthStartMs, + last30DaysStartMs, + nowMs: now.getTime(), + }); + const rawByPeriod: Record = { + today: emptyPeriodRawData(), + thisWeek: emptyPeriodRawData(), + lastWeek: emptyPeriodRawData(), + thisMonth: emptyPeriodRawData(), + last30Days: emptyPeriodRawData(), + allTime: emptyPeriodRawData(), + }; + const costByDayIdx = new Map(); + const seenSessions = new Set(); + const seenHashes = new Set(); + const scannedSessions = buildScannedSessionIndex(current); + const resolvedToolChildren = resolvedToolChildIdentities(current, scannedSessions); + let processedFiles = 0; + + for (const filePath of filePaths) { + const state = current.get(filePath); + if (!state || !state.parsed.sessionId) continue; + + if (++processedFiles % AGGREGATE_YIELD_EVERY_FILES === 0) { + await new Promise((resolve) => setImmediate(resolve)); + if (signal?.aborted) return null; + } + + // Deduplicate copied history across branched session files, computing + // adjacency metadata (idle gaps, previous context) on the raw file order + // so branch copies do not distort miss classification. + const toolMessages = state.parsed.toolUsages.flatMap((tool) => toolUsageMessages(filePath, tool, scannedSessions, resolvedToolChildren)); + const rawMsgs = toolMessages.length > 0 ? [...state.parsed.messages, ...toolMessages] : state.parsed.messages; + const deduped: SessionMessage[] = []; + const meta: MessageMeta[] = []; + let previousAssistant: SessionMessage | null = null; + for (const m of rawMsgs) { + // Auxiliary usage is interleaved with conversation entries, but it must + // not become the "previous message" for cache-miss classification. + const prev = m.source === "assistant" ? previousAssistant : null; + if (m.source === "assistant") previousAssistant = m; + + // Pi entry ids survive copied branch history and distinguish parallel + // tool results that happen to report identical usage in the same ms. + const tokenFingerprint = m.input + m.output + m.cacheRead + m.cacheWrite; + const hash = + m.source === "auxiliary" && m.sourceId + ? `auxiliary:${m.sourceId}:${m.timestamp}:${tokenFingerprint}` + : `${m.source}:${m.timestamp}:${tokenFingerprint}`; + if (seenHashes.has(hash)) continue; + seenHashes.add(hash); + deduped.push(m); + meta.push({ + gapMs: prev && prev.timestamp > 0 && m.timestamp > 0 ? m.timestamp - prev.timestamp : -1, + prevCtx: prev ? prev.input + prev.cacheRead + prev.cacheWrite : 0, + modelSwitched: prev !== null && (prev.provider !== m.provider || prev.model !== m.model), + isSessionStart: false, + }); + } + if (deduped.length === 0) continue; + const firstAssistantIndex = deduped.findIndex((m) => m.source === "assistant"); + if (firstAssistantIndex !== -1 && !seenSessions.has(state.parsed.sessionId)) { + seenSessions.add(state.parsed.sessionId); + meta[firstAssistantIndex]!.isSessionStart = true; + } + + addMessagesToUsageData( + data, + state.parsed.sessionId, + projectLabelFromCwd(state.parsed.cwd), + deduped, + meta, + todayMs, + weekStartMs, + lastWeekStartMs, + thisMonthStartMs, + last30DaysStartMs, + rawByPeriod, + costByDayIdx + ); + } + + // Burn trend: last 7 calendar days vs the average weekly pace of the prior 28. + let last7 = 0; + let prior28 = 0; + for (const [idx, c] of costByDayIdx) { + if (idx >= -6) last7 += c; + else if (idx >= -34) prior28 += c; + } + const trend: TrendInfo | null = prior28 > 0 ? { last7Cost: last7, priorWeeklyPace: prior28 / 4 } : null; + + for (const period of TAB_ORDER) { + data[period].insights = computeInsights(rawByPeriod[period], trend); + } + + return data; +} + +// ============================================================================= +// Insights +// ============================================================================= + +// Context tax (structure) +const CTX_TAX_THRESHOLD = 150_000; +const CTX_LOW_THRESHOLD = 100_000; +// Project mix (structure) +const PROJECT_TOP_COUNT = 3; +const PROJECT_MAX_DOMINANCE_PERCENT = 90; +// Reasoning share (structure) +const REASONING_MIN_PERCENT = 5; +// Burn trend (structure) +const TREND_HIGH_RATIO = 1.5; +const TREND_LOW_RATIO = 0.6; +// Cache-miss alarms +const TTL_GAP_MS = 5 * 60_000; +const MISS_MIN_PREV_CONTEXT = 20_000; +const MISS_MAX_CACHE_READ = 5_000; +/** pi's built-in test providers never send anything to a real API. */ +const EXCLUDED_PROVIDERS = new Set(["faux-provider", "fake-provider"]); + +const CACHE_MISS_ALARM_PERCENT = 2; +const CACHE_MISS_ALARM_MIN_COST = 1; +// Concentration / upfront alarms +const TOP_SESSION_COUNT = 5; +const CONCENTRATION_ALARM_PERCENT = 35; +const UPFRONT_ALARM_PERCENT = 8; +// Cache-leverage alarm +const LEVERAGE_FLOOR = 5; +const LEVERAGE_MIN_COST = 5; +const LEVERAGE_MIN_FRESH_TOKENS = 1_000_000; + +function fmtMoney(v: number): string { + if (v >= 1000) return `$${(v / 1000).toFixed(1)}k`; + if (v >= 100) return `$${Math.round(v)}`; + return `$${v.toFixed(2)}`; +} + +function fmtPercent(p: number): string { + return p >= 10 ? `${Math.round(p)}%` : `${p.toFixed(1)}%`; +} + +/** + * Insights come in two kinds: + * - structure: always-on decomposition of where the period's cost went. + * - alarm: fires only when a wasteful pattern is material for the period, so + * an all-clear period shows a calm panel instead of a wall of 2% factoids. + * Periods with zero recorded cost produce an empty list — the UI renders a + * distinct empty-state for that case. + */ +function computeInsights(raw: PeriodRawData, trend: TrendInfo | null): PeriodInsights { + if (raw.totalCost <= 0) { + return { insights: [] }; + } + const total = raw.totalCost; + const assistantTotal = raw.assistantCost; + const assistantPctLabel = raw.auxiliaryCost > 0 ? "助手消息花费" : "本期花费"; + const insights: Insight[] = []; + + // --- Alarms (listed first) --- + + const ttlPct = assistantTotal > 0 ? (raw.ttlMissCost / assistantTotal) * 100 : 0; + if (ttlPct >= CACHE_MISS_ALARM_PERCENT && raw.ttlMissCost >= CACHE_MISS_ALARM_MIN_COST) { + insights.push({ + kind: "alarm", + stat: fmtMoney(raw.ttlMissCost), + headline: `花在停顿后恢复会话上(占${assistantPctLabel}的 ${fmtPercent(ttlPct)})`, + advice: + "已发送的上下文只有几分钟可复用。停顿较久后,下一条消息要按全价重发整段对话。趁会话还新鲜时继续回复即可避免。", + }); + } + + const switchPct = assistantTotal > 0 ? (raw.modelSwitchMissCost / assistantTotal) * 100 : 0; + if (switchPct >= CACHE_MISS_ALARM_PERCENT && raw.modelSwitchMissCost >= CACHE_MISS_ALARM_MIN_COST) { + insights.push({ + kind: "alarm", + stat: fmtMoney(raw.modelSwitchMissCost), + headline: `花在对话中途切换模型上(占${assistantPctLabel}的 ${fmtPercent(switchPct)})`, + advice: + "换模型会按全价重发整段对话 — 上一个模型存下的上下文不会转移。改为在两个任务之间切换即可避免。", + }); + } + + const prefixPct = assistantTotal > 0 ? (raw.prefixMissCost / assistantTotal) * 100 : 0; + if (prefixPct >= CACHE_MISS_ALARM_PERCENT && raw.prefixMissCost >= CACHE_MISS_ALARM_MIN_COST) { + insights.push({ + kind: "alarm", + stat: fmtMoney(raw.prefixMissCost), + headline: `花在会话中途重发上下文上(占${assistantPctLabel}的 ${fmtPercent(prefixPct)})`, + advice: + "这些消息为已经发过的上下文又付了一次全价 — 且没有停顿、压缩或换模型可以解释。通常是某个工具或流程在重启、重写对话。若长期偏高值得排查。", + }); + } + + if (raw.sessionCosts.size > TOP_SESSION_COUNT) { + const sortedSessions = Array.from(raw.sessionCosts.values()).sort((a, b) => b - a); + const topWeight = sortedSessions.slice(0, TOP_SESSION_COUNT).reduce((sum, c) => sum + c, 0); + const topPct = (topWeight / total) * 100; + if (topPct >= CONCENTRATION_ALARM_PERCENT) { + insights.push({ + kind: "alarm", + stat: fmtMoney(topWeight), + headline: `只来自你 ${raw.sessionCosts.size} 个会话中的 ${TOP_SESSION_COUNT} 个(本期 ${fmtPercent(topPct)})`, + advice: "少数几个会话吃掉了大部分花费。图表视图可以看出它们在做什么。", + }); + } + } + + const upfrontPct = assistantTotal > 0 ? (raw.upfrontCost / assistantTotal) * 100 : 0; + if (upfrontPct >= UPFRONT_ALARM_PERCENT) { + insights.push({ + kind: "alarm", + stat: fmtMoney(raw.upfrontCost), + headline: `花在新会话的首条消息上(占${assistantPctLabel}的 ${fmtPercent(upfrontPct)})`, + advice: "会话的第一条消息要从零发送全部内容。更少、更长的会话可以降低这部分开销。", + }); + } + + if (assistantTotal >= LEVERAGE_MIN_COST && raw.freshTokens >= LEVERAGE_MIN_FRESH_TOKENS) { + const leverage = raw.cacheReadTokens / raw.freshTokens; + if (leverage < LEVERAGE_FLOOR) { + insights.push({ + kind: "alarm", + stat: `${leverage.toFixed(1)}×`, + headline: "历史复用倍数(每付一次全价的 token)", + advice: + "典型交互式用法能复用 10× 以上。数值偏低说明对话在反复从零发送 — 找找有没有会重启会话的流程。", + }); + } + } + + // --- Structure (always-on) --- + + if (raw.auxiliaryCost > 0) { + const pct = (raw.auxiliaryCost / total) * 100; + if (pct >= 1) { + insights.push({ + kind: "structure", + stat: fmtPercent(pct), + headline: "的花费来自工具与对话摘要上报的用量", + advice: "Pi 单独记录这部分,因为它无法可靠归属到某个具体渠道和模型。", + }); + } + } + + if (raw.ctxHigh.messages > 0 && assistantTotal > 0) { + const pct = (raw.ctxHigh.cost / assistantTotal) * 100; + if (pct >= 1) { + const avgHigh = raw.ctxHigh.cost / raw.ctxHigh.messages; + const avgLow = raw.ctxLow.messages > 0 ? raw.ctxLow.cost / raw.ctxLow.messages : 0; + const cmp = + avgLow > 0 + ? ` — 每条 ${fmtMoney(avgHigh)},而低于 ${formatThresholdTokens(CTX_LOW_THRESHOLD)} 时为 ${fmtMoney(avgLow)}` + : ""; + insights.push({ + kind: "structure", + stat: fmtPercent(pct), + headline: `的${raw.auxiliaryCost > 0 ? "助手消息花费" : "花费"}来自载入 ≥${formatThresholdTokens(CTX_TAX_THRESHOLD)} token 的消息${cmp}`, + advice: "长对话每条消息都更贵。任务中段 /compact、任务之间 /clear 可以让对话保持精简。", + }); + } + } + + if (raw.projectCosts.size >= 2) { + const top = [...raw.projectCosts.entries()].sort((a, b) => b[1] - a[1]).slice(0, PROJECT_TOP_COUNT); + const topPct = (top[0]![1] / total) * 100; + if (topPct < PROJECT_MAX_DOMINANCE_PERCENT) { + const rest = top + .slice(1) + .map(([label, c]) => `${label} ${fmtPercent((c / total) * 100)}`) + .join(", "); + insights.push({ + kind: "structure", + stat: fmtPercent(topPct), + headline: `的花费来自 ${top[0]![0]}${rest ? ` — 其次是 ${rest}` : ""}`, + advice: "", + }); + } + } + + if (raw.outputTokens > 0) { + const reasoningPct = (raw.reasoningTokens / raw.outputTokens) * 100; + if (reasoningPct >= REASONING_MIN_PERCENT) { + insights.push({ + kind: "structure", + stat: fmtPercent(reasoningPct), + headline: "的输出 token 属于隐藏推理", + advice: + "模型会按输出 token 收取后台思考的费用。pi 自 0.80.3(2026 年 6 月)起才记录此项,更早的周期会偏低。", + }); + } + } + + if (trend && trend.priorWeeklyPace > 0) { + const ratio = trend.last7Cost / trend.priorWeeklyPace; + const advice = + ratio >= TREND_HIGH_RATIO + ? "花费相对你自己的基线在上升 — 图表视图可以看出变化来自哪里。" + : ratio <= TREND_LOW_RATIO + ? "花费明显低于你近期的基线。" + : ""; + insights.push({ + kind: "structure", + stat: `${ratio.toFixed(1)}×`, + headline: `最近 7 天(${fmtMoney(trend.last7Cost)})对比此前 4 周的周均(${fmtMoney(trend.priorWeeklyPace)}/周)`, + advice, + }); + } + + return { insights }; +} + +function formatThresholdTokens(n: number): string { + if (n >= 1_000_000) return `${n / 1_000_000}M`; + if (n >= 1_000) return `${n / 1_000}k`; + return String(n); +} diff --git a/export.ts b/export.ts new file mode 100644 index 0000000..2b32e6e --- /dev/null +++ b/export.ts @@ -0,0 +1,146 @@ +/** + * Pure builders for /usage export ([e] key). + * + * Each view exports its current slice: the table as per-model CSV rows, the + * graph as one CSV column per visible series, and insights as structured JSON. + * Builders are pure string producers so they stay trivially testable; the + * component owns file naming and disk writes. + */ + +import { join } from "node:path"; +import type { Insight, ProviderStats, TotalStats } from "./data.ts"; +import type { GraphModel } from "./graph.ts"; + +/** + * Read the configured export directory from settings.json content, if any. + * Config shape: `{ "usage-extension": { "exportDir": "~/Downloads" } }`. + */ +export function parseExportDirSetting(settingsJson: string): string | null { + try { + const parsed = JSON.parse(settingsJson) as { "usage-extension"?: { exportDir?: unknown } }; + const dir = parsed["usage-extension"]?.exportDir; + return typeof dir === "string" && dir.trim() !== "" ? dir.trim() : null; + } catch { + return null; + } +} + +/** + * Pick the export directory. A configured dir wins (with `~` expanded); + * otherwise exports go to /tmp so they never litter a repo or home + * directory, falling back to the OS temp dir where /tmp doesn't exist. + */ +export function resolveExportDir( + configured: string | null, + home: string, + slashTmpExists: boolean, + fallbackTmp: string, +): string { + if (configured !== null) { + if (configured === "~") return home; + if (configured.startsWith("~/")) return join(home, configured.slice(2)); + return configured; + } + return slashTmpExists ? "/tmp" : fallbackTmp; +} + +/** Quote a CSV field only when it needs it (comma, quote, or newline). */ +function csvField(value: string | number): string { + const s = String(value); + return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +function csvLine(fields: (string | number)[]): string { + return fields.map(csvField).join(","); +} + +/** Per-model rows (provider repeated), then a TOTAL row. */ +export function buildTableCsv(providers: ReadonlyMap, totals: TotalStats): string { + const lines = [ + csvLine([ + "provider", + "model", + "sessions", + "messages", + "cost_usd", + "fresh_tokens", + "input_tokens", + "output_tokens", + "cache_read_tokens", + "cache_write_tokens", + ]), + ]; + const sorted = Array.from(providers.entries()).sort((a, b) => b[1].cost - a[1].cost); + for (const [providerName, provider] of sorted) { + const models = Array.from(provider.models.entries()).sort((a, b) => b[1].cost - a[1].cost); + for (const [modelName, model] of models) { + lines.push( + csvLine([ + providerName, + modelName, + model.sessions.size, + model.messages, + model.cost, + model.tokens.total, + model.tokens.input, + model.tokens.output, + model.tokens.cacheRead, + model.tokens.cacheWrite, + ]) + ); + } + } + lines.push( + csvLine([ + "TOTAL", + "", + totals.sessions, + totals.messages, + totals.cost, + totals.tokens.total, + totals.tokens.input, + totals.tokens.output, + totals.tokens.cacheRead, + totals.tokens.cacheWrite, + ]) + ); + return lines.join("\n") + "\n"; +} + +/** + * One row per time bucket, one column per visible series, values exactly as + * plotted (per-bucket or cumulative, current metric). + */ +export function buildGraphCsv(model: GraphModel): string { + const visible = model.series.filter((s) => !s.hidden); + const lines = [csvLine(["bucket_start", ...visible.map((s) => s.label)])]; + for (let i = 0; i < model.bucketStarts.length; i++) { + lines.push(csvLine([new Date(model.bucketStarts[i]!).toISOString(), ...visible.map((s) => s.points[i] ?? 0)])); + } + return lines.join("\n") + "\n"; +} + +/** Structured JSON of the period's insights plus headline totals. */ +export function buildInsightsJson(period: string, totals: TotalStats, insights: Insight[]): string { + return ( + JSON.stringify( + { + period, + generatedAt: new Date().toISOString(), + totals: { costUsd: totals.cost, messages: totals.messages, sessions: totals.sessions }, + insights: insights.map((i) => ({ kind: i.kind, stat: i.stat, headline: i.headline, advice: i.advice })), + }, + null, + "\t" + ) + "\n" + ); +} + +/** usage--[-]-. in the current directory. */ +export function exportFileName(view: string, period: string, slice: string | null, ext: string, now: Date): string { + const pad = (n: number) => String(n).padStart(2, "0"); + const stamp = + `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` + + `-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; + return ["usage", view, period, ...(slice ? [slice] : []), stamp].join("-") + `.${ext}`; +} diff --git a/graph.ts b/graph.ts new file mode 100644 index 0000000..90eddcb --- /dev/null +++ b/graph.ts @@ -0,0 +1,413 @@ +/** + * Graph explorer model + braille chart rendering for /usage. + * + * Everything here is pure and theme-free: series building works off the hourly + * buckets produced by data.ts, and the renderer emits plain text plus a + * colorize callback so the UI layer owns all styling. This keeps the module + * fully unit-testable. + */ + +// Explicit .ts extension so plain `node --test` (type stripping) can resolve +// this module too; pi's extension loader accepts it as well. +import type { HourlyCell, HourlyKey, PeriodBounds, TabName } from "./data.ts"; +import { splitHourlyKey } from "./data.ts"; + +// ============================================================================= +// Options and model types +// ============================================================================= + +export type GraphMetric = "cost" | "tokens" | "messages" | "reasoning"; +export type GraphGroupBy = "provider" | "model" | "thinking" | "total"; + +export const METRIC_ORDER: GraphMetric[] = ["cost", "tokens", "messages", "reasoning"]; +export const GROUP_ORDER: GraphGroupBy[] = ["provider", "model", "thinking", "total"]; + +export const METRIC_LABELS: Record = { + cost: "花费", + tokens: "Token", + messages: "消息数", + reasoning: "推理 Token", +}; + +export const GROUP_LABELS: Record = { + provider: "按渠道", + model: "按模型", + thinking: "按思考等级", + total: "仅合计", +}; + +/** Series beyond this cap are merged into a single "other" series. */ +export const MAX_GROUP_SERIES = 6; + +export const TOTAL_SERIES_KEY = "\u0000total"; +export const OTHER_SERIES_KEY = "\u0000other"; + +export interface GraphOptions { + period: TabName; + metric: GraphMetric; + groupBy: GraphGroupBy; + cumulative: boolean; + /** Series keys hidden via the legend. */ + hidden?: ReadonlySet; + bounds: PeriodBounds; +} + +export interface GraphSeries { + key: string; + label: string; + /** One value per bucket. Cumulative when options.cumulative. */ + points: number[]; + /** Period total for this series (not affected by cumulative). */ + total: number; + hidden: boolean; + /** First bucket index with activity, or -1 when the series is empty. */ + firstIdx: number; + /** Last bucket index with activity, or -1 when the series is empty. */ + lastIdx: number; +} + +export interface GraphModel { + series: GraphSeries[]; + /** Bucket start timestamps (ms), ascending. */ + bucketStarts: number[]; + bucketMs: number; + domainStartMs: number; + domainEndMs: number; + /** Max point value across visible series (y-axis scale). */ + yMax: number; + /** Sum of totals across grouped (non-total) series, for legend percentages. */ + groupedTotal: number; +} + +// ============================================================================= +// Series building +// ============================================================================= + +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; +/** Periods spanning at most this many hours use hourly buckets; otherwise daily. */ +const MAX_HOURLY_BUCKETS = 8 * 24; + +function metricOf(cell: HourlyCell, metric: GraphMetric): number { + switch (metric) { + case "cost": + return cell.cost; + case "tokens": + // Matches the dashboard formula: fresh tokens = input + output + cacheWrite. + return cell.input + cell.output + cell.cacheWrite; + case "messages": + return cell.messages; + case "reasoning": + return cell.reasoning; + } +} + +function groupKeyOf(key: HourlyKey, groupBy: GraphGroupBy): string { + if (groupBy === "total") return TOTAL_SERIES_KEY; + const { provider, model, thinkingLevel } = splitHourlyKey(key); + if (groupBy === "provider") return provider; + if (groupBy === "model") return model; + return thinkingLevel === "" ? "未知" : thinkingLevel; +} + +function domainFor(period: TabName, bounds: PeriodBounds, hourly: Map>): { startMs: number; endMs: number } { + switch (period) { + case "today": + return { startMs: bounds.todayMs, endMs: bounds.nowMs }; + case "thisWeek": + return { startMs: bounds.weekStartMs, endMs: bounds.nowMs }; + case "lastWeek": + return { startMs: bounds.lastWeekStartMs, endMs: bounds.weekStartMs }; + case "thisMonth": + return { startMs: bounds.thisMonthStartMs, endMs: bounds.nowMs }; + case "last30Days": + return { startMs: bounds.last30DaysStartMs, endMs: bounds.nowMs }; + case "allTime": { + let first = Number.POSITIVE_INFINITY; + for (const hour of hourly.keys()) if (hour < first) first = hour; + if (!Number.isFinite(first)) first = bounds.todayMs; + return { startMs: Math.min(first, bounds.nowMs), endMs: bounds.nowMs }; + } + } +} + +/** + * Build the graph model for one (period, metric, groupBy) view. + * + * Buckets are hourly for short periods and daily for long ones. Group series + * are capped at MAX_GROUP_SERIES by period total; the rest merge into "other". + * A Total series is always present (first). Hidden series keep their points + * but are excluded from the y-axis scale. + */ +export function buildGraphModel( + hourly: Map>, + options: GraphOptions +): GraphModel { + const { startMs, endMs } = domainFor(options.period, options.bounds, hourly); + const spanMs = Math.max(endMs - startMs, 1); + const bucketMs = spanMs / HOUR_MS <= MAX_HOURLY_BUCKETS ? HOUR_MS : DAY_MS; + + // Bucket starts aligned to the domain start so "day" buckets follow the + // local-midnight period boundaries computed by data.ts (DST shifts move a + // boundary by an hour, which is invisible at graph resolution). + const bucketCount = Math.max(1, Math.ceil(spanMs / bucketMs)); + const bucketStarts: number[] = []; + for (let i = 0; i < bucketCount; i++) bucketStarts.push(startMs + i * bucketMs); + + // Accumulate per-group bucket values. + const groupValues = new Map(); + const groupTotals = new Map(); + const totalPoints = new Array(bucketCount).fill(0); + let totalSum = 0; + + for (const [hour, bucket] of hourly) { + if (hour < startMs || hour >= endMs) continue; + const idx = Math.min(bucketCount - 1, Math.floor((hour - startMs) / bucketMs)); + for (const [key, cell] of bucket) { + const value = metricOf(cell, options.metric); + if (value === 0) continue; + totalPoints[idx] += value; + totalSum += value; + if (options.groupBy !== "total") { + const groupKey = groupKeyOf(key, options.groupBy); + let points = groupValues.get(groupKey); + if (!points) { + points = new Array(bucketCount).fill(0); + groupValues.set(groupKey, points); + } + points[idx] += value; + groupTotals.set(groupKey, (groupTotals.get(groupKey) ?? 0) + value); + } + } + } + + // Rank groups and cap at MAX_GROUP_SERIES; merge the tail into "other". + const ranked = Array.from(groupTotals.entries()).sort((a, b) => b[1] - a[1]); + const kept = ranked.slice(0, MAX_GROUP_SERIES); + const merged = ranked.slice(MAX_GROUP_SERIES); + + const hidden = options.hidden ?? new Set(); + const series: GraphSeries[] = []; + + // Active range per series (computed on raw per-bucket values, before any + // cumulative transform): lines are later drawn only between the first and + // last bucket with usage, so late-starting or retired series do not drag a + // flat zero/flat tail across the whole period. + const activeRange = (points: number[]): { firstIdx: number; lastIdx: number } => { + let firstIdx = -1; + let lastIdx = -1; + for (let i = 0; i < points.length; i++) { + if (points[i] !== 0) { + if (firstIdx === -1) firstIdx = i; + lastIdx = i; + } + } + return { firstIdx, lastIdx }; + }; + + series.push({ + key: TOTAL_SERIES_KEY, + label: "合计", + points: totalPoints.slice(), + total: totalSum, + hidden: hidden.has(TOTAL_SERIES_KEY), + ...activeRange(totalPoints), + }); + + for (const [groupKey, total] of kept) { + const points = groupValues.get(groupKey)!; + series.push({ + key: groupKey, + label: groupKey, + points, + total, + hidden: hidden.has(groupKey), + ...activeRange(points), + }); + } + + if (merged.length > 0) { + const points = new Array(bucketCount).fill(0); + let total = 0; + for (const [groupKey, groupTotal] of merged) { + const groupPoints = groupValues.get(groupKey)!; + for (let i = 0; i < bucketCount; i++) points[i] += groupPoints[i]!; + total += groupTotal; + } + series.push({ + key: OTHER_SERIES_KEY, + label: `其他 (${merged.length})`, + points, + total, + hidden: hidden.has(OTHER_SERIES_KEY), + ...activeRange(points), + }); + } + + if (options.cumulative) { + for (const s of series) { + let running = 0; + s.points = s.points.map((v) => (running += v)); + } + } + + let yMax = 0; + for (const s of series) { + if (s.hidden) continue; + for (const v of s.points) if (v > yMax) yMax = v; + } + + return { + series, + bucketStarts, + bucketMs, + domainStartMs: startMs, + domainEndMs: endMs, + yMax, + groupedTotal: totalSum, + }; +} + +// ============================================================================= +// Braille chart rendering +// ============================================================================= + +/** + * Style callback: seriesIndex is the index into model.series, or -1 for + * chart furniture (axes). Return the text styled for the terminal. + */ +export type ChartColorize = (seriesIndex: number, text: string) => string; + +export interface ChartRenderOptions { + width: number; + /** Text rows for the plot area (each row is 4 braille dots tall). */ + height: number; + formatValue: (value: number) => string; + formatTime: (ms: number) => string; + colorize?: ChartColorize; +} + +const BRAILLE_BASE = 0x2800; +// Dot bit masks by (x: 0=left, 1=right) and (y: 0=top .. 3=bottom). +const DOT_BITS = [ + [0x01, 0x02, 0x04, 0x40], + [0x08, 0x10, 0x20, 0x80], +] as const; + +/** + * Render the model as a braille line chart with a y-axis and an x-axis line. + * Returns exactly height + 1 lines (plot rows + x-axis labels). + */ +export function renderChart(model: GraphModel, options: ChartRenderOptions): string[] { + const colorize: ChartColorize = options.colorize ?? ((_i, text) => text); + const plotHeightForLabels = Math.max(options.height, 4); + const midRowForLabels = Math.floor((plotHeightForLabels - 1) / 2); + const midValue = (model.yMax * (plotHeightForLabels - 1 - midRowForLabels)) / (plotHeightForLabels - 1); + const yLabelWidth = Math.max( + options.formatValue(model.yMax).length, + options.formatValue(midValue).length, + options.formatValue(0).length + ); + const axisWidth = yLabelWidth + 2; // label + " ┤" / " │" + const plotWidth = Math.max(options.width - axisWidth, 10); + const plotHeight = Math.max(options.height, 4); + const dotW = plotWidth * 2; + const dotH = plotHeight * 4; + + // masks[row][col] per series index — draw order decides which color wins a cell. + const cellMasks: number[][] = Array.from({ length: plotHeight }, () => new Array(plotWidth).fill(0)); + const cellOwner: number[][] = Array.from({ length: plotHeight }, () => new Array(plotWidth).fill(-1)); + + const yMax = model.yMax > 0 ? model.yMax : 1; + const bucketCount = model.bucketStarts.length; + + const plot = (seriesIndex: number, points: number[], firstIdx: number, lastIdx: number) => { + if (firstIdx < 0) return; + let prevX = -1; + let prevY = -1; + for (let i = firstIdx; i <= lastIdx; i++) { + const x = bucketCount === 1 ? dotW - 1 : Math.round((i / (bucketCount - 1)) * (dotW - 1)); + const y = Math.round((1 - (points[i]! / yMax)) * (dotH - 1)); + if (prevX >= 0) { + // Connect with a vertical-stepped segment for continuity. + const steps = Math.max(Math.abs(x - prevX), Math.abs(y - prevY), 1); + for (let s = 1; s <= steps; s++) { + const ix = Math.round(prevX + ((x - prevX) * s) / steps); + const iy = Math.round(prevY + ((y - prevY) * s) / steps); + setDot(ix, iy, seriesIndex); + } + } else { + setDot(x, y, seriesIndex); + } + prevX = x; + prevY = y; + } + }; + + const setDot = (x: number, y: number, seriesIndex: number) => { + if (x < 0 || y < 0 || x >= dotW || y >= dotH) return; + const col = Math.floor(x / 2); + const row = Math.floor(y / 4); + cellMasks[row]![col]! |= DOT_BITS[x % 2]![y % 4]!; + cellOwner[row]![col] = seriesIndex; + }; + + // Draw least-important first so important series own contested cells: + // other → smallest groups → largest group → total. + const drawOrder = model.series + .map((s, i) => ({ s, i })) + .filter(({ s }) => !s.hidden) + .sort((a, b) => { + const rank = (entry: { s: GraphSeries; i: number }) => + entry.s.key === TOTAL_SERIES_KEY ? Number.POSITIVE_INFINITY : entry.s.key === OTHER_SERIES_KEY ? -1 : entry.s.total; + return rank(a) - rank(b); + }); + for (const { s, i } of drawOrder) plot(i, s.points, s.firstIdx, s.lastIdx); + + // Compose text rows. + const lines: string[] = []; + const midRow = Math.floor((plotHeight - 1) / 2); + for (let row = 0; row < plotHeight; row++) { + let label = ""; + if (row === 0) label = options.formatValue(model.yMax); + else if (row === midRow && plotHeight > 2) label = options.formatValue(midValue); + else if (row === plotHeight - 1) label = options.formatValue(0); + const axisChar = label ? "┤" : "│"; + let line = colorize(-1, label.padStart(yLabelWidth) + " " + axisChar); + // Batch consecutive cells with the same owning series into one colorize + // call to keep ANSI overhead proportional to color changes, not cells. + let runOwner = -2; + let runText = ""; + const flush = () => { + if (!runText) return; + line += runOwner === -2 ? runText : colorize(runOwner, runText); + runText = ""; + }; + for (let col = 0; col < plotWidth; col++) { + const mask = cellMasks[row]![col]!; + const owner = mask === 0 ? -2 : cellOwner[row]![col]!; + if (owner !== runOwner) { + flush(); + runOwner = owner; + } + runText += mask === 0 ? " " : String.fromCharCode(BRAILLE_BASE + mask); + } + flush(); + lines.push(line); + } + + // X-axis labels: start, optional middle, end. + const startLabel = options.formatTime(model.domainStartMs); + const endLabel = options.formatTime(model.domainEndMs); + const midLabel = plotWidth >= startLabel.length + endLabel.length + 14 ? options.formatTime(model.domainStartMs + (model.domainEndMs - model.domainStartMs) / 2) : ""; + let axis = " ".repeat(yLabelWidth + 2) + startLabel; + if (midLabel) { + const midPos = yLabelWidth + 2 + Math.floor(plotWidth / 2 - midLabel.length / 2); + axis = axis.padEnd(midPos) + midLabel; + } + const endPos = yLabelWidth + 2 + plotWidth - endLabel.length; + axis = axis.padEnd(Math.max(endPos, axis.length + 1)) + endLabel; + lines.push(colorize(-1, axis)); + + return lines; +} diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..ffb9a3d --- /dev/null +++ b/index.ts @@ -0,0 +1,1009 @@ +/** + * /usage - Usage statistics dashboard + * + * Shows an inline view with usage stats grouped by provider. + * - Tab cycles: Today → This Week → Last Week → This Month → All Time + * - Arrow keys navigate providers + * - Enter expands/collapses to show models + * + * Data collection and caching live in ./data.ts. + */ + +import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent"; +import { DynamicBorder } from "@earendil-works/pi-coding-agent"; +import { CancellableLoader, Container, Spacer, matchesKey, visibleWidth, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui"; + +import { collectUsageData, getAgentDir, TAB_ORDER } from "./data"; +import type { CollectProgress } from "./data"; +import type { BaseStats, ProviderStats, TabName, TotalStats, UsageData } from "./data"; +import { + buildGraphModel, + renderChart, + GROUP_LABELS, + GROUP_ORDER, + METRIC_LABELS, + METRIC_ORDER, + TOTAL_SERIES_KEY, +} from "./graph"; +import type { GraphGroupBy, GraphMetric, GraphModel } from "./graph"; +import { + buildGraphCsv, + buildInsightsJson, + buildTableCsv, + exportFileName, + parseExportDirSetting, + resolveExportDir, +} from "./export"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; + +type ViewMode = "table" | "insights" | "graph"; + +const VIEW_CYCLE: ViewMode[] = ["graph", "table", "insights"]; + +const VIEW_LABELS: Record = { + graph: "图表", + table: "表格", + insights: "洞察", +}; + +// ============================================================================= +// Column Configuration +// ============================================================================= + +interface DataColumn { + label: string; + width: number; + dimmed?: boolean; + getValue: (stats: BaseStats & { sessions: Set | number }) => string; +} + +interface TableLayoutCandidate { + columns: DataColumn[]; + minNameWidth: number; + compact?: boolean; +} + +interface TableLayout { + columns: DataColumn[]; + nameWidth: number; + tableWidth: number; + compact: boolean; +} + +const MAX_NAME_COL_WIDTH = 26; + +const SESSIONS_COLUMN: DataColumn = { + label: "会话", + width: 9, + getValue: (s) => formatNumber(typeof s.sessions === "number" ? s.sessions : s.sessions.size), +}; + +const MSGS_COLUMN: DataColumn = { + label: "消息", + width: 9, + getValue: (s) => formatNumber(s.messages), +}; + +const COST_COLUMN: DataColumn = { + label: "花费", + width: 9, + getValue: (s) => formatCost(s.cost), +}; + +const TOKENS_COLUMN: DataColumn = { + label: "Token", + width: 9, + getValue: (s) => formatTokens(s.tokens.total), +}; + +const INPUT_COLUMN: DataColumn = { + label: "↑输入", + width: 8, + dimmed: true, + // Include cacheWrite so this reflects fresh input tokens sent this turn, + // even for providers like Anthropic that split cached prompt creation out + // from the regular input token count. + getValue: (s) => formatTokens(s.tokens.input + s.tokens.cacheWrite), +}; + +const OUTPUT_COLUMN: DataColumn = { + label: "↓输出", + width: 8, + dimmed: true, + getValue: (s) => formatTokens(s.tokens.output), +}; + +const CACHE_COLUMN: DataColumn = { + label: "缓存", + width: 8, + dimmed: true, + getValue: (s) => formatTokens(s.tokens.cacheRead + s.tokens.cacheWrite), +}; + +const FULL_DATA_COLUMNS: DataColumn[] = [ + SESSIONS_COLUMN, + MSGS_COLUMN, + COST_COLUMN, + TOKENS_COLUMN, + INPUT_COLUMN, + OUTPUT_COLUMN, + CACHE_COLUMN, +]; + +const TABLE_LAYOUTS: TableLayoutCandidate[] = [ + { columns: FULL_DATA_COLUMNS, minNameWidth: MAX_NAME_COL_WIDTH }, + { columns: [SESSIONS_COLUMN, MSGS_COLUMN, COST_COLUMN, TOKENS_COLUMN], minNameWidth: 14, compact: true }, + { columns: [SESSIONS_COLUMN, COST_COLUMN, TOKENS_COLUMN], minNameWidth: 12, compact: true }, + { columns: [COST_COLUMN, TOKENS_COLUMN], minNameWidth: 10, compact: true }, + { columns: [COST_COLUMN], minNameWidth: 8, compact: true }, +]; + +// ============================================================================= +// Formatting Helpers +// ============================================================================= + +function formatCost(cost: number): string { + if (cost === 0) return "-"; + if (cost < 0.01) return `$${cost.toFixed(4)}`; + if (cost < 1) return `$${cost.toFixed(2)}`; + if (cost < 10) return `$${cost.toFixed(2)}`; + if (cost < 100) return `$${cost.toFixed(1)}`; + return `$${Math.round(cost)}`; +} + +function formatTokens(count: number): string { + if (count === 0) return "-"; + if (count < 1000) return count.toString(); + if (count < 10000) return `${(count / 1000).toFixed(1)}k`; + if (count < 1000000) return `${Math.round(count / 1000)}k`; + if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`; + return `${Math.round(count / 1000000)}M`; +} + +function formatNumber(n: number): string { + if (n === 0) return "-"; + return n.toLocaleString(); +} + +// Compact axis/legend formatters for the graph view. +function formatAxisCost(v: number): string { + if (v === 0) return "$0"; + if (v < 1) return `$${v.toFixed(2)}`; + if (v < 100) return `$${v.toFixed(1)}`; + if (v < 10_000) return `$${Math.round(v)}`; + if (v < 1_000_000) return `$${(v / 1000).toFixed(1)}k`; + return `$${(v / 1_000_000).toFixed(2)}M`; +} + +function formatAxisCount(v: number): string { + if (v === 0) return "0"; + if (v < 1000) return String(Math.round(v)); + if (v < 1_000_000) return `${(v / 1000).toFixed(v < 10_000 ? 1 : 0)}k`; + if (v < 1_000_000_000) return `${(v / 1_000_000).toFixed(1)}M`; + return `${(v / 1_000_000_000).toFixed(1)}B`; +} + +// Bright ANSI palette for graph series (Total uses index 0). +const SERIES_COLORS = ["\x1b[97m", "\x1b[96m", "\x1b[95m", "\x1b[93m", "\x1b[92m", "\x1b[94m", "\x1b[91m", "\x1b[90m"]; +const COLOR_RESET = "\x1b[39m"; + +function seriesColor(index: number): string { + return SERIES_COLORS[index % SERIES_COLORS.length]!; +} + +/** "14:32" if the timestamp is today, otherwise "16 Jul" (with year if not this year). */ +function formatSinceDate(ms: number): string { + const d = new Date(ms); + const now = new Date(); + if (d.toDateString() === now.toDateString()) { + return d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" }); + } + const opts: Intl.DateTimeFormatOptions = { day: "numeric", month: "short" }; + if (d.getFullYear() !== now.getFullYear()) opts.year = "numeric"; + return d.toLocaleDateString(undefined, opts); +} + +function padLeft(s: string, len: number): string { + const vis = visibleWidth(s); + if (vis >= len) return s; + return " ".repeat(len - vis) + s; +} + +function padRight(s: string, len: number): string { + const vis = visibleWidth(s); + if (vis >= len) return s; + return s + " ".repeat(len - vis); +} + +function sumColumnWidths(columns: DataColumn[]): number { + return columns.reduce((sum, col) => sum + col.width, 0); +} + +function fitCell(s: string, len: number, align: "left" | "right" = "left"): string { + if (len <= 0) return ""; + const truncated = truncateToWidth(s, len); + return align === "right" ? padLeft(truncated, len) : padRight(truncated, len); +} + +function clampLines(lines: string[], width: number): string[] { + return lines.map((line) => truncateToWidth(line, Math.max(width, 0))); +} + +function pickFittingText(width: number, variants: string[]): string { + for (const variant of variants) { + if (visibleWidth(variant) <= width) return variant; + } + return variants[variants.length - 1] || ""; +} + +function getTableLayout(width: number): TableLayout { + const safeWidth = Math.max(width, 0); + + for (const candidate of TABLE_LAYOUTS) { + const columnsWidth = sumColumnWidths(candidate.columns); + const nameWidth = Math.min(MAX_NAME_COL_WIDTH, Math.max(safeWidth - columnsWidth, 0)); + if (nameWidth >= candidate.minNameWidth) { + return { + columns: candidate.columns, + nameWidth, + tableWidth: nameWidth + columnsWidth, + compact: candidate.compact ?? false, + }; + } + } + + const fallback = TABLE_LAYOUTS[TABLE_LAYOUTS.length - 1]!; + const fallbackColumnsWidth = sumColumnWidths(fallback.columns); + const fallbackNameWidth = Math.min(MAX_NAME_COL_WIDTH, Math.max(safeWidth - fallbackColumnsWidth, 0)); + return { + columns: fallback.columns, + nameWidth: fallbackNameWidth, + tableWidth: fallbackNameWidth + fallbackColumnsWidth, + compact: fallback.compact ?? false, + }; +} + +// ============================================================================= +// Component +// ============================================================================= + +const TAB_LABELS: Record = { + today: "今天", + thisWeek: "本周", + lastWeek: "上周", + thisMonth: "本月", + last30Days: "近30天", + allTime: "累计", +}; + +class UsageComponent { + private activeTab: TabName = "allTime"; + private viewMode: ViewMode = "graph"; + private data: UsageData; + private selectedIndex = 0; + private expanded = new Set(); + private providerOrder: string[] = []; + private theme: Theme; + private requestRender: () => void; + private done: () => void; + + // Graph explorer state. + private graphMetric: GraphMetric = "cost"; + private graphGroupBy: GraphGroupBy = "provider"; + private graphCumulative = true; + private exportNote: { text: string; ok: boolean } | null = null; + private tableHidden = new Set(); + private tableFilter = ""; + private tableFilterEditing = false; + private graphHidden = new Set(); + private graphLegendIndex = 0; + + constructor(theme: Theme, data: UsageData, requestRender: () => void, done: () => void) { + this.theme = theme; + this.requestRender = requestRender; + this.done = done; + this.data = data; + this.updateProviderOrder(); + } + + private updateProviderOrder(): void { + const stats = this.data[this.activeTab]; + this.providerOrder = Array.from(stats.providers.entries()) + .sort((a, b) => b[1].cost - a[1].cost) + .map(([name]) => name); + this.clampTableSelection(); + } + + private clampTableSelection(): void { + this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.visibleTable().providers.size - 1)); + } + + /** + * The table slice after hides and the text filter. A filter matches a + * provider name (whole provider stays) or individual model names, in which + * case the provider row is synthesized from just the matching models so + * the totals row and exports reflect exactly what is on screen. + */ + private visibleTable(): { providers: Map; totals: TotalStats } { + const stats = this.data[this.activeTab]; + const q = this.tableFilter.trim().toLowerCase(); + // Always iterate providerOrder so the map is cost-sorted — selection + // indexes and rendered rows must agree on ordering. + const providers = new Map(); + for (const name of this.providerOrder) { + if (this.tableHidden.has(name)) continue; + const full = stats.providers.get(name)!; + if (!q || name.toLowerCase().includes(q)) { + providers.set(name, full); + continue; + } + const models = new Map(Array.from(full.models).filter(([model]) => model.toLowerCase().includes(q))); + if (models.size === 0) continue; + const synth: ProviderStats = { + messages: 0, + cost: 0, + tokens: { total: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + sessions: new Set(), + models, + }; + for (const model of models.values()) { + synth.messages += model.messages; + synth.cost += model.cost; + synth.tokens.total += model.tokens.total; + synth.tokens.input += model.tokens.input; + synth.tokens.output += model.tokens.output; + synth.tokens.cacheRead += model.tokens.cacheRead; + synth.tokens.cacheWrite += model.tokens.cacheWrite; + for (const s of model.sessions) synth.sessions.add(s); + } + providers.set(name, synth); + } + if (!q && this.tableHidden.size === 0) return { providers, totals: stats.totals }; + + const totals: TotalStats = { + sessions: 0, + messages: 0, + cost: 0, + tokens: { total: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }; + const sessions = new Set(); + for (const provider of providers.values()) { + totals.messages += provider.messages; + totals.cost += provider.cost; + totals.tokens.total += provider.tokens.total; + totals.tokens.input += provider.tokens.input; + totals.tokens.output += provider.tokens.output; + totals.tokens.cacheRead += provider.tokens.cacheRead; + totals.tokens.cacheWrite += provider.tokens.cacheWrite; + for (const s of provider.sessions) sessions.add(s); + } + totals.sessions = sessions.size; + return { providers, totals }; + } + + handleInput(data: string): void { + // Filter typing captures printable keys, so it runs before everything. + if (this.viewMode === "table" && this.tableFilterEditing) { + if (matchesKey(data, "escape")) { + this.tableFilter = ""; + this.tableFilterEditing = false; + } else if (matchesKey(data, "enter")) { + this.tableFilterEditing = false; + } else if (matchesKey(data, "backspace")) { + this.tableFilter = this.tableFilter.slice(0, -1); + } else if (data.length === 1 && data >= " " && data !== "\x7f") { + this.tableFilter += data; + } + this.clampTableSelection(); + this.requestRender(); + return; + } + + if (matchesKey(data, "escape") || matchesKey(data, "q")) { + this.done(); + return; + } + + if (matchesKey(data, "v")) { + const idx = VIEW_CYCLE.indexOf(this.viewMode); + this.viewMode = VIEW_CYCLE[(idx + 1) % VIEW_CYCLE.length]!; + this.exportNote = null; + this.requestRender(); + return; + } + + if (matchesKey(data, "e")) { + this.exportCurrentView(); + this.requestRender(); + return; + } + + if (this.viewMode === "graph" && this.handleGraphInput(data)) { + return; + } + + if (matchesKey(data, "tab") || matchesKey(data, "right")) { + const idx = TAB_ORDER.indexOf(this.activeTab); + this.activeTab = TAB_ORDER[(idx + 1) % TAB_ORDER.length]!; + this.updateProviderOrder(); + this.exportNote = null; + this.requestRender(); + } else if (matchesKey(data, "shift+tab") || matchesKey(data, "left")) { + const idx = TAB_ORDER.indexOf(this.activeTab); + this.activeTab = TAB_ORDER[(idx - 1 + TAB_ORDER.length) % TAB_ORDER.length]!; + this.updateProviderOrder(); + this.exportNote = null; + this.requestRender(); + } else if (this.viewMode === "graph") { + // Graph-specific keys were handled above; swallow table-only keys. + } else if (this.viewMode === "table" && data === "/") { + this.tableFilterEditing = true; + this.requestRender(); + } else if (this.viewMode === "table" && data === "x") { + const visible = Array.from(this.visibleTable().providers.keys()); + const provider = visible[this.selectedIndex]; + if (provider) { + this.tableHidden.add(provider); + this.clampTableSelection(); + this.requestRender(); + } + } else if (this.viewMode === "table" && data === "a") { + this.tableHidden.clear(); + this.tableFilter = ""; + this.tableFilterEditing = false; + this.clampTableSelection(); + this.requestRender(); + } else if (this.viewMode === "table" && matchesKey(data, "up")) { + if (this.selectedIndex > 0) { + this.selectedIndex--; + this.requestRender(); + } + } else if (this.viewMode === "table" && matchesKey(data, "down")) { + if (this.selectedIndex < this.visibleTable().providers.size - 1) { + this.selectedIndex++; + this.requestRender(); + } + } else if (this.viewMode === "table" && (matchesKey(data, "enter") || matchesKey(data, "space"))) { + const provider = Array.from(this.visibleTable().providers.keys())[this.selectedIndex]; + if (provider) { + if (this.expanded.has(provider)) { + this.expanded.delete(provider); + } else { + this.expanded.add(provider); + } + this.requestRender(); + } + } + } + + // ------------------------------------------------------------------------- + // Render Methods + // ------------------------------------------------------------------------- + + private handleGraphInput(data: string): boolean { + if (matchesKey(data, "m")) { + const idx = METRIC_ORDER.indexOf(this.graphMetric); + this.graphMetric = METRIC_ORDER[(idx + 1) % METRIC_ORDER.length]!; + } else if (matchesKey(data, "g")) { + const idx = GROUP_ORDER.indexOf(this.graphGroupBy); + this.graphGroupBy = GROUP_ORDER[(idx + 1) % GROUP_ORDER.length]!; + this.graphHidden.clear(); + this.graphLegendIndex = 0; + } else if (matchesKey(data, "c")) { + this.graphCumulative = !this.graphCumulative; + } else if (matchesKey(data, "a")) { + this.graphHidden.clear(); + } else if (matchesKey(data, "up")) { + this.graphLegendIndex = Math.max(0, this.graphLegendIndex - 1); + } else if (matchesKey(data, "down")) { + const count = this.buildGraphModelForView().series.length; + this.graphLegendIndex = Math.min(Math.max(count - 1, 0), this.graphLegendIndex + 1); + } else if (matchesKey(data, "enter") || matchesKey(data, "space")) { + const model = this.buildGraphModelForView(); + const target = model.series[this.graphLegendIndex]; + if (target) { + if (this.graphHidden.has(target.key)) this.graphHidden.delete(target.key); + else this.graphHidden.add(target.key); + } + } else { + return false; + } + this.requestRender(); + return true; + } + + private exportCurrentView(): void { + const now = new Date(); + let name: string; + let content: string; + const stats = this.data[this.activeTab]; + if (this.viewMode === "graph") { + const slice = `${this.graphCumulative ? "cumulative" : "per-bucket"}-${this.graphMetric}-by-${this.graphGroupBy}`; + name = exportFileName("graph", this.activeTab, slice, "csv", now); + content = buildGraphCsv(this.buildGraphModelForView()); + } else if (this.viewMode === "insights") { + name = exportFileName("insights", this.activeTab, null, "json", now); + content = buildInsightsJson(this.activeTab, stats.totals, stats.insights.insights); + } else { + const visible = this.visibleTable(); + const sliced = this.tableFilter.trim() !== "" || this.tableHidden.size > 0; + name = exportFileName("table", this.activeTab, sliced ? "filtered" : null, "csv", now); + content = buildTableCsv(visible.providers, visible.totals); + } + try { + let configured: string | null = null; + try { + configured = parseExportDirSetting(readFileSync(join(getAgentDir(), "settings.json"), "utf8")); + } catch { + // No settings file or unreadable: fall through to the default dir. + } + const home = homedir(); + const dir = resolveExportDir(configured, home, existsSync("/tmp"), tmpdir()); + mkdirSync(dir, { recursive: true }); + const path = join(dir, name); + writeFileSync(path, content); + const shown = path.startsWith(home + "/") ? "~" + path.slice(home.length) : path; + this.exportNote = { text: `已保存 ${shown}`, ok: true }; + } catch (err) { + this.exportNote = { text: `导出失败:${err instanceof Error ? err.message : String(err)}`, ok: false }; + } + } + + private buildGraphModelForView(): GraphModel { + return buildGraphModel(this.data.hourly, { + period: this.activeTab, + metric: this.graphMetric, + groupBy: this.graphGroupBy, + cumulative: this.graphCumulative, + hidden: this.graphHidden, + bounds: this.data.bounds, + }); + } + + render(width: number): string[] { + if (this.viewMode === "graph") { + return clampLines( + [...this.renderTitle(width), ...this.renderTabs(width, getTableLayout(width)), ...this.renderGraph(width), ...this.renderHelp(width)], + width + ); + } + + if (this.viewMode === "insights") { + return clampLines( + [ + ...this.renderTitle(width), + ...this.renderTabs(width, getTableLayout(width)), + ...this.renderInsights(width), + ...this.renderHelp(width), + ], + width + ); + } + + const layout = getTableLayout(width); + return clampLines( + [ + ...this.renderTitle(width), + ...this.renderTabs(width, layout), + ...this.renderHeader(layout), + ...this.renderRows(layout), + ...this.renderTotals(layout), + ...this.renderFormulaNote(width), + ...this.renderHelp(width), + ], + width + ); + } + + private renderTitle(width: number): string[] { + const th = this.theme; + const title = th.fg("accent", th.bold("用量")); + // Render the views as a tab strip (like the period tabs) so it is + // obvious there are multiple views and [v] switches between them. + const fullStrip = VIEW_CYCLE.map((view) => + view === this.viewMode ? th.fg("accent", `[${VIEW_LABELS[view]}]`) : th.fg("dim", ` ${VIEW_LABELS[view]} `) + ).join(" "); + const activeOnly = th.fg("accent", `[${VIEW_LABELS[this.viewMode]}]`); + const line = pickFittingText(width, [ + `${title} ${fullStrip} ${th.fg("dim", "[v]")}`, + `${title} ${activeOnly} ${th.fg("dim", "[v]")}`, + `${title} ${activeOnly}`, + ]); + return [line, ""]; + } + + private renderGraph(width: number): string[] { + const th = this.theme; + const model = this.buildGraphModelForView(); + const lines: string[] = []; + + const modeLabel = `${this.graphCumulative ? "累计" : "分桶"} ${METRIC_LABELS[this.graphMetric]} · ${GROUP_LABELS[this.graphGroupBy]}`; + lines.push(th.fg("muted", modeLabel)); + lines.push(""); + + if (model.groupedTotal === 0 && model.series.every((s) => s.total === 0)) { + lines.push(th.fg("dim", " 本期无用量数据")); + lines.push(""); + return lines; + } + + const formatValue = this.graphMetric === "cost" ? formatAxisCost : formatAxisCount; + const spanMs = model.domainEndMs - model.domainStartMs; + const formatTime = (ms: number): string => { + const d = new Date(ms); + if (spanMs <= 26 * 3_600_000) { + return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; + } + // 图表 x 轴用 ASCII 月/日:renderChart 用字符串长度算轴位, + // 中文 locale 的 "8月14日" 显示宽度是长度的两倍,会把末尾标签挤掉。 + const mm = d.getMonth() + 1; + const dd = d.getDate(); + return d.getFullYear() === new Date().getFullYear() ? `${mm}/${dd}` : `${String(d.getFullYear()).slice(2)}/${mm}/${dd}`; + }; + + const chartHeight = 12; + const chart = renderChart(model, { + width: Math.max(Math.min(width, 110), 30), + height: chartHeight, + formatValue, + formatTime, + colorize: (seriesIndex, text) => { + if (seriesIndex < 0) return th.fg("dim", text); + return seriesColor(seriesIndex) + text + COLOR_RESET; + }, + }); + lines.push(...chart); + lines.push(""); + + // Legend with selection cursor and hide/show state. + for (let i = 0; i < model.series.length; i++) { + const s = model.series[i]!; + const cursor = i === this.graphLegendIndex ? th.fg("accent", "▸ ") : " "; + const marker = s.hidden ? th.fg("dim", "○") : seriesColor(i) + "●" + COLOR_RESET; + const value = this.graphMetric === "cost" ? formatAxisCost(s.total) : formatAxisCount(s.total); + const pct = + s.key !== TOTAL_SERIES_KEY && model.groupedTotal > 0 + ? ` ${th.fg("dim", `${Math.round((s.total / model.groupedTotal) * 100)}%`)}` + : ""; + const label = s.hidden ? th.fg("dim", s.label) : s.key === TOTAL_SERIES_KEY ? th.bold(s.label) : s.label; + lines.push(`${cursor}${marker} ${padRight(label, 24)} ${padLeft(value, 8)}${pct}`); + } + lines.push(""); + return lines; + } + + private renderInsights(width: number): string[] { + const th = this.theme; + const stats = this.data[this.activeTab]; + const { insights } = stats.insights; + const hasUsage = + stats.totals.messages > 0 || + stats.totals.cost > 0 || + stats.totals.tokens.total > 0 || + stats.totals.tokens.cacheRead > 0; + const hasCost = stats.totals.cost > 0; + const lines: string[] = []; + + // Cap the content column so advice stays readable on very wide terminals. + const contentWidth = Math.max(Math.min(width, 100), 40); + + lines.push(th.bold("你的花费都花在哪了?")); + const subtitle = "近似估算,仅统计本机本地会话(各项相互独立,合计不等于 100%)。"; + for (const wrapped of wrapTextWithAnsi(subtitle, contentWidth)) { + lines.push(th.fg("dim", wrapped)); + } + lines.push(""); + + if (!hasUsage) { + lines.push(th.fg("dim", " 本期无用量记录。")); + lines.push(""); + return lines; + } + if (!hasCost) { + lines.push(th.fg("dim", " 本期无花费记录。")); + lines.push(""); + return lines; + } + if (insights.length === 0) { + lines.push(th.fg("dim", " 本期没有值得注意的项。")); + lines.push(""); + return lines; + } + + // Columns: marker(2) + stat(6) + gap(1); advice aligns under the headline. + const indent = " "; + const adviceWidth = Math.max(contentWidth - indent.length, 30); + + const sectionHeader = (label: string, color: "warning" | "accent"): string => { + const rule = "─".repeat(Math.max(contentWidth - visibleWidth(label) - 1, 4)); + return `${th.fg(color, th.bold(label))} ${th.fg("border", rule)}`; + }; + + const renderOne = (insight: (typeof insights)[number]): void => { + const isAlarm = insight.kind === "alarm"; + const marker = isAlarm ? th.fg("warning", "⚠ ") : " "; + const statText = padLeft(insight.stat, 6); + const stat = isAlarm ? th.fg("warning", th.bold(statText)) : th.fg("accent", th.bold(statText)); + // De-emphasise the trailing period-share parenthetical on alarm headlines. + const match = insight.headline.match(/^(.*?)\s*((本期 [\d.,]+%))$/); + const headline = match ? `${match[1]}${th.fg("dim", match[2]!)}` : insight.headline; + lines.push(`${marker}${stat} ${headline}`); + if (insight.advice) { + for (const wrapped of wrapTextWithAnsi(insight.advice, adviceWidth)) { + lines.push(`${indent}${th.fg("dim", wrapped)}`); + } + } + lines.push(""); + }; + + const alarms = insights.filter((i) => i.kind === "alarm"); + const structure = insights.filter((i) => i.kind === "structure"); + // Facts first, flagged waste second. + if (structure.length > 0) { + lines.push(sectionHeader("花在哪了", "accent")); + for (const insight of structure) renderOne(insight); + } + lines.push(sectionHeader("值得注意", "warning")); + if (alarms.length > 0) { + for (const insight of alarms) renderOne(insight); + } else { + lines.push(` ${th.fg("success", padLeft("✓", 6))} ${th.fg("dim", "本期未发现浪费模式")}`); + lines.push(""); + } + + return lines; + } + + private renderTabs(width: number, layout: TableLayout): string[] { + const th = this.theme; + const fullTabs = TAB_ORDER.map((tab) => { + const label = TAB_LABELS[tab]; + return tab === this.activeTab ? th.fg("accent", `[${label}]`) : th.fg("dim", ` ${label} `); + }).join(" "); + + const activeTabOnly = th.fg("accent", `[${TAB_LABELS[this.activeTab]}]`); + const tabLine = pickFittingText(width, [ + fullTabs, + `${activeTabOnly} ${th.fg("dim", "[Tab/←→]")}`, + activeTabOnly, + ]); + + // Compact-note only applies to the table view — it's meaningless for insights. + const infoLines = + this.viewMode === "table" && layout.compact + ? wrapTextWithAnsi(th.fg("dim", "紧凑视图。拉宽终端可显示更多列。"), Math.max(width, 1)) + : []; + + if (this.viewMode === "table") { + if (this.tableFilterEditing) { + infoLines.push(`${th.fg("accent", `/ ${this.tableFilter}▌`)} ${th.fg("dim", "[Enter] 保留 · [Esc] 清除")}`); + } else if (this.tableFilter.trim() !== "" || this.tableHidden.size > 0) { + const parts: string[] = []; + if (this.tableFilter.trim() !== "") parts.push(`筛选:“${this.tableFilter.trim()}”`); + if (this.tableHidden.size > 0) parts.push(`已隐藏 ${this.tableHidden.size} 项`); + infoLines.push(th.fg("warning", `${parts.join(" · ")} · 合计仅反映此切片 · [a] 重置`)); + } + } + + return [tabLine, ...infoLines, ""]; + } + + private renderHeader(layout: TableLayout): string[] { + const th = this.theme; + + let headerLine = fitCell("渠道 / 模型", layout.nameWidth); + for (const col of layout.columns) { + const label = fitCell(col.label, col.width, "right"); + headerLine += col.dimmed ? th.fg("dim", label) : label; + } + + return [th.fg("muted", headerLine), th.fg("border", "─".repeat(layout.tableWidth))]; + } + + private renderDataRow( + name: string, + stats: BaseStats & { sessions: Set | number }, + layout: TableLayout, + options: { indent?: number; selected?: boolean; dimAll?: boolean; prefix?: string } = {} + ): string { + const th = this.theme; + const { indent = 0, selected = false, dimAll = false, prefix } = options; + + const rawPrefix = prefix ?? " ".repeat(indent); + const safePrefix = layout.nameWidth > 0 ? truncateToWidth(rawPrefix, layout.nameWidth, "") : ""; + const prefixWidth = visibleWidth(safePrefix); + const innerNameWidth = Math.max(layout.nameWidth - prefixWidth, 0); + const truncName = innerNameWidth > 0 ? truncateToWidth(name, innerNameWidth) : ""; + const styledName = selected ? th.fg("accent", truncName) : dimAll ? th.fg("dim", truncName) : truncName; + + let row = safePrefix + (innerNameWidth > 0 ? padRight(styledName, innerNameWidth) : ""); + + for (const col of layout.columns) { + const value = fitCell(col.getValue(stats), col.width, "right"); + const shouldDim = col.dimmed || dimAll; + row += shouldDim ? th.fg("dim", value) : value; + } + + return row; + } + + private renderRows(layout: TableLayout): string[] { + const th = this.theme; + const lines: string[] = []; + + if (this.providerOrder.length === 0) { + lines.push(th.fg("dim", " 本期无用量数据")); + return lines; + } + + const visible = Array.from(this.visibleTable().providers.entries()); + if (visible.length === 0) { + lines.push(th.fg("dim", " 没有匹配当前筛选的行 — [a] 重置")); + return lines; + } + + for (let i = 0; i < visible.length; i++) { + const [providerName, providerStats] = visible[i]!; + const isSelected = i === this.selectedIndex; + const isExpanded = this.expanded.has(providerName); + const arrow = isExpanded ? "▾" : "▸"; + const prefix = isSelected ? th.fg("accent", `${arrow} `) : th.fg("dim", `${arrow} `); + + lines.push( + this.renderDataRow(providerName, providerStats, layout, { + selected: isSelected, + prefix, + }) + ); + + if (isExpanded) { + const models = Array.from(providerStats.models.entries()).sort((a, b) => b[1].cost - a[1].cost); + + for (const [modelName, modelStats] of models) { + lines.push(this.renderDataRow(modelName, modelStats, layout, { indent: 4, dimAll: true })); + } + } + } + + return lines; + } + + private renderTotals(layout: TableLayout): string[] { + const th = this.theme; + const { totals } = this.visibleTable(); + + let totalRow = fitCell(th.bold("合计"), layout.nameWidth); + for (const col of layout.columns) { + const value = fitCell(col.getValue(totals), col.width, "right"); + totalRow += col.dimmed ? th.fg("dim", value) : value; + } + + return [th.fg("border", "─".repeat(layout.tableWidth)), totalRow, ""]; + } + + private renderFormulaNote(width: number): string[] { + const line = pickFittingText(width, [ + "Token = 输入 + 输出 + 缓存写入 · ↑输入 = 输入 + 缓存写入 (自 0.2.0)", + "Token = 输入 + 输出 + 缓存写 · ↑输入 = 输入 + 缓存写 (v0.2.0+)", + "Token 与 ↑输入 含缓存写入 (v0.2.0+)", + "含缓存写入 (v0.2.0+)", + ]); + return [this.theme.fg("dim", line), ""]; + } + + private renderHelp(width: number): string[] { + const noteLines = this.exportNote + ? [this.theme.fg(this.exportNote.ok ? "success" : "error", `${this.exportNote.ok ? "✓" : "✗"} ${this.exportNote.text}`), ""] + : []; + const variants = + this.viewMode === "graph" + ? [ + "[Tab/←→] 周期 [m] 指标 [g] 分组 [c] 累计 [↑↓/Enter] 筛选 [a] 全显 [e] 导出 [v] 视图 [q] 关闭", + "[Tab] 周期 [m] 指标 [g] 分组 [c] 累计 [↑↓/Enter] 筛选 [e] 导出 [v] 视图 [q] 关闭", + "[m] 指标 [g] 分组 [c] 累计 [↑↓] 筛选 [q] 关闭", + "[m] [g] [c] [↑↓] [q]", + "[q] 关闭", + ] + : this.viewMode === "insights" + ? [ + "[Tab/←→] 周期 [e] 导出 [v] 视图 [q] 关闭", + "[Tab] 周期 [e] 导出 [v] 视图 [q] 关闭", + "[v] 视图 [q] 关闭", + "[q] 关闭", + ] + : [ + "[Tab/←→] 周期 [↑↓] 选择 [Enter] 展开 [/] 筛选 [x] 隐藏 [a] 全显 [e] 导出 [v] 视图 [q] 关闭", + "[Tab] 周期 [↑↓] 选择 [Enter] 展开 [/] 筛选 [x] 隐藏 [e] 导出 [v] 视图 [q] 关闭", + "[↑↓] 选择 [Enter] 展开 [/] 筛选 [x] 隐藏 [v] 视图 [q] 关闭", + "[↑↓] 选择 [/] [x] [v] [q]", + "[↑↓] 选择 [q] 关闭", + "[q] 关闭", + ]; + const line = pickFittingText(width, variants); + return [...noteLines, this.theme.fg("dim", line)]; + } + + invalidate(): void {} + dispose(): void {} +} + +// ============================================================================= +// Extension Entry Point +// ============================================================================= + +export default function (pi: ExtensionAPI) { + pi.registerCommand("usage", { + description: "显示用量统计面板", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + if (!ctx.hasUI) { + return; + } + + const data = await ctx.ui.custom((tui, theme, _kb, done) => { + const loader = new CancellableLoader( + tui, + (s: string) => theme.fg("accent", s), + (s: string) => theme.fg("muted", s), + "正在统计用量..." + ); + let finished = false; + const finish = (value: UsageData | null) => { + if (finished) return; + finished = true; + loader.dispose(); + done(value); + }; + + loader.onAbort = () => finish(null); + + const onProgress = (p: CollectProgress): void => { + if (finished || p.filesToParse === 0) return; + const files = `${p.filesParsed.toLocaleString()}/${p.filesToParse.toLocaleString()} 个文件`; + if (p.mode === "update") { + const since = p.sinceMs !== null ? `(自 ${formatSinceDate(p.sinceMs)})` : ""; + loader.setMessage(`正在更新用量历史${since}…(${files})`); + } else if (p.mode === "rebuild") { + loader.setMessage(`正在重建用量历史 — 缓存格式已变更…(${files})`); + } else { + loader.setMessage(`正在首次构建用量历史…(${files})`); + } + }; + + collectUsageData({ signal: loader.signal, onProgress }) + .then(finish) + .catch(() => finish(null)); + + return loader; + }); + + if (!data) { + return; + } + + await ctx.ui.custom((tui, theme, _kb, done) => { + const container = new Container(); + + // Top border + container.addChild(new Spacer(1)); + container.addChild(new DynamicBorder((s: string) => theme.fg("border", s))); + container.addChild(new Spacer(1)); + + const usage = new UsageComponent(theme, data, () => tui.requestRender(), () => done()); + + return { + render: (w: number) => { + const borderLines = clampLines(container.render(w), w); + const usageLines = usage.render(w); + const bottomBorder = theme.fg("border", "─".repeat(w)); + return clampLines([...borderLines, ...usageLines, "", bottomBorder], w); + }, + invalidate: () => container.invalidate(), + handleInput: (input: string) => usage.handleInput(input), + dispose: () => {}, + }; + }); + }, + }); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..55bcc0b --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "pi-usage-extension-zh", + "version": "0.10.2-zh.1", + "private": true, + "description": "Usage statistics dashboard for Pi sessions (Chinese UI fork of @tmustier/pi-usage-extension).", + "license": "MIT", + "keywords": [ + "pi-package" + ], + "repository": { + "type": "git", + "url": "ssh://git@git.cat-shark.xyz:2222/cat-shark/usage-zh.git" + }, + "upstream": { + "package": "@tmustier/pi-usage-extension", + "version": "0.10.2", + "repo": "github.com/tmustier/pi-extensions", + "dir": "usage-extension" + }, + "pi": { + "extensions": [ + "index.ts" + ] + }, + "peerDependencies": { + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*" + } +} diff --git a/scripts/usage-data-smoke.mjs b/scripts/usage-data-smoke.mjs new file mode 100644 index 0000000..9c188c9 --- /dev/null +++ b/scripts/usage-data-smoke.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node +// 数据冒烟:用 jiti 直接加载扩展的 data.ts / export.ts / graph.ts, +// 跑一次采集(会写 ~/.pi/agent/usage-extension-cache.json),打印渠道名、总量、 +// 洞察文案与导出片段。 +// +// 用法: +// node scripts/usage-data-smoke.mjs [--dir <扩展目录>] +// +// 用途:确认文案替换没改坏数据层(模板串、正则、缓存版本), +// 以及导出内容(CSV 表头语言、JSON 键)符合预期。 + +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const argv = process.argv.slice(2); +const i = argv.indexOf("--dir"); +const extDir = (i >= 0 && argv[i + 1] ? argv[i + 1] : repoRoot).replace(/^~(?=\/|$)/, homedir()); + +// jiti 随 pi 一起装在 agent 目录里;给几个候选位置 +const JITI_CANDIDATES = [ + process.env.JITI, + join(homedir(), ".pi/agent/npm/node_modules/jiti/lib/jiti.mjs"), + join(homedir(), ".pi/agent/npm/node_modules/jiti/lib/jiti.cjs"), +].filter(Boolean); +const jitiPath = JITI_CANDIDATES.find((p) => existsSync(p)); +if (!jitiPath) { + console.error("找不到 jiti,请用 JITI=<...>/jiti/lib/jiti.mjs 指定"); + process.exit(2); +} + +const { createJiti } = await import(pathToFileURL(jitiPath).href); +const jiti = createJiti(import.meta.url); +const data = await jiti.import(`${extDir}/data.ts`); +const exp = await jiti.import(`${extDir}/export.ts`); +const graph = await jiti.import(`${extDir}/graph.ts`); + +const t0 = Date.now(); +const d = await data.collectUsageData({}); +console.log(`采集耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s`); +const stats = d.allTime; +console.log("渠道/伪渠道行:", [...stats.providers.keys()].join(", ")); +console.log("总量:", JSON.stringify(stats.totals)); +for (const ins of stats.insights.insights) console.log(`- [${ins.kind}] ${ins.stat} ${ins.headline}\n ${ins.advice}`); + +console.log("\n--- table CSV 前 3 行 ---"); +console.log(exp.buildTableCsv(stats.providers, stats.totals).split("\n").slice(0, 3).join("\n")); +console.log("\n--- graph CSV 前 2 行 ---"); +const gm = graph.buildGraphModel(d.hourly, { + period: "allTime", + metric: "cost", + groupBy: "provider", + cumulative: true, + hidden: new Set(), + bounds: d.bounds, +}); +console.log(exp.buildGraphCsv(gm).split("\n").slice(0, 2).join("\n")); +console.log("\n--- insights JSON 前 8 行 ---"); +console.log(exp.buildInsightsJson("allTime", stats.totals, stats.insights.insights).split("\n").slice(0, 8).join("\n")); diff --git a/scripts/usage-render-smoke.mjs b/scripts/usage-render-smoke.mjs new file mode 100644 index 0000000..9cc7907 --- /dev/null +++ b/scripts/usage-render-smoke.mjs @@ -0,0 +1,116 @@ +#!/usr/bin/env node +// 渲染冒烟:用 pi 自己的扩展加载器加载本扩展,绕过 TUI 直接调用 render(), +// 把图表/表格/洞察三个视图按指定宽度打印成纯文本(去 ANSI),并报告超宽行数。 +// +// 用法: +// node scripts/usage-render-smoke.mjs # 默认 110 列,三视图 +// node scripts/usage-render-smoke.mjs --width 80 --views table,insights +// PI_DIST=/path/to/@earendil-works/pi-coding-agent node scripts/usage-render-smoke.mjs +// +// 只读会话数据,不写任何文件(采集缓存由扩展自己维护)。 + +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +const argv = process.argv.slice(2); +const arg = (name, fallback) => { + const i = argv.indexOf(`--${name}`); + return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback; +}; + +// pi 安装位置:优先 --pi-dist / PI_DIST,其次常见全局路径 +const PI_DIST_CANDIDATES = [ + arg("pi-dist", process.env.PI_DIST), + join(homedir(), ".local/lib/node_modules/@agegr/pi-web/node_modules/@earendil-works/pi-coding-agent"), + join(homedir(), ".local/lib/node_modules/@earendil-works/pi-coding-agent"), + "/usr/lib/node_modules/@earendil-works/pi-coding-agent", + "/usr/local/lib/node_modules/@earendil-works/pi-coding-agent", +].filter(Boolean); +const PI_DIST = PI_DIST_CANDIDATES.find((p) => existsSync(join(p, "dist/core/extensions/loader.js"))); +if (!PI_DIST) { + console.error("找不到 pi 安装目录,请用 PI_DIST=<...>/pi-coding-agent 指定"); + process.exit(2); +} + +const extDir = arg("dir", repoRoot).replace(/^~(?=\/|$)/, homedir()); +const width = Number(arg("width", "110")); +const wantViews = arg("views", "graph,table,insights").split(","); + +const { loadExtensions } = await import(`${PI_DIST}/dist/core/extensions/loader.js`); +const res = await loadExtensions([extDir], process.cwd()); +if (!res.extensions?.length) { + console.error("扩展加载失败:", JSON.stringify(res.errors ?? [], null, 2).slice(0, 2000)); + process.exit(1); +} +const cmd = res.extensions[0].commands.get("usage"); +if (!cmd) { + console.error("未注册 usage 命令"); + process.exit(1); +} + +const strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, ""); +// 主题桩:fg(color, text) / bold(text) 等一律返回原文本,便于纯文本比对。 +const theme = new Proxy({}, { get: () => (a, b) => (typeof a === "string" && typeof b === "string" ? b : a) }); + +let component = null; +const tui = { requestRender() {}, terminal: { columns: width, rows: 60 } }; +const ctx = { + hasUI: true, + ui: { + custom: async (factory) => { + let value; + const done = (v) => (value = v); + const c = await factory({ requestRender() {}, terminal: tui.terminal }, theme, {}, done); + if (c?.render && c?.handleInput) component = c; + await new Promise((resolveWait) => { + const timer = setInterval(() => { + if (value !== undefined) { + clearInterval(timer); + resolveWait(); + } + }, 50); + setTimeout(() => { + clearInterval(timer); + resolveWait(); + }, 300_000); + }); + return value; + }, + }, +}; + +await cmd.handler("", ctx); +if (!component) { + console.error("未捕获渲染组件"); + process.exit(1); +} + +// pi 的 ui.custom 返回包装对象,只暴露 render/handleInput,读不到 viewMode, +// 所以用本地游标跟踪当前视图(切换顺序 = 扩展内的 VIEW_CYCLE:graph → table → insights)。 +const VIEW_CYCLE = ["graph", "table", "insights"]; +let exitCode = 0; +let current = 0; // 当前视图游标(初始 graph) +for (const view of wantViews) { + const target = VIEW_CYCLE.indexOf(view); + if (target < 0) { + console.error(`未知视图: ${view}(可选 ${VIEW_CYCLE.join("/")})`); + current = 0; + continue; + } + const presses = (target - current + VIEW_CYCLE.length) % VIEW_CYCLE.length; + for (let i = 0; i < presses; i++) component.handleInput("v"); + const lines = component.render(width).map(strip); + const over = lines.filter((l) => l.length > width); + console.log(`\n===== view=${view} width=${width} lines=${lines.length} 超宽=${over.length} =====`); + console.log(lines.join("\n")); + current = target; + if (over.length > 0) { + exitCode = 1; + for (const l of over) console.log("OVER:", l); + } +} +process.exit(exitCode); diff --git a/zh-map.mjs b/zh-map.mjs new file mode 100644 index 0000000..bb7634b --- /dev/null +++ b/zh-map.mjs @@ -0,0 +1,241 @@ +// 汉化词表:英文原文 → 中文。apply-zh.mjs 用它对上游文件做精确替换。 +// 规则:每条 en 必须在目标文件中至少出现一次;0 命中会报错(上游改文案时提醒人工跟进)。 +// en 尽量带上足够上下文(含引号与字段名),避免误伤代码里的同名字符串。 + +export const MAP = { + "index.ts": [ + // ---- 视图 / 周期 / 列名 ---- + ['graph: "Graphs",', 'graph: "图表",'], + ['table: "Table",', 'table: "表格",'], + ['insights: "Insights",', 'insights: "洞察",'], + ['label: "Sessions",', 'label: "会话",'], + ['label: "Msgs",', 'label: "消息",'], + ['label: "Cost",', 'label: "花费",'], + ['label: "Tokens",', 'label: "Token",'], + ['label: "↑In",', 'label: "↑输入",'], + ['label: "↓Out",', 'label: "↓输出",'], + ['label: "Cache",', 'label: "缓存",'], + ['today: "Today",', 'today: "今天",'], + ['thisWeek: "This Week",', 'thisWeek: "本周",'], + ['lastWeek: "Last Week",', 'lastWeek: "上周",'], + ['thisMonth: "This Month",', 'thisMonth: "本月",'], + ['last30Days: "Last 30 Days",', 'last30Days: "近30天",'], + ['allTime: "All Time",', 'allTime: "累计",'], + + // ---- 标题 / 图例模式 ---- + ['th.bold("Usage")', 'th.bold("用量")'], + ['this.graphCumulative ? "Cumulative" : "Per bucket"', 'this.graphCumulative ? "累计" : "分桶"'], + + // ---- 空态 / 提示 ---- + ['" No usage data for this period"', '" 本期无用量数据"'], + ['" Nothing matches the current filter — [a] resets"', '" 没有匹配当前筛选的行 — [a] 重置"'], + ['"[Enter] keep · [Esc] clear"', '"[Enter] 保留 · [Esc] 清除"'], + ['`filter: “${this.tableFilter.trim()}”`', '`筛选:“${this.tableFilter.trim()}”`'], + ['`${this.tableHidden.size} hidden`', '`已隐藏 ${this.tableHidden.size} 项`'], + ['totals reflect this slice · [a] reset', '合计仅反映此切片 · [a] 重置'], + ['"Compact view. Widen the terminal for more columns."', '"紧凑视图。拉宽终端可显示更多列。"'], + + // ---- 表头 / 合计 ---- + ['"Provider / Model"', '"渠道 / 模型"'], + ['th.bold("Total")', 'th.bold("合计")'], + + // ---- 表格底部公式说明 ---- + ['"Tokens = Input + Output + CacheWrite · ↑In = Input + CacheWrite (as of 0.2.0)"', '"Token = 输入 + 输出 + 缓存写入 · ↑输入 = 输入 + 缓存写入 (自 0.2.0)"'], + ['"Tokens = In + Out + CacheWrite · ↑In = In + CacheWrite (v0.2.0+)"', '"Token = 输入 + 输出 + 缓存写 · ↑输入 = 输入 + 缓存写 (v0.2.0+)"'], + ['"Tokens & ↑In include CacheWrite (v0.2.0+)"', '"Token 与 ↑输入 含缓存写入 (v0.2.0+)"'], + ['"Incl. CacheWrite (v0.2.0+)"', '"含缓存写入 (v0.2.0+)"'], + + // ---- 洞察页 ---- + ['th.bold("What\'s contributing to your cost?")', 'th.bold("你的花费都花在哪了?")'], + [ + '"Approximate, based on local sessions on this machine (these are independent and don\'t sum to 100%)."', + '"近似估算,仅统计本机本地会话(各项相互独立,合计不等于 100%)。"', + ], + ['" No usage recorded for this period."', '" 本期无用量记录。"'], + ['" No cost data recorded for this period."', '" 本期无花费记录。"'], + ['" Nothing notable for this period."', '" 本期没有值得注意的项。"'], + ['sectionHeader("Where it went", "accent")', 'sectionHeader("花在哪了", "accent")'], + ['sectionHeader("Worth attention", "warning")', 'sectionHeader("值得注意", "warning")'], + ['"no waste patterns flagged for this period"', '"本期未发现浪费模式"'], + // 中文括号里的"本期 x%",正则同步改(用于把括号部分渲染成暗色) + ['/^(.*?)\\s*(\\(\\d[\\d.,]*% of this period\\))$/', '/^(.*?)\\s*((本期 [\\d.,]+%))$/'], + + // ---- 导出回执 ---- + ['`Saved ${shown}`', '`已保存 ${shown}`'], + ['`Export failed: ${err instanceof Error ? err.message : String(err)}`', '`导出失败:${err instanceof Error ? err.message : String(err)}`'], + + // ---- 底部快捷键提示 ---- + [ + '"[Tab/←→] period [m] metric [g] group [c] cumulative [↑↓/Enter] filter [a] all [e] export [v] view [q] close"', + '"[Tab/←→] 周期 [m] 指标 [g] 分组 [c] 累计 [↑↓/Enter] 筛选 [a] 全显 [e] 导出 [v] 视图 [q] 关闭"', + ], + [ + '"[Tab] period [m] metric [g] group [c] cumul [↑↓/Enter] filter [e] export [v] view [q] close"', + '"[Tab] 周期 [m] 指标 [g] 分组 [c] 累计 [↑↓/Enter] 筛选 [e] 导出 [v] 视图 [q] 关闭"', + ], + ['"[m] metric [g] group [c] cumul [↑↓] filter [q] close"', '"[m] 指标 [g] 分组 [c] 累计 [↑↓] 筛选 [q] 关闭"'], + ['"[q] close"', '"[q] 关闭"'], + ['"[Tab/←→] period [e] export [v] view [q] close"', '"[Tab/←→] 周期 [e] 导出 [v] 视图 [q] 关闭"'], + ['"[Tab] period [e] export [v] view [q] close"', '"[Tab] 周期 [e] 导出 [v] 视图 [q] 关闭"'], + ['"[v] view [q] close"', '"[v] 视图 [q] 关闭"'], + [ + '"[Tab/←→] period [↑↓] select [Enter] expand [/] filter [x] hide [a] all [e] export [v] view [q] close"', + '"[Tab/←→] 周期 [↑↓] 选择 [Enter] 展开 [/] 筛选 [x] 隐藏 [a] 全显 [e] 导出 [v] 视图 [q] 关闭"', + ], + [ + '"[Tab] period [↑↓] select [Enter] expand [/] filter [x] hide [e] export [v] view [q] close"', + '"[Tab] 周期 [↑↓] 选择 [Enter] 展开 [/] 筛选 [x] 隐藏 [e] 导出 [v] 视图 [q] 关闭"', + ], + [ + '"[↑↓] select [Enter] expand [/] filter [x] hide [v] view [q] close"', + '"[↑↓] 选择 [Enter] 展开 [/] 筛选 [x] 隐藏 [v] 视图 [q] 关闭"', + ], + ['"[↑↓] select [/] [x] [v] [q]"', '"[↑↓] 选择 [/] [x] [v] [q]"'], + ['"[↑↓] select [q] close"', '"[↑↓] 选择 [q] 关闭"'], + + // ---- 加载与进度 ---- + ['"Loading Usage..."', '"正在统计用量..."'], + [ + '`${p.filesParsed.toLocaleString()}/${p.filesToParse.toLocaleString()} files`', + '`${p.filesParsed.toLocaleString()}/${p.filesToParse.toLocaleString()} 个文件`', + ], + ['` since ${formatSinceDate(p.sinceMs)}`', '`(自 ${formatSinceDate(p.sinceMs)})`'], + ['`Updating your usage history${since}… (${files})`', '`正在更新用量历史${since}…(${files})`'], + [ + '`Rebuilding your usage history — the cache format changed… (${files})`', + '`正在重建用量历史 — 缓存格式已变更…(${files})`', + ], + ['`Building your usage history for the first time… (${files})`', '`正在首次构建用量历史…(${files})`'], + + // ---- 命令描述 ---- + ['description: "Show usage statistics dashboard",', 'description: "显示用量统计面板",'], + ], + + "graph.ts": [ + ['cost: "cost",', 'cost: "花费",'], + ['tokens: "tokens",', 'tokens: "Token",'], + ['messages: "messages",', 'messages: "消息数",'], + ['reasoning: "reasoning tokens",', 'reasoning: "推理 Token",'], + ['provider: "by provider",', 'provider: "按渠道",'], + ['model: "by model",', 'model: "按模型",'], + ['thinking: "by thinking level",', 'thinking: "按思考等级",'], + ['total: "total only",', 'total: "仅合计",'], + ['label: "Total",', 'label: "合计",'], + ['label: `other (${merged.length})`', 'label: `其他 (${merged.length})`'], + ['thinkingLevel === "" ? "unknown" : thinkingLevel', 'thinkingLevel === "" ? "未知" : thinkingLevel'], + ], + + "data.ts": [ + // 辅助用量(工具/摘要)伪渠道名会写入缓存,故同时 bump CACHE_VERSION 强制重建一次 + ['export const AUXILIARY_PROVIDER = "Tools";', 'export const AUXILIARY_PROVIDER = "工具";'], + ['export const AUXILIARY_MODEL = "summaries";', 'export const AUXILIARY_MODEL = "摘要";'], + ['export const AUXILIARY_THINKING_LEVEL = "Tools/summaries";', 'export const AUXILIARY_THINKING_LEVEL = "工具/摘要";'], + ['const CACHE_VERSION = 6;', 'const CACHE_VERSION = 7;'], + + [ + 'raw.auxiliaryCost > 0 ? "assistant-message cost" : "this period";', + 'raw.auxiliaryCost > 0 ? "助手消息花费" : "本期花费";', + ], + + // --- 告警:停顿后恢复 --- + [ + 'headline: `spent resuming conversations after a break (${fmtPercent(ttlPct)} of ${assistantPctLabel})`', + 'headline: `花在停顿后恢复会话上(占${assistantPctLabel}的 ${fmtPercent(ttlPct)})`', + ], + [ + '"Sent context is only reusable for a few minutes. After a longer pause, the next message pays to send the whole conversation again. Replying while a session is fresh avoids this."', + '"已发送的上下文只有几分钟可复用。停顿较久后,下一条消息要按全价重发整段对话。趁会话还新鲜时继续回复即可避免。"', + ], + // --- 告警:中途换模型 --- + [ + 'headline: `spent switching models mid-conversation (${fmtPercent(switchPct)} of ${assistantPctLabel})`', + 'headline: `花在对话中途切换模型上(占${assistantPctLabel}的 ${fmtPercent(switchPct)})`', + ], + [ + '"Changing model re-sends the whole conversation at full price — the previous model\'s saved context doesn\'t transfer. Switching between tasks instead of mid-conversation avoids this."', + '"换模型会按全价重发整段对话 — 上一个模型存下的上下文不会转移。改为在两个任务之间切换即可避免。"', + ], + // --- 告警:中途重发前缀 --- + [ + 'headline: `spent re-sending conversations mid-session (${fmtPercent(prefixPct)} of ${assistantPctLabel})`', + 'headline: `花在会话中途重发上下文上(占${assistantPctLabel}的 ${fmtPercent(prefixPct)})`', + ], + [ + '"These messages paid full price for context that had already been sent — with no break, compaction, or model switch to explain it. Usually a tool or workflow is restarting or rewriting conversations. Worth a look if it stays high."', + '"这些消息为已经发过的上下文又付了一次全价 — 且没有停顿、压缩或换模型可以解释。通常是某个工具或流程在重启、重写对话。若长期偏高值得排查。"', + ], + // --- 告警:花费集中 --- + [ + 'headline: `came from just ${TOP_SESSION_COUNT} of your ${raw.sessionCosts.size} sessions (${fmtPercent(topPct)} of this period)`', + 'headline: `只来自你 ${raw.sessionCosts.size} 个会话中的 ${TOP_SESSION_COUNT} 个(本期 ${fmtPercent(topPct)})`', + ], + [ + '"A handful of sessions drove most of the spend. The graph view can show what they were doing."', + '"少数几个会话吃掉了大部分花费。图表视图可以看出它们在做什么。"', + ], + // --- 告警:开场消息开销 --- + [ + 'headline: `spent on the opening message of new sessions (${fmtPercent(upfrontPct)} of ${assistantPctLabel})`', + 'headline: `花在新会话的首条消息上(占${assistantPctLabel}的 ${fmtPercent(upfrontPct)})`', + ], + [ + '"A session\'s first message sends everything from scratch. Fewer, longer sessions cut this overhead."', + '"会话的第一条消息要从零发送全部内容。更少、更长的会话可以降低这部分开销。"', + ], + // --- 告警:缓存复用倍数偏低 --- + [ + 'headline: "tokens reused from history for every token paid at full price"', + 'headline: "历史复用倍数(每付一次全价的 token)"', + ], + [ + '"Typical interactive use reuses 10× or more. A low number means conversations keep being sent from scratch — look for workflows that restart sessions."', + '"典型交互式用法能复用 10× 以上。数值偏低说明对话在反复从零发送 — 找找有没有会重启会话的流程。"', + ], + // --- 结构:工具/摘要用量 --- + [ + 'headline: "of your cost came from usage reported by tools and conversation summaries"', + 'headline: "的花费来自工具与对话摘要上报的用量"', + ], + [ + '"Pi records this separately because it cannot be attributed reliably to a specific provider and model."', + '"Pi 单独记录这部分,因为它无法可靠归属到某个具体渠道和模型。"', + ], + // --- 结构:长上下文税 --- + [ + '` — ${fmtMoney(avgHigh)}/msg vs ${fmtMoney(avgLow)} under ${formatThresholdTokens(CTX_LOW_THRESHOLD)}`', + '` — 每条 ${fmtMoney(avgHigh)},而低于 ${formatThresholdTokens(CTX_LOW_THRESHOLD)} 时为 ${fmtMoney(avgLow)}`', + ], + [ + 'headline: `of your ${raw.auxiliaryCost > 0 ? "assistant-message cost" : "cost"} came from messages with ≥${formatThresholdTokens(CTX_TAX_THRESHOLD)} tokens loaded${cmp}`', + 'headline: `的${raw.auxiliaryCost > 0 ? "助手消息花费" : "花费"}来自载入 ≥${formatThresholdTokens(CTX_TAX_THRESHOLD)} token 的消息${cmp}`', + ], + [ + '"Long conversations cost more per message. /compact mid-task and /clear between tasks keep them lean."', + '"长对话每条消息都更贵。任务中段 /compact、任务之间 /clear 可以让对话保持精简。"', + ], + // --- 结构:项目分布 --- + [ + 'headline: `of your cost was ${top[0]![0]}${rest ? ` — then ${rest}` : ""}`', + 'headline: `的花费来自 ${top[0]![0]}${rest ? ` — 其次是 ${rest}` : ""}`', + ], + // --- 结构:隐藏推理占比 --- + [ + 'headline: "of your output tokens were hidden reasoning"', + 'headline: "的输出 token 属于隐藏推理"', + ], + [ + '"Models charge for their behind-the-scenes thinking as output tokens. pi records this only from 0.80.3 (June 2026), so older periods understate it."', + '"模型会按输出 token 收取后台思考的费用。pi 自 0.80.3(2026 年 6 月)起才记录此项,更早的周期会偏低。"', + ], + // --- 结构:花费趋势 --- + [ + '"Spending is up against your own baseline — the graph view shows what changed."', + '"花费相对你自己的基线在上升 — 图表视图可以看出变化来自哪里。"', + ], + ['"Spending is well below your recent baseline."', '"花费明显低于你近期的基线。"'], + [ + 'headline: `your last 7 days (${fmtMoney(trend.last7Cost)}) vs your prior 4-week pace (${fmtMoney(trend.priorWeeklyPace)}/wk)`', + 'headline: `最近 7 天(${fmtMoney(trend.last7Cost)})对比此前 4 周的周均(${fmtMoney(trend.priorWeeklyPace)}/周)`', + ], + ], +};