Files
plugins/packages/amp-usage/README.md
T
ming_jiang 4b0aef5327 amp-usage: Amp usage page with background collection; day-card 0.3.1 (#1000)
Adds packages/amp-usage (@magpie-community/page-amp-usage 0.1.0). It is a magpie page that reads Amp's local thread files and the gateway's usage.jsonl and shows per-day usage. The service listens on loopback only and requires a per-start service token on every API call. The page that carries the token is served only to a navigation (Sec-Fetch-Mode). The gateway log is read incrementally from a saved offset, whole lines only, and is re-indexed on rotation. The UI words are in ui/words.js (en, zh).

Also bumps packages/day-card to 0.3.1.

Round 3 (13c1f33) adds three things:
- a test that bytes before the gateway-log offset are never re-read;
- ui.test.mjs, which checks that every error code the server can return has words in each language, and that an unknown code falls back;
- words.js, moved out of app.js, served at /words.js and included in the pack.

What ran, at 13c1f33 merged with main 14187408, on mica:
- amp-usage `node --test`: 47/47.
- `bun test packages/amp-usage packages/day-card`: 65 pass, 0 fail.
- `bun scripts/check.mjs`, all packages: ok.
- `npm pack --dry-run`: amp-usage 0.1.0 has 19 files including ui/words.js; day-card 0.3.1 has 17 files.
- Root `bun test` with a temp HOME: 8362 pass, 0 fail (8382 tests, 590 files).
- Render smoke in Chromium and WebKit at 1200 and 420px, en and zh: words.js loads, both languages show their own words, no page errors, no horizontal overflow.

Broken by hand, each run with node and bun:
- collector.mjs:102 made to re-read the whole file every scan: the new offset test goes red.
- `const cut = buf.length`, so a partial line is taken: red.
- Raw error codes shown instead of their words (`w.err[code] || code`): red.
- A zh string deleted: red.

Not tried:
- A real Amp account or the real `amp` CLI.
- Changing the auto-refresh default from 300 to 60 fails no test. The author left it untested and round 2 called it optional.

Rounds 1 and 2 also ran the 1M-line log probe (rss steady at about 363MB, scans of 70 to 114ms after the first), the bad-record and paging probes, and the full render matrix including dark mode.
2026-11-11 21:43:59 +08:00

101 lines
9.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Amp 用量采集
在 Magpie 中增加「Amp 用量」看板:按今天、24 小时、7 天、30 天、全部或自定义日期查看 Amp 的请求数、输入、输出、缓存读写、缓存命中率,以及每小时、每日和各模型的用量。后台采集服务同时把这些记录通过 `POST /v1/magpie/usage/requests` 写入现有用量账本,来源为 `reported`,Agent 为 `amp`。请求统计与 Day card 可直接使用这些记录,无需替换内置页面。
需要 Magpie **0.1.3681 或更新版本**。读取 Amp 账号需要支持 `threads list --json` 和 `threads export` 的 Amp CLI,且已登录。已检查的 CLI 为 `0.0.1794052841-g6d76b7`。只读本地旧文件不需要 Amp CLI;Node.js 20+ 用于开发测试,安装后的后台由 Magpie 的 Bun 宿主运行。
## 安装与使用
从仓库安装本地包:
```sh
magpie plugin add /absolute/path/to/plugins/packages/amp-usage
```
安装后后台每 5 分钟读取一次 Amp 用量并同步到 Magpie,页面关闭后仍继续,插件关闭或 Magpie 退出时停止。页面只展示用量,没有同步开关;只想看看板、不写入 Magpie 时,在插件选项里设 `"sync": false`。
- 顶部左侧切换时间段;一两天以内按小时出图,更长按日出图。
- 右侧的刷新按钮立即重新读取,旁边选择页面打开时的自动刷新间隔(关闭、30 秒、1 分钟、5 分钟,默认 5 分钟)。
- 一条记录需要在两次读取之间保持不变(默认至少 120 秒)才会写入 Magpie。未计入的记录按原因归类,折叠在看板下方。
- 在「观测 → 用量 → 请求」按 Agent `amp` 或上报来源筛选可以看到同步过去的记录;Day card 使用相同账本。
首次读取云端时每轮最多导出 20 个变化线程;页面打开期间会自动继续,直到导完或出错。未变化线程复用缓存,失败线程沿用上次的副本,不推进导出检查点。
关闭同步只停止未来导入,不删除已写入的历史。已接受的记录不能通过同 ID 上报覆盖;若 Amp 后续修改已导入记录,插件会提示,保持原记录而不重复增加。
## 采集与统计口径
实现参考 [Tokscale 的 Amp 解析器](https://github.com/junhoyeo/tokscale/blob/b0991187b0af99614b48230f17d13a1fe06f28fa/crates/tokscale-core/src/sessions/amp.rs) 与 [CLI 同步器](https://github.com/junhoyeo/tokscale/blob/b0991187b0af99614b48230f17d13a1fe06f28fa/crates/tokscale-cli/src/amp.rs),采用 MIT 许可,见 `NOTICE` 和 `LICENSE`。
- 本地旧文件和云端账号每轮都读取,不需要选择来源。同一条记录两边都有时以本地为准(它带真实时间和账本);没有安装 Amp CLI 时只读本地。
- 云端使用当前已登录 Amp CLI 的 `threads list --json --include-archived` 分页列举及 `threads export`,不直接读取 Amp 密钥。列表按更新时间从新到旧,翻到整页都没有新变化时即停止;每天完整列举一次,移除已删除的线程。
- 本地默认读取 `$XDG_DATA_HOME/amp/threads`,未设置时为 `~/.local/share/amp/threads`。这些文件可能仅包含旧历史,目录不存在时直接跳过。配置多个目录时,同线程内容冲突会被排除。
- 账本与消息优先按 `toMessageId` / `messageId` 对齐;没有 ID 匹配时按模型、token 和兼容时间一对一匹配。保留账本独有事件与消息独有用量,避免只选一个来源造成漏计。
- 稳定上报 ID 以线程 ID 和消息 ID 为基础;搜索、标题生成等辅助调用使用账本事件自带的 ID,没有 ID 的事件不导入。消息 ID 冲突、身份变化或导入后变化会提示并保留,不自动修正。
- 父线程账本里的子代理汇总事件不计入,子代理的调用由它自己的线程逐条计入,避免重复。
- 账本事件通常只带输入和输出;与消息对齐后,缓存读写取消息上的数值。
- **请求日期**:优先用记录自身的时间;云端导出的助手消息没有时间,按所在轮次用户消息的发送时间(`meta.sentAt`)计。跨过午夜的一轮会整体记在开始那天,导入后不能更正。不使用线程创建时间、文件修改时间或消息序号;仍然没有时间的记录不计入。
- 正在生成、取消、刚更新的记录不导入。两次扫描间用量变化会重置稳定等待时间。
- 输入、输出、缓存读取、缓存创建分别上报;不使用 `totalInputTokens` 再叠加缓存。Amp credits 不作为美元费用,上报省略 `cost`,由 Magpie 估算 API 等价费用,未知模型可能没有价格。
- `provider` 使用宿主的 `session-unknown`,避免把模型厂商冒充实际付款渠道;`model` 保留 Amp 原始值。
### 去重的范围
已接受记录按稳定 `rid` 去重,Magpie 重启后也不会重复接受。传输中断或应答丢失可安全重试。Magpie 因其中一条无效而拒绝整批(HTTP 400)时,插件对半拆分找出该记录,计为「被拒绝」,其余照常导入;被拒绝的记录在下一轮重试。插件另保存已确认记录的指纹,检测后续修订。
读取同一 Magpie 配置目录的 `usage.jsonl` 检查网关已有请求(只在还有未判定的记录时读取;首次读取建立索引,此后只读追加部分,文件轮转后重建。判定结果会保存,账本轮转后仍然有效):模型和四类 token 相同,且会话 ID 相同或时间相距不超过 5 秒时,保守排除重复候选。标记为 Magpie 路由的模型也会排除。这个匹配不是完整的跨系统请求身份协议:不识别线程的代理、时间或模型改写、已归档不在该日志中的网关记录,仍可能无法关联。使用自定义网关时,应通过 `excludedThreadIds` 或 `excludedModels` 排除相关来源;分支复制历史若没有可验证的父子标识,也不能保证跨线程自动去重。
插件只扫描当前机器或当前 Amp CLI 账号;不会补齐未导出账号的数据。新增云端格式需要真实脱敏样本验证。
## 插件选项
在 Magpie 插件选项中配置。服务只允许上报到本机 HTTP 网关;不自动寻找凭据或向远端上报。
```json
{
"port": 3497,
"sync": true,
"gatewayURL": "http://127.0.0.1:3425",
"intervalSeconds": 300,
"settleSeconds": 120,
"ampPath": "",
"threadDirs": [],
"excludedThreadIds": [],
"excludedModels": []
}
```
- `port`:页面服务端口,仅监听 `127.0.0.1`,被占用时明确报错。
- `sync`:是否把读到的用量写入 Magpie,默认 `true`。设为 `false` 时只读取和展示。
- `gatewayURL`:Magpie 网关地址,仅支持 `127.0.0.1` 或 `::1`,可带 `/v1`;自定义端口需同步修改。需要额外鉴权的网关目前会报 HTTP 错误,不自动读取其他插件或账号的密钥。
- `intervalSeconds`:60–3600 秒,默认 300。
- `settleSeconds`:30–3600 秒,默认 120。
- `ampPath`:Amp 可执行文件路径,留空时查找 PATH 和 Amp 的常见安装位置;不经过 shell 执行。Windows 需要可执行的 `amp.exe`。
- `threadDirs`:本地线程目录的绝对路径数组;空数组使用默认目录,不递归扫描、不跟随目录项符号链接。
- `excludedThreadIds` / `excludedModels`:精确排除的线程 ID 或模型名。
Magpie 的远程网页通过声明的页面服务代理访问;不要求向网络开放采集服务端口。页面 API 使用每次启动生成的随机令牌,校验 Host 和 Origin,并限制请求大小。
## 本地状态与隐私
状态位于插件宿主提供的 Magpie 配置目录下的 `amp-usage/`,并以私有文件权限写入:
- `state.json`:已确认记录指纹、待稳定记录、网关重复的判定。
- `cloud-index.json`:线程导出检查点。
- `cloud/`:只包含用量、消息标识、完成状态、时间和各轮发送时间的精简导出。
- `collector.lock`:防止多个服务同时维护同一检查点;进程退出时删除,残留的陈旧或损坏的锁在下次启动时自动接管。
Amp 导出命令的完整结果会短暂经过内存,但不保存提示词、回复、工具内容、项目路径或账号密钥。页面不会展示线程原文。日志解析失败时保留原状态,不静默清空去重数据。看板的数字来自插件自己读到的 Amp 记录,不是重新查询的 Magpie 账本;费用仍在 Magpie 的用量页查看。页面支持中文和英文,并跟随 Magpie 的主题。
## 验证
```sh
node --test packages/amp-usage/test/*.test.mjs
bun scripts/check.mjs amp-usage
MAGPIE_BINARY="$(command -v magpie)" node --test packages/amp-usage/test/host.integration.mjs
```
覆盖解析对账、真实脱敏字段样本、时间缺失与按轮次计日、子代理去重、看板汇总、流式状态、重复 ID、稳定等待、重启、失败重试、网关重复候选、云端检查点、分页进度及页面服务鉴权。
`test/fixtures/amp-local.json` 来自真实旧版 Amp 本地记录,只保留一条已完成消息的计量字段,线程与消息标识已替换,未包含对话内容。其他测试构造专门的异常边界,不冒充真实客户端样本。修改 Tokscale 本地仓库不是本插件安装或运行的必要步骤。