@chenlongapps/opencode-token-usage 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/usage.d.ts CHANGED
@@ -91,16 +91,48 @@ export declare function summarize(messages: Iterable<UsageMessage>, catalog?: Pr
91
91
  total: number;
92
92
  cacheRate: number;
93
93
  steps: number;
94
+ calls: number;
94
95
  cost: number;
95
96
  costStatus: CostStatus;
96
97
  };
97
98
  export type Summary = ReturnType<typeof summarize>;
99
+ export interface ModelCost {
100
+ model: string;
101
+ calls: number;
102
+ tokens: number;
103
+ cost: number;
104
+ costStatus: CostStatus;
105
+ }
106
+ /** Groups the same per-message estimates used by the tree total; unlabelled calls stay visible. */
107
+ export declare function summarizeModels(messages: Iterable<UsageMessage>, catalog?: PriceCatalog): ModelCost[];
98
108
  export interface ContextUsage {
99
109
  used: number;
100
110
  limit: number;
101
111
  percent: number;
102
112
  }
113
+ export interface ContextDetails {
114
+ usage: ContextUsage;
115
+ tokens: Tokens;
116
+ }
117
+ export declare function contextDetails(messages: readonly UsageMessage[], limit?: number): ContextDetails | undefined;
103
118
  export declare function contextUsage(messages: readonly UsageMessage[], limit?: number): ContextUsage | undefined;
104
119
  export declare function formatTokens(value: number): string;
105
120
  export declare const formatCost: (value: number) => string;
121
+ export declare function formatEstimatedCost(cost: number, status: CostStatus): string | undefined;
122
+ /** Compact display for scan-first views: 812, 139.4K, 3.70M. Detailed views keep formatTokens. */
123
+ export declare function formatCompact(value: number): string;
124
+ /** Splits a percentage into filled and empty cell counts for a plain-text bar. */
125
+ export declare function bar(percent: number, width: number): {
126
+ filled: number;
127
+ empty: number;
128
+ };
129
+ /**
130
+ * One model request: the five categories of the last assistant call plus its cache rate.
131
+ * Compact mode hides zero rows and drops percentages; detailed mode keeps both.
132
+ */
133
+ export declare function requestRows(details: ContextDetails, compact: boolean): readonly (readonly [string, string])[];
134
+ /** Tree summary rows for the dialog's detailed Session view, calls included. */
135
+ export declare function summaryRows(summary: Summary): readonly (readonly [string, string])[];
136
+ /** `1 step` reads better than `1 steps` in the dialog's single-line summaries. */
137
+ export declare const countLabel: (value: number, noun: string) => string;
106
138
  export declare function usageRows(summary?: Summary, context?: ContextUsage, performance?: PerformanceSummary): readonly (readonly [string, string])[];
package/dist/usage.js CHANGED
@@ -22,6 +22,22 @@ export function estimate(tokens, prices = []) {
22
22
  && (rate === undefined || !Number.isFinite(rate) || rate < 0))),
23
23
  };
24
24
  }
25
+ function priceMessage(tokens, model, catalog) {
26
+ if (!model)
27
+ return undefined;
28
+ let value = estimate(tokens, catalog.get(modelKey(model)));
29
+ if (value.defaultPrice || value.cost === 0) {
30
+ const snapshot = estimate(tokens, officialPrice(model)?.prices);
31
+ if (!snapshot.defaultPrice)
32
+ value = snapshot;
33
+ }
34
+ return value.defaultPrice ? undefined : value.cost;
35
+ }
36
+ function costStatus(known, missing) {
37
+ if (missing > 0)
38
+ return known > 0 ? "partial" : "unavailable";
39
+ return known > 0 ? "complete" : "empty";
40
+ }
25
41
  /** Prices every call with its recorded model. A complete non-zero OpenCode
26
42
  * price wins; a complete snapshot price can replace a complete OpenCode zero.
27
43
  * Incomplete OpenCode prices fall back to the snapshot as a whole. */
