dsh-cost-meter 1.9.72 → 1.9.73

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
@@ -3,7 +3,7 @@
3
3
  <p align="center">Cost tracking and subscription quotas for DeepSeek Harness</p>
4
4
 
5
5
  <p align="center">
6
- <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.72-4176E6?style=flat-square" alt="version"></a>
6
+ <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.73-4176E6?style=flat-square" alt="version"></a>
7
7
  <a href="https://www.npmjs.com/package/dsh-cost-meter"><img src="https://img.shields.io/npm/dm/dsh-cost-meter?label=downloads&style=flat-square&color=4176E6" alt="npm monthly downloads"></a>
8
8
  <a href="https://github.com/Han-1413141/dsh-cost-meter/stargazers"><img src="https://img.shields.io/github/stars/Han-1413141/dsh-cost-meter?label=stars&style=flat-square&color=D9A400" alt="GitHub stars"></a>
9
9
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="MIT license"></a>
@@ -42,20 +42,20 @@ Restart `dsh web` after installation or updates. **Desktop** uses its bundled CL
42
42
  The PowerShell installer checks pnpm and Git and uses the `web` profile by default:
43
43
 
44
44
  ```powershell
45
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.72/install.ps1 | iex
45
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.73/install.ps1 | iex
46
46
  ```
47
47
 
48
48
  Install a pinned Git tag:
49
49
 
50
50
  ```sh
51
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.72
51
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.73
52
52
  ```
53
53
 
54
54
  See [installation and updates](docs/install.en.md) for uninstalling or installing without Git.
55
55
 
56
56
  </details>
57
57
 
