dsh-cost-meter 1.9.36 → 1.9.38
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 +10 -8
- package/README.zh-CN.md +10 -8
- package/docs/update-notes-1.9.37.md +31 -0
- package/docs/update-notes-1.9.38.md +31 -0
- package/lib/billing-export.js +139 -0
- package/lib/billing-statistics.js +2 -2
- package/lib/client.js +6 -6
- package/lib/client.plan-settings.js +1 -1
- package/lib/client.settings-overview.js +1 -1
- package/lib/client.statistics.js +9 -9
- package/lib/coding-plans.js +8 -12
- package/lib/index.js +16 -6
- package/lib/ledger-writer-worker.js +1 -1
- package/lib/plan-billing.js +1 -1
- package/lib/store.js +2 -0
- package/lib/turn-cost.js +8 -4
- package/lib/typert.host.js +7 -0
- package/lib/workbuddy-accounts.js +28 -11
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
**Session cost tracking plugin for the DeepSeek Harness web GUI (bilingual UI)**
|
|
8
8
|
|
|
9
|
-
[](https://github.com/Han-1413141/dsh-cost-meter)
|
|
10
10
|
[](https://www.npmjs.com/package/dsh-cost-meter)
|
|
11
11
|
[](https://dshfind.com/zh/plugins/Han-1413141/dsh-cost-meter?ref=badge)
|
|
12
12
|
[](LICENSE)
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
|
|
17
17
|
</div>
|
|
18
18
|
|
|
19
|
-
**v1.9.
|
|
19
|
+
**v1.9.38** adds dsh-xdpool WorkBuddy credits: CN/global accounts, source selection and current/all/selected balances, with matching WorkBuddy billing classification.
|
|
20
20
|
|
|
21
21
|
**Host floor: DSH 0.2.0** · Adaptation target: **0.2.1-rc.2** (npm `next`). Expand the compatibility notes below for exact declarations, host records and troubleshooting.
|
|
22
22
|
|
|
23
|
-
Release notes: [v1.9.
|
|
23
|
+
Release notes: [v1.9.38](docs/update-notes-1.9.38.md#english). Fully restart DSH after updating.
|
|
24
24
|
|
|
25
25
|

|
|
26
26
|
|
|
@@ -132,6 +132,8 @@ The `extract` rules accept four forms: a numeric constant, a dot path string, `a
|
|
|
132
132
|
|
|
133
133
|
### WorkBuddy credits example (local plugin route)
|
|
134
134
|
|
|
135
|
+
The dedicated **WorkBuddy credits** quota card now supports dsh-xdpool. Select **Credit source → dsh-xdpool** when using multiple connectors; current, all and selected accounts work across CN/global pools. See the [integration notes](docs/update-notes-1.9.38.md#english).
|
|
136
|
+
|
|
135
137
|
With `dsh-workbuddy-connect` installed, its web status route already returns the aggregated credit total — no credential needs to be copied:
|
|
136
138
|
|
|
137
139
|
```json
|
|
@@ -352,22 +354,22 @@ On Node.js 20, use `npm install -g pnpm@10` instead. See [pnpm installation and
|
|
|
352
354
|
dsh plugin --profile web add dsh-cost-meter
|
|
353
355
|
```
|
|
354
356
|
|
|
355
|
-
**PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.9.
|
|
357
|
+
**PowerShell one-click script** (copy the whole line, paste, press Enter; pnpm is provisioned automatically, git is auto-detected — no clone needed; the install chain is **pinned to the release tag `v1.9.38`** — review the script before running):
|
|
356
358
|
|
|
357
359
|
```powershell
|
|
358
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.
|
|
360
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.38/install.ps1 | iex
|
|
359
361
|
```
|
|
360
362
|
|
|
361
363
|
**Or a plain command line** (the machine must already have pnpm and git; also pinned to the tag):
|
|
362
364
|
|
|
363
365
|
```sh
|
|
364
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.
|
|
366
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.38
|
|
365
367
|
```
|
|
366
368
|
|
|
367
369
|
Without git, use the GitHub tag archive:
|
|
368
370
|
|
|
369
371
|
```sh
|
|
370
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.
|
|
372
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.38.tar.gz
|
|
371
373
|
```
|
|
372
374
|
|
|
373
375
|
After installing, **restart** `dsh web` (plugin rows, the Typert manifest and the client bundle are all scanned at startup):
|
|
@@ -432,7 +434,7 @@ Workarounds:
|
|
|
432
434
|
|
|
433
435
|
```yaml
|
|
434
436
|
minimumReleaseAgeExclude:
|
|
435
|
-
- dsh-cost-meter@1.9.
|
|
437
|
+
- dsh-cost-meter@1.9.38
|
|
436
438
|
```
|
|
437
439
|
|
|
438
440
|
3. For a one-off CLI operation, forward the pnpm flag: `dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0` (or add `--trust-lockfile` when only lockfile verification fails). Both flags were verified against pnpm 11.28.5 in a temporary profile.
|
package/README.zh-CN.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
**DeepSeek Harness 会话费用统计插件(界面中英双语)**
|
|
8
8
|
|
|
9
|
-
[](https://github.com/Han-1413141/dsh-cost-meter)
|
|
10
10
|
[](https://www.npmjs.com/package/dsh-cost-meter)
|
|
11
11
|
[](https://dshfind.com/zh/plugins/Han-1413141/dsh-cost-meter?ref=badge)
|
|
12
12
|
[](LICENSE)
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
|
|
17
17
|
</div>
|
|
18
18
|
|
|
19
|
-
**v1.9.
|
|
19
|
+
**v1.9.38** 支持 dsh-xdpool 的国内/国际 WorkBuddy 积分、多账号筛选与来源选择,并同步适配对应路由的 API / Plan 归属。
|
|
20
20
|
|
|
21
21
|
**宿主要求:DSH 0.2.0 起支持** · 适配目标 **0.2.1-rc.2**(npm `next`)。完整声明、历史记录与安装排障见下方展开项。
|
|
22
22
|
|
|
23
|
-
更新说明:[v1.9.
|
|
23
|
+
更新说明:[v1.9.38](docs/update-notes-1.9.38.md#中文)。更新后完全重启 DSH。
|
|
24
24
|
|
|
25
25
|

|
|
26
26
|
|
|
@@ -131,6 +131,8 @@ CLIProxyAPI 网关来源卡片可勾选「只显示 Gemini 额度」,仅影响
|
|
|
131
131
|
|
|
132
132
|
### WorkBuddy 积分示例(本机插件路由)
|
|
133
133
|
|
|
134
|
+
“费用 → 额度”的 **WorkBuddy 积分** 卡现已支持 dsh-xdpool。多个连接插件同时使用时,可将“积分来源”选为 dsh-xdpool;支持国内/国际池的当前、全部或勾选账号。详见[适配说明](docs/update-notes-1.9.38.md#中文)。
|
|
135
|
+
|
|
134
136
|
已安装 `dsh-workbuddy-connect` 时,其 Web 状态路由直接返回聚合积分,无需复制任何凭据:
|
|
135
137
|
|
|
136
138
|
```json
|
|
@@ -352,22 +354,22 @@ Node.js 20 请改用 `npm install -g pnpm@10`。版本要求见 [pnpm 官方安
|
|
|
352
354
|
dsh plugin --profile web add dsh-cost-meter
|
|
353
355
|
```
|
|
354
356
|
|
|
355
|
-
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.9.
|
|
357
|
+
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.9.38`**,建议先下载审阅再运行):
|
|
356
358
|
|
|
357
359
|
```powershell
|
|
358
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.
|
|
360
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.38/install.ps1 | iex
|
|
359
361
|
```
|
|
360
362
|
|
|
361
363
|
**或直接命令行**(机器上需已有 pnpm 与 git;同样固定到 tag):
|
|
362
364
|
|
|
363
365
|
```sh
|
|
364
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.
|
|
366
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.38
|
|
365
367
|
```
|
|
366
368
|
|
|
367
369
|
没有 git 时可用 GitHub tag 打包直链:
|
|
368
370
|
|
|
369
371
|
```sh
|
|
370
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.
|
|
372
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.38.tar.gz
|
|
371
373
|
```
|
|
372
374
|
|
|
373
375
|
安装后**重启** `dsh web`(插件行、Typert 清单与客户端 bundle 均在启动时扫描):
|
|
@@ -432,7 +434,7 @@ DSH **0.2.1-rc.1 / 0.2.1-rc.2** 宿主自带 pnpm **11.28.5**,默认启用内
|
|
|
432
434
|
|
|
433
435
|
```yaml
|
|
434
436
|
minimumReleaseAgeExclude:
|
|
435
|
-
- dsh-cost-meter@1.9.
|
|
437
|
+
- dsh-cost-meter@1.9.38
|
|
436
438
|
```
|
|
437
439
|
|
|
438
440
|
3. 仅本次操作用 CLI 透传 pnpm 参数:`dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0`;若只是 lockfile 校验阶段失败,可改用 `--trust-lockfile`。这两个参数已在本机 pnpm 11.28.5 临时 Profile 上实测可用。
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# v1.9.37:对话费用导出与额度窗口排序
|
|
2
|
+
|
|
3
|
+
## 中文
|
|
4
|
+
|
|
5
|
+
打开单个对话的“费用明细”,点击右上角“导出费用记录”,即可导出该对话。费用设置的“概览”也增加了统一入口;“计费统计”右上角可以导出当前筛选范围或全部保留记录。
|
|
6
|
+
|
|
7
|
+
支持三种格式:
|
|
8
|
+
|
|
9
|
+
- CSV 汇总:每个对话一行,使用账本中保存的费用和 Token。
|
|
10
|
+
- CSV 调用明细:每次调用一行,包含对话、模型、时间、Token 和费用。
|
|
11
|
+
- JSON 完整费用记录:包含账本汇总、调用明细及计费单价,便于自行处理。
|
|
12
|
+
|
|
13
|
+
文件同时保留 API 费用和 Plan 等值,金额使用当前显示币种;有历史价格和汇率记录时沿用历史记录。导出不受界面 25 个对话 / 50 次调用分页限制。开启“计入子代理费用”时,子代理归入所属对话,每次调用只导出一次。
|
|
14
|
+
|
|
15
|
+
导出不包含对话正文、工具输入输出或凭据。对话 ID 和标题会保留,分享前可自行修改。若调用日志缺失或与账本不同,文件及下载提示会标注;JSON 和汇总 CSV 保留账本金额,调用 CSV 不补造缺失调用。未归属到对话的旧账单独列在总体汇总中。
|
|
16
|
+
|
|
17
|
+
导出期间可取消。文件上限 64 MiB、调用明细上限 20 万条,超限时提示缩小范围,不会静默截断。导出只生成本地下载文件,不上传记录。
|
|
18
|
+
|
|
19
|
+
额度窗口按 5h → 日 → 周 → 月排列,只显示该订阅实际支持的窗口。根据[火山官方说明](https://docs.volcengine.com/docs/ark/coding-plan-personal-faq?lang=zh),火山 Coding Plan 只有 5h、周和订阅月;此次删除混入的日窗口。其他产品原有的日额度继续保留。
|
|
20
|
+
|
|
21
|
+
## English
|
|
22
|
+
|
|
23
|
+
Use **Export cost records** in a conversation's cost details to export that conversation. The cost settings overview also has an export entry; the statistics page supports current filters or all retained records.
|
|
24
|
+
|
|
25
|
+
Choose summary CSV (one row per conversation), call CSV (one row per call), or JSON with recorded totals, call details and rates. Files include API costs and Plan equivalents in the selected display currency, using retained historical pricing and FX where available. Conversation and call pagination does not limit exports. Enabled subagent costs belong to their conversation and are exported once.
|
|
26
|
+
|
|
27
|
+
Conversation IDs/titles are included; message text, tool content and credentials are excluded. Missing or differing details are marked. JSON and summary CSV preserve recorded ledger amounts; call CSV never fabricates missing calls. Unassigned legacy ledger amounts appear separately in overall summaries.
|
|
28
|
+
|
|
29
|
+
Downloads can be cancelled and are local only. Exports above 64 MiB or 200,000 calls ask for a narrower range instead of truncating data.
|
|
30
|
+
|
|
31
|
+
Supported quota windows are ordered 5h, daily, weekly, monthly. Volcano Coding Plan only displays its official 5h, weekly and subscription-month windows. Daily windows for other products remain available.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# v1.9.38:dsh-xdpool 的 WorkBuddy 积分适配
|
|
2
|
+
|
|
3
|
+
## 中文
|
|
4
|
+
|
|
5
|
+
在“费用 → 额度”开启并展开“WorkBuddy 积分”,即可读取同一 DSH 中的 dsh-xdpool 账号积分,无需复制登录凭据。已验证 dsh-xdpool 2.4.6 的发布包接口。
|
|
6
|
+
|
|
7
|
+
“积分来源”支持自动识别、WorkBuddy 连接插件和 dsh-xdpool。自动识别优先读取 dsh-connect-workbuddy 的账号列表,其次读取 XD Pool;旧连接插件的状态接口与明文登录文件兼容方式继续保留。多个插件同时使用时,选择 dsh-xdpool 并刷新即可指定来源。
|
|
8
|
+
|
|
9
|
+
“统计账号”继续支持当前账号、全部账号和勾选账号。XD Pool 的当前账号按其状态接口返回的 activeAccountId 确定,国内和国际分别读取。账号 ID 区分地区和插件来源,已有的连接插件账号筛选不会误选同 ID 的池账号。
|
|
10
|
+
|
|
11
|
+
积分读取失败、冷却期间未返回积分或已移除的勾选账号显示未知值,完整汇总显示“—”;已读取的积分可在账号列表查看。观测减少量沿用现有统计规则:充值或赠送不算减少,过期可能算减少,积分不折算为货币账单。
|
|
12
|
+
|
|
13
|
+
xdpool 和 xdpool-global 两条 WorkBuddy 路由按现有 WorkBuddy 的 API / Plan 设置归类,并尊重手动覆盖。升级时仅修正账本的 API / Plan 归属,保留总金额、Token、调用和历史汇率;其他聚合、扫码及组合路由不据此归入 WorkBuddy。
|
|
14
|
+
|
|
15
|
+
兼容验证执行了发布包中的实际状态路由与序列化函数,并检查国内/国际账号、来源选择、失败及冷却状态、双端 codec、保存后重开和窄屏设置界面。积分查询使用同一宿主的 GET 状态接口,不执行切号、签到、自动化或模型测试。
|
|
16
|
+
|
|
17
|
+
需求建议来自 [@qiyeren 的 issue #404](https://github.com/Han-1413141/dsh-cost-meter/issues/404);接口来源为 [@XDTrees 维护的 dsh-xdpool](https://github.com/XDTrees/dsh-xdpool)。
|
|
18
|
+
|
|
19
|
+
## English
|
|
20
|
+
|
|
21
|
+
Enable **WorkBuddy credits** under cost settings → quotas to read dsh-xdpool accounts from the same DSH host. No credential copying is required. Compatibility was checked against the published dsh-xdpool 2.4.6 status route and serializers.
|
|
22
|
+
|
|
23
|
+
**Credit source** supports Automatic, WorkBuddy connectors and dsh-xdpool. Automatic uses dsh-connect-workbuddy account lists first, then XD Pool. Select dsh-xdpool and refresh when multiple connectors are installed. Existing legacy connector/file compatibility remains available.
|
|
24
|
+
|
|
25
|
+
Current, all and selected accounts are supported. Current uses the pool's activeAccountId per region. Account IDs include region and source so selections and observed credit decreases do not mix different plugins. Missing, failed or unavailable cooling balances remain unknown, and incomplete totals display a dash.
|
|
26
|
+
|
|
27
|
+
Only xdpool and xdpool-global belong to WorkBuddy billing. Existing API / Plan settings and explicit overrides apply. Historical classification repairs preserve recorded totals, tokens, calls and FX. Other aggregate, OAuth and combo routes are not treated as WorkBuddy credits.
|
|
28
|
+
|
|
29
|
+
Tests cover the published status implementation, source selection, partial data, codecs, persistence and narrow layouts. Integration only reads local GET status endpoints; it does not switch accounts, claim rewards, run automation or probe models.
|
|
30
|
+
|
|
31
|
+
Requested by [@qiyeren in issue #404](https://github.com/Han-1413141/dsh-cost-meter/issues/404), using the public interface maintained by [@XDTrees](https://github.com/XDTrees/dsh-xdpool).
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/** Explicit, local-only exports. Jobs retain immutable bytes; RPC transports bounded chunks. */
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { setImmediate } from 'node:timers/promises'
|
|
4
|
+
import { currencyLedger } from './currency-view.js'
|
|
5
|
+
import { billingStatistics, ledgerStatisticsQuery, STAT_FIELDS } from './billing-statistics.js'
|
|
6
|
+
import { getSessionBillingSnapshot } from './turn-cost.js'
|
|
7
|
+
import { readSessionHeaders, sessionCostIds } from './session-tree.js'
|
|
8
|
+
import { bindPricingHistory, pricingHistoryOf } from './billing-history.js'
|
|
9
|
+
|
|
10
|
+
const MAX_BYTES = 64 * 1024 * 1024, CHUNK_BYTES = 48 * 1024, TTL = 10 * 60_000
|
|
11
|
+
const numeric = value => typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
12
|
+
const buckets = (row, factor = 1) => Object.fromEntries(STAT_FIELDS.map(key => [key, numeric(row?.[key]) * (['cost', 'apiCost'].includes(key) ? factor : 1)]))
|
|
13
|
+
const same = (a, b) => Math.abs(a - b) <= Math.max(1e-8, Math.abs(a) * 1e-8)
|
|
14
|
+
const cell = value => {
|
|
15
|
+
let text = value == null ? '' : String(value)
|
|
16
|
+
if (typeof value === 'string' && /^[\s\x00-\x1f]*[=+@-]/.test(text)) text = "'" + text
|
|
17
|
+
return '"' + text.replaceAll('"', '""') + '"'
|
|
18
|
+
}
|
|
19
|
+
export function billingExportCsv(headers, rows) {
|
|
20
|
+
return '\uFEFF' + [headers, ...rows].map(row => row.map(cell).join(',')).join('\r\n') + '\r\n'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function encodeBillingExport(data, format) {
|
|
24
|
+
if (format === 'json') return JSON.stringify(data, null, 2) + '\n'
|
|
25
|
+
const en = data.locale === 'en', text = (zh, english) => en ? english : zh
|
|
26
|
+
const common = [text('对话 ID', 'Conversation ID'), text('对话标题', 'Conversation title'), text('币种', 'Currency')]
|
|
27
|
+
if (format === 'csv-summary') {
|
|
28
|
+
const headers = [...common, text('调用次数', 'Calls'), 'Input tokens', 'Cache read tokens', 'Cache write tokens', 'Output tokens', 'Reasoning tokens',
|
|
29
|
+
text('账本总费用', 'Recorded total cost'), text('API 费用', 'API cost'), text('Plan 等值', 'Plan equivalent'), text('已解析调用', 'Parsed calls'), text('明细状态', 'Detail status')]
|
|
30
|
+
return billingExportCsv(headers, data.sessions.map(row => [row.id, row.title, data.currency, row.recorded.calls, row.recorded.input, row.recorded.cacheRead, row.recorded.cacheWrite, row.recorded.output, row.recorded.reasoning,
|
|
31
|
+
row.recorded.cost, row.recorded.apiCost, Math.max(0, row.recorded.cost - row.recorded.apiCost), row.calls.length, row.detailStatus]))
|
|
32
|
+
}
|
|
33
|
+
const headers = [...common, text('实际会话 ID', 'Actual session ID'), text('时间 (UTC)', 'Time (UTC)'), text('类型', 'Kind'), text('轮次', 'Turn'), text('步骤', 'Step'), text('渠道', 'Provider'), text('模型', 'Model'),
|
|
34
|
+
'Input tokens', 'Cache read tokens', 'Cache write tokens', 'Output tokens', 'Reasoning tokens', text('费用', 'Cost'), text('API 费用', 'API cost'), text('Plan 等值', 'Plan equivalent'), text('已定价', 'Priced'),
|
|
35
|
+
text('会话账本总额(参考)', 'Conversation ledger total (reference)'), text('会话明细状态', 'Conversation detail status')]
|
|
36
|
+
return billingExportCsv(headers, data.sessions.flatMap(row => row.calls.map(call => [row.id, row.title, data.currency, call.sessionId, new Date(call.atMs).toISOString(), call.kind, call.turn, call.step, call.provider, call.model,
|
|
37
|
+
call.input, call.cacheRead, call.cacheWrite, call.output, call.reasoning, call.cost, call.apiCost, Math.max(0, call.cost - call.apiCost), call.priced, row.recorded.cost, row.detailStatus])))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Internal detail snapshots never cross RPC without pagination. Only whitelisted billing fields leave here. */
|
|
41
|
+
export async function collectBillingExport(ledger, ctx, raw, { active = () => true, progress = () => {}, detail = getSessionBillingSnapshot, now = Date.now } = {}) {
|
|
42
|
+
const cutoff = now(), query = ledgerStatisticsQuery(ledger, { ...raw, basis: 'total' })
|
|
43
|
+
// Analytics transports USD-normalized display values; files contain real units
|
|
44
|
+
// of their declared currency, including the saved historical FX amounts.
|
|
45
|
+
const factor = ledger.config._displayCurrency ? ledger.config.exchangeRate : 1
|
|
46
|
+
const ids = query.sessionId ? await sessionCostIds(ledger, ctx, query.sessionId) : null
|
|
47
|
+
const headers = !query.sessionId && ledger.config.includeSubagentCost ? await readSessionHeaders(ctx) : []
|
|
48
|
+
const stats = billingStatistics(ledger, query, ids, headers, { allSessions: true })
|
|
49
|
+
const rows = query.sessionId ? [{ id: query.sessionId, title: stats.sessions.find(row => row.id === query.sessionId)?.title || query.sessionId, ...stats.totals }] : stats.sessions
|
|
50
|
+
const data = { schema: 'dsh-cost-meter/billing-export/v1', exportedAt: new Date(cutoff).toISOString(), currency: raw.displayCurrency || ledger.config.currency || 'USD', locale: raw.locale === 'en' ? 'en' : 'zh',
|
|
51
|
+
from: query.from, to: query.to, provider: query.provider, model: query.model, includeSubagents: ledger.config.includeSubagentCost === true, totals: buckets(stats.totals, factor), unassignedCost: stats.unassignedCost * factor, sessions: [] }
|
|
52
|
+
let count = 0
|
|
53
|
+
for (const row of rows) {
|
|
54
|
+
if (!active()) throw new Error('cancelled')
|
|
55
|
+
const session = { id: row.id, title: row.title || row.id, recorded: buckets(row, factor), detailStatus: 'complete', calls: [] }
|
|
56
|
+
if (raw.format !== 'csv-summary') {
|
|
57
|
+
try {
|
|
58
|
+
const full = await detail(ledger, ctx, { ...query, sessionId: row.id, background: false })
|
|
59
|
+
if (!active()) throw new Error('cancelled')
|
|
60
|
+
for (const call of full.calls) {
|
|
61
|
+
if (call.atMs > cutoff) continue
|
|
62
|
+
const tokens = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, reasoning: 0 }
|
|
63
|
+
for (const part of call.rows) if (Object.hasOwn(tokens, part.bucket)) tokens[part.bucket] += numeric(part.tokens)
|
|
64
|
+
session.calls.push({ sessionId: call.sessionId || row.id, atMs: call.atMs, kind: call.kind, turn: call.turn, step: call.step, provider: call.provider, model: call.model,
|
|
65
|
+
...tokens, cost: numeric(call.cost) * factor, apiCost: numeric(call.apiCost) * factor, plan: call.plan === true, priced: call.priced === true,
|
|
66
|
+
rates: call.rows.map(part => ({ bucket: part.bucket, tokens: numeric(part.tokens), requests: numeric(part.requests), rate: numeric(part.rate) * factor, cost: numeric(part.cost) * factor, priced: part.priced === true })) })
|
|
67
|
+
if (++count > 200000) throw new Error('EXPORT_LIMIT')
|
|
68
|
+
}
|
|
69
|
+
if (session.calls.length !== row.calls || !same(session.calls.reduce((sum, call) => sum + call.cost, 0), session.recorded.cost)) session.detailStatus = 'ledger-detail-difference'
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (!active() || error.message === 'EXPORT_LIMIT') throw error
|
|
72
|
+
session.detailStatus = 'details-unavailable'
|
|
73
|
+
}
|
|
74
|
+
} else session.detailStatus = 'not-requested'
|
|
75
|
+
data.sessions.push(session)
|
|
76
|
+
progress(data.sessions.length, rows.length)
|
|
77
|
+
await setImmediate()
|
|
78
|
+
}
|
|
79
|
+
if (!query.sessionId) {
|
|
80
|
+
const assigned = Object.fromEntries(STAT_FIELDS.map(key => [key, data.sessions.reduce((sum, row) => sum + row.recorded[key], 0)]))
|
|
81
|
+
const remaining = Object.fromEntries(STAT_FIELDS.map(key => [key, Math.max(0, data.totals[key] - assigned[key])]))
|
|
82
|
+
if (Object.values(remaining).some(value => value > 1e-8)) data.sessions.push({ id: '', title: data.locale === 'en' ? 'Ledger entries without a conversation' : '未归属对话的账本记录', recorded: remaining, detailStatus: 'ledger-only', calls: [] })
|
|
83
|
+
}
|
|
84
|
+
return data
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function createBillingExporter(ledger, ctx, { now = Date.now, collect = collectBillingExport } = {}) {
|
|
88
|
+
const jobs = new Map(); let closed = false
|
|
89
|
+
const response = (job, offset = 0) => {
|
|
90
|
+
const bytes = job.bytes ?? Buffer.alloc(0), nextOffset = Math.min(bytes.length, offset + CHUNK_BYTES)
|
|
91
|
+
return { id: job.id, status: job.status, filename: job.filename, mime: job.mime, totalBytes: bytes.length, offset, nextOffset, data: bytes.subarray(offset, nextOffset).toString('base64'),
|
|
92
|
+
completedSessions: job.completedSessions, totalSessions: job.totalSessions, rows: job.rows, message: job.message }
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
get(raw = {}) {
|
|
96
|
+
const time = now()
|
|
97
|
+
for (const [id, job] of jobs) if (time - job.touched > TTL) { job.cancelled = true; jobs.delete(id) }
|
|
98
|
+
if (closed) throw new Error('Export service is closed')
|
|
99
|
+
if (raw.id) {
|
|
100
|
+
const job = jobs.get(raw.id)
|
|
101
|
+
if (!job) throw new Error('Export expired; start again')
|
|
102
|
+
job.touched = time
|
|
103
|
+
if (raw.cancel === true) { job.cancelled = true; jobs.delete(raw.id); return response({ ...job, status: 'cancelled', bytes: null }) }
|
|
104
|
+
const offset = raw.offset ?? 0
|
|
105
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || offset > (job.bytes?.length ?? 0)) throw new Error('Invalid export offset')
|
|
106
|
+
return response(job, offset)
|
|
107
|
+
}
|
|
108
|
+
if (jobs.size >= 2) throw new Error('Two exports are already active; close one before starting another')
|
|
109
|
+
if (!['csv-summary', 'csv-calls', 'json'].includes(raw.format)) throw new Error('Invalid export format')
|
|
110
|
+
if (raw.displayCurrency && !['USD', 'CNY', 'EUR'].includes(raw.displayCurrency)) throw new Error('Invalid export currency')
|
|
111
|
+
ledger.refresh?.()
|
|
112
|
+
const request = { ...raw, displayCurrency: raw.displayCurrency || ledger.config.currency || 'USD' }
|
|
113
|
+
const config = bindPricingHistory(structuredClone(ledger.config), structuredClone(pricingHistoryOf(ledger.config)))
|
|
114
|
+
const frozen = currencyLedger({ path: ledger.path, days: structuredClone(ledger.days), _config: config, get config() { return this._config } }, request.displayCurrency)
|
|
115
|
+
ledgerStatisticsQuery(frozen, request)
|
|
116
|
+
const id = randomUUID(), suffix = (raw.sessionId || 'all-conversations').replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 60)
|
|
117
|
+
const job = { id, touched: time, status: 'preparing', cancelled: false, completedSessions: 0, totalSessions: 0, rows: 0, message: '',
|
|
118
|
+
filename: `dsh-cost-${suffix}-${new Date(time).toISOString().replace(/[:.]/g, '-')}.${raw.format === 'json' ? 'json' : 'csv'}`, mime: raw.format === 'json' ? 'application/json;charset=utf-8' : 'text/csv;charset=utf-8' }
|
|
119
|
+
jobs.set(id, job)
|
|
120
|
+
const active = () => !closed && !job.cancelled && jobs.get(id) === job
|
|
121
|
+
Promise.resolve().then(async () => {
|
|
122
|
+
const data = await collect(frozen, ctx, request, { now: () => time, active, progress: (completed, total) => { job.completedSessions = completed; job.totalSessions = total } })
|
|
123
|
+
if (!active()) return
|
|
124
|
+
const bytes = Buffer.from(encodeBillingExport(data, raw.format))
|
|
125
|
+
if (bytes.length > MAX_BYTES) throw new Error('EXPORT_LIMIT')
|
|
126
|
+
job.rows = raw.format === 'csv-summary' ? data.sessions.length : data.sessions.reduce((sum, row) => sum + row.calls.length, 0)
|
|
127
|
+
const incomplete = data.sessions.filter(row => !['complete', 'not-requested'].includes(row.detailStatus)).length
|
|
128
|
+
if (incomplete) job.message = raw.locale === 'en' ? `${incomplete} conversation(s) have missing or differing call details. JSON and summary CSV preserve recorded ledger totals.` : `${incomplete} 个对话的调用明细缺失或与账本不同;JSON 和汇总 CSV 保留账本金额。`
|
|
129
|
+
job.bytes = bytes; job.status = 'ready'
|
|
130
|
+
}).catch(error => {
|
|
131
|
+
if (!active()) return
|
|
132
|
+
job.status = 'error'
|
|
133
|
+
job.message = error.message === 'EXPORT_LIMIT' ? (raw.locale === 'en' ? 'Export is too large. Select a smaller date range or one conversation.' : '记录过多,请缩小日期范围或选择单个对话。') : (raw.locale === 'en' ? 'Export failed. Try again.' : '导出失败,请重试。')
|
|
134
|
+
})
|
|
135
|
+
return response(job)
|
|
136
|
+
},
|
|
137
|
+
dispose() { closed = true; for (const job of jobs.values()) job.cancelled = true; jobs.clear() },
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -37,7 +37,7 @@ export function selectedStats(container, query) {
|
|
|
37
37
|
return total
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
export function billingStatistics(ledger, raw, sessionIds = null, headers = []) {
|
|
40
|
+
export function billingStatistics(ledger, raw, sessionIds = null, headers = [], { allSessions = false } = {}) {
|
|
41
41
|
const query = ledgerStatisticsQuery(ledger, raw), totals = emptyStats(), days = [], models = new Map(), sessions = new Map()
|
|
42
42
|
const providers = new Set(), modelOptions = new Set(), retained = Object.keys(ledger.days ?? {}).sort()
|
|
43
43
|
const assigned = emptyStats(), modeled = emptyStats()
|
|
@@ -82,7 +82,7 @@ export function billingStatistics(ledger, raw, sessionIds = null, headers = [])
|
|
|
82
82
|
const sort = (a, b) => valueOf(b, query.basis) - valueOf(a, query.basis) || b.calls - a.calls || String(a.id ?? a.key).localeCompare(String(b.id ?? b.key))
|
|
83
83
|
return { from: query.from, to: query.to, retainedFrom: retained[0] ?? '', retainedTo: retained.at(-1) ?? '',
|
|
84
84
|
totals, days, models: [...models.values()].sort(sort), providers: [...providers].sort(), modelOptions: [...modelOptions].sort(),
|
|
85
|
-
sessions: [...sessions.values()].sort(sort).slice(query.offset, query.offset + 25), sessionCount: sessions.size, offset: query.offset,
|
|
85
|
+
sessions: allSessions ? [...sessions.values()].sort(sort) : [...sessions.values()].sort(sort).slice(query.offset, query.offset + 25), sessionCount: sessions.size, offset: query.offset,
|
|
86
86
|
unassignedCost: Math.max(0, valueOf(totals, query.basis) - valueOf(assigned, query.basis)),
|
|
87
87
|
unmodeledCost: Math.max(0, valueOf(totals, query.basis) - valueOf(modeled, query.basis)),
|
|
88
88
|
}
|