dsh-cost-meter 1.9.36 → 1.9.37
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 +8 -8
- package/README.zh-CN.md +8 -8
- package/docs/update-notes-1.9.37.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 +7 -11
- package/lib/index.js +4 -0
- package/lib/turn-cost.js +8 -4
- package/lib/typert.host.js +6 -0
- package/package.json +3 -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.37** adds single-conversation and overall billing exports (CSV / JSON), and orders quota windows consistently. Volcano Coding Plan now shows only its supported 5h, weekly and monthly windows.
|
|
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.37](docs/update-notes-1.9.37.md#english). Fully restart DSH after updating.
|
|
24
24
|
|
|
25
25
|

|
|
26
26
|
|
|
@@ -352,22 +352,22 @@ On Node.js 20, use `npm install -g pnpm@10` instead. See [pnpm installation and
|
|
|
352
352
|
dsh plugin --profile web add dsh-cost-meter
|
|
353
353
|
```
|
|
354
354
|
|
|
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.
|
|
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.37`** — review the script before running):
|
|
356
356
|
|
|
357
357
|
```powershell
|
|
358
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.
|
|
358
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.37/install.ps1 | iex
|
|
359
359
|
```
|
|
360
360
|
|
|
361
361
|
**Or a plain command line** (the machine must already have pnpm and git; also pinned to the tag):
|
|
362
362
|
|
|
363
363
|
```sh
|
|
364
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.
|
|
364
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.37
|
|
365
365
|
```
|
|
366
366
|
|
|
367
367
|
Without git, use the GitHub tag archive:
|
|
368
368
|
|
|
369
369
|
```sh
|
|
370
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.
|
|
370
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.37.tar.gz
|
|
371
371
|
```
|
|
372
372
|
|
|
373
373
|
After installing, **restart** `dsh web` (plugin rows, the Typert manifest and the client bundle are all scanned at startup):
|
|
@@ -432,7 +432,7 @@ Workarounds:
|
|
|
432
432
|
|
|
433
433
|
```yaml
|
|
434
434
|
minimumReleaseAgeExclude:
|
|
435
|
-
- dsh-cost-meter@1.9.
|
|
435
|
+
- dsh-cost-meter@1.9.37
|
|
436
436
|
```
|
|
437
437
|
|
|
438
438
|
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.37** 新增单个对话和总体费用导出(CSV / JSON),统一额度窗口顺序;火山 Coding Plan 只显示实际支持的 5h、周、月。
|
|
20
20
|
|
|
21
21
|
**宿主要求:DSH 0.2.0 起支持** · 适配目标 **0.2.1-rc.2**(npm `next`)。完整声明、历史记录与安装排障见下方展开项。
|
|
22
22
|
|
|
23
|
-
更新说明:[v1.9.
|
|
23
|
+
更新说明:[v1.9.37](docs/update-notes-1.9.37.md#中文)。更新后完全重启 DSH。
|
|
24
24
|
|
|
25
25
|

|
|
26
26
|
|
|
@@ -352,22 +352,22 @@ Node.js 20 请改用 `npm install -g pnpm@10`。版本要求见 [pnpm 官方安
|
|
|
352
352
|
dsh plugin --profile web add dsh-cost-meter
|
|
353
353
|
```
|
|
354
354
|
|
|
355
|
-
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.9.
|
|
355
|
+
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.9.37`**,建议先下载审阅再运行):
|
|
356
356
|
|
|
357
357
|
```powershell
|
|
358
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.
|
|
358
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.37/install.ps1 | iex
|
|
359
359
|
```
|
|
360
360
|
|
|
361
361
|
**或直接命令行**(机器上需已有 pnpm 与 git;同样固定到 tag):
|
|
362
362
|
|
|
363
363
|
```sh
|
|
364
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.
|
|
364
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.37
|
|
365
365
|
```
|
|
366
366
|
|
|
367
367
|
没有 git 时可用 GitHub tag 打包直链:
|
|
368
368
|
|
|
369
369
|
```sh
|
|
370
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.
|
|
370
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.9.37.tar.gz
|
|
371
371
|
```
|
|
372
372
|
|
|
373
373
|
安装后**重启** `dsh web`(插件行、Typert 清单与客户端 bundle 均在启动时扫描):
|
|
@@ -432,7 +432,7 @@ DSH **0.2.1-rc.1 / 0.2.1-rc.2** 宿主自带 pnpm **11.28.5**,默认启用内
|
|
|
432
432
|
|
|
433
433
|
```yaml
|
|
434
434
|
minimumReleaseAgeExclude:
|
|
435
|
-
- dsh-cost-meter@1.9.
|
|
435
|
+
- dsh-cost-meter@1.9.37
|
|
436
436
|
```
|
|
437
437
|
|
|
438
438
|
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,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
|
}
|