dsh-cost-meter 1.9.48 → 1.9.49

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.
@@ -150,7 +150,7 @@ export function createNativeSearchBilling({ account, record = () => {}, uncovere
150
150
  : path === '/anthropic/v1/messages' && signal?.pending && !signal.owner?.closed && now() - signal.at < 60_000 ? signal : null
151
151
  }
152
152
  const restoreFetch = observeSearchFetch({ target: fetchTarget, seen,
153
- context: path => active ? currentSearch(path) : null,
153
+ context: path => active && !fetchScope.getStore() ? currentSearch(path) : null,
154
154
  run(attempt, operation) {
155
155
  const signal = searchSignal.getStore()
156
156
  if (signal) finishSignal(signal)
@@ -263,6 +263,7 @@ export function createNativeSearchBilling({ account, record = () => {}, uncovere
263
263
  signal(session, event) {
264
264
  if (!active) return
265
265
  if (event?.type === 'web/deepseek-search-llm-request') {
266
+ restoreFetch.refresh()
266
267
  seen('searchEvent')
267
268
  if (event.data?.endpoint !== 'https://api.deepseek.com/anthropic/v1/messages') { seen('otherEndpoint'); return }
268
269
  const at = now()
@@ -276,6 +277,7 @@ export function createNativeSearchBilling({ account, record = () => {}, uncovere
276
277
  }
277
278
  },
278
279
  async run(operation, session, directOnly = false) {
280
+ if (active) restoreFetch.refresh()
279
281
  const parent = scope.getStore()
280
282
  if (!active || parent && !parent.closed && (!parent.directOnly || directOnly) && (!session || parent.session?.id === session.id)) return operation()
281
283
  seen('searchScope')
@@ -1,38 +1,48 @@
1
- /** Observe the parsed response of a scoped official search, including non-Undici fetch transports. */
2
- export function observeSearchFetch({ context, run, complete, failed, ignored, seen, target = globalThis }) {
3
- const original = target.fetch
4
- if (typeof original !== 'function' || Object.getOwnPropertyDescriptor(target, 'fetch')?.writable === false) return () => {}
5
- const wrapped = function (...args) {
6
- const [input, init] = args
7
- let url, method
8
- try {
9
- url = typeof input === 'string' ? input : input instanceof URL ? input.href : input?.url
10
- method = init?.method ?? input?.method ?? 'GET'
11
- } catch { return Reflect.apply(original, this, args) }
12
- const paths = ['https://api.deepseek.com/anthropic/v1/messages', 'https://api.deepseek.com/v1/tools/search', 'https://api.deepseek.com/v1/tools/fetch']
13
- const path = paths.includes(url) ? new URL(url).pathname : ''
14
- const current = path && String(method).toUpperCase() === 'POST' ? context(path) : null
15
- if (!current) return Reflect.apply(original, this, args)
16
- const attempt = { current, path, accounted: false }
17
- seen('fetchRequest')
18
- // Observe the same promise and parsed value; do not tee/consume streams, read
19
- // credentials or queries, alter the dispatcher, or delay the caller's result.
20
- const promise = run(attempt, () => Reflect.apply(original, this, args))
21
- Promise.resolve(promise).then(response => {
22
- if (!response?.ok) { ignored(attempt); return }
23
- if (path !== '/anthropic/v1/messages' && (response.status !== 200 || response.redirected)) { ignored(attempt); return }
24
- if (typeof response.json !== 'function') return
25
- const own = Object.getOwnPropertyDescriptor(response, 'json'), json = response.json
26
- if (own?.configurable === false || !Object.isExtensible(response)) return
27
- Object.defineProperty(response, 'json', { configurable: true, writable: true, value: function (...jsonArgs) {
28
- let result
29
- try { result = Reflect.apply(json, this, jsonArgs) } catch (error) { failed(attempt); throw error }
30
- Promise.resolve(result).then(value => complete(attempt, value), () => failed(attempt)).catch(() => {})
31
- return result
32
- } })
33
- }, () => failed(attempt)).catch(() => {})
34
- return promise
35
- }
36
- target.fetch = wrapped
37
- return () => { if (target.fetch === wrapped) target.fetch = original }
38
- }
1
+ /** Observe the parsed response of a scoped official search, including non-Undici fetch transports. */
2
+ export function observeSearchFetch({ context, run, complete, failed, ignored, seen, target = globalThis }) {
3
+ const wrappers = new WeakSet(), restorers = []
4
+ const refresh = () => {
5
+ const original = target.fetch
6
+ if (typeof original !== 'function' || wrappers.has(original) || Object.getOwnPropertyDescriptor(target, 'fetch')?.writable === false) return
7
+ const wrapped = function (...args) {
8
+ const [input, init] = args
9
+ let url, method
10
+ try {
11
+ url = typeof input === 'string' ? input : input instanceof URL ? input.href : input?.url
12
+ method = init?.method ?? input?.method ?? 'GET'
13
+ } catch { return Reflect.apply(original, this, args) }
14
+ const paths = ['https://api.deepseek.com/anthropic/v1/messages', 'https://api.deepseek.com/v1/tools/search', 'https://api.deepseek.com/v1/tools/fetch']
15
+ const path = paths.includes(url) ? new URL(url).pathname : ''
16
+ const current = path && String(method).toUpperCase() === 'POST' ? context(path) : null
17
+ if (!current) return Reflect.apply(original, this, args)
18
+ const attempt = { current, path, accounted: false }
19
+ seen('fetchRequest')
20
+ // Observe the same promise and parsed value; do not tee/consume streams, read
21
+ // credentials or queries, alter the dispatcher, or delay the caller's result.
22
+ const promise = run(attempt, () => Reflect.apply(original, this, args))
23
+ Promise.resolve(promise).then(response => {
24
+ if (!response?.ok) { ignored(attempt); return }
25
+ if (path !== '/anthropic/v1/messages' && (response.status !== 200 || response.redirected)) { ignored(attempt); return }
26
+ if (typeof response.json !== 'function') return
27
+ const own = Object.getOwnPropertyDescriptor(response, 'json'), json = response.json
28
+ if (own?.configurable === false || !Object.isExtensible(response)) return
29
+ Object.defineProperty(response, 'json', { configurable: true, writable: true, value: function (...jsonArgs) {
30
+ let result
31
+ try { result = Reflect.apply(json, this, jsonArgs) } catch (error) { failed(attempt); throw error }
32
+ Promise.resolve(result).then(value => complete(attempt, value), () => failed(attempt)).catch(() => {})
33
+ return result
34
+ } })
35
+ }, () => failed(attempt)).catch(() => {})
36
+ return promise
37
+ }
38
+ target.fetch = wrapped
39
+ wrappers.add(wrapped)
40
+ restorers.push(() => { if (target.fetch === wrapped) target.fetch = original })
41
+ }
42
+ refresh()
43
+ const dispose = () => { for (const restore of restorers.reverse()) restore(); restorers.length = 0 }
44
+ // A host/plugin may replace fetch after mounting. Re-observe only when a search
45
+ // begins, retaining the replacement's transport and restoring only our wrappers.
46
+ dispose.refresh = refresh
47
+ return dispose
48
+ }
@@ -22,6 +22,7 @@ export function recordNativeSearchUsage(ledgerPath, sessionId, data) {
22
22
  // Whitelist fields: no prompt, response body, credential, or Session object is persisted.
23
23
  const event = { type: NATIVE_SEARCH_USAGE_EVENT, sessionId, time: data.startedAtMs, data: {
24
24
  model: data.model, provider: data.provider, startedAtMs: data.startedAtMs, requestId: data.requestId,
25
+ ...(data.recordedBy === 'manual' ? { recordedBy: 'manual' } : {}),
25
26
  ...(data.webSource ? { webSource: data.webSource } : {}), ...(data.webSelection ? { webSelection: data.webSelection } : {}),
26
27
  ...(data.requestFee ? { requestFee: { kind: data.requestFee.kind, requests: data.requestFee.requests, rateCny: data.requestFee.rateCny, ...(data.requestFee.source ? { source: data.requestFee.source } : {}) } } : {}),
27
28
  usage: Object.fromEntries(['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'].map(key => [key, data.usage[key]])),
@@ -0,0 +1,54 @@
1
+ /** Explicit, idempotent request-fee corrections. Never infer missing model tokens. */
2
+ import { createHash } from 'node:crypto'
3
+ import { readFileSync, mkdirSync } from 'node:fs'
4
+ import { Ledger, sanitizeConfig } from './store.js'
5
+ import { withLedgerLock, writeLedger, writeDurableJson } from './ledger-persistence.js'
6
+ import { recordNativeSearchUsage } from './native-search-history.js'
7
+ import { WEB_REQUEST_RATE_CNY, SERVER_SEARCH_BILLING_START } from './web-request-pricing.js'
8
+
9
+ const hash = text => createHash('sha256').update(text).digest('hex')
10
+ const uuid = text => hash(text).slice(0, 32).replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')
11
+ export function recordManualSearchFees(path, options) {
12
+ const { id, at, session, source = 'server-tool', apply = false } = options
13
+ const count = Number(options.count), atMs = Date.parse(at)
14
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/.test(id ?? '')) throw Error('--id must be a stable correction ID (letters, digits, ._-; max 80)')
15
+ if (!Number.isSafeInteger(count) || count < 1 || count > 10000) throw Error('--count must be an integer from 1 to 10000')
16
+ if (typeof at !== 'string' || !/(Z|[+-]\d\d:\d\d)$/.test(at) || !Number.isFinite(atMs) || atMs <= 0 || atMs > Date.now()) throw Error('--at must be a past ISO timestamp with a timezone')
17
+ if (!['server-tool', 'search-api'].includes(source)) throw Error('--source must be server-tool or search-api')
18
+ if (session !== undefined && (typeof session !== 'string' || !session.trim() || session.length > 512)) throw Error('Invalid --session')
19
+ const sessionId = session ?? 'manual-search:' + id
20
+ const meta = { id, count, at: new Date(atMs).toISOString(), sessionId, source }
21
+ const key = hash('manual-search:' + id), meterSource = uuid(key) + ':' + key
22
+ const receiptPath = `${path}.native-search-manual/${key}.json`
23
+ const operation = () => {
24
+ const raw = JSON.parse(readFileSync(path, 'utf8'))
25
+ if (raw?.version !== 1 || !raw.config || !raw.days || typeof raw.days !== 'object') throw Error('Expected an existing valid cost-meter ledger')
26
+ if (atMs <= (raw.historyReset?.at ?? 0)) throw Error('The timestamp precedes the last history reset')
27
+ try {
28
+ if (JSON.stringify(JSON.parse(readFileSync(receiptPath, 'utf8'))) !== JSON.stringify(meta)) throw Error('This --id already identifies a different correction; reuse its original parameters')
29
+ } catch (error) { if (error.code !== 'ENOENT') throw error }
30
+ const alreadyRecorded = Math.min(count, raw.usageCursors?.[meterSource] ?? 0)
31
+ const rateCny = source === 'server-tool' && atMs < SERVER_SEARCH_BILLING_START ? 0 : WEB_REQUEST_RATE_CNY
32
+ const result = { id, apply, count, alreadyRecorded, added: count - alreadyRecorded, rateCny, amountCny: (count - alreadyRecorded) * rateCny,
33
+ note: 'Manual correction of confirmed successful search requests only; missing model tokens and coverage gaps are unchanged.' }
34
+ if (!apply || alreadyRecorded === count) return result
35
+ mkdirSync(`${path}.native-search-manual`, { recursive: true, mode: 0o700 })
36
+ writeDurableJson(receiptPath, meta)
37
+ const ledger = new Ledger(sanitizeConfig(raw.config), raw.days, path, raw.migrations, raw)
38
+ try {
39
+ for (let i = alreadyRecorded; i < count; i++) {
40
+ const event = { provider: 'deepseek-official', model: source === 'server-tool' ? 'deepseek-search-server' : 'deepseek-search-api',
41
+ webSource: source === 'server-tool' ? 'messages' : 'search-api', startedAtMs: atMs, requestId: uuid(key + ':' + i), recordedBy: 'manual',
42
+ requestFee: { kind: 'search', requests: 1, rateCny, ...(source === 'server-tool' ? { source } : {}) },
43
+ usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 } }
44
+ // Journal first: a retry after interruption reuses IDs, so history and the
45
+ // atomic ledger cursor both deduplicate the same correction.
46
+ recordNativeSearchUsage(path, sessionId, event)
47
+ ledger.account({}, event.model, sessionId, atMs, event.provider, { source: meterSource, seq: i + 1 }, event.requestFee)
48
+ }
49
+ writeLedger(path, ledger.snapshot())
50
+ } finally { clearTimeout(ledger.writeTimer); ledger.closed = true }
51
+ return result
52
+ }
53
+ return apply ? withLedgerLock(path, operation) : operation()
54
+ }
package/lib/store.js CHANGED
@@ -187,6 +187,7 @@ export function defaultConfig() {
187
187
  sidebarTodayMetric: 'cost',
188
188
  sidebarTodayBalanceInline: false,
189
189
  sidebarTextOnly: false, // 侧栏仅保留紧凑文本;不改变查询、计费或原有布局偏好。
190
+ planQuotaStyle: 'bars',
190
191
  sidebarOrder: [], // 侧栏组件顺序;未设置时沿用原布局。
191
192
  showTotalWithPlan: false, // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计;默认按真金白银(apiCost)
192
193
  includeSubagentCost: false, // 本会话展示可合并连续子代理后代;不重复写入每日账本。
@@ -1336,6 +1337,7 @@ export function applyConfigPatch(current, rawPatch) {
1336
1337
  if (candidate[field] !== undefined && typeof candidate[field] !== 'boolean') errors.push(vmsg(locale, 'sidebarSimple'))
1337
1338
  }
1338
1339
  if (candidate.sidebarStyle !== undefined && !['standard', 'compact', 'summary'].includes(candidate.sidebarStyle)) errors.push(vmsg(locale, 'sidebarStyle'))
1340
+ if (!['bars', 'gauge'].includes(candidate.planQuotaStyle)) errors.push('planQuotaStyle must be bars or gauge')
1339
1341
  const sm = candidate.sidebarModels
1340
1342
  if (!sm || typeof sm !== 'object' || Array.isArray(sm)
1341
1343
  || ['enabled', 'defaultOpen', 'remember', 'tokens', 'shares', 'dock'].some(k => typeof sm[k] !== 'boolean')
@@ -1744,6 +1746,7 @@ export function sanitizeConfig(raw) {
1744
1746
  : typeof value === 'number' && Number.isFinite(value) ? Math.min(k === 'topN' ? 10 : 60, Math.max(k === 'topN' ? 1 : 10, Math.floor(value))) : fallback]
1745
1747
  }))
1746
1748
  out.sidebarStyle = oneOf(out.sidebarStyle, ['standard', 'compact', 'summary'], 'standard')
1749
+ out.planQuotaStyle = oneOf(out.planQuotaStyle, ['bars', 'gauge'], 'bars')
1747
1750
  out.priceMatchDismissed = Array.isArray(out.priceMatchDismissed)
1748
1751
  ? [...new Set(out.priceMatchDismissed.filter(key => typeof key === 'string' && key.length > 0 && key.length <= 512))].slice(0, 1000)
1749
1752
  : []
@@ -281,6 +281,7 @@ const configSchema = z.object({
281
281
  billionContextNoticesSeen: z.array(z.string()).optional(),
282
282
  billingStorageRetentionDays: z.union([z.literal(0), z.literal(7), z.literal(30)]).optional(),
283
283
  sidebarStyle: z.enum(['standard', 'compact', 'summary']).optional(),
284
+ planQuotaStyle: z.enum(['bars', 'gauge']).optional(),
284
285
  priceMatchDismissed: z.array(z.string()).optional(),
285
286
  // 安装前历史自动导入完成时刻(issue #27,内部标记;0/缺席 = 尚未跑过)。
286
287
  legacyAutoImportedAt: num.optional(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cost-meter",
3
- "version": "1.9.48",
3
+ "version": "1.9.49",
4
4
  "description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(16 家,含 WorkBuddy 官方积分、OpenDesign 工作区查询、含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching), Coding Plan quota queries & display for 16 vendors (incl. WorkBuddy official credits, OpenDesign workspace queries, Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
5
5
  "type": "module",
6
6
  "main": "lib/bootstrap.js",
@@ -200,7 +200,11 @@
200
200
  "docs/update-notes-1.9.48.md",
201
201
  "docs/provider-peak-schedules.md",
202
202
  "docs/billion-context-peer-discovery.md",
203
- "docs/official-price-sync-safety.md"
203
+ "docs/official-price-sync-safety.md",
204
+ "docs/update-notes-1.9.49.md",
205
+ "docs/billing-review-2026-11-02.md",
206
+ "docs/billing-currency.md",
207
+ "docs/native-search-billing.md"
204
208
  ],
205
209
  "dependencies": {
206
210
  "acorn": "8.15.0",