58
- Current release **v1.9.72**: [release notes](docs/update-notes-1.9.72.md#english) · [troubleshooting](docs/install-troubleshooting.md)
58
+ Current release **v1.9.73**: [release notes](docs/update-notes-1.9.73.md#english) · [troubleshooting](docs/install-troubleshooting.md)
59
59
 
60
60
  ## Feature overview
61
61
 
package/README.zh-CN.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <p align="center">DeepSeek Harness 费用统计与订阅额度插件</p>
4
4
 
5
5
  <p align="center">
6
- <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.72-4176E6?style=flat-square" alt="version"></a>
6
+ <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.73-4176E6?style=flat-square" alt="version"></a>
7
7
  <a href="https://www.npmjs.com/package/dsh-cost-meter"><img src="https://img.shields.io/npm/dm/dsh-cost-meter?label=downloads&style=flat-square&color=4176E6" alt="npm monthly downloads"></a>
8
8
  <a href="https://github.com/Han-1413141/dsh-cost-meter/stargazers"><img src="https://img.shields.io/github/stars/Han-1413141/dsh-cost-meter?label=stars&style=flat-square&color=D9A400" alt="GitHub stars"></a>
9
9
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="MIT license"></a>
@@ -42,20 +42,20 @@ dsh plugin --profile web add dsh-cost-meter
42
42
  PowerShell 脚本自动检查 pnpm 和 Git,默认安装到 `web` Profile:
43
43
 
44
44
  ```powershell
45
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.72/install.ps1 | iex
45
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.73/install.ps1 | iex
46
46
  ```
47
47
 
48
48
  固定 Git tag 安装:
49
49
 
50
50
  ```sh
51
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.72
51
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.73
52
52
  ```
53
53
 
54
54
  更新、卸载及无 Git 的安装方法见[安装说明](docs/install.md)。
55
55
 
56
56
  </details>
57
57
 
58
- 当前版本 **v1.9.72**:[更新说明](docs/update-notes-1.9.72.md#中文) · [安装排障](docs/install-troubleshooting.md)
58
+ 当前版本 **v1.9.73**:[更新说明](docs/update-notes-1.9.73.md#中文) · [安装排障](docs/install-troubleshooting.md)
59
59
 
60
60
  ## 功能总览
61
61
 
@@ -108,3 +108,7 @@ SHA-512 校验、静态契约检查和实际发布包回归通过:原生及代
108
108
  ### 2026-11-17:billion-context 0.1.216
109
109
 
110
110
  处理 github-actions[bot] 在 [#524](https://github.com/Han-1413141/dsh-cost-meter/issues/524) 报告的版本变化。官方发布包 SHA-512 校验通过,接入函数指纹未变。实际发布包的原生与代理计费、四种协议、压缩、重试、缓存、父子会话、API/Plan 分类、回放、重启、取消及原版 CLI 自动接入检查通过。检查使用合成数据和本机服务,外部模型请求为 0。现有 v1.9.71 运行时代码已兼容;本次更新兼容基线并将 0.1.216 加入 CI。
111
+
112
+ ### 2026-11-18:Codex Subscription 3.2.21
113
+
114
+ 官方发布包 SHA-512 校验通过,四个额度接入函数语法指纹及静态契约未变。实际发布包的额度解析、单周和双窗口、默认缓存、强制刷新、账号切换、共享请求取消、登录失效及只读 HTTP/RPC 检查通过;测试仅使用合成数据与本机服务,外部账户及模型请求为 0。兼容基线更新至 `3.2.21`,两个既有宿主的 CI 矩阵均保留旧版本并加入 `3.2.21`。
@@ -0,0 +1,29 @@
1
+ # v1.9.73
2
+
3
+ ## 中文
4
+
5
+ - 修复旧版本升级账本缺少 `deepseek-flash` 条目导致 `magpie:deepseek/deepseek-flash` 等转发路由无法自动匹配 DeepSeek 官方价格的问题:启动时一次性补齐缺失的官方 Flash 规范模型名,保留用户自定义单价及主动移除设置。
6
+ - 修复长会话在历史重算、回填和 RDB 会话读取时,因内存中展开超过 20 万条流式文本/推理增量块而触发事件上限并被误判为“日志缺失”的问题。
7
+ - 修复此前未定价(金额为 0)的会话因宿主自动标题生成等未写入会话日志的附属调用残差而无法重算的问题:按已记录调用重算金额并同步更新本会话费用明细(消除 `0 + ?`),保留账本原有 Token 与调用次数,且重启后仍可继续重算;已有正数费用的不完整日志继续保留原金额。
8
+ - 当插件文件已在磁盘更新但宿主尚未重启时,历史重算提示会明确提醒重启 DSH 使新版服务生效。
9
+ - 验证 `dsh-codex-subscription` 3.2.21,更新兼容基线与 CI。
10
+
11
+ 感谢 [@JokerQyou](https://github.com/JokerQyou) 在 [#499 评论](https://github.com/Han-1413141/dsh-cost-meter/issues/499#issuecomment-6967300277) 反馈 `magpie:deepseek/deepseek-flash` 自动匹配缺失及 651 次长会话历史重算问题并提供截图。
12
+
13
+ ## English
14
+
15
+ - Mount missing canonical `deepseek-flash` entries once on upgraded pre-v1.8.33 ledgers when existing DeepSeek Flash models are present, restoring automatic official price matching for routes such as `magpie:deepseek/deepseek-flash` without overwriting custom rates or resurrecting cleared catalogs.
16
+ - Filter unpacked streaming text, reasoning and tool-input delta chunks before applying session event limits in backfill, historical recalculation and RDB usage reads, preventing large conversations (e.g. 650+ calls with >200k raw stream chunks) from aborting as missing logs.
17
+ - Allow explicit historical recalculation for previously unpriced (`cost = 0`) model buckets whose ledger totals include unlogged host auxiliary calls (such as automatic title generation), preserving recorded token/call counts, updating per-session billing details (`0 + ?`) and keeping subsequent recalculations idempotent across restarts; already-priced partial logs remain protected.
18
+ - Append a restart reminder when historical recalculation runs while updated plugin files on disk have not yet been loaded by DSH.
19
+ - Verify `dsh-codex-subscription` 3.2.21 and update the compatibility baseline and CI.
20
+
21
+ Thanks to [@JokerQyou](https://github.com/JokerQyou) for reporting the `magpie:deepseek/deepseek-flash` auto-matching gap and large-session historical recalculation failure with screenshots in [#499 (comment)](https://github.com/Han-1413141/dsh-cost-meter/issues/499#issuecomment-6967300277).
22
+
23
+ ## 升级 / Upgrade
24
+
25
+ ```sh
26
+ dsh plugin --profile web add dsh-cost-meter@latest
27
+ ```
28
+
29
+ 更新后请**完全退出并重启 DSH** 以加载新版宿主服务。Desktop 用户参见 [安装与更新](https://github.com/Han-1413141/dsh-cost-meter/blob/v1.9.73/docs/install-troubleshooting.md#desktop-安装与更新)。
package/lib/backfill.js CHANGED
@@ -24,7 +24,7 @@ import { isWebRequestModel } from './web-request-pricing.js'
24
24
  import { listSessionLogFiles } from './session-log-files.js'
25
25
  import { listNativeSearchHistory, readNativeSearchHistory, nativeSearchRecordsFor } from './native-search-history.js'
26
26
  import { BILLION_USAGE_EVENT, billionRecordsFor, excludeBillionReportedUsage, listBillionFiles, iterateBillionCalls } from './billion-context-history.js'
27
- import { pricingConfigAt, recordPricingRevision, currentPricingConfig, pricingSnapshot, pricingHistoryFingerprint } from './billing-history.js'
27
+ import { pricingConfigAt, recordPricingRevision, hasUnloggedResidualRevision, currentPricingConfig, pricingSnapshot, pricingHistoryFingerprint } from './billing-history.js'
28
28
 
29
29
  const ZSTD_MAGIC = 4247762216
30
30
  /** 打包行(文本/推理/工具调用增量游程)不含 header 与 usage,回放时跳过。 */
@@ -1166,6 +1166,7 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1166
1166
  const dayPm = day.byProviderModel !== null && typeof day.byProviderModel === 'object' ? day.byProviderModel : {}
1167
1167
  // Token 计价只要求五桶一致;按请求收费仍须核对 calls。重算只改金额,保留账本计量。
1168
1168
  let replaceable = newKeys.length > 0 && newKeys.length === Object.keys(oldPm).length
1169
+ const residualModels = []
1169
1170
  for (const key of new Set([...Object.keys(oldPm), ...newKeys])) {
1170
1171
  const oldBucket = oldPm[key]
1171
1172
  const dayBucket = dayPm[key]
@@ -1175,10 +1176,22 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1175
1176
  detail(sessionId, date, key, oldBucket === undefined ? 'ledgerModelMissing' : newBucket === undefined ? 'logModelMissing' : 'dayModelMissing')
1176
1177
  continue
1177
1178
  }
1179
+ if (model && key !== model) continue
1178
1180
  const fields = [...tokenFields, 'calls'].map(field => ({ field, ledger: Number(oldBucket[field]) || 0, log: Number(newBucket[field]) || 0 }))
1179
1181
  .filter(row => row.ledger !== row.log)
1180
1182
  const colon = key.indexOf(':')
1181
- if (fields.some(row => row.field !== 'calls' || isWebRequestModel(key.slice(0, colon), key.slice(colon + 1)))) {
1183
+ const webRequest = isWebRequestModel(key.slice(0, colon), key.slice(colon + 1))
1184
+ if (fields.some(row => row.field !== 'calls' || webRequest)) {
1185
+ // 此前未定价(cost=0)的会话若仅有宿主未写入日志的附属调用残差(如自动标题生成,账本五桶 ≥ 日志五桶且日志有实际调用),
1186
+ // 允许按已记录日志调用重算并在价格修订中登记该模型,避免整段历史与本会话明细永久卡在 0 + ?;已记过正数金额的桶仍严格保留原值。
1187
+ const wasUnpriced = ((Number(oldBucket.cost) || 0) === 0 && (Number(oldBucket.apiCost) || 0) === 0)
1188
+ || hasUnloggedResidualRevision(ledger.pricingHistory, sessionId, date, key)
1189
+ const logIsSubset = !webRequest && (Number(newBucket.calls) || 0) > 0
1190
+ && tokenFields.every(field => (Number(oldBucket[field]) || 0) >= (Number(newBucket[field]) || 0))
1191
+ if (explicit && wasUnpriced && logIsSubset) {
1192
+ residualModels.push(key)
1193
+ continue
1194
+ }
1182
1195
  replaceable = false
1183
1196
  detail(sessionId, date, key, 'usage', fields)
1184
1197
  }
@@ -1212,7 +1225,8 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1212
1225
  }
1213
1226
  result.recostedSessions += 1
1214
1227
  touchedDates.add(date)
1215
- if (explicit && ledger.pricingHistory) recordPricingRevision(ledger.pricingHistory, pricingConfig, sessionId, date, startedAt, previousAmount, { cost: row.cost, apiCost: row.apiCost }, model)
1228
+ const selectedResiduals = residualModels.filter(key => selected.includes(key))
1229
+ if (explicit && ledger.pricingHistory) recordPricingRevision(ledger.pricingHistory, pricingConfig, sessionId, date, startedAt, previousAmount, { cost: row.cost, apiCost: row.apiCost }, model, selectedResiduals)
1216
1230
  }
1217
1231
  }
1218
1232
  result.recostedDays = touchedDates.size
@@ -35,12 +35,15 @@ const compare = (a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0) |
35
35
  function indexOf(history) {
36
36
  let index = indexes.get(history)
37
37
  if (index) return index
38
- const revisions = new Map()
38
+ const revisions = new Map(), residualModels = new Set()
39
39
  for (const row of Object.values(history.revisions)) {
40
40
  const key = JSON.stringify([row.sessionId, row.date, row.model ?? '']), previous = revisions.get(key)
41
41
  if (!previous || compare(row, previous) >= 0) revisions.set(key, row)
42
+ if (Array.isArray(row.unloggedResidualModels)) {
43
+ for (const item of row.unloggedResidualModels) residualModels.add(JSON.stringify([row.sessionId, row.date, item]))
44
+ }
42
45
  }
43
- index = { changes: Object.values(history.changes).sort(compare), revisions, fingerprint: hash([history.changes, history.revisions, history.fxChanges]), fx: Object.values(history.fxChanges ?? {}).sort((a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0)) }
46
+ index = { changes: Object.values(history.changes).sort(compare), revisions, residualModels, fingerprint: hash([history.changes, history.revisions, history.fxChanges]), fx: Object.values(history.fxChanges ?? {}).sort((a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0)) }
44
47
  indexes.set(history, index)
45
48
  return index
46
49
  }
@@ -100,6 +103,7 @@ export function normalizePricingHistory(raw, config, previous, stored = false) {
100
103
  }
101
104
  const revisions = Object.fromEntries(Object.entries(raw.revisions ?? {}).filter(([id, row]) => safe(id) && typeof row?.sessionId === 'string'
102
105
  && (row.model === undefined || (typeof row.model === 'string' && row.model.includes(':') && row.model.length <= 2048))
106
+ && (row.unloggedResidualModels === undefined || (Array.isArray(row.unloggedResidualModels) && row.unloggedResidualModels.every(item => typeof item === 'string' && item.includes(':') && item.length <= 2048)))
103
107
  && /^\d{4}-\d{2}-\d{2}$/.test(row.date) && Number.isFinite(row.at) && versions[row.version]))
104
108
  const runs = Object.fromEntries(Object.entries(object(raw.runs) ? raw.runs : {}).filter(([id, row]) => safe(id) && runFields.every(key => Number.isFinite(row?.[key]) && row[key] >= 0))
105
109
  .map(([id, row]) => [id, { ...Object.fromEntries([...runFields, ...['beforeCny', 'afterCny', 'beforeEur', 'afterEur'].filter(key => Number.isFinite(row[key]) && row[key] >= 0)].map(key => [key, row[key]])), ...(typeof row.model === 'string' ? { model: row.model } : {}),
@@ -169,13 +173,18 @@ export function pricingConfigAt(config, at, sessionId = '', model = '') {
169
173
  }
170
174
 
171
175
  /** Repricing affects only fully replayable session/day records explicitly accepted by the user. */
172
- export function recordPricingRevision(history, config, sessionId, date, at, before, after, model = '') {
176
+ export function recordPricingRevision(history, config, sessionId, date, at, before, after, model = '', unloggedResidualModels = []) {
173
177
  const pricing = pricingSnapshot(config), version = hash(pricing)
174
178
  rememberPriceVersion(history.versions, version, pricing, indexOf(history).changes.at(-1)?.version)
175
- history.revisions[randomUUID()] = { sessionId, date, at, ...(model ? { model, preserveFx: true } : { fxRates: fxHistoryRatesOf(config) }), sequence: Object.keys(history.revisions).length + 1, version, before, after }
179
+ const residuals = Array.isArray(unloggedResidualModels) && unloggedResidualModels.length ? [...new Set(unloggedResidualModels)] : null
180
+ history.revisions[randomUUID()] = { sessionId, date, at, ...(model ? { model, preserveFx: true } : { fxRates: fxHistoryRatesOf(config) }), ...(residuals ? { unloggedResidualModels: residuals } : {}), sequence: Object.keys(history.revisions).length + 1, version, before, after }
176
181
  indexes.delete(history)
177
182
  }
178
183
 
184
+ export function hasUnloggedResidualRevision(history, sessionId, date, model) {
185
+ return Boolean(history && typeof model === 'string' && model.length > 0 && indexOf(history).residualModels.has(JSON.stringify([sessionId, date, model])))
186
+ }
187
+
179
188
  export function mergePricingHistory(local, disk) {
180
189
  if (!local) return disk
181
190
  if (!disk) return local
package/lib/bootstrap.js CHANGED
@@ -38,4 +38,4 @@ Issue: `+wi);return i.code=e==="version_too_old"?"BILLION_VERSION_TOO_OLD":"BILL
38
38
  `}else{N(t==="native","unknown_runtime_kind");let c=u("installNativeFetchIntercept"),x=Q(c.body,"send"),g=!1;$(c.body,b=>{b.type==="CallExpression"&&b.callee.type==="MemberExpression"&&b.callee.object.name==="Object"&&b.callee.property.name==="defineProperty"&&b.arguments[1]?.value==="fetch"&&(g=!0)});let v=Q(c.body,"installFetchChain").length;N(x.length>0&&(v===1||v===0&&g&&Q(c.body,"makeChain").length>0)&&Q(c.body,"fetch").length===0,"native_transport_changed");for(let{item:b}of x)N(b.arguments.length>=1&&!b.optional,"native_send_changed"),n.push({start:b.start,end:b.end,text:"__dshCmSend(send, "+b.arguments.map(k=>e.slice(k.start,k.end)).join(", ")+")"});o.nativeSends=x.length,o.nativeTransport=v?"chain":"global-fetch-accessor",d=`import { sendWithBillionMeter as __dshCmSend } from ${JSON.stringify(i.native??"./cost-meter-native.js")};
39
39
  `}n.sort((c,x)=>x.start-c.start||x.end-c.end);for(let c=1;c<n.length;c++)N(n[c].end<=n[c-1].start,"overlapping_runtime_hooks");for(let c of n)e=e.slice(0,c.start)+c.text+e.slice(c.end);let y=e.startsWith("#!")?e.indexOf(`
40
40
  `)+1:0;e=e.slice(0,y)+d+e.slice(y);try{Oe(e,{sourceType:"module",ecmaVersion:"latest"})}catch{throw ge("patched_syntax_changed")}return{source:e,capabilities:o}}var be=Symbol.for("dsh-cost-meter.billion-context.auto.v1"),Ti=Symbol.for("dsh-cost-meter.billion-context.peers.v1"),Vt=Symbol.for("dsh-cost-meter.billion-context.v1"),Fe="x-dsh-cost-meter-group",Li=new URL("./billion-context-preload.js",import.meta.url).href,Ri=e=>["127.0.0.1","localhost","[::1]","::1"].includes(e.hostname);function Tt(e){if(!Number.isSafeInteger(e)||e<1)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Lt(e){try{let t=new URL(e.path,String(e.origin));return Ri(t)&&t.protocol==="http:"?t:null}catch{return null}}function ve(e,t){if(Array.isArray(e)){for(let i=0;i<e.length;i+=2)if(String(e[i]).toLowerCase()===t)return String(e[i+1])}else if(typeof e=="string"){for(let i of e.split(`\r
41
- `))if(i.slice(0,i.indexOf(":")).toLowerCase()===t)return i.slice(i.indexOf(":")+1).trim()}else if(e&&typeof e=="object")return e[t]==null?null:String(e[t]);return null}function Me(e){if(Ue(e).size>32*1024*1024)throw Error("runtime_size_changed");return Pi(e,"utf8")}function Oi(e,t={},i=new Map){if(!Array.isArray(e)||typeof e[0]!="string"||e[0].startsWith("-"))return null;let s;try{s=Ni(Vi(t.cwd??process.cwd(),e[0]))}catch{return null}if(je(s)!=="index.js"||je(De(s))!=="dist")return null;let a=De(De(s)),n;try{n=JSON.parse(Me(Nt(a,"package.json")))}catch{return null}if(n.name!=="billion-context"||n.dshCostMeterCompatibility)return null;if(Pt(n.version)!==!0)return{version:n.version,reason:"needs_update"};if(typeof Rt.register!="function")return{version:n.version,reason:"bridge_missing"};try{let o=Nt(a,"dist/agent/dsh-native.js"),u=[Ue(s),Ue(o)],h=s+":"+u.map(y=>[y.size,y.mtimeMs,y.ctimeMs].join(":")).join(":");if(i.has(h))return i.get(h);let f=Me(s);Be(f,"proxy"),Be(Me(o),"native");let d={script:s,version:n.version,fingerprint:Ii("sha256").update(f).digest("hex")};return i.set(h,d),i.size>8&&i.delete(i.keys().next().value),d}catch{return{version:n.version,reason:"changed"}}}function Ot(){let e=!1,t=c=>()=>{e||(e=!0,Bi(c))},i=globalThis[be];if(i)return i.references++,i.issue&&globalThis[Vt]?.adapterStatus?.(i.issue.version,i.issue.reason),t(i);let s=Ai.ChildProcess.prototype,a=s.spawn,n=new Map,o=new WeakMap,u=new Map,h=globalThis[Ti]??=new Map;i={references:1,original:a,subscriptions:[],children:u,prototype:s};let f=()=>globalThis[Vt],d=function(c){if(i.references<=0||!c||!Array.isArray(c.args)||!Array.isArray(c.envPairs))return a.apply(this,arguments);let x=c.file,g=c.args.slice(1);if(typeof x!="string"||!["node","node.exe","nodejs"].includes(je(x).toLowerCase())&&!c.envPairs.includes("ELECTRON_RUN_AS_NODE=1"))return a.apply(this,arguments);let v;try{v=Oi(g,c,n)}catch{}try{v?.reason&&(i.issue=v,f()?.adapterStatus?.(v.version,v.reason))}catch{}if(!v||v.reason)return a.apply(this,arguments);i.issue=void 0;let b=c.envPairs.filter(ye=>!ye.startsWith("DSH_COST_METER_BILLION_LOADER="));b.push("DSH_COST_METER_BILLION_LOADER="+JSON.stringify({script:v.script,fingerprint:v.fingerprint}));let k=a.call(this,{...c,args:[c.args[0],"--import",Li,...g],envPairs:b}),E=this;u.set(E.pid,E);let ee=()=>{u.delete(E.pid);for(let[ye,Ft]of h)Ft.pid===E.pid&&h.delete(ye)};return E.once("exit",ee),E.once("error",ee),k};i.wrapped=d,s.spawn=d;let y=(c,x)=>{let g=b=>{try{x(b)}catch{}},v=Ei(c);v.subscribe(g),i.subscriptions.push(()=>v.unsubscribe(g))};return y("undici:request:create",({request:c})=>{let x=Lt(c);if(c.method!=="POST")return;if(!x||!x.pathname.startsWith("/bili/")){f()?.begin?.(new URL(c.path,String(c.origin)).href);return}if(ve(c.headers,Fe))return;let g=h.get(x.origin);if(!g||!Tt(g.pid)){h.delete(x.origin),f()?.unsupported?.({changed:!1,missing:!g});return}let v=f(),b=v?.begin(x.href);b&&(c.addHeader(Fe,b),o.set(c,{bridge:v,id:b,origin:x.origin}))}),y("undici:request:headers",({request:c,response:x})=>{let g=Lt(c);if(g&&c.method==="GET"&&g.pathname==="/__bili/health"){let k=Number(ve(x.headers,"x-dsh-cost-meter-pid"));x.statusCode===200&&ve(x.headers,"x-dsh-cost-meter-protocol")==="1"&&Tt(k)?(h.set(g.origin,{pid:k}),h.size>128&&h.delete(h.keys().next().value)):h.delete(g.origin)}let v=o.get(c);if(!v)return;o.delete(c);let b=ve(x.headers,Fe)===v.id;v.bridge.ack(v.id,b),b||h.delete(v.origin)}),y("undici:request:error",({request:c})=>{let x=o.get(c);x&&(o.delete(c),x.bridge.ack(x.id,!1,{transient:!0}),h.delete(x.origin))}),globalThis[be]=i,t(i)}function Bi(e){if(!(--e.references>0||globalThis[be]!==e)){for(let t of e.subscriptions)t();e.prototype.spawn===e.wrapped&&(e.prototype.spawn=e.original),delete globalThis[be]}}var qe=Ot(),Bt;try{Bt=await import("./index.js")}catch(e){throw qe(),e}var Dt=setTimeout(qe,0);Dt.unref?.();var Zi="cost-meter";function Ji(e){clearTimeout(Dt);try{return Bt.apply(e)}finally{qe()}}export{Ji as apply,Zi as name};
41
+ `))if(i.slice(0,i.indexOf(":")).toLowerCase()===t)return i.slice(i.indexOf(":")+1).trim()}else if(e&&typeof e=="object")return e[t]==null?null:String(e[t]);return null}function Me(e){if(Ue(e).size>32*1024*1024)throw Error("runtime_size_changed");return Pi(e,"utf8")}function Oi(e,t={},i=new Map){if(!Array.isArray(e)||typeof e[0]!="string"||e[0].startsWith("-"))return null;let s;try{s=Ni(Vi(t.cwd??process.cwd(),e[0]))}catch{return null}if(je(s)!=="index.js"||je(De(s))!=="dist")return null;let a=De(De(s)),n;try{n=JSON.parse(Me(Nt(a,"package.json")))}catch{return null}if(n.name!=="billion-context"||n.dshCostMeterCompatibility)return null;if(Pt(n.version)!==!0)return{version:n.version,reason:"needs_update"};if(typeof Rt.register!="function")return{version:n.version,reason:"bridge_missing"};try{let o=Nt(a,"dist/agent/dsh-native.js"),u=[Ue(s),Ue(o)],h=s+":"+u.map(y=>[y.size,y.mtimeMs,y.ctimeMs].join(":")).join(":");if(i.has(h))return i.get(h);let f=Me(s);Be(f,"proxy"),Be(Me(o),"native");let d={script:s,version:n.version,fingerprint:Ii("sha256").update(f).digest("hex")};return i.set(h,d),i.size>8&&i.delete(i.keys().next().value),d}catch{return{version:n.version,reason:"changed"}}}function Ot(){let e=!1,t=c=>()=>{e||(e=!0,Bi(c))},i=globalThis[be];if(i)return i.references++,i.issue&&globalThis[Vt]?.adapterStatus?.(i.issue.version,i.issue.reason),t(i);let s=Ai.ChildProcess.prototype,a=s.spawn,n=new Map,o=new WeakMap,u=new Map,h=globalThis[Ti]??=new Map;i={references:1,original:a,subscriptions:[],children:u,prototype:s};let f=()=>globalThis[Vt],d=function(c){if(i.references<=0||!c||!Array.isArray(c.args)||!Array.isArray(c.envPairs))return a.apply(this,arguments);let x=c.file,g=c.args.slice(1);if(typeof x!="string"||!["node","node.exe","nodejs"].includes(je(x).toLowerCase())&&!c.envPairs.includes("ELECTRON_RUN_AS_NODE=1"))return a.apply(this,arguments);let v;try{v=Oi(g,c,n)}catch{}try{v?.reason&&(i.issue=v,f()?.adapterStatus?.(v.version,v.reason))}catch{}if(!v||v.reason)return a.apply(this,arguments);i.issue=void 0;let b=c.envPairs.filter(ye=>!ye.startsWith("DSH_COST_METER_BILLION_LOADER="));b.push("DSH_COST_METER_BILLION_LOADER="+JSON.stringify({script:v.script,fingerprint:v.fingerprint}));let k=a.call(this,{...c,args:[c.args[0],"--import",Li,...g],envPairs:b}),E=this;u.set(E.pid,E);let ee=()=>{u.delete(E.pid);for(let[ye,Ft]of h)Ft.pid===E.pid&&h.delete(ye)};return E.once("exit",ee),E.once("error",ee),k};i.wrapped=d,s.spawn=d;let y=(c,x)=>{let g=b=>{try{x(b)}catch{}},v=Ei(c);v.subscribe(g),i.subscriptions.push(()=>v.unsubscribe(g))};return y("undici:request:create",({request:c})=>{let x=Lt(c);if(c.method!=="POST")return;if(!x||!x.pathname.startsWith("/bili/")){f()?.begin?.(new URL(c.path,String(c.origin)).href);return}if(ve(c.headers,Fe))return;let g=h.get(x.origin);if(!g||!Tt(g.pid)){h.delete(x.origin),f()?.unsupported?.({changed:!1,missing:!g});return}let v=f(),b=v?.begin(x.href);b&&(c.addHeader(Fe,b),o.set(c,{bridge:v,id:b,origin:x.origin}))}),y("undici:request:headers",({request:c,response:x})=>{let g=Lt(c);if(g&&c.method==="GET"&&g.pathname==="/__bili/health"){let k=Number(ve(x.headers,"x-dsh-cost-meter-pid"));x.statusCode===200&&ve(x.headers,"x-dsh-cost-meter-protocol")==="1"&&Tt(k)?(h.set(g.origin,{pid:k}),h.size>128&&h.delete(h.keys().next().value)):h.delete(g.origin)}let v=o.get(c);if(!v)return;o.delete(c);let b=ve(x.headers,Fe)===v.id;v.bridge.ack(v.id,b),b||h.delete(v.origin)}),y("undici:request:error",({request:c})=>{let x=o.get(c);x&&(o.delete(c),x.bridge.ack(x.id,!1,{transient:!0}),h.delete(x.origin))}),globalThis[be]=i,t(i)}function Bi(e){if(!(--e.references>0||globalThis[be]!==e)){for(let t of e.subscriptions)t();e.prototype.spawn===e.wrapped&&(e.prototype.spawn=e.original),delete globalThis[be]}}var qe=Ot(),Bt;try{Bt=await import(new URL("./index.js"+new URL(import.meta.url).search,import.meta.url).href)}catch(e){throw qe(),e}var Dt=setTimeout(qe,0);Dt.unref?.();var Zi="cost-meter";function Ji(e){clearTimeout(Dt);try{return Bt.apply(e)}finally{qe()}}export{Ji as apply,Zi as name};
package/lib/index.js CHANGED
@@ -33,7 +33,7 @@ import { createLlmStreamBilling } from './billing-stream.js'
33
33
  import { contextActivity } from './context-activity.js'
34
34
  import { installBillionContextBilling, syncBillionContextBilling, billionContextBillingStatus } from './billion-context-billing.js'
35
35
  import { installNativeSearchBilling, nativeSearchReconcile, isNativeSearchUsageEvent } from './native-search-billing.js'
36
- import { OFFICIAL_PRICING_URL, OFFICIAL_PRICING_URL_ZH, LEGACY_BASE_BOUNDARY, FLASH_PRICE_EFFECTIVE_AT, parsePricingHtml, repairDefaultPeakPrice, upgradeDeepSeekPriceTable, costOf, providerPriceEntryFor, buildPriceCatalog, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
36
+ import { OFFICIAL_PRICING_URL, OFFICIAL_PRICING_URL_ZH, LEGACY_BASE_BOUNDARY, FLASH_PRICE_EFFECTIVE_AT, parsePricingHtml, repairDefaultPeakPrice, upgradeDeepSeekPriceTable, mountMissingDeepSeekFlashModels, costOf, providerPriceEntryFor, buildPriceCatalog, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
37
37
  import { createUsageDeduper, USAGE_DEDUP_WINDOW_MS, usageFingerprint } from './usage-dedup.js'
38
38
  import { CODING_PLAN_PROVIDERS, CODING_PLAN_PROVIDER_IDS, queryCodingPlan, scnetTokenPlanWindows, qwenTokenPlanWindows, emptyCustomBalance, queryCustomBalance, normalizeVolcengineKey } from './coding-plans.js'
39
39
  import { resolveWorkBuddyCredential } from './workbuddy.js'
@@ -82,6 +82,23 @@ import { repairBillionHostLedger } from './billion-context-repair.js'
82
82
 
83
83
  export const name = 'cost-meter'
84
84
 
85
+ const LOADED_PACKAGE_VERSION = (() => {
86
+ try { return String(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ?? '') } catch { return '' }
87
+ })()
88
+
89
+ function diskPackageVersionNotice(en) {
90
+ if (!LOADED_PACKAGE_VERSION) return ''
91
+ try {
92
+ const current = String(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ?? '')
93
+ if (!current || current === LOADED_PACKAGE_VERSION) return ''
94
+ return en
95
+ ? ` Plugin files on disk were updated (${LOADED_PACKAGE_VERSION} -> ${current}); restart DSH to load the updated service.`
96
+ : ` 检测到插件已更新(当前运行 ${LOADED_PACKAGE_VERSION},磁盘版本 ${current}),请重启 DSH 使新版本生效。`
97
+ } catch {
98
+ return ''
99
+ }
100
+ }
101
+
85
102
  // ── 多语言(中/英) ─────────────────────────────────────────────────────────
86
103
 
87
104
  /** 服务端用户可见文案(zh/en)。 */
@@ -2743,9 +2760,10 @@ function createService(ctx, ledger, openRouterPrices, openDesignPrices, codexSub
2743
2760
  ledger.flush()
2744
2761
  if (ledger.pendingWrite) throw new Error(en ? 'Could not save recalculation; original ledger backup retained.' : '重算结果未能写入,已保留原账本备份。')
2745
2762
  schedulePlanHourRepair()
2746
- return { ok: true, message: en
2763
+ const restartNotice = diskPackageVersionNotice(en)
2764
+ return { ok: true, message: (en
2747
2765
  ? `${model ? model + ': ' : ''}Recalculated ${stats.recostedSessions} session/day records; ${stats.skippedSessions} unchanged.${stats.skippedSessions ? ' See details in recalculation records.' : ''}`
2748
- : `${model ? model + ':' : ''}已重算 ${stats.recostedSessions} 条会话日期记录,${stats.skippedSessions} 条保留原金额。${stats.skippedSessions ? '差异见重算记录。' : ''}`, state: await build(false, true) }
2766
+ : `${model ? model + ':' : ''}已重算 ${stats.recostedSessions} 条会话日期记录,${stats.skippedSessions} 条保留原金额。${stats.skippedSessions ? '差异见重算记录。' : ''}`) + restartNotice, state: await build(false, true) }
2749
2767
  } finally { repricing = false }
2750
2768
  },
2751
2769
 
@@ -3582,6 +3600,7 @@ const DEFAULT_PRICE_MIGRATION_PENDING = 'default-peak-price-pending-v1'
3582
3600
  const SEPTEMBER_PRICE_MIGRATION = 'deepseek-september-2026-prices-v1'
3583
3601
  const SEPTEMBER_PRICE_PENDING = 'deepseek-september-2026-prices-pending-v1'
3584
3602
  const DEEPSEEK_OFFICIAL_PRICE_FIX = 'deepseek-official-pro-prices-v1'
3603
+ const DEEPSEEK_FLASH_CATALOG_MIGRATION = 'deepseek-flash-catalog-v1'
3585
3604
 
3586
3605
  function prepareOfficialDeepSeekPrices(ledger) {
3587
3606
  if (ledger.migrations.includes(DEEPSEEK_OFFICIAL_PRICE_FIX)) return
@@ -3594,6 +3613,16 @@ function prepareOfficialDeepSeekPrices(ledger) {
3594
3613
  ledger.scheduleWrite()
3595
3614
  }
3596
3615
 
3616
+ function prepareDeepSeekFlashCatalog(ledger) {
3617
+ if (ledger.migrations.includes(DEEPSEEK_FLASH_CATALOG_MIGRATION)) return
3618
+ const prices = structuredClone(ledger.config.prices)
3619
+ if (mountMissingDeepSeekFlashModels(prices).length > 0) {
3620
+ ledger.config = { ...ledger.config, prices }
3621
+ }
3622
+ ledger.migrations.push(DEEPSEEK_FLASH_CATALOG_MIGRATION)
3623
+ ledger.scheduleWrite()
3624
+ }
3625
+
3597
3626
  function prepareSeptemberPrices(ledger) {
3598
3627
  if (ledger.migrations.includes(SEPTEMBER_PRICE_MIGRATION) || ledger.migrations.includes(SEPTEMBER_PRICE_PENDING)) return
3599
3628
  const changed = upgradeDeepSeekPriceTable(ledger.config.prices)
@@ -3639,6 +3668,7 @@ export async function runStartupImports(ledger, sessionsRoot, sessionSource = nu
3639
3668
  // RDB 空扫描不消费一次性标记(下次启动重试);JSONL 下保持原语义。
3640
3669
  const jsonlBackend = isJsonlSessionBackend(sessionSource)
3641
3670
  prepareOfficialDeepSeekPrices(ledger)
3671
+ prepareDeepSeekFlashCatalog(ledger)
3642
3672
  prepareDefaultPeakPrice(ledger)
3643
3673
  prepareSeptemberPrices(ledger)
3644
3674
  // Versioned ledgers preserve recorded amounts. Old price migrations must not
@@ -3971,6 +4001,7 @@ function applyCore(ctx) {
3971
4001
  ctx.effect(() => () => statisticsWarmup.dispose(), 'cost-meter: statistics warmup')
3972
4002
  // 必须先于监听器/投影注册,避免延迟历史修复期间的新调用仍使用旧默认谷价。
3973
4003
  prepareOfficialDeepSeekPrices(ledger)
4004
+ prepareDeepSeekFlashCatalog(ledger)
3974
4005
  prepareDefaultPeakPrice(ledger)
3975
4006
  prepareSeptemberPrices(ledger)
3976
4007
  // Cache the installed package version; active runtime status is checked on every state read.