@@ -29,6 +45,7 @@ export function summarize(messages, catalog = new Map()) {
29
45
  const tokens = normalize();
30
46
  let cost = 0;
31
47
  let steps = 0;
48
+ let calls = 0;
32
49
  let knownCosts = 0;
33
50
  let missingCosts = 0;
34
51
  for (const message of messages) {
@@ -46,37 +63,55 @@ export function summarize(messages, catalog = new Map()) {
46
63
  tokens.cache.write += t.cache.write;
47
64
  if (total(t) === 0)
48
65
  continue;
49
- if (!message.model) {
50
- missingCosts++;
51
- continue;
52
- }
53
- let value = estimate(t, catalog.get(modelKey(message.model)));
54
- if (value.defaultPrice || value.cost === 0) {
55
- const snapshot = estimate(t, officialPrice(message.model)?.prices);
56
- if (!snapshot.defaultPrice)
57
- value = snapshot;
58
- }
59
- if (value.defaultPrice)
66
+ // Same population the per-model rows price, so the dialog's call count reconciles with them.
67
+ calls++;
68
+ const value = priceMessage(t, message.model, catalog);
69
+ if (value === undefined)
60
70
  missingCosts++;
61
71
  else {
62
- cost += value.cost;
72
+ cost += value;
63
73
  knownCosts++;
64
74
  }
65
75
  }
66
- const costStatus = missingCosts > 0
67
- ? knownCosts > 0 ? "partial" : "unavailable"
68
- : knownCosts > 0 ? "complete" : "empty";
69
76
  return {
70
77
  tokens, total: total(tokens), cacheRate: incoming(tokens) ? tokens.cache.read / incoming(tokens) : 0,
71
- steps, cost, costStatus,
78
+ steps, calls, cost, costStatus: costStatus(knownCosts, missingCosts),
72
79
  };
73
80
  }
81
+ /** Groups the same per-message estimates used by the tree total; unlabelled calls stay visible. */
82
+ export function summarizeModels(messages, catalog = new Map()) {
83
+ const groups = new Map();
84
+ for (const message of messages) {
85
+ if (message.type !== "assistant" && message.type !== "compaction")
86
+ continue;
87
+ const tokens = normalize(message.tokens);
88
+ const count = total(tokens);
89
+ if (count === 0)
90
+ continue;
91
+ const key = message.model && modelKey(message.model);
92
+ const group = groups.get(key) ?? { calls: 0, tokens: 0, cost: 0, known: 0, missing: 0 };
93
+ group.calls++;
94
+ group.tokens += count;
95
+ const value = priceMessage(tokens, message.model, catalog);
96
+ if (value === undefined)
97
+ group.missing++;
98
+ else {
99
+ group.cost += value;
100
+ group.known++;
101
+ }
102
+ groups.set(key, group);
103
+ }
104
+ return [...groups].map(([model, group]) => ({
105
+ model: model ?? "Unknown model", calls: group.calls, tokens: group.tokens,
106
+ cost: group.cost, costStatus: costStatus(group.known, group.missing),
107
+ })).sort((a, b) => b.cost - a.cost || a.model.localeCompare(b.model));
108
+ }
74
109
  const usableLimit = (value) => value !== undefined && Number.isFinite(value) && value > 0;
75
110
  // Matches the OpenCode 2.0.10 sidebar: the last assistant message with tokens that follows
76
111
  // the last completed compaction carries the current context size. Running or failed
77
112
  // compactions do not reset it, and a last message without usage hides the row entirely
78
113
  // instead of falling back to pre-compaction history.
79
- export function contextUsage(messages, limit) {
114
+ export function contextDetails(messages, limit) {
80
115
  if (!usableLimit(limit))
81
116
  return undefined;
82
117
  let boundary = -1;
@@ -91,15 +126,68 @@ export function contextUsage(messages, limit) {
91
126
  const message = messages[index];
92
127
  if (message.type !== "assistant" || !message.tokens)
93
128
  continue;
94
- const used = total(normalize(message.tokens));
95
- return used > 0 ? { used, limit, percent: used / limit * 100 } : undefined;
129
+ const tokens = normalize(message.tokens);
130
+ const used = total(tokens);
131
+ return used > 0 ? { usage: { used, limit, percent: used / limit * 100 }, tokens } : undefined;
96
132
  }
97
133
  return undefined;
98
134
  }
135
+ export function contextUsage(messages, limit) {
136
+ return contextDetails(messages, limit)?.usage;
137
+ }
99
138
  export function formatTokens(value) {
100
139
  return Math.round(safe(value)).toLocaleString("en-US");
101
140
  }
102
141
  export const formatCost = (value) => value > 0 && value < 0.01 ? "<$0.01" : `$${safe(value).toFixed(2)}`;
142
+ export function formatEstimatedCost(cost, status) {
143
+ if (status === "empty")
144
+ return undefined;
145
+ if (status === "unavailable")
146
+ return "—";
147
+ return `${formatCost(cost)}${status === "partial" ? " · partial" : ""}`;
148
+ }
149
+ /** Compact display for scan-first views: 812, 139.4K, 3.70M. Detailed views keep formatTokens. */
150
+ export function formatCompact(value) {
151
+ const n = safe(value);
152
+ if (n < 1_000)
153
+ return String(Math.round(n));
154
+ const k = n / 1_000;
155
+ return k >= 999.95 ? `${(n / 1_000_000).toFixed(2)}M` : `${k.toFixed(1)}K`;
156
+ }
157
+ /** Splits a percentage into filled and empty cell counts for a plain-text bar. */
158
+ export function bar(percent, width) {
159
+ const size = Math.max(0, Math.floor(width));
160
+ const filled = Math.max(0, Math.min(size, Math.round(percent / 100 * size)));
161
+ return { filled, empty: size - filled };
162
+ }
163
+ /**
164
+ * One model request: the five categories of the last assistant call plus its cache rate.
165
+ * Compact mode hides zero rows and drops percentages; detailed mode keeps both.
166
+ */
167
+ export function requestRows(details, compact) {
168
+ const t = details.tokens;
169
+ const rows = [
170
+ ["Input", t.input], ["Output", t.output], ["Reasoning", t.reasoning],
171
+ ["Cache Read", t.cache.read], ["Cache Write", t.cache.write],
172
+ ].filter(([, count]) => !compact || count > 0);
173
+ const incomingTokens = incoming(t);
174
+ return [
175
+ ...rows.map(([label, count]) => [
176
+ label,
177
+ compact ? formatCompact(count) : `${formatTokens(count)} (${(count / details.usage.used * 100).toFixed(1)}%)`,
178
+ ]),
179
+ ["Cache Rate", `${(incomingTokens ? t.cache.read / incomingTokens * 100 : 0).toFixed(1)}%`],
180
+ ];
181
+ }
182
+ /** Tree summary rows for the dialog's detailed Session view, calls included. */
183
+ export function summaryRows(summary) {
184
+ return [
185
+ ["Steps", formatTokens(summary.steps)], ["Calls", formatTokens(summary.calls)],
186
+ ...usageRows(summary).filter(([label]) => label !== "Steps"),
187
+ ];
188
+ }
189
+ /** `1 step` reads better than `1 steps` in the dialog's single-line summaries. */
190
+ export const countLabel = (value, noun) => `${formatTokens(value)} ${noun}${value === 1 ? "" : "s"}`;
103
191
  export function usageRows(summary, context, performance) {
104
192
  const t = summary?.tokens;
105
193
  const number = (value) => value === undefined ? "—" : formatTokens(value);
@@ -110,12 +198,9 @@ export function usageRows(summary, context, performance) {
110
198
  if (t && t.cache.write > 0)
111
199
  rows.push(["Cache Write", number(t.cache.write)]);
112
200
  rows.push(["Cache Rate", summary ? `${(summary.cacheRate * 100).toFixed(1)}%` : "—"], ["Total", number(summary?.total)]);
113
- if (summary?.costStatus === "complete")
114
- rows.push(["Cost", formatCost(summary.cost)]);
115
- if (summary?.costStatus === "partial")
116
- rows.push(["Cost", `${formatCost(summary.cost)} · partial`]);
117
- if (summary?.costStatus === "unavailable")
118
- rows.push(["Cost", "—"]);
201
+ const cost = summary && formatEstimatedCost(summary.cost, summary.costStatus);
202
+ if (cost !== undefined)
203
+ rows.push(["Cost", cost]);
119
204
  if (performance?.tps !== undefined && Number.isFinite(performance.tps)) {
120
205
  rows.push(["TPS", `${performance.tpsEstimated ? "~" : ""}${Math.max(0, performance.tps).toFixed(1)} tok/s`]);
121
206
  }
@@ -1,5 +1,41 @@
1
1
  # 验证记录
2
2
 
3
+ ## v0.4.0(`/usage` 原生弹窗)
4
+
5
+ 验证日期:2026-09-23。Node.js v22.23.2;`@opencode/plugin`、`@opencode/client` 等 SDK 精确锁定 2.0.11。弹窗布局参考本地 OpenCode 2.0.15 源码中的 `dialog-status.tsx`、`dialog-debug.tsx` 和 `dialog-shell-output.tsx`,通过插件公开的斜杠命令、弹窗、`session.hook("context")` 和 RPC 接口实现,并在真实 OpenCode 2.0.11 宿主中验证。
6
+
7
+ | 检查 | 结果 |
8
+ | --- | --- |
9
+ | `npm run typecheck` | 通过 |
10
+ | `npm test` | 62 项通过 |
11
+ | `npm run build` | 通过,输出 ESM 与类型声明 |
12
+ | `npm run test:smoke` | 通过,使用 `.tgz` 安装产物、真实 OpenCode 2.0.11 与本地模拟提供商 |
13
+
14
+ `/usage` 仅在会话页面注册为 CLI 斜杠/命令面板命令,打开原生弹窗而不向模型发送新消息。弹窗按当前查看会话展示最后一次已完成压缩后的上下文用量;五类 token 的占比以该条 assistant 消息的已用 context 为分母,窗口占用率以活动模型上下文上限为分母。会话树明细沿用侧边栏的完整分页、子代理汇总和分叉继承去重口径;按模型汇总的费用与全树 Cost 共用逐消息计价规则,分别处理免费、缺价、`partial` 及内置官方价格回退。
15
+
16
+ 自动化测试新增:五类 context 分类百分比、压缩边界与未知上限;混合模型和 compaction、价格回退、免费与缺价时逐模型费用对全树费用的核对;弹窗详细快照在子会话、刷新失败恢复和切换会话时的生命周期。打包集成测试确认空会话不会伪造上下文占用,真实 `/usage` 可打开与关闭、显示 1,270 token 当前上下文分类和模型费用;100 × 28 终端内滚动可到达模型费用;真实子代理合并后显示全树 5,080 token;切换活动模型后弹窗上限变为 32,000,历史消息费用仍列在原模型下。2.0.11 子代理视图最初处于宿主的子代理覆盖层,不提供斜杠输入;其全树面板验证继续由 `session.composer.top` 覆盖。
17
+
18
+ 新增 **Context Sources · estimated**:服务端只在 `context` 钩子中观察最近一次已组装的模型请求,按可识别的消息文本、系统工具定义/Code Mode 目录、系统提示词、技能文本/目录、MCP 指令/工具以及其他内容分别估算,持久化的仅是六类数值、模型和采样时间;CLI 通过位置限定的 RPC 读取。估算使用 UTF-8 字节数近似,不是提供商真实 token 归因,媒体负载及提供商包装无法准确计量,也不会与含输出/推理的实测 Context 相加一致。未捕获过请求的会话显示不可用;服务端插件或 RPC 不可用时仍显示实测统计。测试覆盖六类独立归因、占比分母、无技能/MCP 时的零值、Code Mode 后续项目指令、工具结果媒体忽略、无效 RPC 数据,以及 RPC 缓慢/失败时不阻塞实测用量或串会话。真实 2.0.11 打包集成验证了请求钩子记录与 CLI 弹窗读取均生效。
19
+
20
+ ## v0.4.0(`/usage` 弹窗信息架构重构)
21
+
22
+ 验证日期:2026-09-23。Node.js v22.23.2;SDK 仍精确锁定 2.0.11。本轮只改弹窗的数据映射与呈现,统计与定价逻辑不变。
23
+
24
+ | 检查 | 结果 |
25
+ | --- | --- |
26
+ | `npm run typecheck` | 通过 |
27
+ | `npm test` | 62 项通过 |
28
+ | `npm run build` | 通过 |
29
+ | `npm run test:smoke` | 通过,真实 OpenCode 2.0.11 + 本地模拟提供商 |
30
+
31
+ 信息架构由 `Context / Context Sources / Session Tree / Cost by Model` 改为 **Context Window / Last Request / Context Breakdown / Session / By Model**:Context Window 只呈现上下文占用(分母为活动模型上限)并带条形图;原 Context 内的五类 token 迁入 Last Request 并补充该次请求的缓存率;`Context Sources · estimated` 改名 Context Breakdown;`Session Tree` 改名 Session,因为面板本来就是全树汇总而非树结构;`Cost by Model` 改名 By Model。标题下方新增一行显示会话名与活动模型(多模型时显示模型数量),正文不再重复模型名,弹窗改用宿主 `centered` 选项垂直居中。
32
+
33
+ 默认紧凑模式使用 K/M 缩写(< 1,000 精确、< 1,000,000 一位小数 K、≥ 1,000,000 两位小数 M,四舍五入不会出现 `1000.0K`),隐藏零值行,并把 Context Breakdown 的两类工具合并为 `Tools` 行按占比降序;按 `d` 切换详细模式,恢复精确数字、零值行、`System Tools` / `MCP Tools` 拆分以及 Session 逐类明细(含 Calls)。Session 单行汇总为 `steps · calls · tokens · cached% · cost`,其中 calls 与 By Model 各行同源,可与逐模型行核对。条形图宽度、Last Request 双列与内容宽度随宿主 `large` 档(88 列)收敛,窄终端自动改为单列并收窄条长。
34
+
35
+ 自动化测试新增:`formatCompact` 边界、`bar` 填充与越界、`requestRows` 的紧凑/详细两态、`summarize().calls` 与 `summaryRows`、`countLabel` 单复数、`breakdownRows` 的工具合并、降序与零值策略。打包集成测试确认紧凑与详细两种模式可切换、`Used / Limit` 显示 `1.3K / 128.0K (1.0%)`、Context Breakdown 显示 `Tools` 合并行与条形图、Session 单行汇总、By Model 逐模型费用,以及 100 × 28 终端内滚动仍可到达模型费用。
36
+
37
+ 尚未实现(属于后续评估):真实的分叉/分支树统计、进度条以外的窗口告警色阶、公开价格目录。
38
+
3
39
  ## v0.3.3(GPT 与 Claude Fast 价格)
4
40
 
5
41
  验证日期:2026-09-23。根据 [OpenAI API Pricing](https://developers.openai.com/api/docs/pricing) 与 [Claude Platform Pricing](https://platform.claude.com/docs/en/about-claude/pricing),为当前快照中官方支持 Fast mode 的 GPT-5.5、GPT-5.6 Sol/Terra/Luna、GPT-6 Astra/Sol/Luna,以及 Claude Opus 4.8/5/5.5 分别加入独立 Fast 条目。Fast 费率按官方长上下文档位与缓存倍率记录;GPT-5.5 Fast 未公布长上下文费率,超过 272,000 个传入 token 时显示不可估价。条目分别限制到官方支持 Fast mode 的 OpenAI 与 Anthropic provider;快照由 76 个模型增至 86 个。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chenlongapps/opencode-token-usage",
3
- "version": "0.3.4",
3
+ "version": "0.4.0",
4
4
  "description": "Session-tree token usage, live performance, context window and estimated cost for OpenCode 2",
5
5
  "keywords": [
6
6
  "opencode",