@chenlongapps/opencode-token-usage 0.4.28 → 0.5.1

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/pricing.d.ts CHANGED
@@ -1,23 +1,3 @@
1
- import type { ModelRef, Price } from "./usage.js";
2
- export interface OfficialPriceEntry {
3
- /** Manufacturer, never the provider of a gateway quote. */
4
- providerID: string;
5
- id: string;
6
- /** USD per million tokens, using OpenCode's exclusive context tiers. */
7
- prices: readonly Price[];
8
- source: string;
9
- released?: string;
10
- /** Limited first-party SKUs, such as Fast processing. */
11
- providers?: readonly string[];
12
- reason?: string;
13
- }
14
- /** Checked-in data: updating prices is explicit, not a network request at
15
- * startup, during a refresh, or during an npm build. */
16
- export declare const OFFICIAL_PRICE_SNAPSHOT: {
17
- verified: "2026-11-20";
18
- source: "https://models.dev/api.json";
19
- entries: OfficialPriceEntry[];
20
- };
21
- /** Exact first-party model IDs and known gateway wrappers only. A bare ID may
22
- * resolve at a gateway only when it is unique across manufacturer catalogs. */
23
- export declare function officialPrice(model: ModelRef): OfficialPriceEntry | undefined;
1
+ /** Checked-in data only. Lookup resolves an identity, not a price source. */
2
+ export declare const builtInPrice: (model: import("./usage.js").ModelRef) => import("./price-identity.js").SnapshotPrice | undefined;
3
+ export declare const freeReferencePrice: (model: import("./usage.js").ModelRef) => import("./price-identity.js").SnapshotPrice | undefined;
package/dist/pricing.js CHANGED
@@ -1,98 +1,5 @@
1
- import { MODEL_ALIASES, PROVIDER_ALIASES } from "./aliases.js";
2
- import { ORIGINAL_PROVIDERS, PRICE_OVERRIDES } from "./overrides.js";
1
+ import { snapshotFreeReferenceLookup, snapshotLookup } from "./price-identity.js";
3
2
  import { GENERATED_PRICE_SNAPSHOT } from "./prices.generated.js";
