# 开销统计 / Token 账本 (dsh-token-ledger-pro)

> 本插件由原 `dsh-custom-cost-meter`（计费统计面板）与 `dsh-spend`（开销统计）合并而来：服务端计费 + 输入框旁实时展示，单插件单脚本安装，中英双语。

DeepSeek Harness 会话费用统计插件（服务端计费 + 输入框旁实时展示，中英双语）。

## 功能（当前版本 M1+M2+余额）
- ✅ 自动采集每次 LLM 请求的 token 用量（DSH session 事件），按模型价格实时计费
- ✅ 输入框工具行右侧（模型选择器旁）实时显示：**当前模型 / 账户余额 / 会话 / 今日 / 本月 / 预算横条**（横条按 `alertThreshold` 变色，默认 ≥80% 转橙、≥100% 转红）
- ✅ **账户余额实时查询**：内置 DeepSeek / OpenAI / Anthropic / Kimi / 智谱 / 火山方舟（豆包）/ 阿里云（千问）官方余额 API；未内置的厂商可用自定义 HTTP 端点 + JSONPath 提取；默认 1 分钟缓存（`balanceCacheTtl`）
- ✅ 内置 **16 家厂商、136 个模型**价格目录（`lib/pricing.js` 134 条 + `prices.override.json` 2 条）：DeepSeek、豆包/火山方舟、OpenAI、Anthropic、Gemini、通义千问、腾讯混元、Kimi、MiniMax、智谱 GLM、硅基流动、xAI、Mistral、Meta Llama、Cohere、OpenRouter
- ✅ 智能匹配：精确匹配 → 前缀匹配 → 厂商默认价回退 → 跨厂商全局匹配
- ✅ **未定价模型**：自动回退厂商默认价并显示「未定价」徽标（不再静默显示 ¥0）
- ✅ DeepSeek 峰谷计价（北京时间峰时 ×2；2026-08-23 起周末全天谷价）
- ✅ 缓存价（cacheRead / cacheWrite）单独计价
- ✅ 数据持久化：当日/本月/会话聚合 + 最近 2000 条明细（JSON 原子写，重启不丢）
- ✅ 可选远端价格同步（priceSyncUrl，同构 JSON 覆盖内置目录）

## 安装

### 方式一：命令行安装（推荐，市场同款）

```sh
dsh plugin --profile web add dsh-token-ledger-pro
```

装完重启 DSH Web，浏览器 Ctrl+F5 强刷即可。包已发布到 npm（`dsh-token-ledger-pro`），预构建安装不需要 `allowBuilds` 授权。

### 方式二：本地脚本安装

1. 运行当前目录下的 `install-dsh-token-ledger-pro.ps1`（自动清理旧版本、复制插件、接线DSH profile、建立链接、迁移历史数据）
2. 重启 DSH Web 服务，浏览器 Ctrl+F5 强刷即可

### 其他电脑安装
1. 把整个 `dsh-token-ledger-pro` 文件夹复制到目标电脑任意位置
2. 打开文件夹，运行里面的 `install-dsh-token-ledger-pro.ps1`
3. 重启目标电脑的DSH Web + 强刷即可

### 配置说明
首次安装后打开 `~/.dsh/profiles/web/cordis.patch.yml`，在 `dsh-token-ledger-pro` 的 `balance` 块中填入对应厂商的密钥即可查询余额，所有配置与DSH版本完全兼容。

## 配置余额查询

在 profile 的 `cordis.patch.yml`（或 settings）里给 `dsh-token-ledger-pro` 加 `config.balance`。**按当前选中模型的厂商自动选择对应余额配置**；未配置时显示「--」。

