dsh-cost-meter 1.8.21 → 1.8.22
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 +6 -6
- package/README.zh-CN.md +6 -6
- package/docs/context-costs-design.md +4 -2
- package/docs/qwen-cli-quota.md +5 -4
- package/lib/bailian-cli.js +25 -6
- package/lib/client.statistics.js +8 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
Per-conversation cost · daily totals · OpenCode Go subscription quota display · budget with usage percentage · official account balance · custom provider balance · balance progress bar · history · peak/off-peak pricing hours display (peak hours UTC 01:00–04:00, 06:00–10:00; weekends and Chinese public holidays are off-peak all day, with separate labels) · pre-switch popup & system-notification alerts for peak/off-peak changes (position / lead time / alert type configurable) · one-click price sync from the official docs · Codex-style token usage heat grid · multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching) · mainstream Coding Plan quota queries & display (Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / Volcano Ark / Qwen / Xiaomi MiMo) plan/API dual-track billing (subscription quota vs pay-as-you-go money separated, per-1% & full-window token/equivalent-cost estimates with daily/weekly/monthly curves) · · quota strip above the input box (budget / Go / coding-plan usage in one row, toggleable)
|
|
10
10
|
|
|
11
|
-
[](https://github.com/Han-1413141/dsh-cost-meter)
|
|
12
12
|
|
|
13
|
-
**v1.8.
|
|
13
|
+
**v1.8.22** fixes duplicate Context tabs and integration cleanup after repeated toggles, and restores monthly Token Plan quotas from Bailian CLI. The native conversation tab stays unchanged, and turning integration off immediately removes its cost regions. Published dsh-context 0.62.0, 0.66.0 and 0.68.1 are covered. If an older client already left duplicate tabs, reload the client or restart the host once after updating. See the [guide](docs/context-costs-design.md#english).
|
|
14
14
|
|
|
15
15
|
Desktop users: follow the [Desktop installation instructions](docs/install-troubleshooting.md#desktop-安装与更新) for the application's own CLI and `desktop` Profile.
|
|
16
16
|
|
|
@@ -323,22 +323,22 @@ On Node.js 20, use `npm install -g pnpm@10` instead. See [pnpm installation and
|
|
|
323
323
|
dsh plugin --profile web add dsh-cost-meter
|
|
324
324
|
```
|
|
325
325
|
|
|
326
|
-
**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.8.
|
|
326
|
+
**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.8.22`** — review the script before running):
|
|
327
327
|
|
|
328
328
|
```powershell
|
|
329
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.
|
|
329
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.22/install.ps1 | iex
|
|
330
330
|
```
|
|
331
331
|
|
|
332
332
|
**Or a plain command line** (the machine must already have pnpm and git; also pinned to the tag):
|
|
333
333
|
|
|
334
334
|
```sh
|
|
335
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.
|
|
335
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.22
|
|
336
336
|
```
|
|
337
337
|
|
|
338
338
|
Without git, use the GitHub tag archive:
|
|
339
339
|
|
|
340
340
|
```sh
|
|
341
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.
|
|
341
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.22.tar.gz
|
|
342
342
|
```
|
|
343
343
|
|
|
344
344
|
After installing, **restart** `dsh web` (plugin rows, the Typert manifest and the client bundle are all scanned at startup):
|
package/README.zh-CN.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
本会话费用 · 当日费用 · OpenCode Go 订阅额度显示 · 预算与已用百分比 · 官方账户余额 · 自定义 Provider 余额查询(可配任意 HTTP 端点) · 余额三段进度条 · 历史记录 · 峰谷计价时段显示(UTC 01:00–04:00、06:00–10:00 为峰时段;周末与中国法定假日全天按谷价,分别标注) · 峰/谷切换前弹窗与系统通知提醒(位置/提前量/提醒类型可配) · 官方价格一键同步 · 类 Codex Token 用量热图 · 多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配) · 主流 Coding Plan 额度查询与显示(Anthropic / Z.ai / MiniMax / Kimi / OpenRouter / SiliconFlow / CommandCode / SCNet / 火山方舟 / 千问 / 小米 MiMo 十一家,含 Volcano Ark AK/SK 签名与 MiMo 控制台 Cookie 查询) · Plan/API 双轨计费(订阅额度与按量金额分离统计,每 1% 额度与满窗的 token/等值金额估算及日/周/月曲线) · 输入框上方额度横条(预算/Go/Coding Plan 用量一条横排显示,可开关)
|
|
10
10
|
|
|
11
|
-
[](https://github.com/Han-1413141/dsh-cost-meter)
|
|
12
12
|
|
|
13
|
-
**v1.8.
|
|
13
|
+
**v1.8.22** 修复 dsh-context 重复页签、关闭残留,以及百炼 CLI 月额度卡片空白的问题。会话页保留原生页签,关闭联动立即移除费用区域;覆盖 0.62.0、0.66.0、0.68.1。如旧客户端已累积重复页签,更新后重新加载客户端或重启宿主一次。详见[使用说明](docs/context-costs-design.md)。
|
|
14
14
|
|
|
15
15
|
桌面端用户请按 [Desktop 安装说明](docs/install-troubleshooting.md#desktop-安装与更新),使用应用自带的 CLI 和 `desktop` Profile。
|
|
16
16
|
|
|
@@ -323,22 +323,22 @@ Node.js 20 请改用 `npm install -g pnpm@10`。版本要求见 [pnpm 官方安
|
|
|
323
323
|
dsh plugin --profile web add dsh-cost-meter
|
|
324
324
|
```
|
|
325
325
|
|
|
326
|
-
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.8.
|
|
326
|
+
**PowerShell 一键脚本**(复制整行粘贴回车;自动补齐 pnpm、自动探测 git,无需克隆仓库;安装链**固定到发布 tag `v1.8.22`**,建议先下载审阅再运行):
|
|
327
327
|
|
|
328
328
|
```powershell
|
|
329
|
-
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.
|
|
329
|
+
irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.8.22/install.ps1 | iex
|
|
330
330
|
```
|
|
331
331
|
|
|
332
332
|
**或直接命令行**(机器上需已有 pnpm 与 git;同样固定到 tag):
|
|
333
333
|
|
|
334
334
|
```sh
|
|
335
|
-
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.
|
|
335
|
+
dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.8.22
|
|
336
336
|
```
|
|
337
337
|
|
|
338
338
|
没有 git 时可用 GitHub tag 打包直链:
|
|
339
339
|
|
|
340
340
|
```sh
|
|
341
|
-
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.
|
|
341
|
+
dsh plugin --profile web add https://github.com/Han-1413141/dsh-cost-meter/archive/refs/tags/v1.8.22.tar.gz
|
|
342
342
|
```
|
|
343
343
|
|
|
344
344
|
安装后**重启** `dsh web`(插件行、Typert 清单与客户端 bundle 均在启动时扫描):
|
|
@@ -61,7 +61,9 @@ dsh-context 主要展示上下文占用、组成、变化和注入事件。0.66.
|
|
|
61
61
|
- 开关和“已提示”状态保存在本插件配置中。关闭按钮、Esc、点击遮罩和“暂不启用”均可退出;退出不等待保存请求。浏览器另存提示记录,防止保存失败、重新载入或多个页面造成反复提示。
|
|
62
62
|
- 用户手动重开预览再关闭,不改变已经启用的开关。设置中始终保留开关与预览入口。
|
|
63
63
|
- 自动提示等其他弹窗关闭后再出现。短窗口保持关闭按钮和操作区可见,避开 DSH 桌面标题栏,支持键盘焦点限制与关闭后恢复焦点。
|
|
64
|
-
- 复用 dsh-context 的公开 `contextTimeline.current`
|
|
64
|
+
- 复用 dsh-context 的公开 `contextTimeline.current` 分类;不修改对方文件或注册。会话页保留原始 `conversation.view`,通过独立的会话输入区挂载点向同一会话的当前卡片添加费用区域,避免宿主按原始插槽记录生成重复页签。侧栏与 `/context` 弹窗仍使用公共插槽优先级包装,保留原 props、语言、会话和 hooks。关闭或卸载时撤销自己的注册与观察器。
|
|
65
|
+
- 宿主在插槽注册和撤销时同步发送变更事件。联动在完成一次安装或清理并保存撤销函数后,再处理期间发生的配置通知,避免重入造成重复安装及关闭后残留。
|
|
66
|
+
- 如果旧版本已经累积了重复页签,更新后需重新加载客户端或重启宿主一次,清除旧版本遗留的挂载。修复后的开关切换不需要重启;本插件不会按同名页签批量删除其他插件的注册。
|
|
65
67
|
- 尚未验证的插槽结构不会被覆盖;原面板保留,独立入口继续使用。
|
|
66
68
|
|
|
67
69
|
## 加载与实时性
|
|
@@ -85,7 +87,7 @@ dsh-context 主要展示上下文占用、组成、变化和注入事件。0.66.
|
|
|
85
87
|
|
|
86
88
|
## 验证范围
|
|
87
89
|
|
|
88
|
-
本地合成会话用于核对分类金额总和、长上下文阈值、缓存与输出计价、人民币换算、Plan、零价格和未定价。真实 DSH Session、TokenMeter 和投影服务用于核对取数接口及只读行为。真实发布的 dsh-context
|
|
90
|
+
本地合成会话用于核对分类金额总和、长上下文阈值、缓存与输出计价、人民币换算、Plan、零价格和未定价。真实 DSH Session、TokenMeter 和投影服务用于核对取数接口及只读行为。真实发布的 dsh-context 客户端和宿主页签投影用于验证三个界面入口、先后安装、会话隔离、反复开关、重新载入及原始页签保留。真实 Cordis 与 SlotRegistry 验证同步变更事件重入、关闭、插件卸载及延迟请求完成后的清理。
|
|
89
91
|
|
|
90
92
|
浏览器检查覆盖明暗主题、窄屏和短窗口、预览、关闭方式、焦点恢复及保存失败。预览采用示例数据,所有模型和外部网络请求均被禁用。
|
|
91
93
|
|
package/docs/qwen-cli-quota.md
CHANGED
|
@@ -50,9 +50,10 @@ bl usage coding-plan --output json
|
|
|
50
50
|
|
|
51
51
|
登录最长等待 5 分钟,之后可重试。凭据仍由官方 CLI 保存;插件丢弃登录输出,错误只显示双语分类提示。并发登录合并为一次;切换来源、关闭显示或卸载插件时取消在途登录,旧结果不覆盖新配置。回归使用合成凭据与真实子进程,未执行真实账号浏览器授权。
|
|
52
52
|
|
|
53
|
-
- 一次查询并行执行 `usage token-plan` 与 `usage coding-plan` 两个只读子命令并合并:Token Plan
|
|
54
|
-
- Token Plan 读取 `per5HourPercentage` / `per1WeekPercentage` 及对应的 `ResetTime`;Coding Plan 读取各窗口的 `percentage`(缺失时按 `usedQuota/totalQuota` 推算)。官方 CLI 返回比例值,乘以 100 后保留一位小数,例如 `0.5` 显示为 `50%`。重置时间以 epoch 毫秒转为 ISO。缺失的 Token Plan 窗口、无正额度上限的 Coding Plan 窗口不生成进度条。
|
|
55
|
-
-
|
|
53
|
+
- 一次查询并行执行 `usage token-plan` 与 `usage coding-plan` 两个只读子命令并合并:Token Plan 优先提供同名的 5 小时 / 周 / 月窗口,Coding Plan 补全其余窗口(`per5Hour` / `perWeek` / `perBillMonth`),另附「source」行标注实际应答的订阅与实例(如 `Coding Plan (pro) (CLI)`)。
|
|
54
|
+
- Token Plan 读取 `per5HourPercentage` / `per1WeekPercentage` / `per1MonthPercentage` 及对应的 `ResetTime`;Coding Plan 读取各窗口的 `percentage`(缺失时按 `usedQuota/totalQuota` 推算)。官方 CLI 返回比例值,乘以 100 后保留一位小数,例如 `0.5` 显示为 `50%`。重置时间以 epoch 毫秒转为 ISO。缺失的 Token Plan 窗口、无正额度上限的 Coding Plan 窗口不生成进度条。
|
|
55
|
+
- CLI 2.1.0 的 `usage token-plan` 输出会丢弃月额度字段。常规两路查询均无有效额度且 Token Plan 命令成功时,通过固定的 `console call --api zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage --data '{}'` 读取原始用量,兼容平铺字段和官方 `data` / `DataV2` 响应。正常已有额度时不追加查询。
|
|
56
|
+
- 单个子命令失败时以另一命令的结果作答;两者都失败时给出登录/失败提示,两者皆无有效额度时为软提示(无可识别数据不直接判定为未订阅)。与官方 CLI 档一致:不生成千问「每 1% / 满窗 Token」估算,账号总用量不写入 DSH 账本。
|
|
56
57
|
- 执行安全与 CLI 桥一致:固定参数、不经 shell、单命令 15 秒超时、stdout/stderr 各 1 MiB、窗口隐藏、错误不含子进程原始输出;Windows 下直接以 Node 运行包内 ESM 入口,不执行 npm 的 `.cmd` / `.ps1` 包装脚本。
|
|
57
58
|
- 查询间隔(1–1440 分钟)与并发合并同官方 CLI 档;回归见 `test/bailian-cli.mjs`(真实子进程、双命令合并、单边失败容错、超时/脱敏、缓存/并发/切源、账本三态与 codec),使用合成输出验证,未使用真实百炼订阅账号(`bl usage token-plan` 对未开通账号返回 `{}`)。
|
|
58
59
|
|
|
@@ -82,7 +83,7 @@ Clicking **Login** runs the fixed `bl auth login --console` command and opens th
|
|
|
82
83
|
|
|
83
84
|
Login waits up to five minutes and can be retried. The official CLI owns credentials; the plugin discards login output and returns only classified bilingual errors. Concurrent logins share one process. Source changes, hidden quota display and plugin unload cancel pending login. Regression uses synthetic credentials and real child processes; live account browser authorization was not performed.
|
|
84
85
|
|
|
85
|
-
One query runs `usage token-plan` and `usage coding-plan` in parallel and merges them: Token Plan wins
|
|
86
|
+
One query runs `usage token-plan` and `usage coding-plan` in parallel and merges them: Token Plan wins shared 5-hour/week/monthly windows and Coding Plan fills missing windows, and a `source` row names the subscriptions that answered (e.g. `Coding Plan (pro) (CLI)`). Token Plan uses the flat `per5HourPercentage` / `per1WeekPercentage` / `per1MonthPercentage` fields and their reset times. Coding Plan uses nested `per5Hour` / `perWeek` / `perBillMonth` windows. CLI ratios are multiplied by 100 (0.5 becomes 50%); missing Coding Plan ratios are derived from used/total. Percentages retain one decimal, and reset times are epoch milliseconds. Missing Token Plan windows and Coding Plan windows without positive limits are skipped. When one subcommand fails the other answers; both failing shows the login/failure hint, and no recognized quota produces an actionable soft notice. If both normal responses have no valid quota and the Token Plan command succeeded, a fixed read-only console usage call recovers monthly fields stripped by CLI 2.1.0. Existing valid quota avoids this extra query; flat and official data/DataV2 envelopes are supported. Like the Official CLI source this mode creates no per-1%/full-window estimates and writes no account totals into the ledger. Execution uses the shared CLI bridge (fixed arguments, no shell, 15s timeout, 1 MiB caps, hidden window, no raw child output; Windows runs the package ESM entry directly via Node). Refresh interval and concurrency coalescing match the Official CLI source. Regression: `test/bailian-cli.mjs` with synthetic output and real child processes; no live Bailian subscription was used (`bl usage token-plan` returns `{}` for accounts without Token Plan).
|
|
86
87
|
|
|
87
88
|
Tests use synthetic output, real child processes and bilingual component callbacks. No live Qianwen subscription account was used.
|
|
88
89
|
|
package/lib/bailian-cli.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Official Bailian CLI bridge (GitHub modelstudioai/cli, npm bailian-cli, `bl` / `bailian`).
|
|
3
3
|
* Credentials remain owned by the CLI (bl auth login --console / --api-key).
|
|
4
|
-
* Reads Token Plan + Coding Plan quota windows
|
|
4
|
+
* Reads Token Plan + Coding Plan quota windows through fixed read-only commands.
|
|
5
5
|
*/
|
|
6
6
|
import { bridgeCode, resolveNpmCli, runCliJson, runCliCommand } from './cli-bridge.js'
|
|
7
7
|
|
|
8
8
|
export const BAILIAN_TOKEN_PLAN_ARGS = Object.freeze(['usage', 'token-plan', '--output', 'json', '--quiet'])
|
|
9
9
|
export const BAILIAN_CODING_PLAN_ARGS = Object.freeze(['usage', 'coding-plan', '--output', 'json', '--quiet'])
|
|
10
|
+
export const BAILIAN_TOKEN_PLAN_RAW_ARGS = Object.freeze(['console', 'call', '--api', 'zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage', '--data', '{}', '--output', 'json', '--quiet'])
|
|
10
11
|
export const BAILIAN_AUTH_STATUS_ARGS = Object.freeze(['auth', 'status', '--output', 'json', '--quiet'])
|
|
11
12
|
export const BAILIAN_LOGIN_ARGS = Object.freeze(['auth', 'login', '--console'])
|
|
12
13
|
|
|
@@ -16,7 +17,7 @@ const MESSAGES = {
|
|
|
16
17
|
failed: '百炼 CLI 查询失败,请运行 bl auth status --output json 检查登录后重试。',
|
|
17
18
|
timeout: '百炼 CLI 查询超时,请检查网络后刷新。',
|
|
18
19
|
invalid: '百炼 CLI 返回的额度格式无效,请更新 CLI 后重试。',
|
|
19
|
-
unavailable: '百炼 CLI
|
|
20
|
+
unavailable: '百炼 CLI 未返回可识别的计划额度,请检查订阅或更新 CLI 与插件。',
|
|
20
21
|
auth: '百炼 CLI 未登录,请点击"登录"按钮或运行 bl auth login --console 完成授权。',
|
|
21
22
|
loginFailed: '百炼 CLI 登录失败,请在 DSH 主机运行 bl auth login --console 检查后重试。',
|
|
22
23
|
loginTimeout: '百炼 CLI 登录超时,请重新点击登录并在 DSH 主机的浏览器完成授权。',
|
|
@@ -27,7 +28,7 @@ const MESSAGES = {
|
|
|
27
28
|
failed: 'Bailian CLI query failed. Check bl auth status --output json and retry.',
|
|
28
29
|
timeout: 'Bailian CLI query timed out. Check the network and refresh.',
|
|
29
30
|
invalid: 'Bailian CLI returned invalid quota data. Update the CLI and retry.',
|
|
30
|
-
unavailable: 'Bailian CLI returned no
|
|
31
|
+
unavailable: 'Bailian CLI returned no recognized plan quota. Check the subscription or update the CLI and plugin.',
|
|
31
32
|
auth: 'Bailian CLI not authenticated. Click the "Login" button or run bl auth login --console to authorize.',
|
|
32
33
|
loginFailed: 'Bailian CLI login failed. Run bl auth login --console on the DSH host and retry.',
|
|
33
34
|
loginTimeout: 'Bailian CLI login timed out. Retry and complete authorization in the DSH host browser.',
|
|
@@ -54,13 +55,20 @@ function windowOf(ratio, reset, locale) {
|
|
|
54
55
|
|
|
55
56
|
function tokenWindows(payload, locale) {
|
|
56
57
|
const windows = {}
|
|
57
|
-
for (const [prefix, name] of [['per5Hour', 'fiveHour'], ['per1Week', 'weekly']]) {
|
|
58
|
+
for (const [prefix, name] of [['per5Hour', 'fiveHour'], ['per1Week', 'weekly'], ['per1Month', 'monthly']]) {
|
|
58
59
|
const ratio = payload[`${prefix}Percentage`]
|
|
59
60
|
if (ratio !== undefined) windows[name] = windowOf(ratio, payload[`${prefix}ResetTime`], locale)
|
|
60
61
|
}
|
|
61
62
|
return windows
|
|
62
63
|
}
|
|
63
64
|
|
|
65
|
+
// Official CLI console responses may carry data.DataV2.data.data, data.data,
|
|
66
|
+
// or a flat payload. Keep this adapter limited to that published envelope.
|
|
67
|
+
function rawTokenPayload(response) {
|
|
68
|
+
const data = response?.data, v2 = data?.DataV2
|
|
69
|
+
return v2?.data?.data ?? v2?.data ?? v2 ?? data?.data ?? data ?? response
|
|
70
|
+
}
|
|
71
|
+
|
|
64
72
|
function codingWindows(payload, locale) {
|
|
65
73
|
const windows = {}
|
|
66
74
|
for (const [rawKey, name] of PERIOD_KEYS) {
|
|
@@ -80,8 +88,8 @@ function codingWindows(payload, locale) {
|
|
|
80
88
|
|
|
81
89
|
/**
|
|
82
90
|
* Merge both payloads into the normalized windows contract.
|
|
83
|
-
* Token Plan wins same-name
|
|
84
|
-
*
|
|
91
|
+
* Token Plan wins same-name windows, including the monthly personal plan;
|
|
92
|
+
* Coding Plan fills missing windows. `source` records the subscriptions.
|
|
85
93
|
*/
|
|
86
94
|
export function parseBailianUsage(payloads, locale = 'zh') {
|
|
87
95
|
const token = payloads?.token, coding = payloads?.coding
|
|
@@ -175,6 +183,17 @@ export async function queryBailianCli(locale = 'zh', options = {}) {
|
|
|
175
183
|
coding: settled[1].status === 'fulfilled' ? settled[1].value : null,
|
|
176
184
|
}, locale)
|
|
177
185
|
} catch (error) {
|
|
186
|
+
// CLI 2.1.0 strips per1Month* before emitting usage token-plan JSON. Only
|
|
187
|
+
// recover raw usage when no regular quota exists and Token Plan answered.
|
|
188
|
+
if (error.code === 'unavailable' && settled[0].status === 'fulfilled' && record(settled[0].value)) {
|
|
189
|
+
let raw
|
|
190
|
+
try { raw = await run(BAILIAN_TOKEN_PLAN_RAW_ARGS) }
|
|
191
|
+
catch (failure) { signal?.throwIfAborted(); throw fail(locale, bridgeCode(failure, { authExitCode: 3 })) }
|
|
192
|
+
signal?.throwIfAborted()
|
|
193
|
+
try {
|
|
194
|
+
return parseBailianUsage({ token: rawTokenPayload(raw), coding: settled[1].status === 'fulfilled' ? settled[1].value : null }, locale)
|
|
195
|
+
} catch (failure) { if (failure.code !== 'unavailable') throw failure }
|
|
196
|
+
}
|
|
178
197
|
// With one command broken, a surviving source still answers; only when nothing
|
|
179
198
|
// valid remains does the broken command's real failure become the message.
|
|
180
199
|
if (error.code === 'unavailable') {
|
package/lib/client.statistics.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:Ht=>{const wt=Ht("react"),{createElement:t,useState:
|
|
1
|
+
window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",factory:Ht=>{const wt=Ht("react"),{createElement:t,useState:A,useEffect:ct,useRef:dt,Fragment:Z}=wt,ze=["input","output","cacheRead","cacheWrite","reasoning","calls","cost","apiCost"],W=(e,n)=>n==="total"?e.cost:n==="plan"?Math.max(0,e.cost-e.apiCost):e.apiCost,gt=e=>e.input+e.cacheRead+e.cacheWrite+e.output,_=(e,n)=>n>0?(100*e/n).toFixed(1)+"%":"—",Xt=(e,n)=>new Date(Date.parse(e)+n*864e5).toISOString().slice(0,10),At=e=>n=>{if(typeof n!==e||e==="number"&&!Number.isFinite(n))throw new Error("Invalid statistics "+e);return n},N=At("number"),x=At("string"),K=At("boolean"),at=e=>e===null?null:N(e),Q=e=>n=>{if(!Array.isArray(n))throw new Error("Invalid statistics array");return n.map(e)},F=e=>n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid statistics object");return Object.fromEntries(Object.entries(e).map(([l,o])=>[l,o(n[l])]))},ot=Object.fromEntries(ze.map(e=>[e,N])),Yt=F(ot),qt=F({provider:x,model:x,bucket:x,tokens:N,rate:N,cost:N,priced:K,plan:K}),Lt=e=>x(e??""),Gt=F({sessionId:Lt,logSeq:e=>at(e??null),kind:x,turn:at,step:at,provider:x,model:x,atMs:N,cost:N,apiCost:N,plan:K,priced:K,longContext:K,rows:Q(qt)}),Bt=F({from:x,to:x,retainedFrom:x,retainedTo:x,totals:Yt,days:Q(F({...ot,date:x})),models:Q(F({...ot,key:x,provider:x,model:x,priced:K})),sessions:Q(F({...ot,id:x,title:x})),providers:Q(x),modelOptions:Q(x),sessionCount:N,offset:N,unassignedCost:N,unmodeledCost:N}),Dt=F({found:K,cost:N,apiCost:N,rows:Q(qt),calls:Q(Gt),totalCalls:N,offset:N,recorded:Yt,agents:e=>Q(F({...ot,id:x,title:x}))(e??[]),callShares:e=>Q(F({index:N,cost:N,apiCost:N,tokens:N,calls:N,other:K,unpriced:K}))(e??[]),kinds:Q(F({...ot,kind:x,unpriced:K})),turns:Q(F({...ot,sessionId:Lt,turn:at,unpriced:K})),totalTurns:N,turnOffset:N,stepShares:F(Object.fromEntries(["cost","calls"].map(e=>[e,Q(F({...ot,sessionId:Lt,turn:at,step:at,other:K,unpriced:K}))])))}),St=F({found:K,turn:N,input:x,inputTruncated:K,totalTools:N,offset:N,tools:Q(F({seq:N,step:at,name:x,callId:x,atMs:N,arguments:x,result:x,truncated:K,status:x}))}),Zt=e=>({...F({found:K,kind:x,input:x,injected:x,skills:x,precedingTools:x,output:x,reasoning:x,truncated:K,totalTools:N,offset:N})(e),tools:St({...e,turn:0,inputTruncated:!1}).tools.map((n,l)=>({...n,durationMs:at(e.tools[l].durationMs??null)}))}),It=["system","tools","user","inject","skill","assistant","tool","other"],Tt=e=>{if(N(e)<0)throw new Error("Invalid context costs amount");return e},te=F(Object.fromEntries(["input","cacheRead","cacheWrite","output","reasoning"].map(e=>[e,Tt]))),Pe=e=>e===null?null:te(e),Ut=F({status:x,sessionId:x,generatedAt:N,revision:N,provider:x,model:x,basis:x,priced:K,source:x,linked:K,contextTokens:Tt,components:Q(F({key:e=>{if(!It.includes(e))throw new Error("Invalid context costs category");return e},tokens:Tt})),rates:Pe,longContext:e=>e===null?null:{...te(e),aboveInputTokens:Tt(e.aboveInputTokens)},lastCall:e=>e===null?null:Gt(e)}),zt=e=>{const n=x(e?.sessionId);if(!n||n.length>512)throw new Error("Invalid context costs session");return{sessionId:n}},ee=F({version:x,compatible:K,reason:x}),ae=F({cost:N,apiCost:N,totalSteps:N,offset:N,shares:Q(F({key:x,sessionId:x,turn:at,step:at,kind:x,tools:Q(x),cost:N,apiCost:N,unpriced:K,other:K,count:N})),groups:Q(F({key:x,kind:x,tools:Q(x),steps:N,cost:N,apiCost:N,unpriced:K})),steps:Q(F({key:x,sessionId:x,turn:at,step:at,kind:x,tools:Q(x),atMs:N,calls:N,cost:N,apiCost:N,unpriced:K,rows:Q(qt)}))}),se=e=>{const n={...zt(e),basis:x(e.basis??"total"),offset:N(e.offset??0)};if(!["api","plan","total"].includes(n.basis)||!Number.isSafeInteger(n.offset)||n.offset<0||n.offset>1e7)throw new Error("Invalid step billing query");return n},ne=e=>{const n=F({sessionId:x,turn:N,offset:N})({...e,offset:e.offset??0});if(!n.sessionId||n.sessionId.length>512||![n.turn,n.offset].every(l=>Number.isSafeInteger(l)&&l>=0)||n.offset>1e7)throw new Error("Invalid turn inspection query");return n},ce=e=>{const n=F({from:x,to:x,provider:x,model:x,sessionId:x,basis:x,offset:N})(e);if(n.turnOffset=N(e.turnOffset??0),!["api","plan","total"].includes(n.basis)||![n.offset,n.turnOffset].every(l=>Number.isSafeInteger(l)&&l>=0&&l<=1e7))throw new Error("Invalid statistics query");return n},oe=e=>{const n={...zt(e),seq:N(e.seq),atMs:N(e.atMs),offset:N(e.offset??0)};if(![n.seq,n.offset].every(l=>Number.isSafeInteger(l)&&l>=0)||n.offset>1e7||n.atMs<=0)throw new Error("Invalid call inspection query");return n},Wt=(e,n)=>{const l={parse:n};return{mode:"strict",typeSymbol:"dsh-cost-meter#"+e,schema:l,create:()=>l}},le={package:"dsh-cost-meter/statistics",descriptors:[["getSessionTrajectory","Trajectory",ae,se],["getBillingStatistics","BillingStatistics",Bt],["getSessionBilling","SessionBilling",Dt],["getTurnInspection","TurnInspection",St,ne],["getCallInspection","CallInspection",Zt,oe],["getContextCosts","ContextCosts",Ut,zt]].map(([e,n,l,o])=>({id:"dsh-cost-meter#costMeter/"+e,service:"costMeter",namespace:"costMeter",method:e,invocation:{kind:"direct"},parameters:[{name:"query",wire:"query",source:"json",codec:Wt(o?n+"Query":"StatisticsQuery",o??ce)}],result:Wt(n,l)})).concat({id:"dsh-cost-meter#costMeter/getContextIntegration",service:"costMeter",namespace:"costMeter",method:"getContextIntegration",invocation:{kind:"direct"},parameters:[],result:Wt("ContextIntegration",ee)})},re=`
|
|
2
2
|
.cm-stat{--cm-accent:var(--dsw-alias-state-business-primary,#4d6bfe);--cm-plan:var(--dsw-alias-label-tertiary,#8b9099);--cm-muted:var(--dsw-alias-label-tertiary,#858a94);--cm-border:var(--dsw-alias-border-l3,#e9eaed);--cm-surface:var(--dsw-alias-bg-layer-1,#f7f8fa);color:var(--dsw-alias-label-primary,#25262b);font-family:var(--ds-font-family-sans,inherit);font-size:13px;line-height:1.55;container-type:inline-size}
|
|
3
3
|
.cm-stat *{box-sizing:border-box}.cm-stat h2,.cm-stat h3,.cm-stat p{margin:0}.cm-stat h2{font-size:18px;font-weight:600;letter-spacing:0}.cm-stat h3{font-size:14px;font-weight:500}
|
|
4
4
|
.cm-stat-head{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0 0 18px}.cm-stat-sub{font-size:12px;color:var(--cm-muted)}
|
|
@@ -20,7 +20,7 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
|
|
|
20
20
|
.cm-stat-dialog{border-color:var(--dsw-alias-border-l3,#e9eaed);box-shadow:var(--dsw-elevation-prominent,0 20px 90px #0002)}.cm-stat-dialog-head>.cm-btn{border:0;border-radius:8px;background:transparent;font-size:22px;line-height:28px;width:32px;height:32px;padding:0}.cm-stat-dialog-head>.cm-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#f0f1f4)}.cm-stat-dialog-head>.cm-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:2px}.cm-session-options{margin-top:8px;border-top:1px solid var(--cm-border);padding-top:8px}.cm-session-options>summary{color:var(--cm-muted);font-size:12px}.cm-session-options .cm-context-setting{border:0;padding:0}.cm-stat-session>.cm-stat-panel{border:0;padding:0;margin:0}.cm-stat-session .cm-stat-metrics{margin-top:0}.cm-stat-session .cm-plan{margin:20px 0}
|
|
21
21
|
@container(max-width:700px){.cm-stat-shares{grid-template-columns:1fr;gap:20px}.cm-stat-step-list{columns:1}.cm-stat-turn-toggle{align-items:flex-start}.cm-stat-turn-toggle>span:last-child{max-width:60%}.cm-stat-metric{padding:10px!important}.cm-stat-metric:nth-child(2){border:0}.cm-stat-page{gap:8px}}
|
|
22
22
|
@container(max-width:700px){.cm-stat-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.cm-stat-grid{grid-template-columns:1fr}.cm-stat-panel{padding:12px}.cm-stat-head{align-items:start}.cm-stat-controls label{flex:1}.cm-stat input,.cm-stat select{max-width:100%;width:100%}.cm-stat-value{font-size:23px}}
|
|
23
|
-
`;function ie(e,n){return e.key===n?{...e,error:"",failed:!1,loading:!0}:{value:null,error:"",failed:!1,loading:!0,key:n}}function ft(e,n){return{value:n,error:"",failed:!1,loading:!1,key:e}}function pe(e,n,l){return{value:e.key===n?e.value:null,error:String(l?.message??l),failed:!0,loading:!1,key:n}}function Pt(e){return!e.value&&(e.loading||e.failed===!0)}function Rt(e,n){const l=[e.meta.dayKey,e.total?.calls,e.total?.cost,e.total?.apiCost,e.today?.calls,e.today?.cost,e.today?.apiCost].join(":"),o=JSON.stringify([e.config.prices,e.config.priceOverrides,e.config.priceMatch,e.config.planBilling,e.config.codingPlans,e.config.goQuota?.enabled,e.config.peakEnabled,e.config.peakEffectiveAt,e.config.peakWindows,e.config.peakHolidays,e.config.fetchedAt,e.config.priceSource,e.config.currency,e.config.exchangeRate,e.config.decimals,e.config.showTotalWithPlan,e.config.includeSubagentCost]);return n+":"+l+":"+o}const Ft=new WeakMap;function bt(e,n,l){let o=Ft.get(e);o||Ft.set(e,o=new Map);const c=n+":"+JSON.stringify(l);let a=o.get(c);return a||(a={},o.set(c,a),o.size>32&&o.delete(o.keys().next().value)),a}const ht=(e,n)=>e.revision===n?e.value:null;function Mt(e,n,l,o,c=!1){const a=bt(e,n,l);if(a.pending&&a.pendingRevision===o)return a.pending;if(!c&&ht(a,o)&&Date.now()-a.at<1e3)return Promise.resolve(a.value);const
|
|
23
|
+
`;function ie(e,n){return e.key===n?{...e,error:"",failed:!1,loading:!0}:{value:null,error:"",failed:!1,loading:!0,key:n}}function ft(e,n){return{value:n,error:"",failed:!1,loading:!1,key:e}}function pe(e,n,l){return{value:e.key===n?e.value:null,error:String(l?.message??l),failed:!0,loading:!1,key:n}}function Pt(e){return!e.value&&(e.loading||e.failed===!0)}function Rt(e,n){const l=[e.meta.dayKey,e.total?.calls,e.total?.cost,e.total?.apiCost,e.today?.calls,e.today?.cost,e.today?.apiCost].join(":"),o=JSON.stringify([e.config.prices,e.config.priceOverrides,e.config.priceMatch,e.config.planBilling,e.config.codingPlans,e.config.goQuota?.enabled,e.config.peakEnabled,e.config.peakEffectiveAt,e.config.peakWindows,e.config.peakHolidays,e.config.fetchedAt,e.config.priceSource,e.config.currency,e.config.exchangeRate,e.config.decimals,e.config.showTotalWithPlan,e.config.includeSubagentCost]);return n+":"+l+":"+o}const Ft=new WeakMap;function bt(e,n,l){let o=Ft.get(e);o||Ft.set(e,o=new Map);const c=n+":"+JSON.stringify(l);let a=o.get(c);return a||(a={},o.set(c,a),o.size>32&&o.delete(o.keys().next().value)),a}const ht=(e,n)=>e.revision===n?e.value:null;function Mt(e,n,l,o,c=!1){const a=bt(e,n,l);if(a.pending&&a.pendingRevision===o)return a.pending;if(!c&&ht(a,o)&&Date.now()-a.at<1e3)return Promise.resolve(a.value);const m=(async()=>e[n](l))().then(u=>(a.pending===m&&Object.assign(a,{value:u,revision:o,at:Date.now()}),u)).finally(()=>{a.pending===m&&(a.pending=null)});return a.pending=m,a.pendingRevision=o,m}function vt(e,n,l,o){const c=JSON.stringify(l),[a,m]=A(()=>({...ft(c,ht(bt(e,n,l),o)),loading:!0}));return ct(()=>{let u=!0;return m(r=>r.key===c?ie(r,c):{...ft(c,ht(bt(e,n,l),o)),loading:!0}),Mt(e,n,JSON.parse(c),o).then(r=>{u&&m(ft(c,r))},r=>{u&&m(b=>pe(b,c,r))}),()=>{u=!1}},[e,n,c,o]),a.key===c?a:{...ft(c,ht(bt(e,n,l),o)),loading:!0}}const Y=(e,n,l={})=>t("button",{type:"button",className:"cm-stat-btn",onClick:n,...l},e),lt=e=>t("p",{className:"cm-stat-error",role:"alert"},e);function me(e){const n=!!e.longContext&&e.contextTokens>e.longContext.aboveInputTokens,l=n?e.longContext:e.rates,o=e.components.map(c=>({...c,cost:l?c.tokens*l.input/1e6:0}));return{long:n,rates:l,parts:o,cost:o.reduce((c,a)=>c+a.cost,0)}}const jt=`
|
|
24
24
|
.cm-plan{font:13px/1.55 var(--ds-font-family-sans,system-ui);color:var(--dsw-alias-label-primary);min-width:0;container-type:inline-size;--cmp-border:var(--dsw-alias-border-l3,#e5e7eb);--cmp-muted:var(--dsw-alias-label-secondary,#737780);--cmp-bg:var(--dsw-alias-bg-layer-2,#f6f7f9);--cmp-accent:var(--dsw-alias-state-business-primary,#4d6bfe)}
|
|
25
25
|
.cm-plan *{box-sizing:border-box}.cm-plan h3,.cm-plan p{margin:0}.cm-plan h3{font-size:14px;font-weight:500}.cm-plan-head{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}.cm-plan-sub{font-size:11px;color:var(--cmp-muted);overflow-wrap:anywhere}.cm-plan button,.cm-plan input{font:inherit;color:inherit}.cm-plan button{border:.5px solid var(--cmp-border);border-radius:var(--dsw-radius-sm,8px);padding:4px 9px;background:transparent;cursor:pointer}.cm-plan button:hover{background:var(--cmp-bg)}.cm-plan button:disabled{opacity:.5;cursor:default}.cm-plan input:focus-visible,.cm-plan button:focus-visible{outline:2px solid var(--cmp-accent);outline-offset:2px}
|
|
26
26
|
.cm-plan-summary{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;margin:14px 0;padding:14px 0;border-block:1px solid var(--cmp-border)}.cm-plan-amount{font-size:clamp(16px,4cqw,24px);font-variant-numeric:tabular-nums;font-weight:500;overflow-wrap:anywhere}.cm-plan-stack{display:flex;height:10px;overflow:hidden;border-radius:4px;background:var(--cmp-bg);margin-bottom:12px}.cm-plan-stack span{min-width:0}
|
|
@@ -30,7 +30,7 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
|
|
|
30
30
|
@container(max-width:540px){.cm-cost-chart{grid-template-columns:128px minmax(0,1fr);gap:10px 12px}.cm-cost-donut{width:128px;height:128px}.cm-cost-center{inset:32px 18px}.cm-cost-center b{font-size:21px}.cm-cost-legend{grid-template-columns:1fr;gap:1px}.cm-plan .cm-cost-key{padding:4px;font-size:11px}}
|
|
31
31
|
@container(max-width:320px){.cm-cost-chart{grid-template-columns:1fr}.cm-cost-donut{margin:auto}.cm-cost-legend{grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 8px}}
|
|
32
32
|
@container(max-width:420px){.cm-plan-summary{gap:8px;grid-template-columns:1fr 1fr}.cm-plan-part-head{align-items:start;flex-wrap:wrap}}
|
|
33
|
-
@media(prefers-reduced-motion:reduce){.cm-cost-arc{transition:none}}`,
|
|
33
|
+
@media(prefers-reduced-motion:reduce){.cm-cost-arc{transition:none}}`,tt=["#627bff","#f6b64b","#30c89c","#ad78f5","#fb8c6f","#42b4f5","#24bdc9","#a0aec5"].map((e,n)=>"var(--cm-chart-"+n+","+e+")"),Ot={input:0,cacheRead:6,cacheWrite:1,output:5,reasoning:3},Re=`
|
|
34
34
|
.cm-context-compact>.cm-plan-head{margin-bottom:10px}.cm-context-compact .cm-context-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.cm-context-compact .cm-context-current,.cm-context-compact .cm-plan-last{min-width:0;container-type:inline-size}.cm-context-compact .cm-plan-last{border:0;border-left:1px solid var(--cmp-border);padding:0 0 0 18px;margin:0}.cm-context-compact .cm-plan-summary{margin:10px 0;padding:8px 0;gap:8px}.cm-context-compact .cm-plan-amount{font-size:18px}.cm-context-compact .cm-cost-chart{margin-top:10px;gap:6px 10px}.cm-context-compact .cm-cost-legend{grid-template-columns:1fr}.cm-context-compact .cm-plan-sub{font-size:10px}.cm-context-compact .cm-plan-total{margin-top:6px!important}.cm-context-compact .cm-plan-note{grid-column:1/-1}
|
|
35
35
|
@container(max-width:740px){.cm-context-compact .cm-context-columns{grid-template-columns:1fr}.cm-context-compact .cm-plan-last{border:0;border-top:1px solid var(--cmp-border);padding:12px 0 0}}
|
|
36
36
|
|
|
@@ -38,22 +38,22 @@ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.statistics.js",f
|
|
|
38
38
|
|
|
39
39
|
.cm-spend{margin:20px 0}.cm-spend-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.cm-spend-card{border:1px solid var(--cmp-border);border-radius:12px;padding:18px;container-type:inline-size;min-width:0}.cm-spend-card .cm-cost-legend{grid-template-columns:1fr}.cm-spend-card .cm-cost-chart{margin-bottom:0}.cm-spend-card h3{font-weight:500}.cm-cache-compare{border-top:1px solid var(--cmp-border);padding-top:16px;margin-top:20px}.cm-cache-compare h3{font-size:12px;margin-bottom:12px}.cm-cache-compare>div{margin-top:10px}.cm-spend>.cm-plan-sub{margin-top:10px}.cm-cost-key-amount{display:block;font-size:10px;font-weight:400;margin-top:3px;color:var(--cmp-muted);font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.cm-cost-key-label{overflow-wrap:anywhere}.cm-call-share{display:inline-block;border-radius:5px;padding:1px 7px;margin-left:8px;background:var(--cm-surface);color:var(--cm-accent);font-size:11px;font-variant-numeric:tabular-nums}.cm-plan .cm-cost-key[data-active=true]{background:var(--dsw-alias-interactive-bg-hover,#f2f5fc)}
|
|
40
40
|
@container(max-width:740px){.cm-spend-grid{grid-template-columns:1fr}}
|
|
41
|
-
`;function lt({rows:e,total:n,label:l,text:o,onSelect:c,amounts:a=!1}){const[p,u]=j(""),[r,b]=j(""),x=e.find(g=>g.key===(p||r)),m=g=>g.unpriced&&g.value===0?"—":n>0?_(g.value,n):"—",I=g=>g.meta??g.tokens.toLocaleString()+" tokens",d=g=>({"data-active":x?.key===g.key,onMouseEnter:()=>u(g.key),onMouseLeave:()=>u(""),onFocus:P=>{P.currentTarget.matches(":focus-visible")&&b(g.key)},onBlur:()=>b(""),onPointerDown:()=>b(""),onClick:()=>c?.(g),onKeyDown:P=>{P.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(P.key)&&(P.preventDefault(),c?.(g))}});let z=0;const w=e.filter(g=>g.value>0&&n>0).map(g=>{const P=Math.min(100,g.value/n*100),Q=z;z+=P;const O=Math.min(.8,P*.15);return t("circle",{...d(g),key:g.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":g.label+" · "+m(g)+" · "+g.amount+" · "+I(g),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:g.color,strokeWidth:18,strokeDasharray:P-O+" "+(100-P+O),strokeDashoffset:-Q-O/2,transform:"rotate(-90 78 78)"})});return t("div",{className:"cm-cost-chart","aria-label":l,"data-inspecting":!!x,onMouseLeave:()=>u("")},t("div",{className:"cm-cost-donut"},t("svg",{viewBox:"0 0 156 156","aria-label":l},t("circle",{cx:78,cy:78,r:61,fill:"none",stroke:"var(--cmp-bg)",strokeWidth:16}),...w),t("div",{className:"cm-cost-center","aria-hidden":!0},t("b",null,x?m(x):n>0?"100%":"—"),t("small",null,x?.label??l))),t("div",{className:"cm-cost-legend"},...e.map(g=>t("button",{...d(g),type:"button",key:g.key,className:"cm-cost-key","aria-label":g.label+" "+m(g)},t("i",{className:"cm-plan-dot",style:{background:g.color}}),t("span",{className:"cm-cost-key-label"},g.label,a?t("small",{className:"cm-cost-key-amount"},g.amount):null),t("span",{className:"cm-cost-key-share"},m(g))))),t("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},x?t(tt,null,t("strong",null,x.label),t("span",null,I(x)),t("strong",null,x.amount)):null))}function Et({api:e,sessionId:n,revision:l="",text:o=(r,b)=>b,money:c=r=>"$"+r.toLocaleString("en-US",{maximumFractionDigits:6}),integrated:a=!1,compact:p=!1,expanded:u=!1}){const r=dt(null),b=dt(()=>{}),x=dt(l);x.current=l;const[m,I]=j(()=>({value:ht(bt(e,"getContextCosts",{sessionId:n}),l),error:"",busy:!0}));nt(()=>{let v=!0,F=!1,H=typeof IntersectionObserver!="function";const R=async(A=!1)=>{if(!(!v||F||!H||document.hidden)){F=!0,I(W=>({...W,busy:!0}));try{const W=await Mt(e,"getContextCosts",{sessionId:n},x.current,A===!0);if(W.sessionId!==n)throw new Error("Context costs session mismatch");v&&I({value:W,error:"",busy:!1})}catch{v&&I(W=>({...W,busy:!1,error:o("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{F=!1}}};b.current=R;const S=typeof IntersectionObserver=="function"?new IntersectionObserver(A=>{H=A.some(W=>W.isIntersecting),H&&R()}):null;r.current&&S?.observe(r.current),R();const E=setInterval(R,1e4);return document.addEventListener("visibilitychange",R),()=>{v=!1,clearInterval(E),S?.disconnect(),document.removeEventListener("visibilitychange",R)}},[e,n]),nt(()=>{const v=setTimeout(()=>b.current(),250);return()=>clearTimeout(v)},[l]);const d=m.value?.sessionId===n?m.value:null,z=t("div",{className:"cm-plan-head"},t("h3",null,o("上下文费用构成","Context cost breakdown")),t("div",null,a&&e.disableIntegration?t("button",{type:"button",onClick:e.disableIntegration},o("关闭联动","Turn off integration")):null,t("button",{type:"button",onClick:()=>b.current(!0),disabled:m.busy},o("刷新","Refresh")))),w=v=>t("section",{className:"cm-plan"+(p?" cm-context-compact":""),ref:r,"aria-label":o("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},t("style",null,jt),z,a?t("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,m.error?t("p",{role:"alert",className:"cm-plan-error"},m.error):null,v);if(!d||d.status!=="ready")return w(t("p",{className:"cm-plan-note"},d?d.status==="route-unavailable"?o("完成一次请求后,可显示该模型的上下文费用。","Complete a request to see context costs at that model’s rates."):d.status==="session-unavailable"?o("打开此会话后可读取当前上下文。","Open this conversation to read its current context."):o("当前宿主未提供上下文测量;已发生费用仍可在费用明细中查看。","Context measurement is unavailable on this host. Recorded costs remain available in billing details."):m.error?o("点击刷新重试。","Select Refresh to retry."):o("正在读取当前上下文…","Reading current context…")));const g=me(d),P=d.priced&&!!g.rates,Q=[o("系统提示","System prompt"),o("工具定义","Tool schemas"),o("用户输入","User messages"),o("注入内容","Injected context"),o("技能","Skills"),o("历史回复","Prior replies"),o("工具结果","Tool results"),o("其他","Other")],O=v=>Math.round(v).toLocaleString(),k=v=>P?"≈ "+c(v):o("未定价","Unpriced"),T=d.lastCall,V={input:o("非缓存输入","Uncached input"),cacheRead:o("缓存读取","Cache reads"),cacheWrite:o("缓存写入","Cache writes"),output:o("输出(含推理 Token)","Output (including reasoning tokens)"),reasoning:o("单独推理费用","Separate reasoning fees")};return w(t("div",{className:"cm-context-columns"},t("div",{className:"cm-context-current"},t("p",{className:"cm-plan-sub"},d.provider+" / "+d.model),t("div",{className:"cm-plan-summary"},t("div",null,t("div",{className:"cm-plan-sub"},o("当前上下文","Current context")),t("div",{className:"cm-plan-amount"},"≈ "+O(d.contextTokens)+" tokens")),t("div",null,t("div",{className:"cm-plan-sub"},d.basis==="plan"?o("Plan 输入等值","Plan input equivalent"):o("非缓存输入估算","Uncached input estimate")),t("div",{className:"cm-plan-amount"},k(g.cost)))),t(lt,{rows:g.parts.filter(v=>v.tokens>0).map(v=>({key:v.key,label:Q[It.indexOf(v.key)],tokens:Math.round(v.tokens),value:P?v.cost:v.tokens,amount:k(v.cost),color:G[It.indexOf(v.key)]})),total:P?g.cost:d.contextTokens,label:P?o("参考费用占比","Reference cost share"):o("Token 占比","Token share"),text:o}),t("details",{className:"cm-cost-table",open:u},t("summary",null,o("各部分计费","Component costs")),t("ul",{className:"cm-plan-parts"},...g.parts.filter(v=>v.tokens>0).map(v=>{const F=It.indexOf(v.key);return t("li",{key:v.key},t("div",{className:"cm-plan-part-head"},t("span",null,t("i",{className:"cm-plan-dot",style:{background:G[F]}}),Q[F]),t("span",null,k(v.cost))),t("div",{className:"cm-plan-part-meta"},t("span",null,"≈ "+O(v.tokens)+" tokens"),t("span",null,P?_(v.cost,g.cost):"—")))})))),T?t("section",{className:"cm-plan-last"},t("h3",null,o("最近一次调用 · 用量计费","Latest call · usage-based costs")),t("p",{className:"cm-plan-sub"},T.provider+" / "+T.model+" · "+new Date(T.atMs).toLocaleString()),t(lt,{rows:T.rows.filter(v=>v.tokens>0&&(v.bucket!=="reasoning"||v.rate>0)).map(v=>({key:v.bucket,label:V[v.bucket]??v.bucket,tokens:v.tokens,value:v.cost,amount:T.priced?c(v.cost):o("未定价","Unpriced"),color:G[Ot[v.bucket]??7]})),total:T.priced?T.cost:0,label:o("费用占比","Cost share"),text:o}),t("details",{className:"cm-cost-table",open:u},t("summary",null,o("调用计费明细","Call billing details")),t("ul",{className:"cm-plan-parts",style:{marginTop:12}},...T.rows.filter(v=>v.bucket!=="reasoning"||v.rate>0).map(v=>t("li",{key:v.bucket},t("div",{className:"cm-plan-part-head"},t("span",null,V[v.bucket]??v.bucket),t("span",null,T.priced?c(v.cost):o("未定价","Unpriced"))),t("div",{className:"cm-plan-part-meta"},t("span",null,O(v.tokens)+" tokens"),t("span",null,T.priced?_(v.cost,T.cost):"—")))))),t("p",{className:"cm-plan-total"},o("合计 ","Total ")+(T.priced?c(T.cost):o("未定价","Unpriced"))+(T.plan?o(" · Plan 的 API 等值"," · Plan API equivalent"):""))):t("p",{className:"cm-plan-note"},o("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),P?null:t("p",{className:"cm-plan-note"},o("未配置模型单价","Model rates not configured"))))}const Kt=[["conversation.view","id","context"],["sidebar.right.pane.tab","key","dsh-context"],["conversation.input.overlay","id","context-modal"]];function de(e,n,l,o,c){const a=e.get("slots");if(!["entries","subscribe","register","entriesOfSlot"].every(x=>typeof a?.[x]=="function"))return()=>{};const p=[],u=new Map;let r=!0;function b(x){return function(I){c&&wt.useSyncExternalStore(c.subscribe,l);const d=dt(null),[z,w]=j(null),g=I.useProjection?.("contextBreakdown"),P=I.useProjection?.("tokenUsage"),Q=JSON.stringify([g,P]);nt(()=>{if(!d.current||typeof MutationObserver!="function")return;const k=document.createElement("div");k.className="cm-plan-host",k.dataset.cmContextCosts="";const T=()=>{const v=d.current?.querySelector("[data-lc-current]");if(!v){k.remove(),w(null);return}k.parentElement!==v&&(v.appendChild(k),w(k))},V=new MutationObserver(T);return V.observe(d.current,{childList:!0,subtree:!0}),T(),()=>{V.disconnect(),k.remove()}},[I.sessionId]);const O=(k,T)=>l()==="en"?T:k;return t("div",{ref:d,style:{display:"contents"},"data-cm-context-bridge":I.sessionId},t(x,I),z&&I.sessionId?o(t(Et,{key:I.sessionId,api:n,sessionId:I.sessionId,integrated:!0,text:O,revision:Q}),z):null)}}for(const[x,m,I]of Kt){let d=!1;const z=()=>{if(!(!r||d)){d=!0;try{const w=a.entries(x).filter(T=>T.locale==="dsh-context"&&T.options[m]===I&&T.registrant!=="dsh-cost-meter-context-bridge"),g=w.length===1?w[0]:null,P=u.get(x);if(P?.original===g&&a.entries(x).some(T=>T.component===P.component)||(P?.dispose(),u.delete(x),!g||g.children||g.store||typeof g.component!="function")||a.entriesOfSlot(x).find(T=>T.options[m]===I)!==g)return;const O=b(g.component),k=a.register({name:x,...g.options,inject:g.inject,locale:g.locale,priority:(g.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},O);u.set(x,{original:g,component:O,dispose:k})}finally{d=!1}}};p.push(a.subscribe(x,z)),z()}return()=>{r=!1;for(const x of p)x();for(const x of u.values())x.dispose();u.clear()}}const $t="dsh-cost-meter:context-intro-seen",ue=()=>{try{return localStorage.getItem($t)==="1"}catch{return!1}},Me=()=>{try{localStorage.setItem($t,"1")}catch{}};function ge(e,n,l,o,c){const a=e.get("slots"),p=new Set,u=[];let r=!0,b=null,x=[],m=!1,I=0,d=ue(),z=null,w=0,g=Promise.resolve(),P={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const Q=["entries","entriesOfSlot","register","subscribe"].every(S=>typeof a?.[S]=="function"),O=S=>{P={...P,...S};for(const E of p)E()},k=()=>{if(!r)return;const S=l.getSnapshot().state?.config,E=Q&&P.peer.compatible&&x.length>0,A=E&&!P.saving&&(z??S?.contextCostsEnabled)===!0;if(!A&&b){const i=b;b=null,i()}A&&!b&&(b=de(e,{...n,disableIntegration:()=>{v(!1)}},o,c,l));const W=P.prompt&&(P.manual||E);O({available:E,enabled:A,prompt:W||!!(S&&E&&!S.contextCostsPromptSeen&&!S.contextCostsEnabled&&!d)})},T=async(S=!1)=>{if(!r||!Q)return;const E=Kt.flatMap(([W,i,M])=>a.entries(W).filter(h=>h.locale==="dsh-context"&&h.options[i]===M&&h.registrant!=="dsh-cost-meter-context-bridge"&&!h.children&&!h.store&&typeof h.component=="function"));if(!S&&m&&E.length===x.length&&E.every((W,i)=>W===x[i]))return;x=E,m=!0;const A=++I;O({peer:{version:"",compatible:!1,reason:E.length?"unavailable":"missing"}}),k();try{const W=await n.getContextIntegration();r&&A===I&&(O({peer:W}),k())}catch{r&&A===I&&k()}};function V(){d=!0,Me()}async function v(S,E=!1){if(!r||S&&!P.available&&!E)return;const A=++w;V(),z=S,O({prompt:!1,manual:!1,saving:!0,error:""}),k();const W=g.catch(()=>{}).then(()=>n.saveIntegration(S));g=W;try{await W,r&&A===w&&(z=null,O({saving:!1}),k())}catch{r&&A===w&&(z=!1,O({saving:!1,error:"save"}),k())}}if(u.push(l.subscribe(k)),Q)for(const[S]of Kt)u.push(a.subscribe(S,()=>{T()}));const F=()=>{document.hidden||T(!0)};document.addEventListener("visibilitychange",F);const H=S=>{S.key===$t&&S.newValue==="1"&&!d&&(d=!0,O({prompt:!1}),k())};return window.addEventListener("storage",H),T(),k(),{getSnapshot:()=>P,subscribe:S=>(p.add(S),()=>p.delete(S)),choose:v,dismiss:()=>v(P.manual?l.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:V,preview:()=>O({prompt:!0,manual:!0}),refresh:()=>{T(!0)},dispose:()=>{r=!1,++I;for(const S of u)S();b?.(),p.clear(),document.removeEventListener("visibilitychange",F),window.removeEventListener("storage",H)}}}const fe=`
|
|
41
|
+
`;function rt({rows:e,total:n,label:l,text:o,onSelect:c,amounts:a=!1}){const[m,u]=A(""),[r,b]=A(""),C=e.find(v=>v.key===(m||r)),i=v=>v.unpriced&&v.value===0?"—":n>0?_(v.value,n):"—",M=v=>v.meta??v.tokens.toLocaleString()+" tokens",d=v=>({"data-active":C?.key===v.key,onMouseEnter:()=>u(v.key),onMouseLeave:()=>u(""),onFocus:j=>{j.currentTarget.matches(":focus-visible")&&b(v.key)},onBlur:()=>b(""),onPointerDown:()=>b(""),onClick:()=>c?.(v),onKeyDown:j=>{j.currentTarget.tagName.toLowerCase()==="circle"&&["Enter"," "].includes(j.key)&&(j.preventDefault(),c?.(v))}});let w=0;const y=e.filter(v=>v.value>0&&n>0).map(v=>{const j=Math.min(100,v.value/n*100),$=w;w+=j;const P=Math.min(.8,j*.15);return t("circle",{...d(v),key:v.key,className:"cm-cost-arc",role:"button",tabIndex:0,"aria-label":v.label+" · "+i(v)+" · "+v.amount+" · "+M(v),cx:78,cy:78,r:61,pathLength:100,fill:"none",stroke:v.color,strokeWidth:18,strokeDasharray:j-P+" "+(100-j+P),strokeDashoffset:-$-P/2,transform:"rotate(-90 78 78)"})});return t("div",{className:"cm-cost-chart","aria-label":l,"data-inspecting":!!C,onMouseLeave:()=>u("")},t("div",{className:"cm-cost-donut"},t("svg",{viewBox:"0 0 156 156","aria-label":l},t("circle",{cx:78,cy:78,r:61,fill:"none",stroke:"var(--cmp-bg)",strokeWidth:16}),...y),t("div",{className:"cm-cost-center","aria-hidden":!0},t("b",null,C?i(C):n>0?"100%":"—"),t("small",null,C?.label??l))),t("div",{className:"cm-cost-legend"},...e.map(v=>t("button",{...d(v),type:"button",key:v.key,className:"cm-cost-key","aria-label":v.label+" "+i(v)},t("i",{className:"cm-plan-dot",style:{background:v.color}}),t("span",{className:"cm-cost-key-label"},v.label,a?t("small",{className:"cm-cost-key-amount"},v.amount):null),t("span",{className:"cm-cost-key-share"},i(v))))),t("div",{className:"cm-cost-inspect",role:"status","aria-live":"polite"},C?t(Z,null,t("strong",null,C.label),t("span",null,M(C)),t("strong",null,C.amount)):null))}function Et({api:e,sessionId:n,revision:l="",text:o=(r,b)=>b,money:c=r=>"$"+r.toLocaleString("en-US",{maximumFractionDigits:6}),integrated:a=!1,compact:m=!1,expanded:u=!1}){const r=dt(null),b=dt(()=>{}),C=dt(l);C.current=l;const[i,M]=A(()=>({value:ht(bt(e,"getContextCosts",{sessionId:n}),l),error:"",busy:!0}));ct(()=>{let g=!0,O=!1,V=typeof IntersectionObserver!="function";const I=async(R=!1)=>{if(!(!g||O||!V||document.hidden)){O=!0,M(L=>({...L,busy:!0}));try{const L=await Mt(e,"getContextCosts",{sessionId:n},C.current,R===!0);if(L.sessionId!==n)throw new Error("Context costs session mismatch");g&&M({value:L,error:"",busy:!1})}catch{g&&M(L=>({...L,busy:!1,error:o("上下文费用刷新失败,保留上次结果。","Context cost refresh failed; previous results are retained.")}))}finally{O=!1}}};b.current=I;const q=typeof IntersectionObserver=="function"?new IntersectionObserver(R=>{V=R.some(L=>L.isIntersecting),V&&I()}):null;r.current&&q?.observe(r.current),I();const H=setInterval(I,1e4);return document.addEventListener("visibilitychange",I),()=>{g=!1,clearInterval(H),q?.disconnect(),document.removeEventListener("visibilitychange",I)}},[e,n]),ct(()=>{const g=setTimeout(()=>b.current(),250);return()=>clearTimeout(g)},[l]);const d=i.value?.sessionId===n?i.value:null,w=t("div",{className:"cm-plan-head"},t("h3",null,o("上下文费用构成","Context cost breakdown")),t("div",null,a&&e.disableIntegration?t("button",{type:"button",onClick:e.disableIntegration},o("关闭联动","Turn off integration")):null,t("button",{type:"button",onClick:()=>b.current(!0),disabled:i.busy},o("刷新","Refresh")))),y=g=>t("section",{className:"cm-plan"+(m?" cm-context-compact":""),ref:r,"aria-label":o("当前上下文费用构成","Current context cost breakdown"),"data-cm-plan-session":n},t("style",null,jt),w,a?t("p",{className:"cm-plan-sub"},"dsh-context × dsh-cost-meter · USD"):null,i.error?t("p",{role:"alert",className:"cm-plan-error"},i.error):null,g);if(!d||d.status!=="ready")return y(t("p",{className:"cm-plan-note"},d?d.status==="route-unavailable"?o("完成一次请求后,可显示该模型的上下文费用。","Complete a request to see context costs at that model’s rates."):d.status==="session-unavailable"?o("打开此会话后可读取当前上下文。","Open this conversation to read its current context."):o("当前宿主未提供上下文测量;已发生费用仍可在费用明细中查看。","Context measurement is unavailable on this host. Recorded costs remain available in billing details."):i.error?o("点击刷新重试。","Select Refresh to retry."):o("正在读取当前上下文…","Reading current context…")));const v=me(d),j=d.priced&&!!v.rates,$=[o("系统提示","System prompt"),o("工具定义","Tool schemas"),o("用户输入","User messages"),o("注入内容","Injected context"),o("技能","Skills"),o("历史回复","Prior replies"),o("工具结果","Tool results"),o("其他","Other")],P=g=>Math.round(g).toLocaleString(),S=g=>j?"≈ "+c(g):o("未定价","Unpriced"),z=d.lastCall,E={input:o("非缓存输入","Uncached input"),cacheRead:o("缓存读取","Cache reads"),cacheWrite:o("缓存写入","Cache writes"),output:o("输出(含推理 Token)","Output (including reasoning tokens)"),reasoning:o("单独推理费用","Separate reasoning fees")};return y(t("div",{className:"cm-context-columns"},t("div",{className:"cm-context-current"},t("p",{className:"cm-plan-sub"},d.provider+" / "+d.model),t("div",{className:"cm-plan-summary"},t("div",null,t("div",{className:"cm-plan-sub"},o("当前上下文","Current context")),t("div",{className:"cm-plan-amount"},"≈ "+P(d.contextTokens)+" tokens")),t("div",null,t("div",{className:"cm-plan-sub"},d.basis==="plan"?o("Plan 输入等值","Plan input equivalent"):o("非缓存输入估算","Uncached input estimate")),t("div",{className:"cm-plan-amount"},S(v.cost)))),t(rt,{rows:v.parts.filter(g=>g.tokens>0).map(g=>({key:g.key,label:$[It.indexOf(g.key)],tokens:Math.round(g.tokens),value:j?g.cost:g.tokens,amount:S(g.cost),color:tt[It.indexOf(g.key)]})),total:j?v.cost:d.contextTokens,label:j?o("参考费用占比","Reference cost share"):o("Token 占比","Token share"),text:o}),t("details",{className:"cm-cost-table",open:u},t("summary",null,o("各部分计费","Component costs")),t("ul",{className:"cm-plan-parts"},...v.parts.filter(g=>g.tokens>0).map(g=>{const O=It.indexOf(g.key);return t("li",{key:g.key},t("div",{className:"cm-plan-part-head"},t("span",null,t("i",{className:"cm-plan-dot",style:{background:tt[O]}}),$[O]),t("span",null,S(g.cost))),t("div",{className:"cm-plan-part-meta"},t("span",null,"≈ "+P(g.tokens)+" tokens"),t("span",null,j?_(g.cost,v.cost):"—")))})))),z?t("section",{className:"cm-plan-last"},t("h3",null,o("最近一次调用 · 用量计费","Latest call · usage-based costs")),t("p",{className:"cm-plan-sub"},z.provider+" / "+z.model+" · "+new Date(z.atMs).toLocaleString()),t(rt,{rows:z.rows.filter(g=>g.tokens>0&&(g.bucket!=="reasoning"||g.rate>0)).map(g=>({key:g.bucket,label:E[g.bucket]??g.bucket,tokens:g.tokens,value:g.cost,amount:z.priced?c(g.cost):o("未定价","Unpriced"),color:tt[Ot[g.bucket]??7]})),total:z.priced?z.cost:0,label:o("费用占比","Cost share"),text:o}),t("details",{className:"cm-cost-table",open:u},t("summary",null,o("调用计费明细","Call billing details")),t("ul",{className:"cm-plan-parts",style:{marginTop:12}},...z.rows.filter(g=>g.bucket!=="reasoning"||g.rate>0).map(g=>t("li",{key:g.bucket},t("div",{className:"cm-plan-part-head"},t("span",null,E[g.bucket]??g.bucket),t("span",null,z.priced?c(g.cost):o("未定价","Unpriced"))),t("div",{className:"cm-plan-part-meta"},t("span",null,P(g.tokens)+" tokens"),t("span",null,z.priced?_(g.cost,z.cost):"—")))))),t("p",{className:"cm-plan-total"},o("合计 ","Total ")+(z.priced?c(z.cost):o("未定价","Unpriced"))+(z.plan?o(" · Plan 的 API 等值"," · Plan API equivalent"):""))):t("p",{className:"cm-plan-note"},o("尚无已完成调用的用量数据。","No reported usage from a completed call yet.")),j?null:t("p",{className:"cm-plan-note"},o("未配置模型单价","Model rates not configured"))))}const Kt=[["conversation.view","id","context"],["sidebar.right.pane.tab","key","dsh-context"],["conversation.input.overlay","id","context-modal"]];function de(e,n,l,o,c){const a=e.get("slots");if(!["entries","subscribe","register","entriesOfSlot"].every(i=>typeof a?.[i]=="function"))return()=>{};const m=[],u=new Map;let r=!0;function b(i){return function(d){c&&wt.useSyncExternalStore(c.subscribe,l);const w=dt(null),[y,v]=A(null),j=d.useProjection?.("contextBreakdown"),$=d.useProjection?.("tokenUsage"),P=JSON.stringify([j,$]);ct(()=>{const E=i?w.current:w.current?.closest("[data-conversation-session]");if(!E||!i&&E.dataset.conversationSession!==d.sessionId||typeof MutationObserver!="function")return;const g=document.createElement("div");g.className="cm-plan-host",g.dataset.cmContextCosts="";const O=()=>{const I=i?E.querySelector("[data-lc-current]"):[...E.querySelectorAll('[data-slot="conversation.view"] [data-lc-current]')].find(q=>q.closest("[data-conversation-session]")===E);if(!I){g.remove(),v(null);return}g.parentElement!==I&&(I.appendChild(g),v(g))},V=new MutationObserver(O);return V.observe(E,{childList:!0,subtree:!0}),O(),()=>{V.disconnect(),g.remove()}},[d.sessionId]);const S=(E,g)=>l()==="en"?g:E,z=y&&d.sessionId?o(t(Et,{key:d.sessionId,api:n,sessionId:d.sessionId,integrated:!0,text:S,revision:P}),y):null;return i?t("div",{ref:w,style:{display:"contents"},"data-cm-context-bridge":d.sessionId},t(i,d),z):t(Z,null,t("span",{ref:w,hidden:!0}),z)}}const C=()=>{r=!1;for(const i of m)i();for(const i of u.values())i.dispose();u.clear()};try{for(const[i,M,d]of Kt){const w=i==="conversation.view",y=w?"conversation.input.overlay":i;let v=!1;const j=()=>{if(!(!r||v)){v=!0;try{const $=a.entries(i).filter(O=>O.locale==="dsh-context"&&O.options[M]===d&&O.registrant!=="dsh-cost-meter-context-bridge"),P=$.length===1?$[0]:null,S=u.get(i),z=a.entriesOfSlot(i).find(O=>O.options[M]===d);if(S?.original===P&&a.entries(y).some(O=>O.component===S.component)&&(w?z===P:z?.component===S.component)||(S?.dispose(),u.delete(i),!P||P.children||P.store||typeof P.component!="function")||a.entriesOfSlot(i).find(O=>O.options[M]===d)!==P||w&&typeof a.spec=="function"&&!a.spec(y))return;const E=b(w?null:P.component),g=a.register(w?{name:y,id:"cost-meter-context-main",registrant:"dsh-cost-meter-context-bridge"}:{name:i,...P.options,inject:P.inject,locale:P.locale,priority:(P.options.priority??0)-1,registrant:"dsh-cost-meter-context-bridge"},E);u.set(i,{original:P,component:E,dispose:g})}finally{v=!1}}};m.push(a.subscribe(i,j)),w&&m.push(a.subscribe(y,j)),j()}}catch(i){throw C(),i}return C}const $t="dsh-cost-meter:context-intro-seen",ue=()=>{try{return localStorage.getItem($t)==="1"}catch{return!1}},Me=()=>{try{localStorage.setItem($t,"1")}catch{}};function ge(e,n,l,o,c){const a=e.get("slots"),m=new Set,u=[];let r=!0,b=null,C=[],i=!1,M=0,d=ue(),w=null,y=0,v=Promise.resolve(),j=!1,$=!1,P={peer:{version:"",compatible:!1,reason:"unavailable"},available:!1,enabled:!1,saving:!1,error:"",prompt:!1,manual:!1};const S=["entries","entriesOfSlot","register","subscribe"].every(R=>typeof a?.[R]=="function"),z=R=>{P={...P,...R};for(const L of m)L()},E=()=>{if(r){if(j){$=!0;return}j=!0;try{do{$=!1;const R=l.getSnapshot().state?.config,L=S&&P.peer.compatible&&C.length>0,p=L&&!P.saving&&(w??R?.contextCostsEnabled)===!0;if(!p&&b){const h=b;b=null,h()}if(p&&!b){const h=de(e,{...n,disableIntegration:()=>{V(!1)}},o,c,l);r?b=h:h()}const T=P.prompt&&(P.manual||L);r&&z({available:L,enabled:p,prompt:T||!!(R&&L&&!R.contextCostsPromptSeen&&!R.contextCostsEnabled&&!d)})}while(r&&$)}finally{j=!1}}},g=async(R=!1)=>{if(!r||!S)return;const L=Kt.flatMap(([T,h,B])=>a.entries(T).filter(G=>G.locale==="dsh-context"&&G.options[h]===B&&G.registrant!=="dsh-cost-meter-context-bridge"&&!G.children&&!G.store&&typeof G.component=="function"));if(!R&&i&&L.length===C.length&&L.every((T,h)=>T===C[h]))return;C=L,i=!0;const p=++M;z({peer:{version:"",compatible:!1,reason:L.length?"unavailable":"missing"}}),E();try{const T=await n.getContextIntegration();r&&p===M&&(z({peer:T}),E())}catch{r&&p===M&&E()}};function O(){d=!0,Me()}async function V(R,L=!1){if(!r||R&&!P.available&&!L)return;const p=++y;O(),w=R,z({prompt:!1,manual:!1,saving:!0,error:""}),E();const T=v.catch(()=>{}).then(()=>n.saveIntegration(R));v=T;try{await T,r&&p===y&&(w=null,z({saving:!1}),E())}catch{r&&p===y&&(w=!1,z({saving:!1,error:"save"}),E())}}if(u.push(l.subscribe(E)),S)for(const[R]of Kt)u.push(a.subscribe(R,()=>{g()}));const I=()=>{document.hidden||g(!0)};document.addEventListener("visibilitychange",I);const q=R=>{R.key===$t&&R.newValue==="1"&&!d&&(d=!0,z({prompt:!1}),E())};return window.addEventListener("storage",q),g(),E(),{getSnapshot:()=>P,subscribe:R=>(m.add(R),()=>m.delete(R)),choose:V,dismiss:()=>V(P.manual?l.getSnapshot().state?.config?.contextCostsEnabled===!0:!1,!0),opened:O,preview:()=>z({prompt:!0,manual:!0}),refresh:()=>{g(!0)},dispose:()=>{r=!1,++M;for(const R of u)R();b?.(),m.clear(),document.removeEventListener("visibilitychange",I),window.removeEventListener("storage",q)}}}const fe=`
|
|
42
42
|
.cm-context-intro{--cmp-top:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,var(--dsh-windows-titlebar-height,0px)));inset:var(--cmp-top) 0 0;pointer-events:auto;overflow:hidden;box-sizing:border-box;color:var(--dsw-alias-label-primary,#25262b);background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,#fff));font:13px/1.6 var(--ds-font-family-sans,system-ui);border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:var(--dsw-radius-xl,16px);padding:0;width:min(760px,calc(100vw - 32px));max-height:calc(100dvh - var(--cmp-top) - 32px);margin:auto;box-shadow:var(--dsw-elevation-prominent,0 24px 80px #0003)}[data-fullscreen] .cm-context-intro{--cmp-top:0px}
|
|
43
43
|
.cm-context-intro[open]{display:flex;flex-direction:column}.cm-context-intro::backdrop{inset:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,var(--dsh-windows-titlebar-height,0px))) 0 0;background:#0005}[data-fullscreen] .cm-context-intro::backdrop{inset:0}.cm-context-intro *{box-sizing:border-box}.cm-context-intro h2,.cm-context-intro p{margin:0}.cm-context-intro h2{font-size:18px;font-weight:600}.cm-context-intro button{font:inherit;cursor:pointer;border:1px solid var(--dsw-alias-border-l3,#e9eaed);background:transparent;border-radius:8px;padding:7px 14px;color:inherit}.cm-context-intro button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:2px}.cm-context-intro button:disabled{opacity:.5;cursor:default}
|
|
44
44
|
.cm-context-intro-head,.cm-context-intro-foot{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:18px 24px;flex:none;z-index:1}.cm-context-intro-head{top:0;border-bottom:1px solid var(--dsw-alias-border-l3,#e9eaed)}.cm-context-intro-foot{bottom:0;border-top:1px solid var(--dsw-alias-border-l3,#e9eaed);flex-wrap:wrap}.cm-context-intro-body{padding:20px 24px;overflow:auto;min-height:0;overscroll-behavior:contain}.cm-context-intro button.cm-context-close{border:0;padding:0;width:30px;height:30px;flex-shrink:0;font-size:22px;line-height:30px}.cm-context-intro .cm-context-primary{background:var(--dsw-alias-state-business-primary,#4d6bfe);color:#fff;border-color:transparent}.cm-context-muted{font-size:12px;color:var(--dsw-alias-label-secondary,#737780)}.cm-context-intro-actions{display:flex;gap:8px;margin-left:auto}
|
|
45
45
|
.cm-context-previews{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin:18px 0}.cm-context-preview{border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:12px;padding:14px;min-width:0;background:var(--dsw-alias-bg-layer-1,#f7f8fa)}.cm-context-preview h3{font-size:12px;font-weight:500;margin:0 0 12px}.cm-context-preview-card{background:var(--dsw-alias-bg-base,#fff);border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:10px;padding:14px}.cm-context-preview-number{font-size:22px;font-variant-numeric:tabular-nums;margin:6px 0}.cm-context-preview-number span{font-size:11px;font-weight:400}.cm-context-preview-bar{height:8px;display:flex;overflow:hidden;border-radius:4px;margin:10px 0}.cm-context-preview-bar i{display:block}.cm-context-preview-legend{display:flex;flex-wrap:wrap;gap:4px 10px;font-size:10px;color:var(--dsw-alias-label-secondary,#737780)}.cm-context-preview-extra{border-top:1px solid var(--dsw-alias-border-l3,#e9eaed);margin-top:14px;padding-top:12px}.cm-context-preview-metrics{display:flex;gap:12px;margin:8px 0}.cm-context-preview-metrics span{display:block;font-size:10px;color:var(--dsw-alias-label-secondary,#737780)}.cm-context-preview-metrics b{font-size:15px;font-weight:500}.cm-context-preview-row{display:flex;justify-content:space-between;font-size:11px;margin-top:8px}
|
|
46
46
|
.cm-context-setting{border:1px solid var(--dsw-alias-border-l3,#e9eaed);border-radius:12px;padding:14px 16px;margin-bottom:18px}.cm-context-setting label{display:flex;align-items:center;gap:9px;cursor:pointer}.cm-context-setting input{accent-color:var(--dsw-alias-state-business-primary,#4d6bfe);width:15px;height:15px}.cm-context-setting p{margin-top:7px}.cm-context-setting .cm-plan-actions{margin-top:8px}
|
|
47
47
|
@media(max-width:580px){.cm-context-previews{grid-template-columns:1fr}.cm-context-intro-body{padding:16px}.cm-context-intro-head,.cm-context-intro-foot{padding:14px 16px}.cm-context-intro-foot>p{width:100%}.cm-context-intro-actions{width:100%}.cm-context-intro-actions button{flex:1}}
|
|
48
|
-
`;function Jt({after:e,text:n}){const l=[n("系统","System"),n("工具定义","Tools"),n("用户","User"),n("历史回复","Replies"),n("工具结果","Results")],o=[0,1,2,5,6].map(c=>G[c]);return t("section",{className:"cm-context-preview","aria-label":e?n("启用后预览","Enabled preview"):n("启用前预览","Before preview")},t("h3",null,e?n("启用后 · 上下文 + 费用","After · context + costs"):n("启用前 · 上下文","Before · context")),t("div",{className:"cm-context-preview-card"},t("p",null,n("当前上下文","Current context")),t("div",{className:"cm-context-preview-number"},"12,000",t("span",null," / 128,000 tokens")),t("div",{className:"cm-context-preview-bar","aria-hidden":!0,style:{background:"var(--dsw-alias-border-l3,#e5e7eb)"}},...[10,15,10,15,50].map((c,a)=>t("i",{key:a,style:{width:c*12e3/128e3+"%",background:o[a]}}))),t("div",{className:"cm-context-preview-legend"},...l.map((c,a)=>t("span",{key:c},t("i",{className:"cm-plan-dot",style:{background:o[a]}}),c))),e?t("div",{className:"cm-plan cm-context-preview-extra"},t("p",null,n("上下文费用构成","Context cost breakdown")),t("div",{className:"cm-context-preview-metrics"},t("div",null,t("span",null,n("输入费用参考","Input cost reference")),t("b",null,"≈ $0.012"))),t("p",{className:"cm-context-muted"},n("按非缓存单价估算","Estimated at uncached rates")),t(lt,{text:n,total:12e3,label:n("费用占比","Cost share"),rows:[1200,1800,1200,1800,6e3].map((c,a)=>({key:String(a),label:l[a],value:c,tokens:c,amount:"≈ $"+c/1e6,color:o[a]}))}),t("div",{className:"cm-context-preview-extra"},t("p",null,n("最近一次调用","Latest call")),t("div",{className:"cm-context-preview-row"},t("span",null,n("输入 $0.012 · 输出 $0.004","Input $0.012 · output $0.004"))),t("p",{className:"cm-context-muted"},n("用量计费合计 $0.016","Usage-based total $0.016")))):null))}function be({manager:e,getLocale:n}){const l=wt.useSyncExternalStore(e.subscribe,e.getSnapshot),o=dt(null),c=(a,p)=>n()==="en"?p:a;return nt(()=>{const a=o.current;if(!l.prompt||!a)return;let p=!0,u=!1,r=null;const b=()=>{if(!(!p||u||document.hidden)){if(!l.manual&&ue()){e.dismiss();return}if(!(!l.manual&&[...document.querySelectorAll('dialog[open],[role="dialog"],[aria-modal="true"],.lc-modal-backdrop')].some(m=>m!==a&&m.getClientRects().length)))try{r=document.activeElement,a.showModal(),u=!0,e.opened()}catch{}}};b();const x=setInterval(b,1e3);return()=>{p=!1,clearInterval(x),a.open&&a.close(),u&&r?.isConnected&&r.focus?.({preventScroll:!0})}},[l.prompt,l.manual,e]),l.prompt?t("dialog",{ref:o,className:"cm-context-intro","aria-labelledby":"cm-context-intro-title","aria-describedby":"cm-context-intro-description",onKeyDown:a=>{if(a.key!=="Tab")return;const p=[...a.currentTarget.querySelectorAll("button:not(:disabled)")].filter(b=>b.getClientRects().length),u=p[0],r=p.at(-1);(a.shiftKey&&document.activeElement===u||!a.shiftKey&&document.activeElement===r)&&(a.preventDefault(),(a.shiftKey?r:u)?.focus())},onCancel:a=>{a.preventDefault(),e.dismiss()},onClose:()=>{e.getSnapshot().prompt&&e.dismiss()},onClick:a=>{if(a.target===a.currentTarget){const p=a.currentTarget.getBoundingClientRect();(a.clientX<p.left||a.clientX>p.right||a.clientY<p.top||a.clientY>p.bottom)&&e.dismiss()}}},t("style",null,jt+fe),t("header",{className:"cm-context-intro-head"},t("div",null,t("h2",{id:"cm-context-intro-title"},c("让上下文占用与费用一起可见","See context usage and costs together")),t("p",{className:"cm-context-muted"},"dsh-context × dsh-cost-meter")),t("button",{type:"button",className:"cm-context-close","aria-label":c("关闭预览","Close preview"),autoFocus:!0,onClick:()=>{e.dismiss()}},"×")),t("div",{className:"cm-context-intro-body"},t("p",{id:"cm-context-intro-description"},l.available?c("已检测到兼容版本 ","Compatible version detected: ")+"dsh-context "+l.peer.version+c("。启用后,在它的当前上下文面板内增加上下文费用区。",". Add context costs inside its current-context panel."):c("界面预览。检测到已验证的兼容版本后,可以开启联动。","Interface preview. Enable integration when a verified compatible version is detected.")),t("div",{className:"cm-context-previews"},t(Jt,{text:c,after:!1}),t(Jt,{text:c,after:!0}))),t("footer",{className:"cm-context-intro-foot"},t("div",{className:"cm-context-intro-actions"},t("button",{type:"button",onClick:()=>{e.dismiss()}},l.manual?c("关闭预览","Close preview"):c("暂不启用","Not now")),t("button",{type:"button",className:"cm-context-primary",disabled:!l.available||l.saving,onClick:()=>{e.choose(!0)}},c("启用联动","Enable integration"))))):null}function Qt({manager:e,getLocale:n}){const l=wt.useSyncExternalStore(e.subscribe,e.getSnapshot),o=(c,a)=>n()==="en"?a:c;return t("details",{className:"cm-plan cm-context-setting","aria-label":o("dsh-context 联动设置","dsh-context integration settings")},t("style",null,jt+fe),t("summary",null,"dsh-context "+o("联动","integration")+" · "+(l.enabled?o("已启用","On"):o("未启用","Off"))),t("div",null,t("label",null,t("input",{type:"checkbox",role:"switch",checked:l.enabled,disabled:l.saving||!l.available,onChange:c=>{e.choose(c.target.checked)}}),o("在 dsh-context 面板中显示上下文费用","Show context costs in dsh-context")),t("p",{className:"cm-plan-sub"},l.available?"dsh-context "+l.peer.version:l.peer.reason==="missing"?o("请安装并启用 dsh-context,然后重新检测。","Install and enable dsh-context, then check again."):l.peer.reason==="unavailable"?o("无法读取 dsh-context 状态,请重新检测。","Could not read dsh-context status. Check again."):o("当前 dsh-context 未提供所需界面接口,请更新插件或宿主后重新检测。","Required dsh-context view interfaces are unavailable. Update the plugin or host, then check again.")),l.error?t("p",{className:"cm-plan-error",role:"alert"},o("设置保存失败,联动保持关闭。可在此重试。","Could not save the setting; integration remains off. Retry here.")):null,t("div",{className:"cm-plan-actions"},t("button",{type:"button",onClick:e.preview},o("查看启用前后预览","Preview before and after")),t("button",{type:"button",onClick:e.refresh},o("重新检测","Check again")))))}function xt({offset:e,count:n,size:l,onChange:o,text:c}){return t("div",{className:"cm-stat-page"},t("span",{className:"cm-stat-sub"},n?`${e+1}–${Math.min(e+l,n)} / ${n}`:"0"),Y(c("上一页","Previous"),()=>o(Math.max(0,e-l)),{disabled:!e}),Y(c("下一页","Next"),()=>o(e+l),{disabled:e+l>=n}))}function he({rows:e,money:n,text:l,onSelect:o,label:c}){const a=Math.max(0,...e.map(u=>u.value)),p=e.reduce((u,r)=>u+r.value,0);return t("div",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c),t("span",{className:"cm-stat-sub"},l("最高 ","Peak ")+n(a)+" · "+l("合计 ","Total ")+n(p))),t("div",{className:"cm-stat-chart",role:"group","aria-label":c},e.map((u,r)=>t("button",{key:r,type:"button",className:"cm-stat-bar",title:u.label+" · "+n(u.value),"aria-label":u.label+" · "+n(u.value),onClick:()=>o(u)},t("span",{style:{height:a?Math.max(1,u.value/a*100)+"%":"0%",opacity:u.value?void 0:.2}})))),t("div",{className:"cm-stat-axis"},t("span",null,e[0]?.label),t("span",null,e.at(-1)?.label)))}function ve(e,n){const l=Math.max(1,Math.ceil(e.length/60)),o=[];for(let c=0;c<e.length;c+=l){const a=e.slice(c,c+l),p=a[0].date,u=a.at(-1).date;o.push({from:p,to:u,label:p===u?p:p+" – "+u,value:a.reduce((r,b)=>r+D(b,n),0)})}return o}function xe({title:e,rows:n,total:l,format:o,text:c,columns:a=!1}){return t("section",{"aria-label":e},t("h3",null,e),l<=0?t("p",{className:"cm-stat-sub"},c("暂无可计算的占比","No measurable share yet")):t("ol",{className:"cm-stat-share-list"+(a?" cm-stat-step-list":"")},n.map((p,u)=>t("li",{key:u,"data-other":p.other||void 0},t("div",{className:"cm-stat-share-head"},t("span",null,p.label),t("span",{className:"cm-stat-share-value"},o(p.value)+(p.unpriced?" + ?":"")+" · "+_(p.value,l))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{className:"cm-stat-share-fill",style:{width:Math.min(100,100*p.value/l)+"%"}}))))))}function ye({api:e,sessionId:n,turn:l,revision:o,text:c}){const[a,p]=j(0),[u,r]=j(0),b=vt(e,"getTurnInspection",{sessionId:n,turn:l,offset:a},o+":"+u),x=()=>Y(c("重试","Retry"),()=>r(z=>z+1)),m=t("div",{className:"cm-stat-inspection"},ot(b.error),x()),I=b.failed?m:null;if(Pt(b))return b.loading?t("p",{className:"cm-stat-empty",role:"status"},c("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…")):m;const d=b.value;return d.found?t("div",{className:"cm-stat-inspection"},I,t("h4",null,c("本轮用户输入","User input for this turn")),d.input?t("pre",{className:"cm-stat-pre"},d.input):t("p",{className:"cm-stat-sub"},c("日志未记录本轮用户输入。","No user input is recorded for this turn.")),d.inputTruncated?t("p",{className:"cm-stat-truncated"},c("显示前 16,000 字符","First 16,000 characters")):null,t("h4",null,c("工具调用","Tool calls")+" · "+d.totalTools),d.totalTools?null:t("p",{className:"cm-stat-sub"},c("这一轮没有工具调用记录。","No tool calls are recorded in this turn.")),d.tools.map(z=>t("details",{key:z.seq,className:"cm-stat-tool"},t("summary",null,t("span",null,(z.step==null?"":c("步骤 ","Step ")+z.step+" · ")+z.name),t("span",{className:"cm-stat-sub"},{complete:c("已完成","Completed"),error:c("调用失败","Failed"),pending:c("未记录结果","No recorded result")}[z.status])),t("h4",{style:{marginTop:12}},c("调用参数","Arguments")),t("pre",{className:"cm-stat-pre"},z.arguments),t("h4",null,c("返回结果","Result")),t("pre",{className:"cm-stat-pre"},z.result||c("没有可显示的文本结果","No text result is available")),z.truncated?t("p",{className:"cm-stat-truncated"},c("内容已截取","Content truncated")):null)),t(xt,{offset:a,count:d.totalTools,size:20,onChange:p,text:c})):t(tt,null,I,t("p",{className:"cm-stat-note"},c("这一轮的原始日志不可用。","Original records for this turn are unavailable.")))}function je({api:e,sessionId:n,seq:l,atMs:o,revision:c,text:a,view:p,onViewChange:u}){const[r,b]=j(0),[x,m]=j(0),I=vt(e,"getCallInspection",{sessionId:n,seq:l,atMs:o,offset:r},c+":"+x),d=I.value,z=(w,g,P=!1)=>g?t("details",{className:"cm-stat-tool",open:P},t("summary",null,w,t("span",{className:"cm-stat-sub"},g.length.toLocaleString()+a(" 字符"," chars"))),t("pre",{className:"cm-stat-pre"},g)):null;return t("section",{className:"cm-stat-inspection cm-call-content","aria-label":a("调用内容","Call content")},t("nav",{className:"cm-session-tabs","aria-label":a("调用内容视图","Call content views")},...[["input",a("输入记录","Inputs")],["output",a("模型回复","Response")],["tools",a("工具调用","Tools")+(d?.totalTools?" · "+d.totalTools:"")]].map(([w,g])=>Y(g,()=>u(w),{key:w,"aria-pressed":p===w}))),I.failed?t(tt,null,ot(I.error),Y(a("重试","Retry"),()=>m(w=>w+1))):null,d?d.found?t(tt,null,p==="output"?t(tt,null,z(d.kind==="compaction"?a("压缩摘要","Compaction summary"):a("本次回复","Response"),d.output,!0),z(a("思考内容","Reasoning"),d.reasoning,!d.output),!d.output&&!d.reasoning?t("p",{className:"cm-stat-sub"},d.totalTools?a("本次回复为工具调用","This response contains tool calls"):a("未记录回复内容","No recorded response")):null):null,p==="input"?t(tt,null,z(a("本轮用户输入","Turn input"),d.input,!0),z(a("技能内容","Skills"),d.skills),z(a("注入内容","Injected context"),d.injected),z(a("上一步工具返回","Previous step’s tool results"),d.precedingTools),!d.input&&!d.skills&&!d.injected&&!d.precedingTools?t("p",{className:"cm-stat-sub"},a("未记录输入内容","No recorded input")):null):null,p==="tools"?t(tt,null,d.totalTools?null:t("p",{className:"cm-stat-sub"},a("本次没有工具调用","No tools in this call")),...d.tools.map((w,g)=>t("details",{key:w.callId,className:"cm-stat-tool",open:g===0},t("summary",null,w.name,t("span",{className:"cm-stat-sub"},(w.durationMs!=null?(w.durationMs/1e3).toLocaleString(void 0,{maximumFractionDigits:2})+" s · ":"")+{complete:a("已完成","Completed"),error:a("失败","Failed"),pending:a("未记录结果","No result")}[w.status])),t("div",{className:"cm-call-tool-parts"},t("div",null,t("h4",null,a("参数","Arguments")),t("pre",{className:"cm-stat-pre"},w.arguments)),t("div",null,t("h4",null,a("返回结果","Result")),t("pre",{className:"cm-stat-pre"},w.result||"—"))),w.truncated?t("span",{className:"cm-stat-truncated"},a("内容已截取","Content truncated")):null)),d.totalTools>20?t(xt,{offset:r,count:d.totalTools,size:20,onChange:b,text:a}):null):null,d.truncated?t("span",{className:"cm-stat-truncated"},a("长文本显示前 16,000 字符","Long text limited to 16,000 characters")):null):t("p",{className:"cm-stat-sub"},a("原始内容不可用","Original content unavailable")):I.loading?t("p",{role:"status"},a("读取调用内容…","Loading call content…")):null)}function Oe({call:e,sessionId:n,api:l,revision:o,money:c,text:a,names:p}){const[u,r]=j("output"),b=e.rows.filter(m=>m.tokens>0),x=b.filter(m=>m.bucket!=="reasoning"||m.cost>0||!m.priced).map(m=>({key:m.bucket,label:p[m.bucket],tokens:m.tokens,value:m.cost,unpriced:!m.priced,amount:m.priced?c(m.cost):a("未定价","Unpriced"),color:G[Ot[m.bucket]??7]}));return t("div",{className:"cm-call-detail-grid"},t("style",null,`
|
|
48
|
+
`;function Jt({after:e,text:n}){const l=[n("系统","System"),n("工具定义","Tools"),n("用户","User"),n("历史回复","Replies"),n("工具结果","Results")],o=[0,1,2,5,6].map(c=>tt[c]);return t("section",{className:"cm-context-preview","aria-label":e?n("启用后预览","Enabled preview"):n("启用前预览","Before preview")},t("h3",null,e?n("启用后 · 上下文 + 费用","After · context + costs"):n("启用前 · 上下文","Before · context")),t("div",{className:"cm-context-preview-card"},t("p",null,n("当前上下文","Current context")),t("div",{className:"cm-context-preview-number"},"12,000",t("span",null," / 128,000 tokens")),t("div",{className:"cm-context-preview-bar","aria-hidden":!0,style:{background:"var(--dsw-alias-border-l3,#e5e7eb)"}},...[10,15,10,15,50].map((c,a)=>t("i",{key:a,style:{width:c*12e3/128e3+"%",background:o[a]}}))),t("div",{className:"cm-context-preview-legend"},...l.map((c,a)=>t("span",{key:c},t("i",{className:"cm-plan-dot",style:{background:o[a]}}),c))),e?t("div",{className:"cm-plan cm-context-preview-extra"},t("p",null,n("上下文费用构成","Context cost breakdown")),t("div",{className:"cm-context-preview-metrics"},t("div",null,t("span",null,n("输入费用参考","Input cost reference")),t("b",null,"≈ $0.012"))),t("p",{className:"cm-context-muted"},n("按非缓存单价估算","Estimated at uncached rates")),t(rt,{text:n,total:12e3,label:n("费用占比","Cost share"),rows:[1200,1800,1200,1800,6e3].map((c,a)=>({key:String(a),label:l[a],value:c,tokens:c,amount:"≈ $"+c/1e6,color:o[a]}))}),t("div",{className:"cm-context-preview-extra"},t("p",null,n("最近一次调用","Latest call")),t("div",{className:"cm-context-preview-row"},t("span",null,n("输入 $0.012 · 输出 $0.004","Input $0.012 · output $0.004"))),t("p",{className:"cm-context-muted"},n("用量计费合计 $0.016","Usage-based total $0.016")))):null))}function be({manager:e,getLocale:n}){const l=wt.useSyncExternalStore(e.subscribe,e.getSnapshot),o=dt(null),c=(a,m)=>n()==="en"?m:a;return ct(()=>{const a=o.current;if(!l.prompt||!a)return;let m=!0,u=!1,r=null;const b=()=>{if(!(!m||u||document.hidden)){if(!l.manual&&ue()){e.dismiss();return}if(!(!l.manual&&[...document.querySelectorAll('dialog[open],[role="dialog"],[aria-modal="true"],.lc-modal-backdrop')].some(i=>i!==a&&i.getClientRects().length)))try{r=document.activeElement,a.showModal(),u=!0,e.opened()}catch{}}};b();const C=setInterval(b,1e3);return()=>{m=!1,clearInterval(C),a.open&&a.close(),u&&r?.isConnected&&r.focus?.({preventScroll:!0})}},[l.prompt,l.manual,e]),l.prompt?t("dialog",{ref:o,className:"cm-context-intro","aria-labelledby":"cm-context-intro-title","aria-describedby":"cm-context-intro-description",onKeyDown:a=>{if(a.key!=="Tab")return;const m=[...a.currentTarget.querySelectorAll("button:not(:disabled)")].filter(b=>b.getClientRects().length),u=m[0],r=m.at(-1);(a.shiftKey&&document.activeElement===u||!a.shiftKey&&document.activeElement===r)&&(a.preventDefault(),(a.shiftKey?r:u)?.focus())},onCancel:a=>{a.preventDefault(),e.dismiss()},onClose:()=>{e.getSnapshot().prompt&&e.dismiss()},onClick:a=>{if(a.target===a.currentTarget){const m=a.currentTarget.getBoundingClientRect();(a.clientX<m.left||a.clientX>m.right||a.clientY<m.top||a.clientY>m.bottom)&&e.dismiss()}}},t("style",null,jt+fe),t("header",{className:"cm-context-intro-head"},t("div",null,t("h2",{id:"cm-context-intro-title"},c("让上下文占用与费用一起可见","See context usage and costs together")),t("p",{className:"cm-context-muted"},"dsh-context × dsh-cost-meter")),t("button",{type:"button",className:"cm-context-close","aria-label":c("关闭预览","Close preview"),autoFocus:!0,onClick:()=>{e.dismiss()}},"×")),t("div",{className:"cm-context-intro-body"},t("p",{id:"cm-context-intro-description"},l.available?c("已检测到兼容版本 ","Compatible version detected: ")+"dsh-context "+l.peer.version+c("。启用后,在它的当前上下文面板内增加上下文费用区。",". Add context costs inside its current-context panel."):c("界面预览。检测到已验证的兼容版本后,可以开启联动。","Interface preview. Enable integration when a verified compatible version is detected.")),t("div",{className:"cm-context-previews"},t(Jt,{text:c,after:!1}),t(Jt,{text:c,after:!0}))),t("footer",{className:"cm-context-intro-foot"},t("div",{className:"cm-context-intro-actions"},t("button",{type:"button",onClick:()=>{e.dismiss()}},l.manual?c("关闭预览","Close preview"):c("暂不启用","Not now")),t("button",{type:"button",className:"cm-context-primary",disabled:!l.available||l.saving,onClick:()=>{e.choose(!0)}},c("启用联动","Enable integration"))))):null}function Qt({manager:e,getLocale:n}){const l=wt.useSyncExternalStore(e.subscribe,e.getSnapshot),o=(c,a)=>n()==="en"?a:c;return t("details",{className:"cm-plan cm-context-setting","aria-label":o("dsh-context 联动设置","dsh-context integration settings")},t("style",null,jt+fe),t("summary",null,"dsh-context "+o("联动","integration")+" · "+(l.enabled?o("已启用","On"):o("未启用","Off"))),t("div",null,t("label",null,t("input",{type:"checkbox",role:"switch",checked:l.enabled,disabled:l.saving||!l.available,onChange:c=>{e.choose(c.target.checked)}}),o("在 dsh-context 面板中显示上下文费用","Show context costs in dsh-context")),t("p",{className:"cm-plan-sub"},l.available?"dsh-context "+l.peer.version:l.peer.reason==="missing"?o("请安装并启用 dsh-context,然后重新检测。","Install and enable dsh-context, then check again."):l.peer.reason==="unavailable"?o("无法读取 dsh-context 状态,请重新检测。","Could not read dsh-context status. Check again."):o("当前 dsh-context 未提供所需界面接口,请更新插件或宿主后重新检测。","Required dsh-context view interfaces are unavailable. Update the plugin or host, then check again.")),l.error?t("p",{className:"cm-plan-error",role:"alert"},o("设置保存失败,联动保持关闭。可在此重试。","Could not save the setting; integration remains off. Retry here.")):null,t("div",{className:"cm-plan-actions"},t("button",{type:"button",onClick:e.preview},o("查看启用前后预览","Preview before and after")),t("button",{type:"button",onClick:e.refresh},o("重新检测","Check again")))))}function xt({offset:e,count:n,size:l,onChange:o,text:c}){return t("div",{className:"cm-stat-page"},t("span",{className:"cm-stat-sub"},n?`${e+1}–${Math.min(e+l,n)} / ${n}`:"0"),Y(c("上一页","Previous"),()=>o(Math.max(0,e-l)),{disabled:!e}),Y(c("下一页","Next"),()=>o(e+l),{disabled:e+l>=n}))}function he({rows:e,money:n,text:l,onSelect:o,label:c}){const a=Math.max(0,...e.map(u=>u.value)),m=e.reduce((u,r)=>u+r.value,0);return t("div",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c),t("span",{className:"cm-stat-sub"},l("最高 ","Peak ")+n(a)+" · "+l("合计 ","Total ")+n(m))),t("div",{className:"cm-stat-chart",role:"group","aria-label":c},e.map((u,r)=>t("button",{key:r,type:"button",className:"cm-stat-bar",title:u.label+" · "+n(u.value),"aria-label":u.label+" · "+n(u.value),onClick:()=>o(u)},t("span",{style:{height:a?Math.max(1,u.value/a*100)+"%":"0%",opacity:u.value?void 0:.2}})))),t("div",{className:"cm-stat-axis"},t("span",null,e[0]?.label),t("span",null,e.at(-1)?.label)))}function ve(e,n){const l=Math.max(1,Math.ceil(e.length/60)),o=[];for(let c=0;c<e.length;c+=l){const a=e.slice(c,c+l),m=a[0].date,u=a.at(-1).date;o.push({from:m,to:u,label:m===u?m:m+" – "+u,value:a.reduce((r,b)=>r+W(b,n),0)})}return o}function xe({title:e,rows:n,total:l,format:o,text:c,columns:a=!1}){return t("section",{"aria-label":e},t("h3",null,e),l<=0?t("p",{className:"cm-stat-sub"},c("暂无可计算的占比","No measurable share yet")):t("ol",{className:"cm-stat-share-list"+(a?" cm-stat-step-list":"")},n.map((m,u)=>t("li",{key:u,"data-other":m.other||void 0},t("div",{className:"cm-stat-share-head"},t("span",null,m.label),t("span",{className:"cm-stat-share-value"},o(m.value)+(m.unpriced?" + ?":"")+" · "+_(m.value,l))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{className:"cm-stat-share-fill",style:{width:Math.min(100,100*m.value/l)+"%"}}))))))}function ye({api:e,sessionId:n,turn:l,revision:o,text:c}){const[a,m]=A(0),[u,r]=A(0),b=vt(e,"getTurnInspection",{sessionId:n,turn:l,offset:a},o+":"+u),C=()=>Y(c("重试","Retry"),()=>r(w=>w+1)),i=t("div",{className:"cm-stat-inspection"},lt(b.error),C()),M=b.failed?i:null;if(Pt(b))return b.loading?t("p",{className:"cm-stat-empty",role:"status"},c("读取这一轮的输入和工具调用…","Loading this turn’s input and tools…")):i;const d=b.value;return d.found?t("div",{className:"cm-stat-inspection"},M,t("h4",null,c("本轮用户输入","User input for this turn")),d.input?t("pre",{className:"cm-stat-pre"},d.input):t("p",{className:"cm-stat-sub"},c("日志未记录本轮用户输入。","No user input is recorded for this turn.")),d.inputTruncated?t("p",{className:"cm-stat-truncated"},c("显示前 16,000 字符","First 16,000 characters")):null,t("h4",null,c("工具调用","Tool calls")+" · "+d.totalTools),d.totalTools?null:t("p",{className:"cm-stat-sub"},c("这一轮没有工具调用记录。","No tool calls are recorded in this turn.")),d.tools.map(w=>t("details",{key:w.seq,className:"cm-stat-tool"},t("summary",null,t("span",null,(w.step==null?"":c("步骤 ","Step ")+w.step+" · ")+w.name),t("span",{className:"cm-stat-sub"},{complete:c("已完成","Completed"),error:c("调用失败","Failed"),pending:c("未记录结果","No recorded result")}[w.status])),t("h4",{style:{marginTop:12}},c("调用参数","Arguments")),t("pre",{className:"cm-stat-pre"},w.arguments),t("h4",null,c("返回结果","Result")),t("pre",{className:"cm-stat-pre"},w.result||c("没有可显示的文本结果","No text result is available")),w.truncated?t("p",{className:"cm-stat-truncated"},c("内容已截取","Content truncated")):null)),t(xt,{offset:a,count:d.totalTools,size:20,onChange:m,text:c})):t(Z,null,M,t("p",{className:"cm-stat-note"},c("这一轮的原始日志不可用。","Original records for this turn are unavailable.")))}function je({api:e,sessionId:n,seq:l,atMs:o,revision:c,text:a,view:m,onViewChange:u}){const[r,b]=A(0),[C,i]=A(0),M=vt(e,"getCallInspection",{sessionId:n,seq:l,atMs:o,offset:r},c+":"+C),d=M.value,w=(y,v,j=!1)=>v?t("details",{className:"cm-stat-tool",open:j},t("summary",null,y,t("span",{className:"cm-stat-sub"},v.length.toLocaleString()+a(" 字符"," chars"))),t("pre",{className:"cm-stat-pre"},v)):null;return t("section",{className:"cm-stat-inspection cm-call-content","aria-label":a("调用内容","Call content")},t("nav",{className:"cm-session-tabs","aria-label":a("调用内容视图","Call content views")},...[["input",a("输入记录","Inputs")],["output",a("模型回复","Response")],["tools",a("工具调用","Tools")+(d?.totalTools?" · "+d.totalTools:"")]].map(([y,v])=>Y(v,()=>u(y),{key:y,"aria-pressed":m===y}))),M.failed?t(Z,null,lt(M.error),Y(a("重试","Retry"),()=>i(y=>y+1))):null,d?d.found?t(Z,null,m==="output"?t(Z,null,w(d.kind==="compaction"?a("压缩摘要","Compaction summary"):a("本次回复","Response"),d.output,!0),w(a("思考内容","Reasoning"),d.reasoning,!d.output),!d.output&&!d.reasoning?t("p",{className:"cm-stat-sub"},d.totalTools?a("本次回复为工具调用","This response contains tool calls"):a("未记录回复内容","No recorded response")):null):null,m==="input"?t(Z,null,w(a("本轮用户输入","Turn input"),d.input,!0),w(a("技能内容","Skills"),d.skills),w(a("注入内容","Injected context"),d.injected),w(a("上一步工具返回","Previous step’s tool results"),d.precedingTools),!d.input&&!d.skills&&!d.injected&&!d.precedingTools?t("p",{className:"cm-stat-sub"},a("未记录输入内容","No recorded input")):null):null,m==="tools"?t(Z,null,d.totalTools?null:t("p",{className:"cm-stat-sub"},a("本次没有工具调用","No tools in this call")),...d.tools.map((y,v)=>t("details",{key:y.callId,className:"cm-stat-tool",open:v===0},t("summary",null,y.name,t("span",{className:"cm-stat-sub"},(y.durationMs!=null?(y.durationMs/1e3).toLocaleString(void 0,{maximumFractionDigits:2})+" s · ":"")+{complete:a("已完成","Completed"),error:a("失败","Failed"),pending:a("未记录结果","No result")}[y.status])),t("div",{className:"cm-call-tool-parts"},t("div",null,t("h4",null,a("参数","Arguments")),t("pre",{className:"cm-stat-pre"},y.arguments)),t("div",null,t("h4",null,a("返回结果","Result")),t("pre",{className:"cm-stat-pre"},y.result||"—"))),y.truncated?t("span",{className:"cm-stat-truncated"},a("内容已截取","Content truncated")):null)),d.totalTools>20?t(xt,{offset:r,count:d.totalTools,size:20,onChange:b,text:a}):null):null,d.truncated?t("span",{className:"cm-stat-truncated"},a("长文本显示前 16,000 字符","Long text limited to 16,000 characters")):null):t("p",{className:"cm-stat-sub"},a("原始内容不可用","Original content unavailable")):M.loading?t("p",{role:"status"},a("读取调用内容…","Loading call content…")):null)}function Oe({call:e,sessionId:n,api:l,revision:o,money:c,text:a,names:m}){const[u,r]=A("output"),b=e.rows.filter(i=>i.tokens>0),C=b.filter(i=>i.bucket!=="reasoning"||i.cost>0||!i.priced).map(i=>({key:i.bucket,label:m[i.bucket],tokens:i.tokens,value:i.cost,unpriced:!i.priced,amount:i.priced?c(i.cost):a("未定价","Unpriced"),color:tt[Ot[i.bucket]??7]}));return t("div",{className:"cm-call-detail-grid"},t("style",null,`
|
|
49
49
|
.cm-call-detail-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.35fr);gap:18px;margin-top:12px;align-items:start}
|
|
50
50
|
.cm-call-bill{min-width:0;container-type:inline-size}.cm-call-bill .cm-stat-value{font-size:22px}.cm-call-bill .cm-cost-chart{margin:10px 0 0}.cm-call-bill .cm-stat-table{font-size:11px}.cm-call-bill .cm-stat-table td,.cm-call-bill .cm-stat-table th{padding:8px 6px}.cm-call-bill .cm-stat-table td{font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
51
51
|
.cm-call-content{min-width:0;padding:12px;margin:0}.cm-call-content .cm-session-tabs{margin-bottom:10px}.cm-call-content .cm-stat-pre{max-height:220px;font-size:12px;margin-bottom:8px}.cm-call-content .cm-stat-tool{padding:8px 0}.cm-call-content .cm-stat-tool>summary{color:var(--dsw-alias-label-primary)}.cm-call-tool-parts{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);gap:10px;margin-top:10px}.cm-call-tool-parts>div{min-width:0}
|
|
52
52
|
@container(max-width:850px){.cm-call-detail-grid{grid-template-columns:1fr}.cm-call-tool-parts{grid-template-columns:1fr}}
|
|
53
|
-
`),t("section",{className:"cm-plan cm-call-bill","aria-label":a("本次计费明细","Call billing breakdown")},t("div",{className:"cm-stat-panel-head"},t("h3",null,e.plan?a("Plan 等值费用","Plan equivalent"):a("API 费用","API cost")),t("strong",{className:"cm-stat-value"},e.priced?c(e.cost):"?")),t("p",{className:"cm-stat-sub"},new Date(e.atMs).toLocaleString()),t(
|
|
53
|
+
`),t("section",{className:"cm-plan cm-call-bill","aria-label":a("本次计费明细","Call billing breakdown")},t("div",{className:"cm-stat-panel-head"},t("h3",null,e.plan?a("Plan 等值费用","Plan equivalent"):a("API 费用","API cost")),t("strong",{className:"cm-stat-value"},e.priced?c(e.cost):"?")),t("p",{className:"cm-stat-sub"},new Date(e.atMs).toLocaleString()),t(rt,{rows:C,total:e.cost,label:a("本次费用构成","This call’s costs"),text:a,amounts:!0,onSelect:i=>r(["output","reasoning"].includes(i.key)?"output":"input")}),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[a("计费项目","Component"),"Tokens",a("单价 / 百万","Rate / 1M"),a("金额","Cost"),a("占比","Share")].map(i=>t("th",{key:i},i)))),t("tbody",null,...b.map(i=>{const M=i.bucket==="reasoning"&&i.priced&&i.rate===0;return t("tr",{key:i.bucket},t("td",null,m[i.bucket]),t("td",null,i.tokens.toLocaleString()),t("td",null,i.priced?c(i.rate):"?"),t("td",null,M?a("未单独计费","No separate charge"):i.priced?c(i.cost):"?"),t("td",null,i.priced&&!M?_(i.cost,e.cost):"—"))}))))),e.logSeq!=null?t(je,{api:l,sessionId:e.sessionId||n,seq:e.logSeq,atMs:e.atMs,revision:o,text:a,view:u,onViewChange:r}):t("p",{className:"cm-stat-sub"},a("未保存调用内容","Call content not stored")))}function ke({api:e,sessionId:n,revision:l,money:o,text:c,basis:a,composition:m,detailed:u=!1}){const[r,b]=A(0),[C,i]=A([]),[M,d]=A(""),[w,y]=A([]),[v,j]=A(!1),[$,P]=A(0),S=vt(e,"getSessionTrajectory",{sessionId:n,offset:r,basis:a},l+":"+$);ct(()=>{b(0),i([]),d(""),y([])},[n,l,a]),ct(()=>{S.value?.offset===r&&i(p=>r===0?S.value.steps:[...new Map([...p,...S.value.steps].map(T=>[T.key,T])).values()])},[S.value,r]);const z=S.value,E={input:c("输入","Input"),cacheRead:c("缓存读取","Cache read"),cacheWrite:c("缓存写入","Cache write"),output:c("输出","Output"),reasoning:c("推理","Reasoning")},g=p=>({model:c("模型调用","Model calls"),compaction:c("上下文压缩","Compaction"),search:c("原生搜索","Native search")})[p]??p,O=p=>p.rows.filter(T=>a==="total"||(a==="plan"?T.plan:!T.plan)),V=(p,T)=>{const h=O(p).filter(B=>T.includes(B.bucket));return o(h.reduce((B,G)=>B+G.cost,0))+(h.some(B=>!B.priced)?" + ?":"")};if(!z)return t("p",{className:"cm-stat-sub"},S.error||c("读取步骤费用…","Reading step costs…"),S.error?Y(c("重试","Retry"),()=>P(p=>p+1)):null);const I=W(z,a),q=z.shares.map((p,T)=>({key:p.key,label:p.other?c("其余 ","Other ")+p.count+c(" 步"," steps"):(p.sessionId!==n?c("子代理 · ","Subagent · "):"")+(p.turn==null?g(p.kind):c("轮次 ","Turn ")+p.turn+(p.step==null?"":c(" · 步骤 "," · step ")+p.step)),value:W(p,a),amount:o(W(p,a))+(p.unpriced?" + ?":""),meta:p.tools.join(" + ")||g(p.kind),unpriced:p.unpriced,color:tt[p.other?7:T%7]})),H=C.length?C:z.steps,R=p=>u?!w.includes(p.key):M===p.key,L=p=>u?y(T=>T.includes(p.key)?T.filter(h=>h!==p.key):[...T,p.key]):d(M===p.key?"":p.key);return u?t("section",{className:"cm-step-cards cm-plan","aria-label":c("逐步费用明细","Cost details by step")},t("style",null,`
|
|
54
54
|
.cm-step-cards .cm-trajectory-pie{border:1px solid var(--cm-border);border-radius:12px;padding:14px;margin-bottom:12px}.cm-step-cards .cm-trajectory-pie .cm-cost-chart{grid-template-columns:180px minmax(0,1fr);gap:8px 20px;align-items:center}.cm-step-cards .cm-trajectory-pie .cm-cost-donut{width:180px;height:180px}.cm-step-cards .cm-trajectory-pie .cm-cost-center{inset:47px 30px}.cm-step-cards .cm-trajectory-pie .cm-cost-legend{grid-template-columns:repeat(2,minmax(0,1fr))}.cm-individual-steps>summary{padding:8px 0;font-size:13px}.cm-step-card-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.cm-step-fee-card{border:1px solid var(--cm-border);border-radius:12px;padding:12px;min-width:0;container-type:inline-size}.cm-step-fee-head{display:flex;justify-content:space-between;gap:8px;align-items:start}.cm-step-fee-head .cm-step-name{border:0;background:transparent;padding:0;text-align:left;font-size:12px;font-weight:500;min-width:0}.cm-step-fee-head small{display:block;margin-top:3px;overflow-wrap:anywhere;color:var(--cm-muted);font-size:10px;font-weight:400}.cm-step-fee-head strong{font-size:15px;font-weight:500;font-variant-numeric:tabular-nums}.cm-step-cards .cm-cost-chart{grid-template-columns:104px minmax(0,1fr);gap:5px 12px;margin:8px 0}.cm-step-cards .cm-cost-donut{width:104px;height:104px}.cm-step-cards .cm-cost-center{inset:25px 12px}.cm-step-cards .cm-cost-center b{font-size:19px}.cm-step-cards .cm-cost-legend{grid-template-columns:1fr;gap:2px}.cm-step-cards .cm-cost-key{padding:3px 4px;font-size:11px}.cm-step-cards .cm-cost-inspect{min-height:16px}.cm-step-cards .cm-stat-table td,.cm-step-cards .cm-stat-table th{font-size:10px;padding:6px 4px}.cm-step-cards .cm-step-rates{border-top:1px solid var(--cm-border)}.cm-step-cards .cm-step-rates td:not(:first-child){white-space:nowrap}.cm-step-cards .cm-step-more{text-align:center;margin-top:10px}
|
|
55
55
|
@container(max-width:720px){.cm-step-card-grid{grid-template-columns:1fr}.cm-step-cards .cm-trajectory-pie .cm-cost-chart{grid-template-columns:120px minmax(0,1fr);gap:6px}.cm-step-cards .cm-trajectory-pie .cm-cost-donut{width:120px;height:120px}.cm-step-cards .cm-trajectory-pie .cm-cost-center{inset:30px 18px}.cm-step-cards .cm-trajectory-pie .cm-cost-legend{grid-template-columns:1fr}}
|
|
56
|
-
`),
|
|
56
|
+
`),S.error?t("p",{className:"cm-stat-error"},S.error):null,t("section",{className:"cm-trajectory-pie","aria-label":c("轨迹步骤费用占比","Trajectory step cost shares")},t("div",{className:"cm-stat-panel-head"},t("h3",null,c("轨迹步骤费用占比","Trajectory step cost shares")),t("span",{className:"cm-stat-sub"},z.totalSteps+c(" 步 · "," steps · ")+o(I))),t(rt,{rows:q,total:I,label:c("总费用占比","Total cost share"),text:c,amounts:!0})),t("details",{className:"cm-individual-steps",open:v,onToggle:p=>{p.target===p.currentTarget&&j(p.currentTarget.open)}},t("summary",null,c("逐步费用明细","Individual step details")+" · "+z.totalSteps),v?t("div",{className:"cm-step-card-grid"},...H.map(p=>{const T=new Map;for(const h of O(p)){if(h.bucket==="reasoning"&&h.priced&&h.cost===0)continue;const B=T.get(h.bucket)??{key:h.bucket,label:E[h.bucket]??h.bucket,value:0,tokens:0,unpriced:!1,color:tt[Ot[h.bucket]??7]};B.value+=h.cost,B.tokens+=h.tokens,B.unpriced||=!h.priced,T.set(h.bucket,B)}return t("article",{className:"cm-step-fee-card",key:p.key},t("div",{className:"cm-step-fee-head"},t("button",{type:"button",className:"cm-step-name","aria-expanded":R(p),onClick:()=>L(p)},(R(p)?"⌄ ":"› ")+(p.sessionId!==n?c("子代理 · ","Subagent · "):"")+(p.turn==null?g(p.kind):c("轮次 ","Turn ")+p.turn+(p.step==null?"":c(" · 步骤 "," · step ")+p.step)),t("small",null,p.tools.length?p.tools.join(" + "):g(p.kind))),t("div",{style:{textAlign:"right"}},t("strong",null,o(W(p,a))+(p.unpriced?" + ?":"")),t("small",null,_(W(p,a),I)+c(" 会话费用"," of session cost")))),t(rt,{rows:[...T.values()].map(h=>({...h,amount:o(h.value)+(h.unpriced?" + ?":"")})),total:W(p,a),label:c("本步费用","Step cost"),text:c,amounts:!0}),R(p)?t("div",{className:"cm-step-rates cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("计费项目","Billing item"),"Tokens",c("单价 / 百万","Rate / million"),c("金额","Cost")].map(h=>t("th",{key:h},h)))),t("tbody",null,...O(p).map((h,B)=>t("tr",{key:B},t("td",{title:h.provider+" / "+h.model},E[h.bucket]??h.bucket),t("td",null,h.tokens.toLocaleString()),t("td",null,h.priced?o(h.rate):"—"),t("td",null,h.priced?o(h.cost):c("未定价","Unpriced"))))))):null)})):null),v&&H.length<z.totalSteps?t("div",{className:"cm-step-more"},Y(S.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:S.loading})):null):t("section",{className:"cm-step-costs cm-plan","aria-label":c("步骤计费","Step billing")},t("style",null,`
|
|
57
57
|
.cm-stat-session .cm-step-costs{margin:6px 0}.cm-step-costs .cm-step-name{border:0!important;padding:0!important;background:transparent!important;flex-direction:row!important;align-items:center;gap:8px!important}.cm-step-costs .cm-step-name small{max-width:150px!important}.cm-step-cost-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;align-items:start}.cm-step-cost-grid>section{min-width:0}.cm-step-cost-grid>section:last-child{grid-column:1/-1}.cm-step-costs .cm-spend-card{padding:12px!important}.cm-step-costs .cm-cost-chart{grid-template-columns:98px minmax(0,1fr);gap:4px 8px;margin-top:8px}.cm-step-costs .cm-cost-donut{width:98px;height:98px}.cm-step-costs .cm-cost-center{inset:24px 12px}.cm-step-costs .cm-cost-center b{font-size:18px}.cm-step-costs .cm-cost-key{padding:4px 2px!important;font-size:11px!important}.cm-step-costs .cm-cost-legend{grid-template-columns:1fr}.cm-step-costs .cm-cost-inspect{min-height:16px}.cm-step-costs .cm-stat-table td,.cm-step-costs .cm-stat-table th{padding:6px;font-size:11px}.cm-step-costs td:not(:first-child){white-space:nowrap}.cm-step-costs .cm-step-name{display:flex;flex-direction:column;gap:2px;min-width:100px;font-size:12px}.cm-step-costs .cm-step-name small{color:var(--cm-muted);font-size:10px;max-width:190px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cm-step-costs .cm-step-rates{padding:10px;background:var(--cm-surface)}.cm-step-costs .cm-step-more{margin-top:8px;text-align:center}.cm-step-costs .cm-stat-panel-head{margin-bottom:6px}
|
|
58
58
|
@container(max-width:760px){.cm-step-cost-grid{grid-template-columns:1fr}.cm-step-costs .cm-cost-chart{grid-template-columns:98px minmax(0,1fr)}.cm-step-costs .cm-cost-legend{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
|
59
|
-
`),k.error?t("p",{className:"cm-stat-error"},k.error):null,t("div",{className:"cm-step-cost-grid"},p,u?null:t("section",{className:"cm-spend-card","aria-label":c("步骤费用构成","Step cost composition")},t("h3",null,c("步骤费用构成","Step cost composition")),t(lt,{rows:S,total:R,label:c("费用占比","Cost share"),text:c,amounts:!1})),t("section",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c("计费轨迹","Billing trajectory")+" · "+T.totalSteps+c(" 步"," steps"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("步骤 / 工具","Step / tools"),c("输入","Input"),c("输出","Output"),c("缓存","Cache"),c("费用","Cost"),c("占比","Share")].map(i=>t("th",{key:i},i)))),t("tbody",null,...E.map(i=>t(tt,{key:i.key},t("tr",null,t("td",null,t("button",{type:"button",className:"cm-step-name","aria-expanded":A(i),onClick:()=>W(i)},t("span",null,(A(i)?"⌄ ":"› ")+(i.sessionId!==n?c("子代理 · ","Subagent · "):"")+(i.turn==null?v(i.kind):c("轮次 ","Turn ")+i.turn+(i.step==null?"":c(" · 步骤 "," · step ")+i.step))),t("small",{title:i.tools.join(" + ")},i.tools.length?i.tools.join(" + "):v(i.kind)))),t("td",null,H(i,["input"])),t("td",null,H(i,["output","reasoning"])),t("td",null,H(i,["cacheRead","cacheWrite"])),t("td",null,o(D(i,a))+(i.unpriced?" + ?":"")),t("td",null,_(D(i,a),R))),A(i)?t("tr",null,t("td",{colSpan:6,className:"cm-step-rates"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("模型 / 项目","Model / item"),"Tokens",c("单价 / 百万","Rate / million"),c("金额","Cost")].map(M=>t("th",{key:M},M)))),t("tbody",null,...F(i).map((M,h)=>t("tr",{key:h},t("td",null,M.model+" · "+(V[M.bucket]??M.bucket)),t("td",null,M.tokens.toLocaleString()),t("td",null,M.priced?o(M.rate):"—"),t("td",null,M.priced?o(M.cost):c("未定价","Unpriced")))))))):null))))),E.length<T.totalSteps?t("div",{className:"cm-step-more"},Y(k.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:k.loading})):null)))}function Vt({api:e,query:n,revision:l,money:o,formatTokens:c,text:a,overview:p=!1,children:u}){const[r,b]=j(0),[x,m]=j(-1),[I,d]=j(0),[z,w]=j("summary"),[g,P]=j(!1),[Q,O]=j(null),[k,T]=j("cost"),[V,v]=j(0),F=vt(e,"getSessionBilling",{...n,offset:r,turnOffset:I},l+":"+V),H=dt(!1);nt(()=>{H.current&&!F.loading&&x>=0&&(document.getElementById("cm-stat-call-"+x)?.scrollIntoView({block:"nearest"}),H.current=!1)},[F.loading,F.value,r,x,z]);const R=F.value,S=n.basis,E={input:a("非缓存输入","Uncached input"),output:a("输出","Output"),cacheRead:a("缓存读取","Cache read"),cacheWrite:a("缓存写入","Cache write"),reasoning:a("推理","Reasoning")},A={model:a("模型调用","Model call"),compaction:a("上下文压缩","Compaction"),search:a("原生搜索","Native search")},W=s=>s==null?a("未标明轮次","Turn not recorded"):a("轮次 ","Turn ")+s;if(Pt(F))return F.loading?t("p",{className:"cm-stat-empty",role:"status"},a("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):ot(F.error);const i=F.failed?t("div",null,ot(F.error),Y(a("重试","Retry"),()=>v(s=>s+1))):null;if(!R.found)return t(tt,null,i,t("p",{className:"cm-stat-note"},a("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),u);const M=s=>!s||s===n.sessionId?a("主会话","Main conversation"):a("子代理 ","Subagent ")+((R.agents??[]).find(N=>N.id===s)?.title||s).slice(0,80),h=s=>JSON.stringify([s.sessionId||n.sessionId,s.turn]),B=s=>((R.agents?.length??0)>1?M(s.sessionId)+" · ":"")+W(s.turn),it=s=>S==="total"||(S==="plan"?s.plan:!s.plan),Z=Object.keys(E).map(s=>{const N=R.rows.filter(L=>L.bucket===s&&it(L));return{bucket:s,tokens:N.reduce((L,q)=>L+q.tokens,0),cost:N.reduce((L,q)=>L+q.cost,0),unpriced:N.some(L=>!L.priced)}}),st=D(R,S),pt=D(R.recorded,S),_t=Math.abs(st-pt)>Math.max(1e-8,Math.abs(pt)*1e-8)||R.totalCalls!==R.recorded.calls,yt=Z.some(s=>s.unpriced),$=yt?a("已知费用占比","Known cost share"):a("费用占比","Cost share"),ut=s=>{w("summary"),H.current=!0,b(Math.floor(s/50)*50),m(s%50)},f=s=>({key:s.bucket,label:E[s.bucket],tokens:s.tokens,value:s.cost,unpriced:s.unpriced,amount:s.unpriced&&!s.cost?a("未定价","Unpriced"):o(s.cost)+(s.unpriced?" + ?":""),color:G[Ot[s.bucket]??7]}),X=new Map;for(const s of R.rows.filter(it)){const N=JSON.stringify([s.provider,s.model]),L=X.get(N)??{key:N,label:s.model,provider:s.provider,tokens:0,value:0,unpriced:!1};L.value+=s.cost,L.tokens+=s.bucket==="reasoning"?0:s.tokens,L.unpriced||=!s.priced,X.set(N,L)}const at=[...X.values()].sort((s,N)=>N.value-s.value).map((s,N)=>({...s,label:s.provider+" / "+s.label,amount:s.unpriced&&!s.value?a("未定价","Unpriced"):o(s.value)+(s.unpriced?" + ?":""),color:G[N%7]}));if(at.length>7){const s=at.splice(7),N=s.reduce((q,Ct)=>q+Ct.value,0),L=s.some(q=>q.unpriced);at.push({key:"other-models",label:a("其余 ","Other ")+s.length+a(" 个模型"," models"),value:N,tokens:s.reduce((q,Ct)=>q+Ct.tokens,0),unpriced:L,amount:L&&!N?a("未定价","Unpriced"):o(N)+(L?" + ?":""),color:G[7]})}const kt=Z.find(s=>s.bucket==="cacheRead"),Nt=Z.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)),mt=kt.tokens>0?t("div",{className:"cm-cache-compare"},t("h3",null,a("缓存读取的占比","Cache read share")),...[[a("输入 Token","Input tokens"),kt.tokens,Nt.reduce((s,N)=>s+N.tokens,0)],[a("输入费用","Input cost"),kt.cost,Nt.some(s=>s.unpriced)?0:Nt.reduce((s,N)=>s+N.cost,0)]].map(([s,N,L])=>t("div",{key:s},t("div",{className:"cm-stat-share-head"},t("span",null,s),t("span",null,_(N,L))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{style:{display:"block",height:"100%",width:(L>0?N/L*100:0)+"%",borderRadius:9,background:G[6]}}))))):null,rt=(s,N,L={},q=null)=>t("section",{className:"cm-spend-card","aria-label":s},t("h3",null,s),t(lt,{rows:N,total:st,label:$,text:a,amounts:!0,...L}),q),Ie=(R.callShares?.length??0)>0?rt(a("每次调用费用占比","Cost share per call"),R.callShares.map((s,N)=>({...s,key:String(s.index),label:s.other?a("其余 ","Other ")+s.calls+a(" 次调用"," calls"):a("调用 #","Call #")+(s.index+1),meta:s.other?s.calls+a(" 次调用"," calls"):s.tokens.toLocaleString()+" tokens",value:D(s,S),amount:s.unpriced&&!D(s,S)?a("未定价","Unpriced"):o(D(s,S))+(s.unpriced?" + ?":""),color:G[s.other?7:N%7]})),{onSelect:s=>{s.other||ut(s.index)}}):null,Te=(s,N,L)=>t("div",{className:"cm-stat-scroll",style:{marginTop:20}},t("h3",null,s),t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[s,a("调用次数","Calls"),a("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",a("Plan 等值","Plan equivalent")].map(q=>t("th",{key:q},q)))),t("tbody",null,N.map((q,Ct)=>t("tr",{key:Ct},t("td",null,L(q)),t("td",null,q.calls),t("td",null,[q.input,q.cacheRead+q.cacheWrite,q.output].map(c).join(" / ")),t("td",null,o(q.apiCost)+(q.unpriced?" + ?":"")),t("td",null,o(Math.max(0,q.cost-q.apiCost))+(q.unpriced?" + ?":"")))))));return t("section",{className:"cm-stat-panel"},t("style",null,jt+Re),p?t("nav",{className:"cm-session-tabs","aria-label":a("费用视图","Cost views")},...[["summary",a("费用概览","Overview")],["context",a("费用明细","Cost details")]].map(([s,N])=>Y(N,()=>{w(s),m(-1),P(!1)},{key:s,"aria-pressed":z===s}))):null,p?t("div",{className:"cm-stat-metrics"},...[[S==="total"?a("API + Plan 等值","API + Plan equivalent"):S==="plan"?a("Plan 等值","Plan equivalent"):a("API 费用","API cost"),o(st)+(Z.some(s=>s.unpriced)?" + ?":""),a("按本对话调用日志估算","Estimated from this conversation’s call logs")],[a("调用次数","Calls"),R.totalCalls.toLocaleString(),(R.agents?.length??0)>1?a("包含子代理","Includes subagents"):a("本会话","This conversation")],[a("Token 用量","Token usage"),c(Z.reduce((s,N)=>s+(N.bucket==="reasoning"?0:N.tokens),0)),a("输入、缓存与输出","Input, cache and output")],[a("缓存命中率","Cache hit rate"),_(Z.find(s=>s.bucket==="cacheRead")?.tokens??0,Z.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)).reduce((s,N)=>s+N.tokens,0)),a("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([s,N,L])=>t("div",{className:"cm-stat-metric",key:s},t("div",{className:"cm-stat-sub"},s),t("div",{className:"cm-stat-value"},N),t("div",{className:"cm-stat-sub"},L)))):null,p&&z==="context"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:S,detailed:!0}):null,p?z==="context"?t("details",{className:"cm-stat-secondary"},t("summary",{style:{padding:"8px 0"}},a("上下文费用参考","Context cost reference")),u):null:u,p?null:t("div",{className:"cm-stat-panel-head"},t("h3",null,p?a("已发生费用 · 调用明细","Recorded costs · call details"):a("单对话费用明细","Conversation cost details")),t("span",{className:"cm-stat-sub"},(R.agents?.length??0)>1?a("包含子代理及其后代","Includes subagents and their descendants"):a("本会话自身的调用","Own conversation calls"))),i,!p&&_t?t("p",{className:"cm-stat-note"},a("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+o(pt)+" / "+R.recorded.calls+a(" 次;明细 "," calls; details ")+o(st)+" / "+R.totalCalls+a(" 次。"," calls.")):null,(!p||z==="calls")&&(R.agents?.length??0)>1?Te(a("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),R.agents,s=>M(s.id)):null,p?null:t("div",{className:"cm-plan cm-spend"},yt?t("p",{className:"cm-plan-sub"},a("存在未定价调用","Some calls are unpriced")):null,t("div",{className:"cm-spend-grid"},rt(a("费用构成","Cost composition"),Z.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f),{},mt),Ie,at.length>1?rt(a("模型费用分布","Cost by model"),at):null,R.kinds.length>1?rt(a("各环节费用占比","Cost by activity"),R.kinds.map((s,N)=>({key:s.kind,label:A[s.kind]??s.kind,value:D(s,S),tokens:gt(s),meta:s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok",unpriced:s.unpriced,amount:o(D(s,S))+(s.unpriced?" + ?":""),color:G[N]}))):null)),p&&z==="summary"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:S,composition:rt(a("费用构成","Cost composition"),Z.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f))}):null,!p||z==="summary"?t("details",{className:"cm-call-section",open:!p||g||x>=0,onToggle:s=>{s.target===s.currentTarget&&(P(s.currentTarget.open),s.currentTarget.open||m(-1))}},t("summary",{style:{padding:"10px 0",fontSize:13}},a("逐次调用明细","Individual calls")+" · "+R.totalCalls),p?t("div",{className:"cm-plan cm-spend-grid"},Ie,at.length>1?rt(a("模型费用分布","Cost by model"),at):mt):null,p?null:t("details",{className:"cm-stat-secondary",open:!p},t("summary",null,a("轮次、步骤与单价","Turns, steps and rates")),t("section",{className:"cm-stat-breakdown"},t("div",{className:"cm-stat-panel-head"},t("h3",null,a("各步骤占比","Share by step")),t("div",{className:"cm-stat-periods"},...[["cost",a("费用","Cost")],["calls",a("调用次数","Calls")]].map(([s,N])=>Y(N,()=>T(s),{key:s,"aria-pressed":k===s})))),t(xe,{title:k==="cost"?a("费用占比 · 全部调用","Cost share · all calls"):a("调用次数占比 · 全部调用","Call count share · all calls"),rows:(R.stepShares?.[k]??[]).map(s=>({label:s.other?a("其余步骤合计","All other steps"):B(s)+(s.step==null?"":a(" · 步骤 "," · step ")+s.step),value:k==="cost"?D(s,S):s.calls,unpriced:k==="cost"&&s.unpriced,other:s.other})),total:k==="cost"?st:R.totalCalls,format:k==="cost"?o:s=>s.toLocaleString(),text:a,columns:!0})),t("details",{className:"cm-stat-help"},t("summary",null,a("单价与 Token 明细","Rates and token details")),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[a("费用构成","Cost component"),"Tokens",a("费用","Cost"),a("费用占比","Cost share")].map(s=>t("th",{key:s},s)))),t("tbody",null,Z.map(s=>t("tr",{key:s.bucket},t("td",null,E[s.bucket]),t("td",null,s.tokens.toLocaleString()),t("td",null,o(s.cost)+(s.unpriced?" + ?":"")),t("td",null,_(s.cost,st))))))),Te(a("按调用类型统计","Cost by call type"),R.kinds,s=>A[s.kind]??s.kind)),t("section",{className:"cm-stat-turns"},t("div",{className:"cm-stat-panel-head"},t("h3",null,a("按轮次统计","Cost by turn")),t("span",{className:"cm-stat-sub"},a("展开查看输入和工具调用","Expand to inspect input and tool calls"))),R.turns.map(s=>t("div",{key:h(s),className:"cm-stat-turn"},t("button",{type:"button",className:"cm-stat-turn-toggle",disabled:s.turn==null,"aria-expanded":s.turn!=null&&Q===h(s),onClick:()=>O(N=>N===h(s)?null:h(s))},t("span",null,(s.turn==null?"":Q===h(s)?"⌄ ":"› ")+B(s)),t("span",null,s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok · "+o(D(s,S))+(s.unpriced?" + ?":"")+" · "+_(D(s,S),st))),s.turn!=null&&Q===h(s)?t(ye,{key:h(s),api:e,sessionId:s.sessionId||n.sessionId,turn:s.turn,revision:l,text:a}):null))),t(xt,{offset:I,count:R.totalTurns,size:25,onChange:s=>{d(s),O(null)},text:a})),t("div",{style:{marginTop:24}},t(he,{rows:R.calls.map((s,N)=>({label:"#"+(r+N+1),index:N,value:D(s,S)})),money:o,text:a,label:a("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:s=>{m(s.index),document.getElementById("cm-stat-call-"+s.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),R.calls.map((s,N)=>t("details",{key:r+N,id:"cm-stat-call-"+N,className:"cm-stat-call",open:x===N,onToggle:L=>{L.currentTarget.open?m(N):m(q=>q===N?-1:q)}},t("summary",null,"#"+(r+N+1)+" · "+B(s)+(s.step==null?"":a(" / 步骤 "," / step ")+s.step)+" · "+(A[s.kind]??s.kind)+" · "+s.provider+" / "+s.model+" · "+(s.plan?"Plan ":"API ")+(s.priced?o(s.cost):"?")+(s.longContext?a(" · 长上下文价"," · long-context rate"):""),t("span",{className:"cm-call-share"},(s.priced?_(D(s,S),st):"—")+" · "+$)),x===N?t(Oe,{key:(s.sessionId||n.sessionId)+":"+(s.logSeq??N),call:s,sessionId:n.sessionId,api:e,revision:l,money:o,text:a,names:E}):null)),t(xt,{offset:r,count:R.totalCalls,size:50,onChange:s=>{b(s),m(-1)},text:a})):null)}function Ne(e,n,l){const o=()=>["api","plan","total"].includes(e.statisticsBasis)?e.statisticsBasis:e.showTotalWithPlan?"total":"api",[c,a]=j(o),[p,u]=j(!1),[r,b]=j("");return nt(()=>{p||a(o())},[e.statisticsBasis,e.showTotalWithPlan,p]),{basis:c,choose:async m=>{if(!(p||!["api","plan","total"].includes(m))){a(m),u(!0),b("");try{await n.saveStatisticsBasis(m)}catch{b(l("计费口径保存失败,请重试。","Could not save the cost basis. Try again."))}finally{u(!1)}}},saving:p,error:r}}function Ce({state:e,api:n,sessionId:l,formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:p}){const u=(w,g)=>(a?a(e.config):e.config.locale)==="en"?g:w,[r,b]=j(0),x=Ne(e.config,n,u),{basis:m}=x,I=Rt(e,r),d=w=>o(w,{...e.config,decimals:Math.max(w!==0&&Math.abs(w)<.01?8:4,e.config.decimals??2)}),z={sessionId:l,from:"",to:"",provider:"",model:"",basis:m,offset:0};return t("div",{className:"cm-stat cm-stat-session","data-session-id":l},t("style",null,re),t("div",{className:"cm-stat-panel-head"},t("p",{className:"cm-stat-sub"},u("当前对话 · 全部调用","This conversation · all calls")),Y(u("刷新","Refresh"),()=>b(w=>w+1))),t(Vt,{key:l+":"+m,api:n,query:z,revision:I,money:d,formatTokens:c,text:u,overview:!0},t(Et,{key:l,api:n,sessionId:l,revision:I,money:d,text:u,compact:!0,expanded:!0})),t("details",{className:"cm-session-options"},t("summary",null,u("显示与联动设置","Display and integration settings")),t("div",{className:"cm-stat-controls"},t("label",null,u("计费口径","Cost basis"),t("select",{value:m,disabled:x.saving,onChange:w=>x.choose(w.target.value)},...[["api",u("API 费用","API cost")],["plan",u("Plan 等值","Plan equivalent")],["total",u("API + Plan 等值","API + Plan equivalent")]].map(([w,g])=>t("option",{key:w,value:w},g))))),x.error?ot(x.error):null,p?t(Qt,p):null))}function we({state:e,api:n,sessionId:l="",formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:p}){const u=a?a(e.config)==="en":e.config.locale==="en"||e.config.locale!=="zh"&&(e.config.activeLocale||e.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",r=(f,X)=>u?X:f,[b,x]=j(l?"all":"week"),[m,I]=j(null),[d,z]=j({id:l,title:l}),[w,g]=j(""),[P,Q]=j(""),O=Ne(e.config,n,r),{basis:k}=O,[T,V]=j(0),[v,F]=j(0),[H,R]=j(!1),S=e.meta.dayKey||new Date().toISOString().slice(0,10),E=b==="all"?"":b==="custom"?m?.from||S:Xt(S,b==="week"?-6:b==="month"?-29:0),A=b==="custom"&&m?.to||S,W={from:E,to:A,provider:w,model:P,basis:k,sessionId:d.id,offset:T},i=Rt(e,v),M=vt(n,"getBillingStatistics",W,i),h=M.value,B=f=>o(f,{...e.config,decimals:Math.max(f!==0&&Math.abs(f)<.01?8:4,e.config.decimals??2)}),it=f=>{x(f),V(0)},Z=f=>{z(f),V(0),g(""),Q("")},st=k==="total"?r("API + Plan 等值","API + Plan equivalent"):k==="plan"?r("Plan 等值","Plan equivalent"):r("API 费用","API cost"),pt=(f,X,at,kt,Nt=!1)=>t("label",null,f,t("select",{value:X,disabled:Nt,onChange:mt=>{at(mt.target.value),V(0)}},kt.map(([mt,rt])=>t("option",{key:mt,value:mt},rt)))),_t={input:r("未缓存输入","Uncached input"),cacheRead:r("缓存读取","Cache read"),cacheWrite:r("缓存写入","Cache write"),output:r("输出","Output")},yt=(f,X)=>t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,f)),X),$=h?.totals,ut=(f,X,at)=>t("div",{className:"cm-stat-metric",key:f},t("div",{className:"cm-stat-sub"},f),t("div",{className:"cm-stat-value"},X),t("div",{className:"cm-stat-sub"},at));return t("div",{className:"cm-stat"},t("style",null,re),p?t(Qt,p):null,t("header",{className:"cm-stat-head"},t("div",null,t("h2",null,r("计费统计","Cost statistics")),t("p",{className:"cm-stat-sub"},d.id?r("单对话 · ","Conversation · ")+(d.title===d.id&&h?.sessions[0]?.title||d.title):r("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),Y(r("刷新","Refresh"),()=>F(f=>f+1))),d.id?Y(r("← 全部对话","← All conversations"),()=>Z({id:"",title:""})):null,t("div",{className:"cm-stat-controls"},t("div",{className:"cm-stat-periods"},...[["today",r("今天","Today")],["week",r("近 7 天","Last 7 days")],["month",r("近 30 天","Last 30 days")],["all",r("全部记录","All retained")],["custom",r("自定义","Custom")]].map(([f,X])=>Y(X,()=>it(f),{key:f,"aria-pressed":b===f})))),b==="custom"?t("div",{className:"cm-stat-controls"},...["from","to"].map(f=>t("label",{key:f},f==="from"?r("开始日期","From"):r("结束日期","To"),t("input",{type:"date",value:f==="from"?E:A,onChange:X=>{I({from:E,to:A,[f]:X.target.value}),V(0)}})))):null,t("div",{className:"cm-stat-controls"},pt(r("计费口径","Cost basis"),k,O.choose,[["api",r("API 费用","API cost")],["plan",r("Plan 等值","Plan equivalent")],["total",r("API + Plan 等值","API + Plan equivalent")]],O.saving),pt(r("提供商","Provider"),w,f=>{g(f),Q("")},[["",r("全部提供商","All providers")],...[...new Set([w,...h?.providers??[]])].filter(Boolean).map(f=>[f,f])]),pt(r("模型","Model"),P,Q,[["",r("全部模型","All models")],...[...new Set([P,...h?.modelOptions??[]])].filter(Boolean).map(f=>[f,f])])),O.error?ot(O.error):null,Pt(M)?M.loading?t("p",{className:"cm-stat-empty",role:"status"},r("加载统计…","Loading statistics…")):ot(M.error):h?t(tt,null,M.failed?ot(M.error):null,t("p",{className:"cm-stat-sub",style:{marginTop:8}},h.from+" – "+h.to+(h.retainedFrom?" · "+r("账本保留范围 ","Retained ledger ")+h.retainedFrom+" – "+h.retainedTo:"")),t("div",{className:"cm-stat-metrics"},ut(r("API 费用","API cost"),B($.apiCost),r("已入账估算","Recorded estimate")),ut(r("Plan 等值费用","Plan equivalent"),B(Math.max(0,$.cost-$.apiCost)),""),ut(r("调用次数","Calls"),$.calls.toLocaleString(),h.sessionCount+r(" 个对话 · 平均 "," conversations · average ")+B($.calls?D($,k)/$.calls:0)),ut(r("缓存命中率","Cache hit rate"),_($.cacheRead,$.input+$.cacheRead+$.cacheWrite),c(gt($))+" Tokens")),d.id?t("section",{className:"cm-stat-panel"},t(Et,{key:d.id,api:n,sessionId:d.id,revision:i,money:B,text:r})):null,d.id?t(Vt,{key:JSON.stringify([d.id,E,A,w,P,k]),api:n,query:{...W,from:h.from,to:h.to,offset:0},revision:i,money:B,formatTokens:c,text:r}):null,h.models.some(f=>!f.priced)?t("p",{className:"cm-stat-note"},r("部分模型未配置价格","Some models have no rates")):null,!$.calls&&!$.cost?t("p",{className:"cm-stat-empty"},r("所选范围没有已记录的用量。","No recorded usage in this range.")):null,t("section",{className:"cm-stat-panel"},t(he,{rows:ve(h.days,k),money:B,text:r,label:r("费用趋势 · ","Cost over time · ")+st,onSelect:f=>{I({from:f.from,to:f.to}),it("custom")}})),t("div",{className:"cm-stat-grid"},yt(r("模型费用排行","Cost by model"),t(tt,null,t("ol",{className:"cm-stat-rank"},(H?h.models:h.models.slice(0,8)).map(f=>t("li",{key:f.key},t("button",{type:"button",onClick:()=>{g(f.provider),Q(f.model),V(0)},title:f.key},t("div",{className:"cm-stat-rankline"},t("span",null,f.model),t("span",{className:"cm-stat-number"},B(D(f,k))+(f.priced?"":" + ?"))),t("div",{className:"cm-stat-sub"},f.provider+" · "+f.calls+r(" 次 · "," calls · ")+_(D(f,k),D($,k))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_(D(f,k),D($,k))}}))))),h.models.length>8?Y(H?r("收起","Show less"):r("显示全部模型","Show all models"),()=>R(f=>!f)):null,h.unmodeledCost>1e-8?t("p",{className:"cm-stat-note"},r("历史未分配到模型的费用:","Historical cost without a model: ")+B(h.unmodeledCost)):null)),yt(r("Token 构成","Token composition"),t(tt,null,t("ol",{className:"cm-stat-rank"},Object.entries(_t).map(([f,X])=>t("li",{key:f},t("div",{className:"cm-stat-rankline"},t("span",null,X),t("span",{className:"cm-stat-number"},c($[f]))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_($[f],gt($)),background:f.startsWith("cache")?"var(--cm-plan)":void 0}}))))),t("p",{className:"cm-stat-sub"},r("单独上报的推理 Token:","Reported reasoning tokens: ")+c($.reasoning))))),d.id?null:t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,r("对话费用排行","Cost by conversation")),t("span",{className:"cm-stat-sub"},e.config.includeSubagentCost?r("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):r("点击对话查看明细","Select a conversation for details"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[r("对话","Conversation"),r("调用","Calls"),"API",r("Plan 等值","Plan equivalent"),r("缓存命中","Cache hits")].map(f=>t("th",{key:f},f)))),t("tbody",null,h.sessions.map(f=>t("tr",{key:f.id},t("td",null,t("button",{type:"button",title:f.id,onClick:()=>Z({id:f.id,title:f.title})},f.title)),t("td",null,f.calls.toLocaleString()),t("td",null,B(f.apiCost)),t("td",null,B(Math.max(0,f.cost-f.apiCost))),t("td",null,_(f.cacheRead,f.input+f.cacheRead+f.cacheWrite))))))),h.unassignedCost>1e-8?t("p",{className:"cm-stat-note"},r("未关联对话的费用:","Cost not linked to a conversation: ")+B(h.unassignedCost)):null,t(xt,{offset:T,count:h.sessionCount,size:25,onChange:V,text:r})))):null)}function Se(e,{state:n,sessionId:l=""}={}){if(!n||document.hidden)return;const o=Rt(n,0),c=n.meta.dayKey||new Date().toISOString().slice(0,10),a={sessionId:l,from:l?"":Xt(c,-6),to:l?"":c,provider:"",model:"",basis:n.config.showTotalWithPlan?"total":"api",offset:0};return Promise.all(l?[Mt(e,"getSessionBilling",{...a,turnOffset:0},o+":0")]:[Mt(e,"getBillingStatistics",{from:a.from,to:a.to,provider:"",model:"",basis:a.basis,sessionId:"",offset:0},o)])}async function Ee(e,n,l){const o=typeof n=="function"?n:()=>n&&l?l(n.getSnapshot().state?.config??{activeLocale:n.getSnapshot().locale}):"en",c=await e.get("remote").$mount(le);e.effect(()=>()=>c(),"cost-meter: statistics contribution");const a=e.get("remote.costMeter"),p=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getCallInspection","getContextCosts","getSessionTrajectory"].map(b=>[b,async x=>{const m=await a[b]((b==="getSessionTrajectory"?se:b==="getContextCosts"?zt:b==="getCallInspection"?oe:b==="getTurnInspection"?ne:ce)(x));if(!m?.ok)throw new Error(m?.error?.message||"Statistics request failed");return{getBillingStatistics:Bt,getSessionBilling:Dt,getTurnInspection:St,getCallInspection:Zt,getContextCosts:Ut,getSessionTrajectory:ae}[b](m.value)}]));p.saveStatisticsBasis=async b=>{const x=await a.updateConfig({statisticsBasis:b});if(!x?.ok||x.value?.config?.statisticsBasis!==b)throw new Error("Cost basis setting failed");n?.set?.({status:"ready",error:null,state:x.value})};let u;if(n?.subscribe&&typeof e.get("slots")?.entries=="function"){p.getContextIntegration=async()=>{const m=await a.getContextIntegration();if(!m?.ok)throw new Error("Integration check failed");return ee(m.value)},p.saveIntegration=async m=>{const I=await a.updateConfig({contextCostsEnabled:m,contextCostsPromptSeen:!0});if(!I?.ok||!I.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:I.value})},u=ge(e,p,n,o,Ht("react-dom").createPortal),e.effect(()=>u.dispose,"cost-meter: optional dsh-context integration");const b=e.get("slots"),x=()=>b.register({name:"shell.overlay",id:"cost-meter-context-intro",order:50},()=>t(be,{manager:u,getLocale:o}));typeof b.inject=="function"&&e.effect(()=>b.inject("shell.overlay",x),"cost-meter: context preview prompt")}const r=b=>t(b.sessionId?Ce:we,{...b,api:p,contextIntegration:u?{manager:u,getLocale:o}:null});return r.prefetch=b=>Se(p,b),e.effect(()=>()=>Ft.delete(p),"cost-meter: statistics cache cleanup"),r}return{mount:Ee,prefetchStatistics:Se,Statistics:we,SessionStatistics:Ce,SessionDetail:Vt,TurnInspection:ye,ShareChart:xe,ContextCosts:Et,ContextPrompt:be,ContextPreview:Jt,ContextIntegrationSettings:Qt,createContextIntegration:ge,contextCostBreakdown:me,installContextCosts:de,CONTRIBUTION:le,parseContextCosts:Ut,parseStatistics:Bt,parseDetail:Dt,parseInspection:St,dailyChartRows:ve,requestStart:ie,requestValue:ft,requestFailure:pe,showsPlaceholder:Pt,refreshKeyOf:Rt}}});
|
|
59
|
+
`),S.error?t("p",{className:"cm-stat-error"},S.error):null,t("div",{className:"cm-step-cost-grid"},m,u?null:t("section",{className:"cm-spend-card","aria-label":c("步骤费用构成","Step cost composition")},t("h3",null,c("步骤费用构成","Step cost composition")),t(rt,{rows:q,total:I,label:c("费用占比","Cost share"),text:c,amounts:!1})),t("section",null,t("div",{className:"cm-stat-panel-head"},t("h3",null,c("计费轨迹","Billing trajectory")+" · "+z.totalSteps+c(" 步"," steps"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("步骤 / 工具","Step / tools"),c("输入","Input"),c("输出","Output"),c("缓存","Cache"),c("费用","Cost"),c("占比","Share")].map(p=>t("th",{key:p},p)))),t("tbody",null,...H.map(p=>t(Z,{key:p.key},t("tr",null,t("td",null,t("button",{type:"button",className:"cm-step-name","aria-expanded":R(p),onClick:()=>L(p)},t("span",null,(R(p)?"⌄ ":"› ")+(p.sessionId!==n?c("子代理 · ","Subagent · "):"")+(p.turn==null?g(p.kind):c("轮次 ","Turn ")+p.turn+(p.step==null?"":c(" · 步骤 "," · step ")+p.step))),t("small",{title:p.tools.join(" + ")},p.tools.length?p.tools.join(" + "):g(p.kind)))),t("td",null,V(p,["input"])),t("td",null,V(p,["output","reasoning"])),t("td",null,V(p,["cacheRead","cacheWrite"])),t("td",null,o(W(p,a))+(p.unpriced?" + ?":"")),t("td",null,_(W(p,a),I))),R(p)?t("tr",null,t("td",{colSpan:6,className:"cm-step-rates"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[c("模型 / 项目","Model / item"),"Tokens",c("单价 / 百万","Rate / million"),c("金额","Cost")].map(T=>t("th",{key:T},T)))),t("tbody",null,...O(p).map((T,h)=>t("tr",{key:h},t("td",null,T.model+" · "+(E[T.bucket]??T.bucket)),t("td",null,T.tokens.toLocaleString()),t("td",null,T.priced?o(T.rate):"—"),t("td",null,T.priced?o(T.cost):c("未定价","Unpriced")))))))):null))))),H.length<z.totalSteps?t("div",{className:"cm-step-more"},Y(S.loading?c("读取中…","Loading…"):c("展开更多步骤","Show more steps"),()=>b(r+100),{disabled:S.loading})):null)))}function Vt({api:e,query:n,revision:l,money:o,formatTokens:c,text:a,overview:m=!1,children:u}){const[r,b]=A(0),[C,i]=A(-1),[M,d]=A(0),[w,y]=A("summary"),[v,j]=A(!1),[$,P]=A(null),[S,z]=A("cost"),[E,g]=A(0),O=vt(e,"getSessionBilling",{...n,offset:r,turnOffset:M},l+":"+E),V=dt(!1);ct(()=>{V.current&&!O.loading&&C>=0&&(document.getElementById("cm-stat-call-"+C)?.scrollIntoView({block:"nearest"}),V.current=!1)},[O.loading,O.value,r,C,w]);const I=O.value,q=n.basis,H={input:a("非缓存输入","Uncached input"),output:a("输出","Output"),cacheRead:a("缓存读取","Cache read"),cacheWrite:a("缓存写入","Cache write"),reasoning:a("推理","Reasoning")},R={model:a("模型调用","Model call"),compaction:a("上下文压缩","Compaction"),search:a("原生搜索","Native search")},L=s=>s==null?a("未标明轮次","Turn not recorded"):a("轮次 ","Turn ")+s;if(Pt(O))return O.loading?t("p",{className:"cm-stat-empty",role:"status"},a("正在读取本对话的用量明细…","Loading this conversation’s usage records…")):lt(O.error);const p=O.failed?t("div",null,lt(O.error),Y(a("重试","Retry"),()=>g(s=>s+1))):null;if(!I.found)return t(Z,null,p,t("p",{className:"cm-stat-note"},a("没有可用的调用日志;缺失明细不代表零费用。","Call logs are unavailable; missing details do not mean zero cost.")),u);const T=s=>!s||s===n.sessionId?a("主会话","Main conversation"):a("子代理 ","Subagent ")+((I.agents??[]).find(k=>k.id===s)?.title||s).slice(0,80),h=s=>JSON.stringify([s.sessionId||n.sessionId,s.turn]),B=s=>((I.agents?.length??0)>1?T(s.sessionId)+" · ":"")+L(s.turn),G=s=>q==="total"||(q==="plan"?s.plan:!s.plan),et=Object.keys(H).map(s=>{const k=I.rows.filter(D=>D.bucket===s&&G(D));return{bucket:s,tokens:k.reduce((D,U)=>D+U.tokens,0),cost:k.reduce((D,U)=>D+U.cost,0),unpriced:k.some(D=>!D.priced)}}),nt=W(I,q),pt=W(I.recorded,q),_t=Math.abs(nt-pt)>Math.max(1e-8,Math.abs(pt)*1e-8)||I.totalCalls!==I.recorded.calls,yt=et.some(s=>s.unpriced),J=yt?a("已知费用占比","Known cost share"):a("费用占比","Cost share"),ut=s=>{y("summary"),V.current=!0,b(Math.floor(s/50)*50),i(s%50)},f=s=>({key:s.bucket,label:H[s.bucket],tokens:s.tokens,value:s.cost,unpriced:s.unpriced,amount:s.unpriced&&!s.cost?a("未定价","Unpriced"):o(s.cost)+(s.unpriced?" + ?":""),color:tt[Ot[s.bucket]??7]}),X=new Map;for(const s of I.rows.filter(G)){const k=JSON.stringify([s.provider,s.model]),D=X.get(k)??{key:k,label:s.model,provider:s.provider,tokens:0,value:0,unpriced:!1};D.value+=s.cost,D.tokens+=s.bucket==="reasoning"?0:s.tokens,D.unpriced||=!s.priced,X.set(k,D)}const st=[...X.values()].sort((s,k)=>k.value-s.value).map((s,k)=>({...s,label:s.provider+" / "+s.label,amount:s.unpriced&&!s.value?a("未定价","Unpriced"):o(s.value)+(s.unpriced?" + ?":""),color:tt[k%7]}));if(st.length>7){const s=st.splice(7),k=s.reduce((U,Ct)=>U+Ct.value,0),D=s.some(U=>U.unpriced);st.push({key:"other-models",label:a("其余 ","Other ")+s.length+a(" 个模型"," models"),value:k,tokens:s.reduce((U,Ct)=>U+Ct.tokens,0),unpriced:D,amount:D&&!k?a("未定价","Unpriced"):o(k)+(D?" + ?":""),color:tt[7]})}const kt=et.find(s=>s.bucket==="cacheRead"),Nt=et.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)),mt=kt.tokens>0?t("div",{className:"cm-cache-compare"},t("h3",null,a("缓存读取的占比","Cache read share")),...[[a("输入 Token","Input tokens"),kt.tokens,Nt.reduce((s,k)=>s+k.tokens,0)],[a("输入费用","Input cost"),kt.cost,Nt.some(s=>s.unpriced)?0:Nt.reduce((s,k)=>s+k.cost,0)]].map(([s,k,D])=>t("div",{key:s},t("div",{className:"cm-stat-share-head"},t("span",null,s),t("span",null,_(k,D))),t("div",{className:"cm-stat-share-track","aria-hidden":!0},t("span",{style:{display:"block",height:"100%",width:(D>0?k/D*100:0)+"%",borderRadius:9,background:tt[6]}}))))):null,it=(s,k,D={},U=null)=>t("section",{className:"cm-spend-card","aria-label":s},t("h3",null,s),t(rt,{rows:k,total:nt,label:J,text:a,amounts:!0,...D}),U),Ie=(I.callShares?.length??0)>0?it(a("每次调用费用占比","Cost share per call"),I.callShares.map((s,k)=>({...s,key:String(s.index),label:s.other?a("其余 ","Other ")+s.calls+a(" 次调用"," calls"):a("调用 #","Call #")+(s.index+1),meta:s.other?s.calls+a(" 次调用"," calls"):s.tokens.toLocaleString()+" tokens",value:W(s,q),amount:s.unpriced&&!W(s,q)?a("未定价","Unpriced"):o(W(s,q))+(s.unpriced?" + ?":""),color:tt[s.other?7:k%7]})),{onSelect:s=>{s.other||ut(s.index)}}):null,Te=(s,k,D)=>t("div",{className:"cm-stat-scroll",style:{marginTop:20}},t("h3",null,s),t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[s,a("调用次数","Calls"),a("输入 / 缓存 / 输出 Tokens","Input / cache / output tokens"),"API",a("Plan 等值","Plan equivalent")].map(U=>t("th",{key:U},U)))),t("tbody",null,k.map((U,Ct)=>t("tr",{key:Ct},t("td",null,D(U)),t("td",null,U.calls),t("td",null,[U.input,U.cacheRead+U.cacheWrite,U.output].map(c).join(" / ")),t("td",null,o(U.apiCost)+(U.unpriced?" + ?":"")),t("td",null,o(Math.max(0,U.cost-U.apiCost))+(U.unpriced?" + ?":"")))))));return t("section",{className:"cm-stat-panel"},t("style",null,jt+Re),m?t("nav",{className:"cm-session-tabs","aria-label":a("费用视图","Cost views")},...[["summary",a("费用概览","Overview")],["context",a("费用明细","Cost details")]].map(([s,k])=>Y(k,()=>{y(s),i(-1),j(!1)},{key:s,"aria-pressed":w===s}))):null,m?t("div",{className:"cm-stat-metrics"},...[[q==="total"?a("API + Plan 等值","API + Plan equivalent"):q==="plan"?a("Plan 等值","Plan equivalent"):a("API 费用","API cost"),o(nt)+(et.some(s=>s.unpriced)?" + ?":""),a("按本对话调用日志估算","Estimated from this conversation’s call logs")],[a("调用次数","Calls"),I.totalCalls.toLocaleString(),(I.agents?.length??0)>1?a("包含子代理","Includes subagents"):a("本会话","This conversation")],[a("Token 用量","Token usage"),c(et.reduce((s,k)=>s+(k.bucket==="reasoning"?0:k.tokens),0)),a("输入、缓存与输出","Input, cache and output")],[a("缓存命中率","Cache hit rate"),_(et.find(s=>s.bucket==="cacheRead")?.tokens??0,et.filter(s=>["input","cacheRead","cacheWrite"].includes(s.bucket)).reduce((s,k)=>s+k.tokens,0)),a("输入 Token 中的缓存读取","Cache reads among input tokens")]].map(([s,k,D])=>t("div",{className:"cm-stat-metric",key:s},t("div",{className:"cm-stat-sub"},s),t("div",{className:"cm-stat-value"},k),t("div",{className:"cm-stat-sub"},D)))):null,m&&w==="context"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:q,detailed:!0}):null,m?w==="context"?t("details",{className:"cm-stat-secondary"},t("summary",{style:{padding:"8px 0"}},a("上下文费用参考","Context cost reference")),u):null:u,m?null:t("div",{className:"cm-stat-panel-head"},t("h3",null,m?a("已发生费用 · 调用明细","Recorded costs · call details"):a("单对话费用明细","Conversation cost details")),t("span",{className:"cm-stat-sub"},(I.agents?.length??0)>1?a("包含子代理及其后代","Includes subagents and their descendants"):a("本会话自身的调用","Own conversation calls"))),p,!m&&_t?t("p",{className:"cm-stat-note"},a("账本与可用明细不同:账本 ","Ledger and available details differ: ledger ")+o(pt)+" / "+I.recorded.calls+a(" 次;明细 "," calls; details ")+o(nt)+" / "+I.totalCalls+a(" 次。"," calls.")):null,(!m||w==="calls")&&(I.agents?.length??0)>1?Te(a("主会话与子代理 · 账本费用","Main conversation and subagents · ledger costs"),I.agents,s=>T(s.id)):null,m?null:t("div",{className:"cm-plan cm-spend"},yt?t("p",{className:"cm-plan-sub"},a("存在未定价调用","Some calls are unpriced")):null,t("div",{className:"cm-spend-grid"},it(a("费用构成","Cost composition"),et.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f),{},mt),Ie,st.length>1?it(a("模型费用分布","Cost by model"),st):null,I.kinds.length>1?it(a("各环节费用占比","Cost by activity"),I.kinds.map((s,k)=>({key:s.kind,label:R[s.kind]??s.kind,value:W(s,q),tokens:gt(s),meta:s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok",unpriced:s.unpriced,amount:o(W(s,q))+(s.unpriced?" + ?":""),color:tt[k]}))):null)),m&&w==="summary"?t(ke,{api:e,sessionId:n.sessionId,revision:l,money:o,text:a,basis:q,composition:it(a("费用构成","Cost composition"),et.filter(s=>s.tokens>0&&(s.bucket!=="reasoning"||s.cost>0||s.unpriced)).map(f))}):null,!m||w==="summary"?t("details",{className:"cm-call-section",open:!m||v||C>=0,onToggle:s=>{s.target===s.currentTarget&&(j(s.currentTarget.open),s.currentTarget.open||i(-1))}},t("summary",{style:{padding:"10px 0",fontSize:13}},a("逐次调用明细","Individual calls")+" · "+I.totalCalls),m?t("div",{className:"cm-plan cm-spend-grid"},Ie,st.length>1?it(a("模型费用分布","Cost by model"),st):mt):null,m?null:t("details",{className:"cm-stat-secondary",open:!m},t("summary",null,a("轮次、步骤与单价","Turns, steps and rates")),t("section",{className:"cm-stat-breakdown"},t("div",{className:"cm-stat-panel-head"},t("h3",null,a("各步骤占比","Share by step")),t("div",{className:"cm-stat-periods"},...[["cost",a("费用","Cost")],["calls",a("调用次数","Calls")]].map(([s,k])=>Y(k,()=>z(s),{key:s,"aria-pressed":S===s})))),t(xe,{title:S==="cost"?a("费用占比 · 全部调用","Cost share · all calls"):a("调用次数占比 · 全部调用","Call count share · all calls"),rows:(I.stepShares?.[S]??[]).map(s=>({label:s.other?a("其余步骤合计","All other steps"):B(s)+(s.step==null?"":a(" · 步骤 "," · step ")+s.step),value:S==="cost"?W(s,q):s.calls,unpriced:S==="cost"&&s.unpriced,other:s.other})),total:S==="cost"?nt:I.totalCalls,format:S==="cost"?o:s=>s.toLocaleString(),text:a,columns:!0})),t("details",{className:"cm-stat-help"},t("summary",null,a("单价与 Token 明细","Rates and token details")),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[a("费用构成","Cost component"),"Tokens",a("费用","Cost"),a("费用占比","Cost share")].map(s=>t("th",{key:s},s)))),t("tbody",null,et.map(s=>t("tr",{key:s.bucket},t("td",null,H[s.bucket]),t("td",null,s.tokens.toLocaleString()),t("td",null,o(s.cost)+(s.unpriced?" + ?":"")),t("td",null,_(s.cost,nt))))))),Te(a("按调用类型统计","Cost by call type"),I.kinds,s=>R[s.kind]??s.kind)),t("section",{className:"cm-stat-turns"},t("div",{className:"cm-stat-panel-head"},t("h3",null,a("按轮次统计","Cost by turn")),t("span",{className:"cm-stat-sub"},a("展开查看输入和工具调用","Expand to inspect input and tool calls"))),I.turns.map(s=>t("div",{key:h(s),className:"cm-stat-turn"},t("button",{type:"button",className:"cm-stat-turn-toggle",disabled:s.turn==null,"aria-expanded":s.turn!=null&&$===h(s),onClick:()=>P(k=>k===h(s)?null:h(s))},t("span",null,(s.turn==null?"":$===h(s)?"⌄ ":"› ")+B(s)),t("span",null,s.calls+a(" 次调用"," calls")+" · "+c(gt(s))+" tok · "+o(W(s,q))+(s.unpriced?" + ?":"")+" · "+_(W(s,q),nt))),s.turn!=null&&$===h(s)?t(ye,{key:h(s),api:e,sessionId:s.sessionId||n.sessionId,turn:s.turn,revision:l,text:a}):null))),t(xt,{offset:M,count:I.totalTurns,size:25,onChange:s=>{d(s),P(null)},text:a})),t("div",{style:{marginTop:24}},t(he,{rows:I.calls.map((s,k)=>({label:"#"+(r+k+1),index:k,value:W(s,q)})),money:o,text:a,label:a("逐次调用费用 · 当前页","Cost per call · current page"),onSelect:s=>{i(s.index),document.getElementById("cm-stat-call-"+s.index)?.scrollIntoView({block:"nearest",behavior:"smooth"})}})),I.calls.map((s,k)=>t("details",{key:r+k,id:"cm-stat-call-"+k,className:"cm-stat-call",open:C===k,onToggle:D=>{D.currentTarget.open?i(k):i(U=>U===k?-1:U)}},t("summary",null,"#"+(r+k+1)+" · "+B(s)+(s.step==null?"":a(" / 步骤 "," / step ")+s.step)+" · "+(R[s.kind]??s.kind)+" · "+s.provider+" / "+s.model+" · "+(s.plan?"Plan ":"API ")+(s.priced?o(s.cost):"?")+(s.longContext?a(" · 长上下文价"," · long-context rate"):""),t("span",{className:"cm-call-share"},(s.priced?_(W(s,q),nt):"—")+" · "+J)),C===k?t(Oe,{key:(s.sessionId||n.sessionId)+":"+(s.logSeq??k),call:s,sessionId:n.sessionId,api:e,revision:l,money:o,text:a,names:H}):null)),t(xt,{offset:r,count:I.totalCalls,size:50,onChange:s=>{b(s),i(-1)},text:a})):null)}function Ne(e,n,l){const o=()=>["api","plan","total"].includes(e.statisticsBasis)?e.statisticsBasis:e.showTotalWithPlan?"total":"api",[c,a]=A(o),[m,u]=A(!1),[r,b]=A("");return ct(()=>{m||a(o())},[e.statisticsBasis,e.showTotalWithPlan,m]),{basis:c,choose:async i=>{if(!(m||!["api","plan","total"].includes(i))){a(i),u(!0),b("");try{await n.saveStatisticsBasis(i)}catch{b(l("计费口径保存失败,请重试。","Could not save the cost basis. Try again."))}finally{u(!1)}}},saving:m,error:r}}function Ce({state:e,api:n,sessionId:l,formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:m}){const u=(y,v)=>(a?a(e.config):e.config.locale)==="en"?v:y,[r,b]=A(0),C=Ne(e.config,n,u),{basis:i}=C,M=Rt(e,r),d=y=>o(y,{...e.config,decimals:Math.max(y!==0&&Math.abs(y)<.01?8:4,e.config.decimals??2)}),w={sessionId:l,from:"",to:"",provider:"",model:"",basis:i,offset:0};return t("div",{className:"cm-stat cm-stat-session","data-session-id":l},t("style",null,re),t("div",{className:"cm-stat-panel-head"},t("p",{className:"cm-stat-sub"},u("当前对话 · 全部调用","This conversation · all calls")),Y(u("刷新","Refresh"),()=>b(y=>y+1))),t(Vt,{key:l+":"+i,api:n,query:w,revision:M,money:d,formatTokens:c,text:u,overview:!0},t(Et,{key:l,api:n,sessionId:l,revision:M,money:d,text:u,compact:!0,expanded:!0})),t("details",{className:"cm-session-options"},t("summary",null,u("显示与联动设置","Display and integration settings")),t("div",{className:"cm-stat-controls"},t("label",null,u("计费口径","Cost basis"),t("select",{value:i,disabled:C.saving,onChange:y=>C.choose(y.target.value)},...[["api",u("API 费用","API cost")],["plan",u("Plan 等值","Plan equivalent")],["total",u("API + Plan 等值","API + Plan equivalent")]].map(([y,v])=>t("option",{key:y,value:y},v))))),C.error?lt(C.error):null,m?t(Qt,m):null))}function we({state:e,api:n,sessionId:l="",formatMoneyUsd:o,formatTokens:c,resolveLocale:a,contextIntegration:m}){const u=a?a(e.config)==="en":e.config.locale==="en"||e.config.locale!=="zh"&&(e.config.activeLocale||e.meta?.locale||(typeof navigator<"u"&&/^zh/i.test(navigator.language)?"zh":"en"))==="en",r=(f,X)=>u?X:f,[b,C]=A(l?"all":"week"),[i,M]=A(null),[d,w]=A({id:l,title:l}),[y,v]=A(""),[j,$]=A(""),P=Ne(e.config,n,r),{basis:S}=P,[z,E]=A(0),[g,O]=A(0),[V,I]=A(!1),q=e.meta.dayKey||new Date().toISOString().slice(0,10),H=b==="all"?"":b==="custom"?i?.from||q:Xt(q,b==="week"?-6:b==="month"?-29:0),R=b==="custom"&&i?.to||q,L={from:H,to:R,provider:y,model:j,basis:S,sessionId:d.id,offset:z},p=Rt(e,g),T=vt(n,"getBillingStatistics",L,p),h=T.value,B=f=>o(f,{...e.config,decimals:Math.max(f!==0&&Math.abs(f)<.01?8:4,e.config.decimals??2)}),G=f=>{C(f),E(0)},et=f=>{w(f),E(0),v(""),$("")},nt=S==="total"?r("API + Plan 等值","API + Plan equivalent"):S==="plan"?r("Plan 等值","Plan equivalent"):r("API 费用","API cost"),pt=(f,X,st,kt,Nt=!1)=>t("label",null,f,t("select",{value:X,disabled:Nt,onChange:mt=>{st(mt.target.value),E(0)}},kt.map(([mt,it])=>t("option",{key:mt,value:mt},it)))),_t={input:r("未缓存输入","Uncached input"),cacheRead:r("缓存读取","Cache read"),cacheWrite:r("缓存写入","Cache write"),output:r("输出","Output")},yt=(f,X)=>t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,f)),X),J=h?.totals,ut=(f,X,st)=>t("div",{className:"cm-stat-metric",key:f},t("div",{className:"cm-stat-sub"},f),t("div",{className:"cm-stat-value"},X),t("div",{className:"cm-stat-sub"},st));return t("div",{className:"cm-stat"},t("style",null,re),m?t(Qt,m):null,t("header",{className:"cm-stat-head"},t("div",null,t("h2",null,r("计费统计","Cost statistics")),t("p",{className:"cm-stat-sub"},d.id?r("单对话 · ","Conversation · ")+(d.title===d.id&&h?.sessions[0]?.title||d.title):r("全部对话 · 从总额查看每一笔调用","All conversations · from totals to individual calls"))),Y(r("刷新","Refresh"),()=>O(f=>f+1))),d.id?Y(r("← 全部对话","← All conversations"),()=>et({id:"",title:""})):null,t("div",{className:"cm-stat-controls"},t("div",{className:"cm-stat-periods"},...[["today",r("今天","Today")],["week",r("近 7 天","Last 7 days")],["month",r("近 30 天","Last 30 days")],["all",r("全部记录","All retained")],["custom",r("自定义","Custom")]].map(([f,X])=>Y(X,()=>G(f),{key:f,"aria-pressed":b===f})))),b==="custom"?t("div",{className:"cm-stat-controls"},...["from","to"].map(f=>t("label",{key:f},f==="from"?r("开始日期","From"):r("结束日期","To"),t("input",{type:"date",value:f==="from"?H:R,onChange:X=>{M({from:H,to:R,[f]:X.target.value}),E(0)}})))):null,t("div",{className:"cm-stat-controls"},pt(r("计费口径","Cost basis"),S,P.choose,[["api",r("API 费用","API cost")],["plan",r("Plan 等值","Plan equivalent")],["total",r("API + Plan 等值","API + Plan equivalent")]],P.saving),pt(r("提供商","Provider"),y,f=>{v(f),$("")},[["",r("全部提供商","All providers")],...[...new Set([y,...h?.providers??[]])].filter(Boolean).map(f=>[f,f])]),pt(r("模型","Model"),j,$,[["",r("全部模型","All models")],...[...new Set([j,...h?.modelOptions??[]])].filter(Boolean).map(f=>[f,f])])),P.error?lt(P.error):null,Pt(T)?T.loading?t("p",{className:"cm-stat-empty",role:"status"},r("加载统计…","Loading statistics…")):lt(T.error):h?t(Z,null,T.failed?lt(T.error):null,t("p",{className:"cm-stat-sub",style:{marginTop:8}},h.from+" – "+h.to+(h.retainedFrom?" · "+r("账本保留范围 ","Retained ledger ")+h.retainedFrom+" – "+h.retainedTo:"")),t("div",{className:"cm-stat-metrics"},ut(r("API 费用","API cost"),B(J.apiCost),r("已入账估算","Recorded estimate")),ut(r("Plan 等值费用","Plan equivalent"),B(Math.max(0,J.cost-J.apiCost)),""),ut(r("调用次数","Calls"),J.calls.toLocaleString(),h.sessionCount+r(" 个对话 · 平均 "," conversations · average ")+B(J.calls?W(J,S)/J.calls:0)),ut(r("缓存命中率","Cache hit rate"),_(J.cacheRead,J.input+J.cacheRead+J.cacheWrite),c(gt(J))+" Tokens")),d.id?t("section",{className:"cm-stat-panel"},t(Et,{key:d.id,api:n,sessionId:d.id,revision:p,money:B,text:r})):null,d.id?t(Vt,{key:JSON.stringify([d.id,H,R,y,j,S]),api:n,query:{...L,from:h.from,to:h.to,offset:0},revision:p,money:B,formatTokens:c,text:r}):null,h.models.some(f=>!f.priced)?t("p",{className:"cm-stat-note"},r("部分模型未配置价格","Some models have no rates")):null,!J.calls&&!J.cost?t("p",{className:"cm-stat-empty"},r("所选范围没有已记录的用量。","No recorded usage in this range.")):null,t("section",{className:"cm-stat-panel"},t(he,{rows:ve(h.days,S),money:B,text:r,label:r("费用趋势 · ","Cost over time · ")+nt,onSelect:f=>{M({from:f.from,to:f.to}),G("custom")}})),t("div",{className:"cm-stat-grid"},yt(r("模型费用排行","Cost by model"),t(Z,null,t("ol",{className:"cm-stat-rank"},(V?h.models:h.models.slice(0,8)).map(f=>t("li",{key:f.key},t("button",{type:"button",onClick:()=>{v(f.provider),$(f.model),E(0)},title:f.key},t("div",{className:"cm-stat-rankline"},t("span",null,f.model),t("span",{className:"cm-stat-number"},B(W(f,S))+(f.priced?"":" + ?"))),t("div",{className:"cm-stat-sub"},f.provider+" · "+f.calls+r(" 次 · "," calls · ")+_(W(f,S),W(J,S))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_(W(f,S),W(J,S))}}))))),h.models.length>8?Y(V?r("收起","Show less"):r("显示全部模型","Show all models"),()=>I(f=>!f)):null,h.unmodeledCost>1e-8?t("p",{className:"cm-stat-note"},r("历史未分配到模型的费用:","Historical cost without a model: ")+B(h.unmodeledCost)):null)),yt(r("Token 构成","Token composition"),t(Z,null,t("ol",{className:"cm-stat-rank"},Object.entries(_t).map(([f,X])=>t("li",{key:f},t("div",{className:"cm-stat-rankline"},t("span",null,X),t("span",{className:"cm-stat-number"},c(J[f]))),t("div",{className:"cm-stat-track"},t("span",{style:{width:_(J[f],gt(J)),background:f.startsWith("cache")?"var(--cm-plan)":void 0}}))))),t("p",{className:"cm-stat-sub"},r("单独上报的推理 Token:","Reported reasoning tokens: ")+c(J.reasoning))))),d.id?null:t("section",{className:"cm-stat-panel"},t("div",{className:"cm-stat-panel-head"},t("h3",null,r("对话费用排行","Cost by conversation")),t("span",{className:"cm-stat-sub"},e.config.includeSubagentCost?r("点击查看明细 · 包含子代理,每笔费用只计一次","Select for details · includes subagents, each call counted once"):r("点击对话查看明细","Select a conversation for details"))),t("div",{className:"cm-stat-scroll"},t("table",{className:"cm-stat-table"},t("thead",null,t("tr",null,...[r("对话","Conversation"),r("调用","Calls"),"API",r("Plan 等值","Plan equivalent"),r("缓存命中","Cache hits")].map(f=>t("th",{key:f},f)))),t("tbody",null,h.sessions.map(f=>t("tr",{key:f.id},t("td",null,t("button",{type:"button",title:f.id,onClick:()=>et({id:f.id,title:f.title})},f.title)),t("td",null,f.calls.toLocaleString()),t("td",null,B(f.apiCost)),t("td",null,B(Math.max(0,f.cost-f.apiCost))),t("td",null,_(f.cacheRead,f.input+f.cacheRead+f.cacheWrite))))))),h.unassignedCost>1e-8?t("p",{className:"cm-stat-note"},r("未关联对话的费用:","Cost not linked to a conversation: ")+B(h.unassignedCost)):null,t(xt,{offset:z,count:h.sessionCount,size:25,onChange:E,text:r})))):null)}function Se(e,{state:n,sessionId:l=""}={}){if(!n||document.hidden)return;const o=Rt(n,0),c=n.meta.dayKey||new Date().toISOString().slice(0,10),a={sessionId:l,from:l?"":Xt(c,-6),to:l?"":c,provider:"",model:"",basis:n.config.showTotalWithPlan?"total":"api",offset:0};return Promise.all(l?[Mt(e,"getSessionBilling",{...a,turnOffset:0},o+":0")]:[Mt(e,"getBillingStatistics",{from:a.from,to:a.to,provider:"",model:"",basis:a.basis,sessionId:"",offset:0},o)])}async function Ee(e,n,l){const o=typeof n=="function"?n:()=>n&&l?l(n.getSnapshot().state?.config??{activeLocale:n.getSnapshot().locale}):"en",c=await e.get("remote").$mount(le);e.effect(()=>()=>c(),"cost-meter: statistics contribution");const a=e.get("remote.costMeter"),m=Object.fromEntries(["getBillingStatistics","getSessionBilling","getTurnInspection","getCallInspection","getContextCosts","getSessionTrajectory"].map(b=>[b,async C=>{const i=await a[b]((b==="getSessionTrajectory"?se:b==="getContextCosts"?zt:b==="getCallInspection"?oe:b==="getTurnInspection"?ne:ce)(C));if(!i?.ok)throw new Error(i?.error?.message||"Statistics request failed");return{getBillingStatistics:Bt,getSessionBilling:Dt,getTurnInspection:St,getCallInspection:Zt,getContextCosts:Ut,getSessionTrajectory:ae}[b](i.value)}]));m.saveStatisticsBasis=async b=>{const C=await a.updateConfig({statisticsBasis:b});if(!C?.ok||C.value?.config?.statisticsBasis!==b)throw new Error("Cost basis setting failed");n?.set?.({status:"ready",error:null,state:C.value})};let u;if(n?.subscribe&&typeof e.get("slots")?.entries=="function"){m.getContextIntegration=async()=>{const i=await a.getContextIntegration();if(!i?.ok)throw new Error("Integration check failed");return ee(i.value)},m.saveIntegration=async i=>{const M=await a.updateConfig({contextCostsEnabled:i,contextCostsPromptSeen:!0});if(!M?.ok||!M.value?.config)throw new Error("Integration setting failed");n.set({status:"ready",error:null,state:M.value})},u=ge(e,m,n,o,Ht("react-dom").createPortal),e.effect(()=>u.dispose,"cost-meter: optional dsh-context integration");const b=e.get("slots"),C=()=>b.register({name:"shell.overlay",id:"cost-meter-context-intro",order:50},()=>t(be,{manager:u,getLocale:o}));typeof b.inject=="function"&&e.effect(()=>b.inject("shell.overlay",C),"cost-meter: context preview prompt")}const r=b=>t(b.sessionId?Ce:we,{...b,api:m,contextIntegration:u?{manager:u,getLocale:o}:null});return r.prefetch=b=>Se(m,b),e.effect(()=>()=>Ft.delete(m),"cost-meter: statistics cache cleanup"),r}return{mount:Ee,prefetchStatistics:Se,Statistics:we,SessionStatistics:Ce,SessionDetail:Vt,TurnInspection:ye,ShareChart:xe,ContextCosts:Et,ContextPrompt:be,ContextPreview:Jt,ContextIntegrationSettings:Qt,createContextIntegration:ge,contextCostBreakdown:me,installContextCosts:de,CONTRIBUTION:le,parseContextCosts:Ut,parseStatistics:Bt,parseDetail:Dt,parseInspection:St,dailyChartRows:ve,requestStart:ie,requestValue:ft,requestFailure:pe,showsPlaceholder:Pt,refreshKeyOf:Rt}}});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cost-meter",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.22",
|
|
4
4
|
"description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(11 家,含小米 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 11 vendors (incl. 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/index.js",
|