4
- const index = new Map();
5
- for (const entry of GENERATED_PRICE_SNAPSHOT.entries) {
6
- const key = `${entry.providerID}/${entry.id}`.toLowerCase();
7
- if (index.has(key))
8
- throw new Error(`Duplicate manufacturer price: ${key}`);
9
- index.set(key, { ...entry, source: GENERATED_PRICE_SNAPSHOT.source });
10
- }
11
- for (const entry of PRICE_OVERRIDES) {
12
- // Reviewed exceptions replace a source row as a whole; never mix rate fields.
13
- index.set(`${entry.providerID}/${entry.id}`.toLowerCase(), entry);
14
- }
15
- for (const [alias, target] of Object.entries(MODEL_ALIASES)) {
16
- if (!index.has(target))
17
- throw new Error(`Unknown manufacturer price alias: ${alias} -> ${target}`);
18
- }
19
- /** Checked-in data: updating prices is explicit, not a network request at
20
- * startup, during a refresh, or during an npm build. */
21
- export const OFFICIAL_PRICE_SNAPSHOT = {
22
- verified: GENERATED_PRICE_SNAPSHOT.verified,
23
- source: GENERATED_PRICE_SNAPSHOT.source,
24
- entries: [...index.values()].sort((a, b) => a.providerID.localeCompare(b.providerID) || a.id.localeCompare(b.id)),
25
- };
26
- const byBareID = new Map();
27
- for (const entry of index.values()) {
28
- const id = entry.id.toLowerCase();
29
- const matches = byBareID.get(id) ?? [];
30
- matches.push(entry);
31
- byBareID.set(id, matches);
32
- }
33
- const vendor = (id) => {
34
- const value = PROVIDER_ALIASES[id] ?? id;
35
- return value in ORIGINAL_PROVIDERS || PRICE_OVERRIDES.some(entry => entry.providerID === value) ? value : undefined;
36
- };
37
- const alternateSpelling = (id) => id.replace(/^claude-opus-(\d+)\.(\d+)(?=$|-)/, "claude-opus-$1-$2");
38
- function available(entry, model) {
39
- return entry && (!entry.providers || entry.providers.some(provider => provider === model.providerID.toLowerCase()))
40
- ? entry : undefined;
41
- }
42
- function lookup(manufacturer, id, model) {
43
- const original = `${manufacturer}/${alternateSpelling(id)}`;
44
- const key = MODEL_ALIASES[original] ?? original;
45
- return available(index.get(key), model);
46
- }
47
- /** Exact first-party model IDs and known gateway wrappers only. A bare ID may
48
- * resolve at a gateway only when it is unique across manufacturer catalogs. */
49
- export function officialPrice(model) {
50
- const providerID = model.providerID.toLowerCase();
51
- const raw = model.id.toLowerCase();
52
- const id = providerID === "google-vertex" ? raw.replace(/@default$/, "") : raw;
53
- const candidates = [id];
54
- if (id.endsWith("-free"))
55
- candidates.push(id.slice(0, -5));
56
- if (id.endsWith(":free"))
57
- candidates.push(id.slice(0, -5));
58
- const direct = vendor(providerID);
59
- if (direct) {
60
- for (const candidate of candidates) {
61
- const match = lookup(direct, candidate, model);
62
- if (match)
63
- return match;
64
- }
65
- return undefined;
66
- }
67
- for (const candidate of candidates) {
68
- const slash = candidate.indexOf("/");
69
- if (slash >= 0) {
70
- const slug = candidate.slice(0, slash);
71
- const manufacturer = vendor(slug);
72
- if (!manufacturer)
73
- continue;
74
- const match = lookup(manufacturer, candidate.slice(slash + 1), model)
75
- ?? lookup(manufacturer, candidate, model);
76
- if (match)
77
- return match;
78
- continue;
79
- }
80
- if (providerID === "amazon-bedrock") {
81
- const bedrock = /^(?:(?:us|eu|apac|global)\.)?([a-z0-9-]+)\.(.+)$/.exec(candidate);
82
- const manufacturer = bedrock && vendor(bedrock[1]);
83
- if (manufacturer) {
84
- const match = lookup(manufacturer, bedrock[2], model);
85
- if (match)
86
- return match;
87
- continue;
88
- }
89
- }
90
- const matches = byBareID.get(alternateSpelling(candidate));
91
- if (matches?.length === 1) {
92
- const match = available(matches[0], model);
93
- if (match)
94
- return match;
95
- }
96
- }
97
- return undefined;
98
- }
3
+ /** Checked-in data only. Lookup resolves an identity, not a price source. */
4
+ export const builtInPrice = snapshotLookup(GENERATED_PRICE_SNAPSHOT);
5
+ export const freeReferencePrice = snapshotFreeReferenceLookup(GENERATED_PRICE_SNAPSHOT);
package/dist/tui.js CHANGED
@@ -19,7 +19,7 @@ import { ContextSourceRpc } from "./context-rpc.js";
19
19
  import { breakdownRows } from "./context-sources.js";
20
20
  import { createClickHandlers } from "./click.js";
21
21
  import { createSource } from "./source.js";