### 官方 API（推荐）
```yaml
- id: dsh-token-ledger-pro
  config:
    monthlyBudget: 100
    unknownModel: estimate
    balance:
      deepseek:
        type: deepseek        # 官方余额 API（api.deepseek.com/user/balance）
        apiKey: "sk-你的DeepSeek密钥"
        currency: "CNY"
      openai:
        type: openai          # OpenAI 订阅余额
        apiKey: "sk-你的OpenAI密钥"
        currency: "USD"
      anthropic:
        type: anthropic
        apiKey: "sk-ant-xxx"  # 需在组织设置里补 organization_id
        endpoint: "https://api.anthropic.com/v1/organizations/<你的组织ID>/usage"
        currency: "USD"
      moonshot:
        type: moonshot        # Kimi 余额
        apiKey: "sk-xxx"
        currency: "CNY"
      zhipu:
        type: zhipu           # 智谱余额
        apiKey: "xxx.xxx"
        currency: "CNY"
      # 腾讯混元：按腾讯云账户计费，用费用中心 DescribeAccountBalance（TC3 签名）
      hunyuan:
        type: tencent         # 腾讯云签名接口 billing.tencentcloudapi.com
        secretId: "AKID你的腾讯云SecretId"
        secretKey: "你的腾讯云SecretKey"
        region: "ap-guangzhou"  # 可留空，余额接口不依赖地域
        currency: "CNY"
      # 阿里千问（百炼）：按阿里云账户计费，用 BSS QueryAccountBalance（RPC 签名）
      qwen:
        type: aliyun          # 阿里云签名接口 business.aliyuncs.com
        accessKeyId: "LTAI你的阿里云AccessKeyId"
        accessKeySecret: "你的阿里云AccessKeySecret"
        region: "cn-hangzhou"   # 可留空
        currency: "CNY"
    balanceCacheTtl: 60        # 缓存秒数，默认 60（1 分钟）
```

> ⚠️ 密钥以明文存在本地配置文件中，注意不要泄露；若不想配置官方密钥，可用下方自定义端点。

### 自定义 HTTP 端点（任意厂商 / 中转）
```yaml
- id: dsh-token-ledger-pro
  config:
    balance:
      myproxy:                       # 与模型 provider 名一致
        type: custom
        endpoint: "https://你的中转站/api/balance"
        headers:
          Authorization: "Bearer sk-xxx"
        valuePath: "data.balance"    # JSONPath，从响应 JSON 提取数值
        currency: "CNY"
```

- 内置厂商也可用 `endpoint` 覆盖默认地址
- `valuePath` 支持点号路径：`data.balance`、`balance`、`data.amount`…

### 不支持的 provider 类型
火山方舟/豆包（Volcano Ark）需要 AK/SK 签名，暂未内置；可用 `type: custom` 指向你自己的签名网关。

## 自定义价格
- 本地覆盖：在插件目录放 `lib/prices.override.json`（与服务端 index.js 同级目录），结构：
```json
{
  "deepseek": {
    "default": { "input": 2, "output": 8, "cacheRead": 0.5, "cacheWrite": 2 },
    "models": { "deepseek-chat": { "input": 2, "output": 8 } }
  }
}
```
- 远端同步：`config.priceSyncUrl` 指向同构 JSON。

## HTTP API
- `GET /dsh-token-ledger-pro/summary?session=<sessionId>` — 会话/今日/本月/预算/当前模型计价状态
- `GET /dsh-token-ledger-pro/balance?provider=<provider>` — 账户余额（`{value, currency, updatedAt, error}`）
- `GET /dsh-token-ledger-pro/prices` — 价格目录
- `GET /dsh-token-ledger-pro/config` / `POST /dsh-token-ledger-pro/config` — 读取/修改预算与未知模型策略
- `GET /dsh-token-ledger-pro/history?limit=50` — 最近明细 + 14 日曲线

## 数据文件
`~/.dsh/profiles/<profile>/data/dsh-token-ledger-pro.json`

## 常见问题
- 面板显示「余额 --」：该厂商未配置余额查询（或配置了但请求失败，悬停看原因）；余额按选中模型对应厂商自动匹配
- 面板显示「未定价」：该模型不在目录中，已按厂商默认价估算；可在 `prices.override.json` 补精确价
- 更换模型后无任何费用：请确认 DSH 已重启且插件已出现在 设置 → 插件 列表（fiber 状态 active）
- 峰值时段计费以北京时间（Asia/Shanghai）为准
