@kangyishuai/dsh-advisor 0.4.0 → 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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > A separately configured advisor model the main model can consult when _it_ decides to — before committing to an approach, when an error keeps recurring, before declaring a task done. Advisory only: it reads the conversation, returns structured advice, and never approves, blocks or runs anything.
4
4
 
5
- [![npm](https://img.shields.io/npm/v/@kangyishuai/dsh-advisor?color=cb3837&logo=npm)](https://www.npmjs.com/package/@kangyishuai/dsh-advisor) [![DSH](https://img.shields.io/badge/verified%20on%20DSH-0.2.2--rc.1-4b6bfb)](#compatibility) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
5
+ [![npm](https://img.shields.io/npm/v/@kangyishuai/dsh-advisor?color=cb3837&logo=npm)](https://www.npmjs.com/package/@kangyishuai/dsh-advisor) [![DSH](https://img.shields.io/badge/verified%20on%20DSH-0.2.2--rc.2-4b6bfb)](#compatibility) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
6
6
 
7
7
  [中文](./README.zh-CN.md)
8
8
 
@@ -56,7 +56,7 @@ Settings live in one JSON file, `<DSH_HOME>/advisor.settings.json` (`DSH_HOME` d
56
56
  **Settings UI.** Settings → General → Advisor. With the default `off`, the card shows only the mode, a one-line status and “Configure advisor”. Expanding or enabling it reveals:
57
57
 
58
58
  - **Basics**: mode, currency, provider, model, reasoning effort, daily budget, send scope, redaction.
59
- - **Advanced** (folded by default): call limits, workspace limits, CNY-per-USD rate, prices, output/input caps, advice-item cap, allowlist, auto-review, file reading, shadow dedupe, sent-content recording. The heading shows “Defaults” or “N changed”.
59
+ - **Advanced** (folded by default): call limits, workspace limits, CNY-per-USD rate, prices (including cache read/write), output/input caps, advice-item cap, allowlist, auto-review, file reading, shadow dedupe, sent-content recording. The heading shows “Defaults” or “N changed”.
60
60
  - **Status & diagnostics** (folded by default): calls/tokens/cost, last result/skip reason, send preview, diagnostics, settings and ledger paths.
61
61
 
62
62
  The “?” next to an advanced field expands an inline help block (click or activate with the keyboard) with the description, default/range and technical key; hover is only a supplement. Click **Save** to apply changes to the next consultation.
@@ -79,6 +79,8 @@ Money fields accept decimals: budgets up to 2, unit prices up to 4.
79
79
  | `maxCostPerDay` | Daily budget | `0` | 0–10000, 0 = unlimited; up to 2 decimals | Daily spend ceiling in the selected currency; only counted when prices are set. |
80
80
  | `priceInputPerMTok` | Input price | `0` | 0–1000; up to 4 decimals | Advisor input price in the selected currency per 1M tokens; 0 = do not price. |
81
81
  | `priceOutputPerMTok` | Output price | `0` | 0–1000; up to 4 decimals | Output price in the selected currency per 1M tokens. |
82
+ | `priceCacheReadPerMTok` | Cache-read price | `0` | 0–1000; up to 4 decimals | Input-token price for cache reads/hits in the selected currency; 0 = do not price cache tokens. |
83
+ | `priceCacheWritePerMTok` | Cache-write price | `0` | 0–1000; up to 4 decimals | Input-token price for cache writes/creations in the selected currency; 0 = do not price cache tokens. |
82
84
  | `privacyScope` | Send scope | `"summary"` | off / summary / full | How much conversation content is sent — see Cost & privacy. |
83
85
  | `redact` | Redact before sending | `true` | boolean | Best-effort masking of common key formats; not a guarantee. |
84
86
  | `immuneTurns` | JSON only: Immune turns | `3` | 0–20 | Turns to stay quiet after a delivery; used by shadow delivery. |
@@ -96,6 +98,8 @@ Money fields accept decimals: budgets up to 2, unit prices up to 4.
96
98
  | `timeoutMs` | JSON only: Timeout | `90000` | 5000–600000 | Per-consultation timeout; `/advisor cancel` aborts sooner. |
97
99
  | `maxInputChars` | Input limit | `60000` | 4000–400000 | Total transcript budget; excess in the middle is elided, head/tail kept. |
98
100
 
101
+ **Cache prices.** The host usage exposes `cacheReadTokens` / `cacheWriteTokens`, both input-side; there is no cache-output token. Cache tokens are additional input tokens and are not subtracted from `inputTokens`. `priceCacheReadPerMTok` / `priceCacheWritePerMTok` = 0 means cache tokens are not priced; if the ledger has cache tokens while both are 0, the status area warns that cache tokens are unpriced. Built-in reference prices have no cache prices and the plugin does not guess.
102
+
99
103
  **Currency and ledger.** Amounts and prices in settings are entered in `currency` (USD/CNY); `usdToCny` is a manual rate. The ledger and workspace pool always store USD: limits/prices are converted to USD at call time and displayed back in the selected currency. Switching currency converts the form amounts at the rate before saving; old `maxCostPerDayUsd` / `workspaceMaxCostPerDayUsd` keys migrate as USD to the new keys. A rate change affects future conversion/display, not the historical ledger.
100
104
 
101
105
  > **Note on `sessionCap`, `dedupe`, `immuneTurns`:** `sessionCap` is enforced — after that many delivered items in one session only `blocker` advice is still returned. `dedupe` and `immuneTurns` are persisted and used by the shadow path, but the tool path does not suppress a consultation because of them (you asked for it explicitly). The ceilings that stop _calls_ altogether are `maxCallsPerTurn` / `maxCallsPerSession` / `maxCallsPerHour` / `maxCostPerDay`.
@@ -147,8 +151,8 @@ The `advisor` **tool** is separate from the command: the model calls it, not you
147
151
  This is the section to read before turning it on.
148
152
 
149
153
  - **Every consultation is an extra model call**, billed by the advisor route against that provider's quota. The main model's own usage is unaffected.
150
- - **Token accounting is ours.** DSH records usage only for the main loop's assistant messages, so the plugin writes its own ledger: `<DSH_HOME>/advisor/usage.jsonl`, one JSON object per consultation (time, session id, trigger `tool` / `shadow` / `manual`, provider, model, effort, verdict, severity, input/output/cache tokens, estimated cost, duration, error code). The file is append-only, rolls over to `usage.jsonl.1` at 2 MiB, and totals are restored from its tail on startup.
151
- - **Money needs your prices.** DSH's model metadata has no price field. Set `priceInputPerMTok` and `priceOutputPerMTok` in the selected `currency`; with zeros the ledger records tokens only and no money amount is shown. The ledger stores the USD equivalent; built-in reference prices are USD and are converted for CNY display. The plugin never guesses prices.
154
+ - **Token accounting is ours.** DSH records usage only for the main loop's assistant messages, so the plugin writes its own ledger: `<DSH_HOME>/advisor/usage.jsonl`, one JSON object per consultation (time, session id, trigger `tool` / `shadow` / `manual`, provider, model, effort, verdict, severity, input/output/cache-read/cache-write tokens, estimated cost, duration, error code). The file is append-only, rolls over to `usage.jsonl.1` at 2 MiB, and totals are restored from its tail on startup.
155
+ - **Money needs your prices.** DSH's model metadata has no price field. Set `priceInputPerMTok`, `priceOutputPerMTok`, `priceCacheReadPerMTok` and `priceCacheWritePerMTok` in the selected `currency`; with zeros the ledger records tokens only and no money amount is shown. The ledger stores the USD equivalent; built-in reference prices are USD and are converted for CNY display, but there are no built-in cache prices. The plugin never guesses prices.
152
156
  - **The daily budget counts spend already recorded**, so the one consultation that crosses the ceiling still completes and is charged.
153
157
  - **Conversation content leaves the machine when the advisor route is external.** The transcript — with tool calls and results, bounded by `privacyScope` and `maxInputChars` — is sent to whatever base URL that route points at. If that is another vendor, your conversation leaves this machine. Only a route pointing at a local gateway keeps it local. The plugin sends nothing else: no telemetry, no analytics, no network access besides the consultation itself.
154
158
  - **`privacyScope` decides how much is sent.** `summary` (default): each text block up to 2,000 characters, tool arguments up to 300, tool results up to 700. `off`: user and assistant text only, up to 1,200 characters, with no tool traffic at all. `full`: text up to 4,000, tool arguments up to 1,200, tool results up to 3,500. The rendered transcript is then capped at `maxInputChars` (60,000 by default): the first 30% and the tail are kept and the middle is replaced by an elision marker.
@@ -160,6 +164,7 @@ This is the section to read before turning it on.
160
164
 
161
165
  | DSH version | Status |
162
166
  | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
167
+ | 0.2.2-rc.2 | Verified 2026-11-12: unit tests + `pnpm probe:runtime` 67/67 + web `pnpm smoke:advisor` 13/13 on a throwaway DSH home (no model calls, ledger 0). Desktop read-only regression (live app over CDP): 18 passing + 1 skipped (the session had no advisor records). |
163
168
  | 0.2.2-rc.1 | Verified on this version: unit tests (settings clamping, route selection and pairing, budget guard, transcript rendering, redaction, output contract) and `pnpm probe:runtime`; the desktop read-only regression is `pnpm smoke:advisor-desktop`. Other DSH versions are not verified. |
164
169
 
165
170
  The plugin declares no `engines.dsh` and no `@deepseek-ai/*` peer range: DSH is pre-release and semver ranges over prereleases are unreliable (see [ADR 0005](../../docs/adr/0005-dsh-version-compatibility.md)). Treat this table as the compatibility statement. After a DSH upgrade run `pnpm probe:runtime`, `pnpm smoke:advisor-desktop` and the unit tests, then check `/advisor doctor`.
package/README.zh-CN.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 给主模型配一个单独配置的顾问模型,由**主模型自己决定**什么时候值得问:动手之前、反复失败时、宣告完成之前。顾问只给建议:它读整段对话、返回结构化答复,不批准、不拦截、不执行任何动作。
4
4
 
5
- [![npm](https://img.shields.io/npm/v/@kangyishuai/dsh-advisor?color=cb3837&logo=npm)](https://www.npmjs.com/package/@kangyishuai/dsh-advisor) [![DSH](https://img.shields.io/badge/verified%20on%20DSH-0.2.2--rc.1-4b6bfb)](#兼容性) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
5
+ [![npm](https://img.shields.io/npm/v/@kangyishuai/dsh-advisor?color=cb3837&logo=npm)](https://www.npmjs.com/package/@kangyishuai/dsh-advisor) [![DSH](https://img.shields.io/badge/verified%20on%20DSH-0.2.2--rc.2-4b6bfb)](#兼容性) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
6
6
 
7
7
  [English](./README.md)
8
8
 
@@ -56,7 +56,7 @@ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
56
56
  **设置页。** 设置 → 通用 → 顾问。默认 `off` 时卡片只显示模式、一句状态和「配置顾问」;展开或启用后才显示:
57
57
 
58
58
  - **基础**:模式、币种、服务商、模型、思考档、每日预算、发送范围、发送前脱敏。
59
- - **高级**(默认折叠):调用限额、工作区限额、人民币汇率、单价、输出/输入上限、建议条数、白名单、答后复查、读文件核实、影子去重、记录发送内容;折叠标题会标出「默认值」或「N 项已修改」。
59
+ - **高级**(默认折叠):调用限额、工作区限额、人民币汇率、单价(含缓存读取/写入)、输出/输入上限、建议条数、白名单、答后复查、读文件核实、影子去重、记录发送内容;折叠标题会标出「默认值」或「N 项已修改」。
60
60
  - **状态与诊断**(默认折叠):累计调用/token/金额、最近结果/跳过原因、发送预览、诊断、设置文件与账本路径。
61
61
 
62
62
  高级字段旁的「?」点开或用键盘激活会显示说明、默认值与范围、技术名;悬停只是补充。改完点「保存」才对下一次徵询生效。
@@ -79,6 +79,8 @@ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
79
79
  | `maxCostPerDay` | 每日预算(按币种) | `0` | 0–10000,0 = 不限;最多 2 位小数 | 每天最多花多少(按 `currency`);只有填了单价才计算金额。 |
80
80
  | `priceInputPerMTok` | 输入单价 | `0` | 0–1000;最多 4 位小数 | 顾问模型输入价,按 `currency` / 百万 token;0 = 不算钱。 |
81
81
  | `priceOutputPerMTok` | 输出单价 | `0` | 0–1000;最多 4 位小数 | 输出价,按 `currency` / 百万 token。 |
82
+ | `priceCacheReadPerMTok` | 缓存读取单价 | `0` | 0–1000;最多 4 位小数 | 缓存读取/命中的输入 token 单价,按 `currency`;0 = 不计缓存部分。 |
83
+ | `priceCacheWritePerMTok` | 缓存写入单价 | `0` | 0–1000;最多 4 位小数 | 缓存写入/创建的输入 token 单价,按 `currency`;0 = 不计缓存部分。 |
82
84
  | `privacyScope` | 发送范围 | `"summary"` | off / summary / full | 发多少会话内容,见「成本与隐私」。 |
83
85
  | `redact` | 发送前脱敏 | `true` | 布尔 | 尽量遮掉常见密钥格式;不能保证全部遮住。 |
84
86
  | `immuneTurns` | 仅 JSON:免疫回合 | `3` | 0–20 | 投递后保持安静的回合数;只用于 shadow 投递。 |
@@ -96,6 +98,8 @@ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
96
98
  | `timeoutMs` | 仅 JSON:超时 | `90000` | 5000–600000 | 单次徵询超时;`/advisor cancel` 可以更早中止。 |
97
99
  | `maxInputChars` | 输入上限 | `60000` | 4000–400000 | 会话文本总预算;超出保留首尾、省略中间。 |
98
100
 
101
+ **缓存单价。** 宿主 usage 里只有 `cacheReadTokens` / `cacheWriteTokens`(都是输入侧),没有缓存输出 token;缓存 token 是额外的输入 token,不从 `inputTokens` 扣。`priceCacheReadPerMTok` / `priceCacheWritePerMTok` 为 0 时不计缓存部分;如果账本里有缓存 token 而缓存单价为 0,状态区会提示「缓存 token 未计价」。内置参考价没有缓存价,不做猜测。
102
+
99
103
  **币种与账本。** 设置里的金额和单价按 `currency` 填写(USD/CNY),`usdToCny` 是手动汇率。账本与工作区预算池内部始终记 USD:调用时把设置金额换算成 USD,展示时再换回当前币种。切换币种会按汇率折算当前表单金额,保存前不会落盘;旧版 `maxCostPerDayUsd` / `workspaceMaxCostPerDayUsd` 键会按 USD 自动迁移到新键。汇率变化只影响之后的换算和展示,不会重写历史账本。
100
104
 
101
105
  > **关于 `sessionCap`、`dedupe`、`immuneTurns`:** `sessionCap` 会生效——单会话投递到上限后,只有 `blocker` 级建议还会返回。`dedupe` 与 `immuneTurns` 会被保存并用于 shadow 路径,但工具路径不会因为它们跳过徵询(是模型显式要求的)。真正会拦住**调用本身**的是 `maxCallsPerTurn` / `maxCallsPerSession` / `maxCallsPerHour` / `maxCostPerDay`。
@@ -137,8 +141,8 @@ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
137
141
  这一节请在开启前读完。
138
142
 
139
143
  - **每次徵询都是一次额外的模型调用**,按顾问路由计费,走那家 provider 的额度。主模型自身的 usage 不受影响。
140
- - **token 由插件自己记账。** DSH 只为主动环里的 assistant 消息记 usage,所以插件单写一份账本:`<DSH_HOME>/advisor/usage.jsonl`,一次徵询一行 JSON(时间、会话 id、触发方式 `tool` / `shadow` / `manual`、provider、model、思考档、结论、严重度、输入 / 输出 / 缓存 token、估算金额、耗时、错误码)。文件只追加,超过 2 MiB 滚动到 `usage.jsonl.1`,启动时从文件尾部恢复累计数。
141
- - **算钱需要你填单价。** DSH 的模型元数据没有价格字段。按 `currency` 填 `priceInputPerMTok` 和 `priceOutputPerMTok`;都留 0 时账本只记 token,界面不显示金额。账本内部记 USD 等价,内置参考价是 USD,人民币展示时折算。插件从不猜价格。
144
+ - **token 由插件自己记账。** DSH 只为主动环里的 assistant 消息记 usage,所以插件单写一份账本:`<DSH_HOME>/advisor/usage.jsonl`,一次徵询一行 JSON(时间、会话 id、触发方式 `tool` / `shadow` / `manual`、provider、model、思考档、结论、严重度、输入 / 输出 / 缓存读/写 token、估算金额、耗时、错误码)。文件只追加,超过 2 MiB 滚动到 `usage.jsonl.1`,启动时从文件尾部恢复累计数。
145
+ - **算钱需要你填单价。** DSH 的模型元数据没有价格字段。按 `currency` 填 `priceInputPerMTok`、`priceOutputPerMTok`、`priceCacheReadPerMTok`、`priceCacheWritePerMTok`;都留 0 时账本只记 token,界面不显示金额。账本内部记 USD 等价,内置参考价是 USD,人民币展示时折算;内置参考价没有缓存价。插件从不猜价格。
142
146
  - **每日预算统计的是已经记下的花费**,所以跨过上限的那一次徵询仍会完成并计费。
143
147
  - **顾问路由在外部时,会话内容会离开本机。** 渲染后的会话文本(含工具调用与结果,受 `privacyScope` 和 `maxInputChars` 限制)会发到该路由指向的 baseURL。如果那是另一家厂商,你的对话就离开了这台机器;只有指向本地网关的路由才留在本机。除此之外插件什么都不发:没有遥测,没有统计,除了徵询本身不访问网络。
144
148
  - **`privacyScope` 决定发多少。** `summary`(默认):每个文本块最多 2,000 字符,工具参数最多 300,工具结果最多 700。`off`:只发用户与助手的文本(最多 1,200 字符),完全不发工具往来。`full`:文本最多 4,000,工具参数最多 1,200,工具结果最多 3,500。渲染完再按 `maxInputChars`(默认 60,000)封顶:保留前 30% 和结尾,中间替换成省略标记。
@@ -148,9 +152,10 @@ dsh plugin --profile desktop add /tmp/kangyishuai-dsh-advisor-*.tgz
148
152
 
149
153
  ## 兼容性
150
154
 
151
- | 已验证的 DSH 版本 | 状态 |
152
- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
153
- | 0.2.2-rc.1 | 已在该版本验证:单测(81 条)与 `pnpm probe:runtime`;web 端到端冒烟 `pnpm smoke:advisor`、桌面端只读回归 `pnpm smoke:advisor-desktop`。其他 DSH 版本未验证。 |
155
+ | 已验证的 DSH 版本 | 状态 |
156
+ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
157
+ | 0.2.2-rc.2 | 2026-11-12 已验证:单测 + `pnpm probe:runtime` 67/67 + Web `pnpm smoke:advisor` 13/13(临时 DSH home,不发起模型调用,账本 0)。桌面只读回归(live 桌面版,CDP):18 PASS + 1 SKIP(SKIP 是该会话没有顾问记录)。 |
158
+ | 0.2.2-rc.1 | 已在该版本验证:单测(81 条)与 `pnpm probe:runtime`;web 端到端冒烟 `pnpm smoke:advisor`、桌面端只读回归 `pnpm smoke:advisor-desktop`。其他 DSH 版本未验证。 |
154
159
 
155
160
  插件不声明 `engines.dsh`,也不声明 `@deepseek-ai/*` 的 peer 范围:DSH 还在预发布阶段,semver 对预发布版本不可靠(见 [ADR 0005](../../docs/adr/0005-dsh-version-compatibility.md))。这张表就是兼容性声明。DSH 升级后请跑 `pnpm probe:runtime`、`pnpm smoke:advisor-desktop` 和单测,再看 `/advisor doctor`。
156
161
 
package/lib/catalog.js CHANGED
@@ -113,27 +113,43 @@ export function effectiveRank(tiers, route) {
113
113
  }
114
114
 
115
115
  /**
116
- * 有效单价:用户声明 > 内置;都没有返回 `{ input: 0, output: 0 }`(= 不算钱)。
117
- * @param {{ priceInputPerMTok: number, priceOutputPerMTok: number, currency?: string, usdToCny?: number }} settings
116
+ * 有效单价:输入/输出用「用户声明 > 内置」;缓存读取/写入只有用户声明(内置表没有缓存价)。
117
+ * 0 表示该项不算钱。缓存 token 是额外的输入侧 token,不从 inputTokens 里扣。
118
+ * @param {{ priceInputPerMTok?: number, priceOutputPerMTok?: number, priceCacheReadPerMTok?: number, priceCacheWritePerMTok?: number, currency?: string, usdToCny?: number }} settings
118
119
  * @param {string} modelId
119
- * @returns {{ input: number, output: number, source: "settings"|"builtin"|"none" }}
120
+ * @returns {{ input: number, output: number, cacheRead: number, cacheWrite: number, source: "settings"|"builtin"|"none", cacheSource: "settings"|"none" }}
120
121
  */
121
122
  export function effectivePrice(settings, modelId) {
122
123
  // 设置里的单价按 settings.currency 填写;内部估算统一换算成 USD。
123
- const input = toUsd(
124
- Number(settings?.priceInputPerMTok ?? 0) || 0,
125
- settings?.currency,
126
- settings?.usdToCny,
127
- );
128
- const output = toUsd(
129
- Number(settings?.priceOutputPerMTok ?? 0) || 0,
130
- settings?.currency,
131
- settings?.usdToCny,
132
- );
133
- if (input > 0 || output > 0) return { input, output, source: "settings" };
124
+ /** @param {unknown} value @returns {number} */
125
+ const toPrice = (value) => toUsd(Number(value ?? 0) || 0, settings?.currency, settings?.usdToCny);
126
+ const input = toPrice(settings?.priceInputPerMTok);
127
+ const output = toPrice(settings?.priceOutputPerMTok);
128
+ const cacheRead = toPrice(settings?.priceCacheReadPerMTok);
129
+ const cacheWrite = toPrice(settings?.priceCacheWritePerMTok);
130
+ const cacheSource = cacheRead > 0 || cacheWrite > 0 ? "settings" : "none";
134
131
  const builtin = builtinPrice(modelId);
135
- if (builtin !== undefined) return { ...builtin, source: "builtin" };
136
- return { input: 0, output: 0, source: "none" };
132
+ if (input > 0 || output > 0) {
133
+ return { input, output, cacheRead, cacheWrite, source: "settings", cacheSource };
134
+ }
135
+ if (builtin !== undefined) {
136
+ return {
137
+ input: builtin.input,
138
+ output: builtin.output,
139
+ cacheRead,
140
+ cacheWrite,
141
+ source: "builtin",
142
+ cacheSource,
143
+ };
144
+ }
145
+ return {
146
+ input: 0,
147
+ output: 0,
148
+ cacheRead,
149
+ cacheWrite,
150
+ source: "none",
151
+ cacheSource,
152
+ };
137
153
  }
138
154
 
139
155
  /**
package/lib/client.js CHANGED
@@ -345,7 +345,7 @@ window.__ModuleLoader__.load({
345
345
  ".dsh-advisor-unit{flex:0 0 auto;font-size:11.5px;color:var(--dsw-alias-label-secondary,GrayText);white-space:nowrap;}",
346
346
  ".dsh-advisor-off{display:flex;flex-direction:column;gap:4px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:8px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,Canvas));}",
347
347
  ".dsh-advisor-off-title{font-weight:600;}",
348
- ".dsh-advisor-dirty{font-size:12px;color:var(--dsw-alias-state-warning-primary,#b7791f);}",
348
+ ".dsh-advisor-dirty{font-size:12px;color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary));}",
349
349
  ".dsh-advisor-disclosure{display:flex;flex-direction:column;gap:4px;}",
350
350
  ".dsh-advisor-disclosure-toggle{display:flex;align-items:center;gap:6px;width:100%;padding:4px 0;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;}",
351
351
  ".dsh-advisor-disclosure-toggle:hover{color:var(--dsw-alias-label-primary,CanvasText);}",
@@ -389,7 +389,7 @@ window.__ModuleLoader__.load({
389
389
  ".dsh-advisor-turn-preview{display:flex;flex-direction:column;gap:4px;}",
390
390
  ".dsh-advisor-turn-preview-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;}",
391
391
  ".dsh-advisor-turn-pre{margin:0;padding:8px 10px;max-height:260px;overflow:auto;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:6px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,Canvas));font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;line-height:1.5;white-space:pre-wrap;word-break:break-word;}",
392
- ".dsh-advisor-turn-warn{font-size:11.5px;color:var(--dsw-alias-state-warning-primary,#b7791f);word-break:break-word;}",
392
+ ".dsh-advisor-turn-warn{font-size:11.5px;color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary));word-break:break-word;}",
393
393
  ].join("\n");
394
394
 
395
395
  // ------------------------------------------------------------------
@@ -606,6 +606,8 @@ window.__ModuleLoader__.load({
606
606
  maxCostPerDay: 0,
607
607
  priceInputPerMTok: 0,
608
608
  priceOutputPerMTok: 0,
609
+ priceCacheReadPerMTok: 0,
610
+ priceCacheWritePerMTok: 0,
609
611
  privacyScope: "summary",
610
612
  redact: true,
611
613
  dedupe: true,
@@ -628,6 +630,8 @@ window.__ModuleLoader__.load({
628
630
  maxCostPerDay: [0, 10000],
629
631
  priceInputPerMTok: [0, 1000],
630
632
  priceOutputPerMTok: [0, 1000],
633
+ priceCacheReadPerMTok: [0, 1000],
634
+ priceCacheWritePerMTok: [0, 1000],
631
635
  workspaceMaxCallsPerDay: [0, 100000],
632
636
  workspaceMaxCostPerDay: [0, 10000],
633
637
  usdToCny: [0.1, 100],
@@ -641,6 +645,8 @@ window.__ModuleLoader__.load({
641
645
  workspaceMaxCostPerDay: 2,
642
646
  priceInputPerMTok: 4,
643
647
  priceOutputPerMTok: 4,
648
+ priceCacheReadPerMTok: 4,
649
+ priceCacheWritePerMTok: 4,
644
650
  usdToCny: 4,
645
651
  };
646
652
 
@@ -658,6 +664,8 @@ window.__ModuleLoader__.load({
658
664
  "workspaceMaxCostPerDay",
659
665
  "priceInputPerMTok",
660
666
  "priceOutputPerMTok",
667
+ "priceCacheReadPerMTok",
668
+ "priceCacheWritePerMTok",
661
669
  "usdToCny",
662
670
  "maxTokens",
663
671
  "temperature",
@@ -706,6 +714,8 @@ window.__ModuleLoader__.load({
706
714
  "maxCostPerDay",
707
715
  "priceInputPerMTok",
708
716
  "priceOutputPerMTok",
717
+ "priceCacheReadPerMTok",
718
+ "priceCacheWritePerMTok",
709
719
  "workspaceMaxCallsPerDay",
710
720
  "workspaceMaxCostPerDay",
711
721
  "privacyScope",
@@ -940,6 +950,8 @@ window.__ModuleLoader__.load({
940
950
  workspaceMaxCostPerDay: 2,
941
951
  priceInputPerMTok: 4,
942
952
  priceOutputPerMTok: 4,
953
+ priceCacheReadPerMTok: 4,
954
+ priceCacheWritePerMTok: 4,
943
955
  };
944
956
  for (let key of Object.keys(fields)) {
945
957
  let n = Number(source[key]);
@@ -995,6 +1007,8 @@ window.__ModuleLoader__.load({
995
1007
  calls: countOf(totalsRaw.calls),
996
1008
  inputTokens: countOf(totalsRaw.inputTokens),
997
1009
  outputTokens: countOf(totalsRaw.outputTokens),
1010
+ cacheReadTokens: countOf(totalsRaw.cacheReadTokens),
1011
+ cacheWriteTokens: countOf(totalsRaw.cacheWriteTokens),
998
1012
  costUsd: moneyOf(totalsRaw.costUsd),
999
1013
  },
1000
1014
  pool: {
@@ -1006,8 +1020,11 @@ window.__ModuleLoader__.load({
1006
1020
  priceRaw.source === "builtin" || priceRaw.source === "settings"
1007
1021
  ? priceRaw.source
1008
1022
  : "none",
1023
+ cacheSource: priceRaw.cacheSource === "settings" ? "settings" : "none",
1009
1024
  input: moneyOf(priceRaw.input),
1010
1025
  output: moneyOf(priceRaw.output),
1026
+ cacheRead: moneyOf(priceRaw.cacheRead),
1027
+ cacheWrite: moneyOf(priceRaw.cacheWrite),
1011
1028
  },
1012
1029
  counters: {
1013
1030
  calls: countOf(countersRaw.calls),
@@ -2165,7 +2182,17 @@ window.__ModuleLoader__.load({
2165
2182
  let settings = normalizeSettingsView(
2166
2183
  outcome.settings === null ? committed : outcome.settings,
2167
2184
  );
2168
- setSnap(Object.assign({}, snap, { settings: settings }));
2185
+ // 价格来源/缓存未计价提示要跟着刚保存的设置走,不必等下一次手动重新加载。
2186
+ let cacheSource =
2187
+ settings.priceCacheReadPerMTok > 0 || settings.priceCacheWritePerMTok > 0
2188
+ ? "settings"
2189
+ : "none";
2190
+ setSnap(
2191
+ Object.assign({}, snap, {
2192
+ settings: settings,
2193
+ price: Object.assign({}, snap.price, { cacheSource: cacheSource }),
2194
+ }),
2195
+ );
2169
2196
  setDraft(settings);
2170
2197
  setTexts(textsOf(settings));
2171
2198
  setNotice(t("settings.saved"));
@@ -3169,7 +3196,10 @@ window.__ModuleLoader__.load({
3169
3196
 
3170
3197
  let sep = t("settings.status.sep");
3171
3198
  let totals = snap.totals;
3172
- let priced = snap.price.source !== "none";
3199
+ let priced = snap.price.source !== "none" || snap.price.cacheSource !== "none";
3200
+ let cacheTotal =
3201
+ (Number(totals.cacheReadTokens) || 0) + (Number(totals.cacheWriteTokens) || 0);
3202
+ let cacheUnpriced = cacheTotal > 0 && snap.price.cacheSource === "none";
3173
3203
  let lastText =
3174
3204
  snap.last === null
3175
3205
  ? t("settings.status.none")
@@ -3179,6 +3209,14 @@ window.__ModuleLoader__.load({
3179
3209
  t("settings.status.tokens")
3180
3210
  .replace("{input}", formatCount(totals.inputTokens))
3181
3211
  .replace("{output}", formatCount(totals.outputTokens)),
3212
+ ...(cacheTotal > 0
3213
+ ? [
3214
+ t("settings.status.cache")
3215
+ .replace("{read}", formatCount(totals.cacheReadTokens))
3216
+ .replace("{write}", formatCount(totals.cacheWriteTokens)),
3217
+ ]
3218
+ : []),
3219
+ ...(cacheUnpriced ? [t("settings.status.cacheUnpriced")] : []),
3182
3220
  t("settings.status.cost") +
3183
3221
  sep +
3184
3222
  (priced
@@ -3223,6 +3261,10 @@ window.__ModuleLoader__.load({
3223
3261
  }
3224
3262
 
3225
3263
  let priceSourceText = t(`settings.budget.priceSource.${snap.price.source}`);
3264
+ let cachePriceSourceText =
3265
+ t("settings.budget.cachePriceSource") +
3266
+ sep +
3267
+ t(`settings.budget.cachePriceSource.${snap.price.cacheSource}`);
3226
3268
  let poolLine = t("settings.budget.poolLine")
3227
3269
  .replace("{calls}", formatCount(snap.pool.calls))
3228
3270
  .replace(
@@ -3322,7 +3364,20 @@ window.__ModuleLoader__.load({
3322
3364
  help: t("settings.budget.priceHint"),
3323
3365
  unit: priceUnit(),
3324
3366
  }),
3367
+ numberField("priceCacheReadPerMTok", "settings.budget.priceCacheReadPerMTok", {
3368
+ help: t("settings.budget.cachePriceHint"),
3369
+ unit: priceUnit(),
3370
+ }),
3371
+ numberField("priceCacheWritePerMTok", "settings.budget.priceCacheWritePerMTok", {
3372
+ help: t("settings.budget.cachePriceHint"),
3373
+ unit: priceUnit(),
3374
+ }),
3325
3375
  h("div", { className: "dsh-advisor-readout", key: "priceSource" }, priceSourceText),
3376
+ h(
3377
+ "div",
3378
+ { className: "dsh-advisor-readout", key: "cachePriceSource" },
3379
+ cachePriceSourceText,
3380
+ ),
3326
3381
  ],
3327
3382
  "money",
3328
3383
  ),
@@ -3687,6 +3742,15 @@ window.__ModuleLoader__.load({
3687
3742
  "settings.unit.cnyPerUsd": "元 / USD",
3688
3743
  "settings.budget.maxCostPerDay": "每日预算",
3689
3744
  "settings.budget.workspaceMaxCostPerDay": "工作区每日预算",
3745
+ "settings.budget.priceCacheReadPerMTok": "缓存读取单价",
3746
+ "settings.budget.priceCacheWritePerMTok": "缓存写入单价",
3747
+ "settings.budget.cachePriceHint":
3748
+ "缓存读取/写入的输入 token 单价(按当前币种 / 百万 token);0 = 不计缓存部分。宿主只提供缓存读/写 token,没有缓存输出 token。",
3749
+ "settings.budget.cachePriceSource": "缓存单价",
3750
+ "settings.budget.cachePriceSource.settings": "用户设置",
3751
+ "settings.budget.cachePriceSource.none": "未配置(缓存 token 不计)",
3752
+ "settings.status.cache": "缓存 token:{read} read / {write} write",
3753
+ "settings.status.cacheUnpriced": "账本里有缓存 token,但缓存单价为 0:缓存部分没有计价。",
3690
3754
  "tail.trace.preview": "查看发送内容",
3691
3755
  "tail.trace.previewHide": "收起发送内容",
3692
3756
  "tail.trace.previewTruncated": "实际发送(脱敏后,首尾各 2,000 字符;共 {chars} 字符)",
@@ -3830,6 +3894,16 @@ window.__ModuleLoader__.load({
3830
3894
  "settings.unit.cnyPerUsd": "CNY / USD",
3831
3895
  "settings.budget.maxCostPerDay": "Daily budget",
3832
3896
  "settings.budget.workspaceMaxCostPerDay": "Workspace daily budget",
3897
+ "settings.budget.priceCacheReadPerMTok": "Cache-read price",
3898
+ "settings.budget.priceCacheWritePerMTok": "Cache-write price",
3899
+ "settings.budget.cachePriceHint":
3900
+ "Input-token price for cache reads/writes (selected currency per 1M tokens); 0 = cache tokens are not priced. The host exposes cache-read/write tokens only; there is no cache-output token.",
3901
+ "settings.budget.cachePriceSource": "Cache prices",
3902
+ "settings.budget.cachePriceSource.settings": "user settings",
3903
+ "settings.budget.cachePriceSource.none": "unset (cache tokens not priced)",
3904
+ "settings.status.cache": "Cache tokens: {read} read / {write} write",
3905
+ "settings.status.cacheUnpriced":
3906
+ "The ledger has cache tokens, but cache prices are 0: that part is not priced.",
3833
3907
  "tail.trace.preview": "View sent content",
3834
3908
  "tail.trace.previewHide": "Hide sent content",
3835
3909
  "tail.trace.previewTruncated": "Sent (redacted; first/last 2,000 of {chars} chars)",
@@ -4497,6 +4571,8 @@ window.__ModuleLoader__.load({
4497
4571
  turnNumberOf: turnNumberOf,
4498
4572
  slotTurnNumber: slotTurnNumber,
4499
4573
  isAdviceTurnReady: isAdviceTurnReady,
4574
+ // 注入的样式表文本:给「只用宿主真实存在的主题 token」这条回归用例读。
4575
+ clientCss: () => CSS,
4500
4576
  }),
4501
4577
  });
4502
4578
 
package/lib/guard.js CHANGED
@@ -128,14 +128,27 @@ export function checkBudget(input) {
128
128
 
129
129
  /**
130
130
  * 估算一次调用的美元成本。单价为 0 时返回 0(= 不算钱,只记 token)。
131
- * @param {{ inputTokens: number, outputTokens: number, priceInputPerMTok: number, priceOutputPerMTok: number }} input
131
+ * @param {{ inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number, priceInputPerMTok?: number, priceOutputPerMTok?: number, priceCacheReadPerMTok?: number, priceCacheWritePerMTok?: number }} input
132
132
  * @returns {number}
133
133
  */
134
134
  export function estimateCostUsd(input) {
135
- const { inputTokens, outputTokens, priceInputPerMTok, priceOutputPerMTok } = input;
135
+ const {
136
+ inputTokens,
137
+ outputTokens,
138
+ cacheReadTokens = 0,
139
+ cacheWriteTokens = 0,
140
+ priceInputPerMTok = 0,
141
+ priceOutputPerMTok = 0,
142
+ priceCacheReadPerMTok = 0,
143
+ priceCacheWritePerMTok = 0,
144
+ } = input;
136
145
  const inCost = (Math.max(0, inputTokens) / 1_000_000) * Math.max(0, priceInputPerMTok);
137
146
  const outCost = (Math.max(0, outputTokens) / 1_000_000) * Math.max(0, priceOutputPerMTok);
138
- return inCost + outCost;
147
+ const cacheReadCost =
148
+ (Math.max(0, cacheReadTokens) / 1_000_000) * Math.max(0, priceCacheReadPerMTok);
149
+ const cacheWriteCost =
150
+ (Math.max(0, cacheWriteTokens) / 1_000_000) * Math.max(0, priceCacheWritePerMTok);
151
+ return inCost + outCost + cacheReadCost + cacheWriteCost;
139
152
  }
140
153
 
141
154
  /**
package/lib/ledger.js CHANGED
@@ -28,6 +28,7 @@ export const LEDGER_MAX_BYTES = 2 * 1024 * 1024;
28
28
  * @property {number} inputTokens
29
29
  * @property {number} outputTokens
30
30
  * @property {number} cacheReadTokens
31
+ * @property {number} [cacheWriteTokens]
31
32
  * @property {number} costUsd
32
33
  * @property {number} ms
33
34
  * @property {string} [code]
@@ -62,7 +63,7 @@ export function dayKey(date = new Date()) {
62
63
  * counters: (sessionId: string, now?: number) => SessionCounters,
63
64
  * noteCall: (sessionId: string, input: { turn: number, costUsd: number, at: number }) => void,
64
65
  * resetTurn: (sessionId: string, turn: number) => void,
65
- * totals: () => { calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> },
66
+ * totals: () => { calls: number, inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, costUsd: number, byTrigger: Record<string, number> },
66
67
  * recent: (limit?: number) => LedgerEntry[],
67
68
  * ready: () => Promise<void>,
68
69
  * recordAdvice: (entry: any) => Promise<void>,
@@ -78,8 +79,16 @@ export function createLedger(options) {
78
79
  const countersBySession = new Map();
79
80
  /** @type {LedgerEntry[]} */
80
81
  const recent = [];
81
- /** @type {{ calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
82
- const totals = { calls: 0, inputTokens: 0, outputTokens: 0, costUsd: 0, byTrigger: {} };
82
+ /** @type {{ calls: number, inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
83
+ const totals = {
84
+ calls: 0,
85
+ inputTokens: 0,
86
+ outputTokens: 0,
87
+ cacheReadTokens: 0,
88
+ cacheWriteTokens: 0,
89
+ costUsd: 0,
90
+ byTrigger: {},
91
+ };
83
92
  let loaded = false;
84
93
 
85
94
  /** 读历史账本,恢复「今日花费」与累计数(只读尾部 2MB,避免大文件拖慢启动)。 */
@@ -104,9 +113,13 @@ export function createLedger(options) {
104
113
  const cost = Number(entry.costUsd ?? 0) || 0;
105
114
  const inputTokens = Number(entry.inputTokens ?? 0) || 0;
106
115
  const outputTokens = Number(entry.outputTokens ?? 0) || 0;
116
+ const cacheReadTokens = Number(entry.cacheReadTokens ?? 0) || 0;
117
+ const cacheWriteTokens = Number(entry.cacheWriteTokens ?? 0) || 0;
107
118
  totals.calls += 1;
108
119
  totals.inputTokens += inputTokens;
109
120
  totals.outputTokens += outputTokens;
121
+ totals.cacheReadTokens += cacheReadTokens;
122
+ totals.cacheWriteTokens += cacheWriteTokens;
110
123
  totals.costUsd += cost;
111
124
  const trigger = typeof entry.trigger === "string" ? entry.trigger : "tool";
112
125
  totals.byTrigger[trigger] = (totals.byTrigger[trigger] ?? 0) + 1;
@@ -178,6 +191,8 @@ export function createLedger(options) {
178
191
  totals.calls += 1;
179
192
  totals.inputTokens += entry.inputTokens;
180
193
  totals.outputTokens += entry.outputTokens;
194
+ totals.cacheReadTokens += entry.cacheReadTokens ?? 0;
195
+ totals.cacheWriteTokens += entry.cacheWriteTokens ?? 0;
181
196
  totals.costUsd += entry.costUsd;
182
197
  totals.byTrigger[entry.trigger] = (totals.byTrigger[entry.trigger] ?? 0) + 1;
183
198
 
@@ -232,7 +247,7 @@ export function createLedger(options) {
232
247
  }
233
248
  },
234
249
 
235
- /** @returns {{ calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
250
+ /** @returns {{ calls: number, inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
236
251
  totals() {
237
252
  return { ...totals, byTrigger: { ...totals.byTrigger } };
238
253
  },
package/lib/service.js CHANGED
@@ -512,6 +512,8 @@ export class AdvisorService extends TypertRemoteService {
512
512
  outputTokens: settings.maxTokens / 2,
513
513
  priceInputPerMTok: price.input,
514
514
  priceOutputPerMTok: price.output,
515
+ priceCacheReadPerMTok: price.cacheRead,
516
+ priceCacheWritePerMTok: price.cacheWrite,
515
517
  });
516
518
 
517
519
  const started = Date.now();
@@ -534,26 +536,56 @@ export class AdvisorService extends TypertRemoteService {
534
536
  this.inflight.delete(sessionId);
535
537
  }
536
538
 
537
- const costUsd =
538
- call.ok && call.usage !== undefined
539
+ /** @param {any} usage @returns {number} */
540
+ const costOf = (usage) =>
541
+ call.ok && usage !== undefined
539
542
  ? estimateCostUsd({
540
- inputTokens: call.usage.inputTokens,
541
- outputTokens: call.usage.outputTokens,
543
+ inputTokens: usage.inputTokens,
544
+ outputTokens: usage.outputTokens,
545
+ cacheReadTokens: usage.cacheReadTokens,
546
+ cacheWriteTokens: usage.cacheWriteTokens,
542
547
  priceInputPerMTok: price.input,
543
548
  priceOutputPerMTok: price.output,
549
+ priceCacheReadPerMTok: price.cacheRead,
550
+ priceCacheWritePerMTok: price.cacheWrite,
544
551
  })
545
552
  : 0;
546
553
 
547
- const usageLine = call.ok
548
- ? `${formatTokens(call.usage?.inputTokens ?? 0)} in / ${formatTokens(call.usage?.outputTokens ?? 0)} out / ${formatMs(call.ms)}${
549
- costUsd > 0
550
- ? ` / ≈${formatMoney(
551
- fromUsd(costUsd, settings.currency, settings.usdToCny),
552
- settings.currency,
553
- 4,
554
- )}`
555
- : ""
556
- }`
554
+ /**
555
+ * @param {any} usage
556
+ * @param {number} cost
557
+ * @param {number} ms
558
+ * @returns {string}
559
+ */
560
+ const usageLineOf = (usage, cost, ms) => {
561
+ const parts = [
562
+ `${formatTokens(usage?.inputTokens ?? 0)} in`,
563
+ `${formatTokens(usage?.outputTokens ?? 0)} out`,
564
+ ];
565
+ if ((usage?.cacheReadTokens ?? 0) > 0) {
566
+ parts.push(`${formatTokens(usage.cacheReadTokens)} cache read`);
567
+ }
568
+ if ((usage?.cacheWriteTokens ?? 0) > 0) {
569
+ parts.push(`${formatTokens(usage.cacheWriteTokens)} cache write`);
570
+ }
571
+ parts.push(formatMs(ms));
572
+ if (cost > 0) {
573
+ parts.push(
574
+ `≈${formatMoney(fromUsd(cost, settings.currency, settings.usdToCny), settings.currency, 4)}`,
575
+ );
576
+ }
577
+ if (
578
+ ((usage?.cacheReadTokens ?? 0) > 0 || (usage?.cacheWriteTokens ?? 0) > 0) &&
579
+ price.cacheSource === "none"
580
+ ) {
581
+ parts.push("缓存未计价");
582
+ }
583
+ return parts.join(" / ");
584
+ };
585
+
586
+ let costUsd = costOf(call.usage);
587
+ let usageLine = call.ok
588
+ ? usageLineOf(call.usage, costUsd, call.ms)
557
589
  : `${formatMs(Date.now() - started)}`;
558
590
 
559
591
  const baseResult = {
@@ -588,6 +620,7 @@ export class AdvisorService extends TypertRemoteService {
588
620
  inputTokens: 0,
589
621
  outputTokens: 0,
590
622
  cacheReadTokens: 0,
623
+ cacheWriteTokens: 0,
591
624
  costUsd: 0,
592
625
  ms: Date.now() - started,
593
626
  code: baseResult.code,
@@ -596,12 +629,17 @@ export class AdvisorService extends TypertRemoteService {
596
629
  }
597
630
 
598
631
  const parsed = parseAdvice(call.text ?? "");
599
- const usage = call.usage;
600
- this.ledger.noteCall(sessionId, { turn, costUsd, at: Date.now() });
601
- void this.pool.add({ calls: 1, costUsd });
602
- this.counters.calls += 1;
632
+ let usage = call.usage;
633
+
634
+ // 记一次调用(调用数与最终成本):两阶段取证的额外 usage 合并后再记,避免只记第一轮。
635
+ const charge = () => {
636
+ this.ledger.noteCall(sessionId, { turn, costUsd, at: Date.now() });
637
+ void this.pool.add({ calls: 1, costUsd });
638
+ this.counters.calls += 1;
639
+ };
603
640
 
604
641
  if (!parsed.ok) {
642
+ charge();
605
643
  const result = { ...baseResult, status: "unavailable", code: `advice_${parsed.reason}` };
606
644
  this.counters.failures += 1;
607
645
  this.lastResult = result;
@@ -616,6 +654,7 @@ export class AdvisorService extends TypertRemoteService {
616
654
  inputTokens: usage?.inputTokens ?? 0,
617
655
  outputTokens: usage?.outputTokens ?? 0,
618
656
  cacheReadTokens: usage?.cacheReadTokens ?? 0,
657
+ cacheWriteTokens: usage?.cacheWriteTokens ?? 0,
619
658
  costUsd,
620
659
  ms: Date.now() - started,
621
660
  code: result.code,
@@ -658,6 +697,13 @@ export class AdvisorService extends TypertRemoteService {
658
697
  }
659
698
  }
660
699
 
700
+ // 两阶段可能追加了 usage:用合并后的 token 重算成本/展示,再记这一次调用。
701
+ usage = call.usage;
702
+ costUsd = costOf(usage);
703
+ usageLine = usageLineOf(usage, costUsd, call.ms);
704
+ baseResult.usage = usageLine;
705
+ charge();
706
+
661
707
  const hollow = advice.verdict === "reviewed" && isHollowAdvice(advice.advice);
662
708
 
663
709
  // 证据锚点校验:顾问说「刚才那次失败/这个文件」时,回头核对它引用的东西是否真的存在。
@@ -729,6 +775,7 @@ export class AdvisorService extends TypertRemoteService {
729
775
  inputTokens: usage?.inputTokens ?? 0,
730
776
  outputTokens: usage?.outputTokens ?? 0,
731
777
  cacheReadTokens: usage?.cacheReadTokens ?? 0,
778
+ cacheWriteTokens: usage?.cacheWriteTokens ?? 0,
732
779
  costUsd,
733
780
  ms: Date.now() - started,
734
781
  code: "session_cap",
@@ -816,6 +863,7 @@ export class AdvisorService extends TypertRemoteService {
816
863
  inputTokens: usage?.inputTokens ?? 0,
817
864
  outputTokens: usage?.outputTokens ?? 0,
818
865
  cacheReadTokens: usage?.cacheReadTokens ?? 0,
866
+ cacheWriteTokens: usage?.cacheWriteTokens ?? 0,
819
867
  costUsd,
820
868
  ms: Date.now() - started,
821
869
  });
@@ -1141,7 +1189,7 @@ export class AdvisorService extends TypertRemoteService {
1141
1189
  `币种:${settings.currency}${settings.currency === "CNY" ? `(1 USD = ${settings.usdToCny} CNY)` : ""}`,
1142
1190
  `单价:${
1143
1191
  price.source === "none"
1144
- ? "未配置(只记 token)"
1192
+ ? "输入/输出未配置(只记 token)"
1145
1193
  : `输入 ${formatMoney(
1146
1194
  fromUsd(price.input, settings.currency, settings.usdToCny),
1147
1195
  settings.currency,
@@ -1151,6 +1199,18 @@ export class AdvisorService extends TypertRemoteService {
1151
1199
  settings.currency,
1152
1200
  2,
1153
1201
  )}/M(${price.source === "builtin" ? "内置参考价(USD 折算)" : "用户设置"})`
1202
+ };${
1203
+ price.cacheSource === "none"
1204
+ ? "缓存读取/写入未配置(缓存 token 不计)"
1205
+ : `缓存读取 ${formatMoney(
1206
+ fromUsd(price.cacheRead, settings.currency, settings.usdToCny),
1207
+ settings.currency,
1208
+ 2,
1209
+ )}/M · 缓存写入 ${formatMoney(
1210
+ fromUsd(price.cacheWrite, settings.currency, settings.usdToCny),
1211
+ settings.currency,
1212
+ 2,
1213
+ )}/M`
1154
1214
  }`,
1155
1215
  `工作区今日:${pool.calls} 次(上限 ${settings.workspaceMaxCallsPerDay || "∞"})`,
1156
1216
  ``,
package/lib/settings.js CHANGED
@@ -36,6 +36,8 @@ export const DEFAULT_SETTINGS = Object.freeze({
36
36
  maxCostPerDay: 0,
37
37
  priceInputPerMTok: 0,
38
38
  priceOutputPerMTok: 0,
39
+ priceCacheReadPerMTok: 0,
40
+ priceCacheWritePerMTok: 0,
39
41
  privacyScope: "summary",
40
42
  redact: true,
41
43
  immuneTurns: 3,
@@ -76,6 +78,8 @@ const MONEY_LIMITS = Object.freeze({
76
78
  workspaceMaxCostPerDay: { min: 0, max: 10000, digits: 2 },
77
79
  priceInputPerMTok: { min: 0, max: 1000, digits: 4 },
78
80
  priceOutputPerMTok: { min: 0, max: 1000, digits: 4 },
81
+ priceCacheReadPerMTok: { min: 0, max: 1000, digits: 4 },
82
+ priceCacheWritePerMTok: { min: 0, max: 1000, digits: 4 },
79
83
  });
80
84
 
81
85
  /** 汇率区间:1 USD = 0.1–100 CNY,保留 4 位小数。 */
package/locale/en.json CHANGED
@@ -225,6 +225,14 @@
225
225
  "settings.unit.cnyPerMTok": "CNY / 1M tokens",
226
226
  "settings.budget.maxCostPerDay": "Daily budget",
227
227
  "settings.budget.workspaceMaxCostPerDay": "Workspace daily budget",
228
- "settings.unit.cnyPerUsd": "CNY / USD"
228
+ "settings.unit.cnyPerUsd": "CNY / USD",
229
+ "settings.budget.priceCacheReadPerMTok": "Cache-read price",
230
+ "settings.budget.priceCacheWritePerMTok": "Cache-write price",
231
+ "settings.budget.cachePriceHint": "Input-token price for cache reads/writes (selected currency per 1M tokens); 0 = cache tokens are not priced. The host exposes cache-read/write tokens only; there is no cache-output token.",
232
+ "settings.budget.cachePriceSource": "Cache prices",
233
+ "settings.budget.cachePriceSource.settings": "user settings",
234
+ "settings.budget.cachePriceSource.none": "unset (cache tokens not priced)",
235
+ "settings.status.cache": "Cache tokens: {read} read / {write} write",
236
+ "settings.status.cacheUnpriced": "The ledger has cache tokens, but cache prices are 0: that part is not priced."
229
237
  }
230
238
  }
package/locale/zh.json CHANGED
@@ -225,6 +225,14 @@
225
225
  "settings.unit.cnyPerMTok": "元 / 百万 token",
226
226
  "settings.budget.maxCostPerDay": "每日预算",
227
227
  "settings.budget.workspaceMaxCostPerDay": "工作区每日预算",
228
- "settings.unit.cnyPerUsd": "元 / USD"
228
+ "settings.unit.cnyPerUsd": "元 / USD",
229
+ "settings.budget.priceCacheReadPerMTok": "缓存读取单价",
230
+ "settings.budget.priceCacheWritePerMTok": "缓存写入单价",
231
+ "settings.budget.cachePriceHint": "缓存读取/写入的输入 token 单价(按当前币种 / 百万 token);0 = 不计缓存部分。宿主只提供缓存读/写 token,没有缓存输出 token。",
232
+ "settings.budget.cachePriceSource": "缓存单价",
233
+ "settings.budget.cachePriceSource.settings": "用户设置",
234
+ "settings.budget.cachePriceSource.none": "未配置(缓存 token 不计)",
235
+ "settings.status.cache": "缓存 token:{read} read / {write} write",
236
+ "settings.status.cacheUnpriced": "账本里有缓存 token,但缓存单价为 0:缓存部分没有计价。"
229
237
  }
230
238
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-advisor",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Pair the main model with a stronger advisor model it consults at key moments: autonomous second opinion, cost ledger, and model picker",
5
5
  "keywords": [
6
6
  "dsh",