22
- import { bar, countLabel, fitUsageSummary, formatCompact, formatEstimatedCost, formatRateTier, formatRunTime, formatTokens, rateRows, requestRows, summaryRows, usageRows } from "./usage.js";
22
+ import { bar, countLabel, fitUsageSummary, formatCompact, formatEstimatedCost, formatRateTier, formatRunTime, formatTokens, formatTps, rateRows, requestRows, summaryRows, usageRows } from "./usage.js";
23
23
  function UsageView(props) {
24
24
  const titleClick = createClickHandlers(() => props.openDetails?.(), () => !!props.context.renderer.getSelection()?.getSelectedText());
25
25
  const rows = createMemo(() => usageRows(props.state().summary, props.state().context, props.state().performance, props.state().runtime));
@@ -236,8 +236,7 @@ function ChildUsageLauncher(props) {
236
236
  }[current.status]}`;
237
237
  const context = current.context ? `${formatTokens(current.context.used)} / ${formatTokens(current.context.limit)} (${current.context.percent.toFixed(1)}%)` : "—";
238
238
  const cost = formatEstimatedCost(current.summary.cost, current.summary.costStatus) ?? "—";
239
- const tps = current.performance?.tps !== undefined && Number.isFinite(current.performance.tps) ? `${current.performance.tpsEstimated ? "~" : ""}${Math.max(0, current.performance.tps).toFixed(1)} tok/s` : "—";
240
- return fitUsageSummary([["Context", context], ["Total", formatTokens(current.summary.total)], ["Cost", cost], ["Time", runtime()], ["TPS", tps]], Math.max(20, dimensions().width - 8), current.status === "stale");
239
+ return fitUsageSummary([["Context", context], ["Total", formatTokens(current.summary.total)], ["Cost", cost], ["Time", runtime()], ["TPS", formatTps(current.performance)]], Math.max(20, dimensions().width - 8), current.status === "stale");
241
240
  });
242
241
  return (() => {
243
242
  var _el$17 = _$createElement("box"),
@@ -838,6 +837,17 @@ function UsageDialog(props) {
838
837
  _$insertNode(_el$114, _el$115);
839
838
  _$insert(_el$114, () => number(model.tokens), _el$115);
840
839
  _$insert(_el$114, () => countLabel(model.calls, "call"), null);
840
+ _$insert(_el$110, _$createComponent(Show, {
841
+ get when() {
842
+ return _$memo(() => !!!detailed())() && model.appliedRates.some(rates => rates.source === "Free usage reference");
843
+ },
844
+ get children() {
845
+ var _el$116 = _$createElement("text");
846
+ _$insertNode(_el$116, _$createTextNode(`Includes free usage reference`));
847
+ _$effect(_$p => _$setProp(_el$116, "fg", theme().muted, _$p));
848
+ return _el$116;
849
+ }
850
+ }), null);
841
851
  _$insert(_el$110, _$createComponent(Show, {
842
852
  get when() {
843
853
  return detailed();
@@ -848,34 +858,34 @@ function UsageDialog(props) {
848
858
  return model.appliedRates;
849
859
  },
850
860
  children: rates => (() => {
851
- var _el$118 = _$createElement("box"),
852
- _el$119 = _$createElement("text"),
853
- _el$120 = _$createTextNode(` · `),
854
- _el$121 = _$createTextNode(` · `);
855
- _$insertNode(_el$118, _el$119);
856
- _$setProp(_el$118, "marginTop", 1);
857
- _$insertNode(_el$119, _el$120);
858
- _$insertNode(_el$119, _el$121);
859
- _$setProp(_el$119, "wrapMode", "word");
860
- _$insert(_el$119, () => rates.source, _el$120);
861
- _$insert(_el$119, () => formatRateTier(rates), _el$121);
862
- _$insert(_el$119, () => countLabel(rates.calls, "call"), null);
863
- _$insert(_el$118, () => requestRowsList(rateRows(rates)), null);
864
- _$effect(_$p => _$setProp(_el$119, "fg", theme().muted, _$p));
865
- return _el$118;
861
+ var _el$120 = _$createElement("box"),
862
+ _el$121 = _$createElement("text"),
863
+ _el$122 = _$createTextNode(` · `),
864
+ _el$123 = _$createTextNode(` · `);
865
+ _$insertNode(_el$120, _el$121);
866
+ _$setProp(_el$120, "marginTop", 1);
867
+ _$insertNode(_el$121, _el$122);
868
+ _$insertNode(_el$121, _el$123);
869
+ _$setProp(_el$121, "wrapMode", "word");
870
+ _$insert(_el$121, () => rates.source, _el$122);
871
+ _$insert(_el$121, () => formatRateTier(rates), _el$123);
872
+ _$insert(_el$121, () => countLabel(rates.calls, "call"), null);
873
+ _$insert(_el$120, () => requestRowsList(rateRows(rates)), null);
874
+ _$effect(_$p => _$setProp(_el$121, "fg", theme().muted, _$p));
875
+ return _el$120;
866
876
  })()
867
877
  }), _$createComponent(Show, {
868
878
  get when() {
869
879
  return model.unpricedCalls > 0;
870
880
  },
871
881
  get children() {
872
- var _el$116 = _$createElement("text"),
873
- _el$117 = _$createTextNode(`Pricing unavailable for `);
874
- _$insertNode(_el$116, _el$117);
875
- _$setProp(_el$116, "wrapMode", "word");
876
- _$insert(_el$116, () => countLabel(model.unpricedCalls, "call"), null);
877
- _$effect(_$p => _$setProp(_el$116, "fg", theme().muted, _$p));
878
- return _el$116;
882
+ var _el$118 = _$createElement("text"),
883
+ _el$119 = _$createTextNode(`Pricing unavailable for `);
884
+ _$insertNode(_el$118, _el$119);
885
+ _$setProp(_el$118, "wrapMode", "word");
886
+ _$insert(_el$118, () => countLabel(model.unpricedCalls, "call"), null);
887
+ _$effect(_$p => _$setProp(_el$118, "fg", theme().muted, _$p));
888
+ return _el$118;
879
889
  }
880
890
  })];
881
891
  }
package/dist/usage.d.ts CHANGED
@@ -25,7 +25,7 @@ export interface Price {
25
25
  };
26
26
  input?: number;
27
27
  output?: number;
28
- /** Optional first-party rate when reasoning differs from ordinary output. */
28
+ /** Optional separate rate when reasoning differs from ordinary output. */
29
29
  reasoning?: number;
30
30
  cache?: {
31
31
  read?: number;
@@ -90,7 +90,7 @@ export declare function estimate(tokens: Tokens, prices?: readonly Price[]): {
90
90
  defaultPrice: boolean;
91
91
  };
92
92
  export type CostStatus = "empty" | "complete" | "partial" | "unavailable";
93
- export type PriceSource = "OpenCode" | "Built-in snapshot";
93
+ export type PriceSource = "OpenCode" | "Built-in snapshot" | "Free usage reference";
94
94
  export interface AppliedRates {
95
95
  source: PriceSource;
96
96
  lowerExclusive: number | undefined;
@@ -104,9 +104,8 @@ export interface AppliedRates {
104
104
  cacheWrite: number | undefined;
105
105
  };
106
106
  }
107
- /** Prices every call with its recorded model. A complete non-zero OpenCode
108
- * price wins; a complete snapshot price can replace a complete OpenCode zero.
109
- * Incomplete OpenCode prices fall back to the snapshot as a whole. */
107
+ /** Prices every call with its recorded model. An exactly linked Free SKU can
108
+ * add a paid benchmark to the estimate; every call uses a single schedule. */
110
109
  export declare function summarize(messages: Iterable<UsageMessage>, catalog?: PriceCatalog): {
111
110
  tokens: Tokens;
112
111
  total: number;
@@ -170,4 +169,5 @@ export declare function requestRows(details: RequestDetails, compact: boolean):
170
169
  export declare function summaryRows(summary: Summary): readonly (readonly [string, string])[];
171
170
  /** `1 step` reads better than `1 steps` in the dialog's single-line summaries. */
172
171
  export declare const countLabel: (value: number, noun: string) => string;
172
+ export declare function formatTps(performance?: PerformanceSummary): string | undefined;
173
173
  export declare function usageRows(summary?: Summary, context?: ContextUsage, performance?: PerformanceSummary, runtime?: RuntimeSummary): readonly (readonly [string, string])[];
package/dist/usage.js CHANGED
@@ -1,4 +1,5 @@
1
- import { officialPrice } from "./pricing.js";
1
+ import { billingMode } from "./price-identity.js";
2
+ import { builtInPrice, freeReferencePrice } from "./pricing.js";
2
3
  export const modelKey = (model) => `${model.providerID}/${model.id}`;
3
4
  const safe = (n) => n !== undefined && Number.isFinite(n) ? Math.max(0, n) : 0;
4
5
  export function normalize(tokens) {
@@ -28,14 +29,30 @@ export function estimate(tokens, prices = []) {
28
29
  function priceMessage(tokens, model, catalog) {
29
30
  if (!model)
30
31
  return undefined;
31
- let prices = catalog.get(modelKey(model)) ?? [];
32
+ // OpenCode's model list has a single cost per ID and no variant-specific
33
+ // tariff. Do not mistake the base model's cost for a named serving mode.
34
+ let prices = (billingMode(model) ? undefined : catalog.get(modelKey(model))) ?? [];
32
35
  let source = "OpenCode";
33
36
  let value = estimate(tokens, prices);
37
+ // Zero on its own is not evidence of a Free SKU. Only verified Free links
38
+ // contribute a paid benchmark; ordinary zero rates and promotions remain zero.
34
39
  if (value.defaultPrice || value.cost === 0) {
35
- const fallback = officialPrice(model)?.prices ?? [];
36
- const snapshot = estimate(tokens, fallback);
37
- if (!snapshot.defaultPrice) {
38
- value = snapshot;
40
+ const runtime = selectedPrice(tokens, prices);
41
+ const hasPositiveRate = [runtime?.input, runtime?.output, runtime?.reasoning, runtime?.cache?.read, runtime?.cache?.write]
42
+ .some(rate => rate !== undefined && Number.isFinite(rate) && rate > 0);
43
+ const reference = value.defaultPrice || !hasPositiveRate ? freeReferencePrice(model)?.prices : undefined;
44
+ if (reference) {
45
+ const result = estimate(tokens, reference);
46
+ const price = selectedPrice(tokens, reference);
47
+ if (!result.defaultPrice && price)
48
+ return { cost: result.cost, source: "Free usage reference", price, prices: reference };
49
+ }
50
+ const entry = builtInPrice(model);
51
+ const replaceZero = entry?.zeroException === modelKey(model).toLowerCase()
52
+ && !hasPositiveRate;
53
+ if (value.defaultPrice || replaceZero) {
54
+ const fallback = entry?.prices ?? [];
55
+ value = estimate(tokens, fallback);
39
56
  prices = fallback;
40
57
  source = "Built-in snapshot";
41
58
  }
@@ -69,9 +86,8 @@ function costStatus(known, missing) {
69
86
  return known > 0 ? "partial" : "unavailable";
70
87
  return known > 0 ? "complete" : "empty";
71
88
  }
72
- /** Prices every call with its recorded model. A complete non-zero OpenCode
73
- * price wins; a complete snapshot price can replace a complete OpenCode zero.
74
- * Incomplete OpenCode prices fall back to the snapshot as a whole. */
89
+ /** Prices every call with its recorded model. An exactly linked Free SKU can
90
+ * add a paid benchmark to the estimate; every call uses a single schedule. */
75
91
  export function summarize(messages, catalog = new Map()) {
76
92
  const tokens = normalize();
77
93
  let cost = 0;
@@ -324,6 +340,12 @@ export function summaryRows(summary) {
324
340
  }
325
341
  /** `1 step` reads better than `1 steps` in the dialog's single-line summaries. */
326
342
  export const countLabel = (value, noun) => `${formatTokens(value)} ${noun}${value === 1 ? "" : "s"}`;
343
+ export function formatTps(performance) {
344
+ const tps = performance?.tps;
345
+ if (tps === undefined || !Number.isFinite(tps))
346
+ return undefined;
347
+ return `${performance?.tpsEstimated ? "~" : ""}${tps > 0 && tps < 0.1 ? "<0.1" : Math.max(0, tps).toFixed(1)} tok/s`;
348
+ }
327
349
  export function usageRows(summary, context, performance, runtime) {
328
350
  const t = summary?.tokens;
329
351
  const number = (value) => value === undefined ? "—" : formatTokens(value);
@@ -337,9 +359,9 @@ export function usageRows(summary, context, performance, runtime) {
337
359
  const cost = summary && formatEstimatedCost(summary.cost, summary.costStatus);
338
360
  if (cost !== undefined)
339
361
  rows.push(["Est. Cost", cost]);
340
- if (performance?.tps !== undefined && Number.isFinite(performance.tps)) {
341
- rows.push(["TPS", `${performance.tpsEstimated ? "~" : ""}${Math.max(0, performance.tps).toFixed(1)} tok/s`]);
342
- }
362
+ const tps = formatTps(performance);
363
+ if (tps !== undefined)
364
+ rows.push(["TPS", tps]);
343
365
  if (performance?.ttft !== undefined && Number.isFinite(performance.ttft)) {
344
366
  rows.push(["TTFT", `${(Math.max(0, performance.ttft) / 1_000).toFixed(1)}s`]);
345
367
  }
package/docs/pricing.md CHANGED
@@ -1,39 +1,40 @@
1
- # 内置原厂价格快照
1
+ # 内置官方价与参考价
2
2
 
3
- 插件在 OpenCode 当前模型目录无法为一条消息提供完整价格时,使用仓库内已生成的价格快照。快照的版本、核对日期、逐模型费率和档位见 [`src/prices.generated.ts`](../src/prices.generated.ts);来源是 [models.dev 的 API](https://models.dev/api.json)。少量经原厂核实的例外见 [`src/overrides.ts`](../src/overrides.ts),例外的来源、原因及统一核验日期也保存在该文件。所有金额均为美元 / 100 万 token。
3
+ 插件优先使用 OpenCode 当前解析的费率。需要回退时,离线快照 [`src/prices.generated.ts`](../src/prices.generated.ts) 对每个标准模型或独立计费 SKU **只保存一个来源**;该来源可以包含多个上下文档位。报价候选只存在于生成脚本内存中。快照中的 `lab` / `id` 是模型身份,`sourceProvider` 是报价方(与 `lab` 同名时省略),`reference: true` 表示参考价。`bindings` 和 `freeReferences` 只存精确 SKU 映射,不存报价。金额均为美元 / 100 万 token。
4
4
 
5
- ## 更新方式
5
+ ## 模型身份与选价
6
6
 
7
- GitHub Actions [价格更新工作流](../.github/workflows/update-prices.yml) 每 4 小时从 models.dev 检查一次,也可从 Actions 页面在 `main` 上手动触发。生成快照没有差异就结束,不会因检查日期或 API 中未导入的元数据变化发布新版本。白名单内的快照有变化(包含新增、移除和重新定价)时,先运行类型检查、测试、构建和 `npm pack --dry-run`,全部通过后自动升级 patch 版本,只提交 `src/prices.generated.ts`、`package.json`、`package-lock.json`,原子推送 `main` 与版本标签,再创建 GitHub Release 并显式触发 `publish.yml` 自动发布 npm。
7
+ [models.dev `catalog.json`](https://models.dev/catalog.json) 在同一份响应中返回 Provider 报价和独立的 LAB 型号目录。Provider 模型的 `canonical_model_id` 来源于上游 `base_model`,格式是 `LAB/模型 ID`。生成器用 LAB 目录校验它;缺失时仅接受目录中可验证的精确限定 ID,或精确的 `LAB/本地 ID`。第三方裸 ID 无法凭同名或模型系列取得报价资格。身份冲突或未登记的条目不参与报价。已知的 Free、Fast、Pro 等计费 SKU 与标准费率分开,上游发布的不同版本也不合并。
8
8
 
9
- 验证失败不升版本;并发修改 `main` 会令原子推送失败,不覆盖他人提交或留下孤立的远端标签。已推送但 npm 未完成的自动价格版本会先重试原标签,不再递增版本。npm 查询只有明确的 404 才视为版本不存在,网络错误会停止流程。工作流摘要记录快照条数与新增/移除/变化数量;最终 npm 结果见发布工作流。仓库推送权限与 npm Trusted Publishing 配置见[发布说明](releasing.md)。
9
+ Provider ID 与 LAB 相同即视为该 LAB 的原厂 API;名称不同的可核验关系记录在 [`src/aliases.ts`](../src/aliases.ts),例如 `tencent-tokenhub` → `tencent`、`zai` → `zhipuai`、`amazon-bedrock` → `amazon`。关联只对模型自己的 LAB 生效:Bedrock 转售的 Claude、阿里云转售的 Kimi 均不是官方价。原厂有多个有效非零报价时,优先常用直连 API,再考虑同厂商的其他云/区域 API。普通新模型无需维护系列白名单。
10
10
 
11
- 本地手动更新可在联网的维护环境中运行:
11
+ 1. 选有效的**原厂非零价**。缺失 Cache Read / Write 不会使有效的原厂基础报价让位给第三方。
12
+ 2. 否则依次选有有效非零价的 **OpenRouter**(`openrouter`)、**Vercel AI Gateway**(`vercel`)、**Amazon Bedrock**(`amazon-bedrock`)、**LLM Gateway**(`llmgateway-providers` 为指定上游路由,`llmgateway` 为同一网关的自动路由)。低优先级供应商即使更便宜,也不能覆盖已选报价。同一优先级有多条非零报价时,优先更直接的精确型号路由,再按字段覆盖度、Provider ID 和 SKU 排序。
13
+ 3. 四家都没有有效非零价时,选其他 Provider 中基础档 **Input + Output** 最低的非零价。总和相同,优先选各档位最少缺失的缓存费率,再看是否有独立 Reasoning 费率,最后按 Provider ID 和 SKU 字典序。不会跨 Provider 拼接价格;该比较只是选基准,不能判断每种请求的实际最低成本。
14
+ 4. 全部有效报价均为零时,按原厂、上述供应商顺序、其余 Provider ID 字典序选一条明确的零价。无有效报价则不生成记录。之后应用有来源和原因的人工例外,整条替换选定费率。
15
+
16
+ ## 估算规则与边界
17
+
18
+ - Input / Output 必须同时为有限非负数字;缓存费率允许缺失,但不补零。上游单列 Reasoning 费率时采用该值,否则沿用 Output。存在正数费率的有效档位表不是零价表。上下文按该条消息的 `input + cache read + cache write` 计入档位,阈值为**严格大于**;不从旧 `context_over_200k` 字段或不完整的模式价格猜测档位。
19
+ - 每条 assistant / compaction 消息按记录的模型和实际用到的 token 类别估算。OpenCode 的完整非零价格优先。SDK 只按模型 ID 返回费率;若消息用 `variant` 指定已知独立计费模式,不把标准 SKU 的费率当成模式价。OpenCode 费率缺失或不完整时整条回退。内置价格也缺少实际用到的费率则不能计价,不改选其他 Provider、不混用费率。
20
+ - 若上游明确关联了 Free SKU 和付费型号,且参考价能完整覆盖该调用,则把参考费用计入 `Est. Cost`,例如 `opencode/hy4-flash-free` 对应 `tencent/hy4-flash`。独立计费的 Contributor、Fast 等需找到同模式的付费身份。无法匹配或参考费率不完整时保留有效零价;没有有效零价才显示不可计价。普通 SKU 的完整零价不会仅因参考价存在而被替换,除非有已核实的端点计费例外。
21
+ - 精确的 Provider / SKU 映射优先于精确限定 ID、明确别名和已知包装格式;只在无歧义时兼容完整裸 ID。不会去掉 `-free` / `:free` 后用裸 ID 猜测对应的付费型号。
22
+ - `/token-usage` 的 By Model 标注 `Free usage reference`;详细模式按实际采用的来源和上下文档位列出五类费率及调用数。无法计价显示 `—`,仅部分调用可计价标注 `partial`,确认零价且未应用参考价时显示 `$0.00`。运行时使用当前模型目录和随包价格;不重现历史账单。
23
+ - 只导入可用五类 token 估算的文本费率;独立音频费率、非文本输出、特殊计费或已知订阅/额度报价不能充当标准 token 价。上游 v1 报价也不一定能表达区域、分时、缓存 TTL 等条件。参考价不含其他渠道的加价、折扣、工具费、税费或非文本计费。
24
+
25
+ ## 例外与更新
26
+
27
+ [`PRICE_OVERRIDES`](../src/overrides.ts) 保留出处和原因,例如 DeepSeek 的可核实峰值价、Kimi K3 的五分钟缓存写入费率、OpenAI Fast 的长上下文档位,以及腾讯 Hy3 的按量价格。人工条目也不能用假定费率填补未知档位。另有少量已知字段修正:xAI 在 200K 起涨价,换算为 199,999 的严格大于阈值;Z.ai 按时间收费的缓存存储不解释为免费写入;阿里云隐式和显式写入价格不同,不能用聚合写入计数选择其一。
28
+
29
+ 本地手动更新:
12
30
 
13
31
  ```sh
