feat: /usage 用量面板中文化(上游 0.10.2)

基于 @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/:渲染与数据/导出冒烟脚本
This commit is contained in:
2026-11-18 14:46:30 +08:00
commit 50740b4d08
12 changed files with 4091 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
node_modules/
*.log
.usage-cache-*.tmp
.DS_Store
+21
View File
@@ -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.
+56
View File
@@ -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
+97
View File
@@ -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;
}
+1898
View File
File diff suppressed because it is too large Load Diff
+146
View File
@@ -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<string, ProviderStats>, 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-<view>-<period>[-<slice>]-<stamp>.<ext> 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}`;
}
+413
View File
@@ -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<GraphMetric, string> = {
cost: "花费",
tokens: "Token",
messages: "消息数",
reasoning: "推理 Token",
};
export const GROUP_LABELS: Record<GraphGroupBy, string> = {
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<string>;
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<number, Map<HourlyKey, HourlyCell>>): { 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<number, Map<HourlyKey, HourlyCell>>,
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<string, number[]>();
const groupTotals = new Map<string, number>();
const totalPoints = new Array<number>(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<number>(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<string>();
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<number>(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<number>(plotWidth).fill(0));
const cellOwner: number[][] = Array.from({ length: plotHeight }, () => new Array<number>(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;
}
+1009
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -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": "*"
}
}
+61
View File
@@ -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"));
+116
View File
@@ -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);
+241
View File
@@ -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)}/周)`',
],
],
};