14
32
  npm run prices:update
33
+ npm run lint
15
34
  npm run typecheck
16
35
  npm test
17
36
  npm run build
37
+ npm pack --dry-run
18
38
  ```
19
39
 
20
- 本地更新时,审阅生成文件与 `overrides.ts` 的差异后提交。更新脚本只请求 `https://models.dev/api.json`,从人工确认的**原厂 Provider + 自家模型系列**提取公开的文本模型价格;原厂平台上托管的其他厂商模型、OpenRouter 等网关报价、地域性/订阅制费率不作为回退价格来源。自动化不修改来源白名单、别名或人工例外。API 不标注模型的真实厂商,因此新增原厂或新系列需要维护者先审核并扩充 `ORIGINAL_PROVIDERS`,不能按相似名称自动猜测。
21
-
22
- `src/prices.generated.ts` 是随 npm 包发布的离线快照:插件启动、刷新、构建、打包和测试均不请求 models.dev。`src/aliases.ts` 只记录无法按已知包装形式解决的厂商 slug 与精确模型 ID 差异;`src/overrides.ts` 只记录有原厂来源的缺失 SKU、已核实的例外费率及无法直接使用的 API 字段。普通价格变动通过重新生成快照维护,不往别名或例外表中增加常规型号。
23
-
24
- ## 估算规则与边界
25
-
26
- - 每条 assistant / compaction 消息使用自身记录的模型和五类 token 用量计价。OpenCode 当前解析出的完整非零价格优先;价格不完整时,整条消息回退到快照;完整零价只有在快照能覆盖该消息实际使用的类别时才被替换。两套价格不混用。
27
- - 上下文档位按该条消息的 `input + cache read + cache write` 选择,档位阈值为**严格大于**。输出与推理分开统计;原厂明确提供不同 `reasoning` 单价时分别计费,否则沿用输出单价。
28
- - 缺少实际用到的 token 类别费率就不能按该来源完整计价,不把缺价填作零。无法计价显示 `—`,部分可计价显示 `partial`,明确零价显示 `$0.00`。
29
- - `/usage` 的 By Model 详细模式仅列出有用量模型在**当前估算**中实际采用的费率,按来源与上下文档位归组,并显示每组调用数;无法定价的调用单独计数。五类费率均为美元/百万文本 token,缺少某类价格显示 `—`,Reasoning 未单列价格时沿用 Output。这里使用当前解析出的模型目录或打包快照重新估算历史消息,不代表消息生成时的实际价格或提供商账单。
30
- - 网关仅通过精确原厂 ID、唯一的完整裸 ID、明确别名及已知包装格式匹配。终尾 `-free` / `:free` 可在精确匹配失败后再去掉;不剥离 `-fast`、`-pro` 等其他后缀。Fast 模式只匹配支持它的原厂 Provider;不会把普通费率借给网关 Fast 变体。
31
- - 导入文本输入与文本输出的 token 费率;图片、音频、视频、存储时长、搜索和工具调用等独立计费项无法由五类 token 可靠还原。音频输出另有不同价格的型号不会导入;其余多模态请求仍可能超出此文本估算范围。
32
-
33
- ## 人工核实的例外
34
-
35
- `overrides.ts` 保存较少量的可追溯例外,而不是另一份手动维护的完整价格目录。例如 DeepSeek 的历史消息没有计费时段,因此使用官网峰值价而不是 API 的低峰价;xAI 在 200K 起涨价,需要把目录中的阈值调整为符合 OpenCode 严格大于比较的 199,999;Z.ai 的缓存存储按时间收费,不把目录中的 `cache_write: 0` 解释为免费;阿里云隐式和显式缓存写入费率不同,不把聚合的 Cache Write 当作其中一种。
36
-
37
- 另外,OpenAI Fast 的长上下文档、Step 5 Preview 的缓存写入、Kimi K3 的五分钟缓存写入、腾讯 Hy3 的按量价格,以及 models.dev 暂无原厂条目的少数型号(如 Aion)均按文件中标注的原厂页面和理由维护。Meta Contributor 是具有单独条件价格的原厂 SKU;仅精确匹配对应 Contributor 型号,不将普通 Muse Spark 一概按该价计算。
38
-
39
- **Est. Cost 仍只是估算,不代表提供商账单**:快照可能滞后,也不含网关加价、地域价、未记录的促销或折扣、工具费和税费。更新时应复核有时效性的人工例外。
40
+ [价格更新工作流](../.github/workflows/update-prices.yml) 每 4 小时检查一次,也可在 `main` 上手动触发。检查日期、记录顺序、未胜出的费率变化和无关元数据不会触发发布;选定来源、费率或查找结果实际变化时,才验证、升级 patch、原子推送价格提交及标签并显式触发 `publish.yml`。待发布的手动版本会延期,已有自动价格标签只重试原版本。详见[发布说明](releasing.md)。更新脚本联网,插件运行、正常构建和测试离线。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chenlongapps/opencode-token-usage",
3
- "version": "0.4.28",
3
+ "version": "0.5.1",
4
4
  "description": "OpenCode 2 plugin for session-tree token usage, context window monitoring, estimated costs, and performance metrics (TPS, TTFT, run time).",
5
5
  "keywords": [
6
6
  "opencode",