diff --git a/README.md b/README.md
index e6aa6b8..669a7b7 100644
--- a/README.md
+++ b/README.md
@@ -186,6 +186,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
|---|---|---|
| [usage](packages/usage) | Usage glance: calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them | `usage:summary` |
| [free-tokens](packages/free-tokens) | AIHOT's Token freebies in three tiers (already configured and usable / needs one more plugin / no plugin yet), with the plugin to install or the exact login step for each | none; its host part reads magpie's folder (providers/checkin) and fetches aihot.news/free-tokens.data once each time the plugin host starts |
+| [amp-usage](packages/amp-usage) | Amp usage: requests, input/output tokens, cache reads and writes and cache hit rate from Amp's cloud exports and legacy local threads, synced in the background into Magpie's usage ledger for its usage pages and Day card | none; its host part runs the Amp CLI, reads Amp's local thread files and reports usage to the local Magpie |
| [day-card](packages/day-card) | Day card: a day of your usage drawn as a card (tokens, cost, each agent and its models, streak, average day), copied as a picture or saved as a PNG | `usage:day` |
| [powercontext](packages/powercontext) | Connection settings for an independently deployed PowerContext service | None |
| [nowledge-mem](packages/nowledge-mem) | Connection settings, recall and capture switches, a real connection test, and the scope of what is sent | None |
diff --git a/packages/amp-usage/LICENSE b/packages/amp-usage/LICENSE
new file mode 100644
index 0000000..c97ce97
--- /dev/null
+++ b/packages/amp-usage/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2026 magpie-community contributors
+Copyright (c) 2025 Junho Yeo (Tokscale reference and adapted reconciliation)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/amp-usage/NOTICE b/packages/amp-usage/NOTICE
new file mode 100644
index 0000000..b46d13a
--- /dev/null
+++ b/packages/amp-usage/NOTICE
@@ -0,0 +1,18 @@
+Amp usage collection references Tokscale (MIT), Copyright (c) 2025 Junho Yeo.
+https://github.com/junhoyeo/tokscale
+Reference revision: b0991187b0af99614b48230f17d13a1fe06f28fa
+
+Sources consulted:
+- crates/tokscale-core/src/sessions/amp.rs
+- crates/tokscale-cli/src/amp.rs
+
+This package independently implements CLI export caching in JavaScript and
+adapts the ledger/message reconciliation approach. It intentionally omits
+Tokscale's fallback timestamps and does not convert Amp credits to USD.
+The MIT permission notice is included in LICENSE.
+
+The Amp app icon in page/icon.svg is an unmodified official brand asset:
+https://ampcode.com/app-icon.svg
+https://ampcode.com/press-kit
+Amp branding belongs to its respective owner and is not covered by this
+package's MIT license.
diff --git a/packages/amp-usage/README.md b/packages/amp-usage/README.md
new file mode 100644
index 0000000..3b52e57
--- /dev/null
+++ b/packages/amp-usage/README.md
@@ -0,0 +1,100 @@
+# 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 本地仓库不是本插件安装或运行的必要步骤。
diff --git a/packages/amp-usage/index.mjs b/packages/amp-usage/index.mjs
new file mode 100644
index 0000000..250f46c
--- /dev/null
+++ b/packages/amp-usage/index.mjs
@@ -0,0 +1,31 @@
+import { join } from "node:path";
+import { startServer } from "./lib/server.mjs";
+let running, current;
+export default {
+ id: "amp-usage",
+ async server(input, options) {
+ if (!input?.directory)
+ throw new Error("Amp usage needs Magpie's plugin host.");
+ options ||= {};
+ // The host calls again when options change; restart to apply them.
+ const wanted = JSON.stringify([input.directory, options]);
+ if (wanted !== current) {
+ const previous = running;
+ current = wanted;
+ running = (async () => {
+ await (await previous?.catch(() => null))?.close();
+ return startServer({
+ port: Number(options.port ?? 3497),
+ configDir: input.directory,
+ dataDir: join(input.directory, "amp-usage"),
+ options,
+ });
+ })();
+ running.catch(() => {
+ if (current === wanted) current = undefined;
+ });
+ }
+ await running;
+ return {};
+ },
+};
diff --git a/packages/amp-usage/lib/collector.mjs b/packages/amp-usage/lib/collector.mjs
new file mode 100644
index 0000000..759510e
--- /dev/null
+++ b/packages/amp-usage/lib/collector.mjs
@@ -0,0 +1,418 @@
+import { sendUsage } from "./transport.mjs";
+import { createReadStream, unlinkSync } from "node:fs";
+import { mkdir, open, stat, unlink } from "node:fs/promises";
+import { join } from "node:path";
+import { parseThread, fingerprint, tokenSignature } from "./parser.mjs";
+import { readCloud, readLocal, localDirs } from "./sources.mjs";
+import { fail, reasonOf, readJSON, writeJSON } from "./storage.mjs";
+
+export function gatewayURL(raw) {
+ const u = new URL(raw);
+ if (
+ u.protocol !== "http:" ||
+ !["127.0.0.1", "[::1]"].includes(u.hostname) ||
+ u.username ||
+ u.password ||
+ u.search ||
+ u.hash ||
+ !["/", "/v1", "/v1/"].includes(u.pathname)
+ )
+ throw new Error(
+ "Use a loopback HTTP Magpie address, such as http://127.0.0.1:3425.",
+ );
+ return u.origin;
+}
+
+export async function acquireLock(dir) {
+ await mkdir(dir, { recursive: true, mode: 0o700 });
+ const path = join(dir, "collector.lock");
+ for (let i = 0; i < 2; i++) {
+ try {
+ const f = await open(path, "wx", 0o600);
+ await f.writeFile(JSON.stringify({ pid: process.pid }));
+ await f.close();
+ const drop = () => {
+ try {
+ unlinkSync(path);
+ } catch {}
+ };
+ process.once("exit", drop);
+ return () => {
+ process.off("exit", drop);
+ drop();
+ };
+ } catch (e) {
+ if (e.code !== "EEXIST") throw e;
+ // A lock is live only if its PID is a process this user can signal; a
+ // torn write, a dead PID or a stranger's process is a leftover.
+ try {
+ process.kill((await readJSON(path, null)).pid, 0);
+ } catch {
+ await unlink(path).catch(() => {});
+ continue;
+ }
+ throw new Error(
+ "Another Amp collector is running for this Magpie configuration.",
+ );
+ }
+ }
+ throw new Error("Could not acquire collector lock.");
+}
+
+// Magpie's gateway log, indexed once and then read only where it grew. A new
+// file (rotation) or a shorter one starts the index again.
+function gatewayLog(path) {
+ // Key -> [time ms, session, time ms, session, ...]; sessions are shared
+ // strings, so a heavy log stays a modest index.
+ const rows = new Map();
+ const sessions = new Map();
+ let file = null,
+ offset = 0;
+ const add = (line) => {
+ let r;
+ try {
+ r = JSON.parse(line);
+ } catch {
+ return;
+ }
+ if (
+ r?.source === "reported" ||
+ r?.rid?.startsWith?.("amp-usage:") ||
+ !r?.t ||
+ ![r.in, r.out, r.cache_read, r.cache_write].some((n) => n > 0)
+ )
+ return;
+ const key = `${bareModel(r.served || r.model)}:${tokenSignature(r)}`;
+ const session = String(r.session ?? "");
+ if (!sessions.has(session)) sessions.set(session, session);
+ const group = rows.get(key);
+ const entry = [Date.parse(r.t), sessions.get(session)];
+ if (group) group.push(...entry);
+ else rows.set(key, entry);
+ };
+ return async function read() {
+ let st;
+ try {
+ st = await stat(path);
+ } catch (e) {
+ if (e.code !== "ENOENT") throw e;
+ st = null;
+ }
+ const id = st && `${st.dev}:${st.ino}`;
+ if (id !== file || !st || st.size < offset) {
+ rows.clear();
+ sessions.clear();
+ file = id;
+ offset = 0;
+ }
+ if (!st || st.size === offset) return rows;
+ // Only whole lines are taken; a line still being written waits.
+ let rest = Buffer.alloc(0);
+ for await (const chunk of createReadStream(path, {
+ start: offset,
+ end: st.size - 1,
+ })) {
+ const buf = Buffer.concat([rest, chunk]);
+ const cut = buf.lastIndexOf(10) + 1;
+ if (cut) {
+ for (const line of buf.subarray(0, cut).toString("utf8").split("\n"))
+ if (line) add(line);
+ offset += cut;
+ }
+ rest = buf.subarray(cut);
+ }
+ return rows;
+ };
+}
+const bareModel = (s) =>
+ String(s || "")
+ .split("/")
+ .at(-1);
+export function gatewayMatch(record, rows) {
+ const group =
+ rows.get(`${bareModel(record.model)}:${tokenSignature(record)}`) || [];
+ const t = Date.parse(record.t);
+ for (let i = 0; i < group.length; i += 2)
+ if (group[i + 1] === record.session || Math.abs(group[i] - t) <= 5_000)
+ return true;
+ return false;
+}
+
+export async function createCollector({
+ dataDir,
+ configDir,
+ options = {},
+ source,
+ fetchImpl = sendUsage,
+ clock = Date.now,
+}) {
+ const base = gatewayURL(options.gatewayURL || "http://127.0.0.1:3425");
+ const interval =
+ Math.max(60, Math.min(3600, Number(options.intervalSeconds) || 300)) * 1000;
+ const settleMs =
+ Math.max(30, Math.min(3600, Number(options.settleSeconds) || 120)) * 1000;
+ const statePath = join(dataDir, "state.json");
+ const state = await readJSON(statePath, {
+ version: 1,
+ imported: {},
+ pending: {},
+ });
+ if (state.version !== 1 || !state.imported || !state.pending)
+ throw new Error(
+ "Unsupported collector state. Existing state was preserved.",
+ );
+ // Gateway rows leave usage.jsonl when Magpie rotates it; the verdict must not.
+ state.gateway ||= {};
+ const gatewayRows = gatewayLog(join(configDir, "usage.jsonl"));
+ // Installing the plugin is the consent to report; `sync: false` only reads.
+ const syncing = options.sync !== false;
+ // The last scan's records, for the page's own totals.
+ let latest = [];
+ let job = null,
+ timer,
+ closed = false;
+ const emptyStatus = () => ({
+ phase: "idle",
+ lastScan: null,
+ lastImport: null,
+ scannedThreads: 0,
+ eligible: 0,
+ pending: 0,
+ imported: 0,
+ skipped: 0,
+ remaining: 0,
+ issues: {},
+ errors: [],
+ });
+ let status = emptyStatus();
+ const pad = (n) => String(n).padStart(2, "0");
+ function usage() {
+ const rows = new Map();
+ for (const r of latest) {
+ const d = new Date(r.t);
+ // Local hours, so the page can show a day or the last 24 hours.
+ const hour = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}`;
+ const key = `${hour} ${r.model}`;
+ const row = rows.get(key) || {
+ hour,
+ model: r.model,
+ calls: 0,
+ in: 0,
+ out: 0,
+ cache_read: 0,
+ cache_write: 0,
+ };
+ row.calls++;
+ for (const k of ["in", "out", "cache_read", "cache_write"])
+ row[k] += r[k];
+ rows.set(key, row);
+ }
+ return [...rows.values()];
+ }
+ const view = () => ({
+ ...status,
+ usage: usage(),
+ totalImported: Object.keys(state.imported).length,
+ });
+ // Legacy files have real times and the ledger, so they are read first and
+ // win a record both sources hold; the account adds what they lack.
+ async function readThreads() {
+ const dirs = options.threadDirs?.length ? options.threadDirs : null;
+ const local = await readLocal(dirs || localDirs(), { required: !!dirs });
+ let cloud = { threads: [], errors: [], remaining: 0 };
+ try {
+ cloud = await readCloud({
+ dataDir,
+ ampPath: options.ampPath,
+ now: clock,
+ });
+ } catch (e) {
+ cloud.errors.push(reasonOf(e));
+ }
+ return {
+ threads: [...local.threads, ...cloud.threads],
+ errors: [...local.errors, ...cloud.errors],
+ remaining: cloud.remaining,
+ };
+ }
+ const persist = () => writeJSON(statePath, state);
+ // Each record's status, in order. Magpie answers 400 for a whole batch when
+ // one record is invalid, so halve it until that record stands alone.
+ async function post(batch) {
+ const response = await fetchImpl(`${base}/v1/magpie/usage/requests`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(batch),
+ signal: AbortSignal.timeout(15_000),
+ }).catch((e) => {
+ throw fail("magpieUnreachable", `Cannot reach Magpie: ${e.message}`);
+ });
+ if (response.status === 400) {
+ if (batch.length === 1) return ["rejected"];
+ const half = Math.ceil(batch.length / 2);
+ return [
+ ...(await post(batch.slice(0, half))),
+ ...(await post(batch.slice(half))),
+ ];
+ }
+ if (!response.ok)
+ throw fail(
+ "magpieRefused",
+ `Magpie refused usage (HTTP ${response.status}). Check the gateway address and Magpie version.`,
+ );
+ const ack = await response.json();
+ if (
+ !Array.isArray(ack.records) ||
+ ack.records.length !== batch.length ||
+ ack.records.some((a, j) => a.rid !== batch[j].rid)
+ )
+ throw fail(
+ "magpieAck",
+ "Unexpected Magpie acknowledgement; retry is safe with the same record IDs.",
+ );
+ return ack.records.map((a) => a.status);
+ }
+ async function scan() {
+ status = {
+ ...status,
+ phase: "reading",
+ errors: [],
+ issues: {},
+ imported: 0,
+ skipped: 0,
+ };
+ try {
+ const result = await (source || readThreads)();
+ const records = new Map();
+ const issues = {};
+ const addIssue = (k, n = 1) => {
+ issues[k] = (issues[k] || 0) + n;
+ };
+ for (const thread of result.threads) {
+ if (options.excludedThreadIds?.includes(thread.id)) {
+ addIssue("excludedThread");
+ continue;
+ }
+ let parsed;
+ // One malformed thread must not cost the others their records.
+ try {
+ parsed = parseThread(thread, { now: clock(), settleMs });
+ } catch (e) {
+ console.error(`amp-usage: thread skipped: ${e.message}`);
+ addIssue("invalidThread");
+ continue;
+ }
+ for (const [k, n] of Object.entries(parsed.issues)) addIssue(k, n);
+ for (const r of parsed.records) {
+ if (
+ options.excludedModels?.includes(r.model) ||
+ /^(magpie|custom:magpie)[/:]/i.test(r.model)
+ ) {
+ addIssue("excludedModel");
+ continue;
+ }
+ if (!records.has(r.rid)) records.set(r.rid, r);
+ }
+ }
+ let through;
+ const ready = [];
+ const importedFingerprints = new Set(Object.values(state.imported));
+ for (const id of Object.keys(state.pending))
+ if (!records.has(id)) delete state.pending[id];
+ let pending = 0;
+ const shown = [];
+ for (const r of records.values()) {
+ const fp = fingerprint(r);
+ if (state.imported[r.rid]) {
+ if (state.imported[r.rid] !== fp) addIssue("changedAfterImport");
+ shown.push(r);
+ continue;
+ }
+ if (importedFingerprints.has(fp)) {
+ addIssue("identityChanged");
+ continue;
+ }
+ shown.push(r);
+ // Read the gateway log only for records still undecided. If it cannot
+ // be read, fail closed instead of double-counting.
+ if (state.gateway[r.rid] !== fp) through ??= await gatewayRows();
+ if (state.gateway[r.rid] === fp || gatewayMatch(r, through)) {
+ state.gateway[r.rid] = fp;
+ delete state.pending[r.rid];
+ addIssue("gatewayDuplicate");
+ continue;
+ }
+ const previous = state.pending[r.rid];
+ if (!previous || previous.fingerprint !== fp)
+ state.pending[r.rid] = { fingerprint: fp, since: clock() };
+ if (clock() - state.pending[r.rid].since < settleMs) {
+ pending++;
+ continue;
+ }
+ ready.push(r);
+ }
+ latest = shown;
+ status = {
+ ...status,
+ scannedThreads: new Set(result.threads.map((t) => t.id)).size,
+ eligible: ready.length,
+ pending,
+ remaining: result.remaining || 0,
+ issues,
+ errors: [...new Set(result.errors || [])].slice(0, 10),
+ lastScan: new Date(clock()).toISOString(),
+ };
+ await persist();
+ if (syncing) {
+ for (let i = 0; i < ready.length; i += 200) {
+ if (closed) break;
+ const batch = ready.slice(i, i + 200);
+ const results = await post(batch);
+ for (const [j, r] of batch.entries()) {
+ const result = results[j];
+ // A record Magpie refuses is retried later; it must not block the rest.
+ if (!["accepted", "skipped"].includes(result)) {
+ status.issues.rejected = (status.issues.rejected || 0) + 1;
+ continue;
+ }
+ state.imported[r.rid] = fingerprint(r);
+ delete state.pending[r.rid];
+ status[result === "accepted" ? "imported" : "skipped"]++;
+ }
+ await persist();
+ status.eligible -= batch.length;
+ status.lastImport = new Date(clock()).toISOString();
+ }
+ }
+ } catch (e) {
+ const reason = reasonOf(e);
+ if (["unexpected", "magpieRefused", "magpieUnreachable"].includes(reason))
+ console.error(`amp-usage: ${e.message}`);
+ status.errors = [...new Set([...status.errors, reason])].slice(0, 10);
+ } finally {
+ status.phase = "idle";
+ }
+ return view();
+ }
+ function run() {
+ if (closed) return Promise.reject(new Error("Collector is closed."));
+ if (job) return job;
+ job = scan().finally(() => {
+ job = null;
+ });
+ return job;
+ }
+ timer = setInterval(() => {
+ if (syncing && !closed) void run();
+ }, interval);
+ timer.unref?.();
+ return {
+ view,
+ run,
+ async close() {
+ closed = true;
+ clearInterval(timer);
+ if (job) await job;
+ },
+ };
+}
diff --git a/packages/amp-usage/lib/parser.mjs b/packages/amp-usage/lib/parser.mjs
new file mode 100644
index 0000000..1f8b0d6
--- /dev/null
+++ b/packages/amp-usage/lib/parser.mjs
@@ -0,0 +1,256 @@
+// Amp's ledger/message reconciliation follows Tokscale's MIT-licensed parser.
+// See NOTICE. A call with no time of its own takes the moment its turn was
+// sent; nothing is dated from a thread's creation or a file's mtime.
+import { createHash } from "node:crypto";
+
+export const digest = (value) =>
+ createHash("sha256").update(JSON.stringify(value)).digest("hex");
+export const validThread = (id) =>
+ typeof id === "string" && /^T-[a-zA-Z0-9-]{1,120}$/.test(id);
+const idOf = (id) =>
+ (Number.isSafeInteger(id) && id >= 0) ||
+ (typeof id === "string" && /^[\w-]{1,100}$/.test(id))
+ ? String(id)
+ : null;
+// An ISO string or epoch milliseconds; anything a Date cannot hold is no time.
+const timeOf = (t) => {
+ const ms =
+ typeof t === "number"
+ ? t
+ : typeof t === "string" &&
+ /^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(t)
+ ? Date.parse(t)
+ : NaN;
+ return Number.isFinite(ms) && ms >= Date.UTC(2000, 0, 1) && ms <= 8.64e15
+ ? new Date(ms).toISOString()
+ : null;
+};
+const token = (n) =>
+ n == null
+ ? 0
+ : Number.isSafeInteger(n) && n >= 0 && n <= 100_000_000
+ ? n
+ : null;
+const counts = (u, ledger) => [
+ token(ledger ? u.input : u.inputTokens),
+ token(ledger ? u.output : u.outputTokens),
+ token(u.cacheReadInputTokens),
+ token(u.cacheCreationInputTokens),
+];
+const modelOf = (m) =>
+ typeof m === "string" &&
+ m.trim() &&
+ m.length <= 256 &&
+ !/[\x00-\x1f\x7f]/.test(m)
+ ? m.trim()
+ : null;
+export const fingerprint = (r) =>
+ digest([r.session, r.t, r.model, r.in, r.out, r.cache_read, r.cache_write]);
+export const tokenSignature = (r) =>
+ JSON.stringify([
+ r.in || 0,
+ r.out || 0,
+ r.cache_read || 0,
+ r.cache_write || 0,
+ ]);
+
+export function parseThread(
+ thread,
+ { now = Date.now(), settleMs = 120_000 } = {},
+) {
+ if (!thread || !validThread(thread.id))
+ throw new Error("Invalid Amp thread ID");
+ const issues = {};
+ const note = (code) => {
+ issues[code] = (issues[code] || 0) + 1;
+ };
+ const make = (u, ledger, id, state) => {
+ const tokens = counts(u, ledger);
+ const model = modelOf(u.model);
+ if (!model || tokens.includes(null)) {
+ note("invalidUsage");
+ return null;
+ }
+ if (!tokens.some(Boolean)) return null;
+ return {
+ ledger,
+ model,
+ tokens,
+ time: timeOf(u.timestamp),
+ id,
+ state,
+ operation: String(u.operationType || ""),
+ };
+ };
+ let sent = null;
+ const messages = (
+ Array.isArray(thread.messages) ? thread.messages : []
+ ).flatMap((m) => {
+ if (m?.role === "user" && Number.isFinite(m.sentAt))
+ sent = timeOf(m.sentAt);
+ if (m?.role !== "assistant" || !m.usage) return [];
+ const r = make(m.usage, false, idOf(m.messageId), m.state?.type);
+ if (r) r.sent = sent;
+ return r ? [r] : [];
+ });
+ const ledger = (
+ Array.isArray(thread.usageLedger?.events) ? thread.usageLedger.events : []
+ ).flatMap((e) => {
+ if (!e?.tokens) return [];
+ // The subagent's own thread reports these calls one by one, with cache.
+ if (e.operationType === "subagent" && validThread(e.subagentThreadID)) {
+ note("subagentThread");
+ return [];
+ }
+ const r = make(
+ {
+ ...e.tokens,
+ model: e.model,
+ timestamp: e.timestamp,
+ operationType: e.operationType,
+ },
+ true,
+ idOf(e.toMessageId),
+ );
+ if (r) r.event = idOf(e.id);
+ return r ? [r] : [];
+ });
+ const consumed = new Set();
+ const unmatched = [];
+ for (const message of messages) {
+ let index = ledger.findIndex(
+ (r, i) =>
+ !consumed.has(i) &&
+ message.id !== null &&
+ r.id === message.id &&
+ r.model === message.model &&
+ (!r.operation || r.operation === "inference"),
+ );
+ if (index < 0)
+ index = ledger.findIndex(
+ (r, i) =>
+ !consumed.has(i) &&
+ r.model === message.model &&
+ // Amp's ledger usually carries input/output only.
+ r.tokens.every((n, k) => n === message.tokens[k] || (k > 1 && !n)) &&
+ (!r.time || !message.time || r.time === message.time),
+ );
+ if (index < 0) {
+ message.time ||= message.sent;
+ unmatched.push(message);
+ continue;
+ }
+ consumed.add(index);
+ const r = ledger[index];
+ // Message identity survives a ledger appearing in a later export.
+ r.id = message.id ?? r.id;
+ r.matched = true;
+ r.time ||= message.time || message.sent;
+ r.tokens[2] ||= message.tokens[2];
+ r.tokens[3] ||= message.tokens[3];
+ r.state = message.state;
+ }
+ const records = [];
+ const seen = new Map();
+ for (const r of [...ledger, ...unmatched]) {
+ if (r.state && r.state !== "complete") {
+ note("unfinished");
+ continue;
+ }
+ if (!r.time) {
+ note("missingTimestamp");
+ continue;
+ }
+ if (Date.parse(r.time) > now - settleMs) {
+ note("settling");
+ continue;
+ }
+ const messageIdentity =
+ r.id !== null &&
+ (!r.ledger || r.matched || !r.operation || r.operation === "inference");
+ if (!messageIdentity && r.event === null) {
+ note("missingIdentity");
+ continue;
+ }
+ const identity = messageIdentity ? `message:${r.id}` : `event:${r.event}`;
+ const [input, output, cacheRead, cacheWrite] = r.tokens;
+ const rec = {
+ t: r.time,
+ agent: "amp",
+ provider: "session-unknown",
+ model: r.model,
+ in: input,
+ out: output,
+ cache_read: cacheRead,
+ cache_write: cacheWrite,
+ status: 200,
+ session: thread.id,
+ rid: `amp-usage:v1:${digest([thread.id, identity])}`,
+ };
+ if (seen.has(rec.rid)) {
+ if (
+ seen.get(rec.rid) &&
+ fingerprint(seen.get(rec.rid)) !== fingerprint(rec)
+ ) {
+ note("conflictingIdentity");
+ seen.set(rec.rid, null);
+ }
+ continue;
+ }
+ seen.set(rec.rid, rec);
+ }
+ for (const r of seen.values()) if (r) records.push(r);
+ return { records, issues };
+}
+
+// Only metering fields leave the in-memory export; never cache content or titles.
+export function projectThread(t) {
+ const pick = (v, keys) =>
+ Object.fromEntries(
+ keys.filter((k) => v?.[k] !== undefined).map((k) => [k, v[k]]),
+ );
+ const usageKeys = [
+ "model",
+ "timestamp",
+ "inputTokens",
+ "outputTokens",
+ "cacheReadInputTokens",
+ "cacheCreationInputTokens",
+ ];
+ const eventKeys = [
+ "id",
+ "model",
+ "timestamp",
+ "toMessageId",
+ "operationType",
+ "subagentThreadID",
+ ];
+ return {
+ id: t.id,
+ messages: (t.messages || []).flatMap((m) =>
+ m?.role === "assistant" && m.usage
+ ? [
+ {
+ role: m.role,
+ messageId: m.messageId,
+ state: { type: m.state?.type },
+ usage: pick(m.usage, usageKeys),
+ },
+ ]
+ : m?.role === "user" && Number.isFinite(m.meta?.sentAt)
+ ? [{ role: m.role, sentAt: m.meta.sentAt }]
+ : [],
+ ),
+ usageLedger: {
+ events: (t.usageLedger?.events || []).map((e) => ({
+ ...pick(e, eventKeys),
+ tokens: pick(e.tokens, [
+ "input",
+ "output",
+ "cacheReadInputTokens",
+ "cacheCreationInputTokens",
+ ]),
+ })),
+ },
+ };
+}
diff --git a/packages/amp-usage/lib/server.mjs b/packages/amp-usage/lib/server.mjs
new file mode 100644
index 0000000..7e34377
--- /dev/null
+++ b/packages/amp-usage/lib/server.mjs
@@ -0,0 +1,163 @@
+import { createServer } from "node:http";
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { createCollector, acquireLock } from "./collector.mjs";
+
+const ui = fileURLToPath(new URL("../ui/", import.meta.url));
+export async function startServer({
+ port = 3497,
+ dataDir,
+ configDir,
+ options = {},
+ collector: injected,
+} = {}) {
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
+ throw new Error("Invalid service port.");
+ const release = await acquireLock(dataDir);
+ let collector;
+ try {
+ collector =
+ injected || (await createCollector({ dataDir, configDir, options }));
+ } catch (e) {
+ await release();
+ throw e;
+ }
+ const token = randomBytes(32).toString("hex");
+ let actualPort;
+ const send = (res, code, body, type = "application/json") => {
+ res.writeHead(code, {
+ "Content-Type": type,
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ });
+ res.end(type === "application/json" ? JSON.stringify(body) : body);
+ };
+ const server = createServer(async (req, res) => {
+ try {
+ const host = req.headers.host;
+ if (
+ ![`127.0.0.1:${actualPort}`, `localhost:${actualPort}`].includes(host)
+ )
+ return send(res, 403, { error: "Invalid host." });
+ const url = new URL(req.url, `http://${host}`);
+ const origin = req.headers.origin;
+ const originOK =
+ !origin || origin === "null" || origin === `http://${host}`;
+ if (!originOK) return send(res, 403, { error: "Invalid origin." });
+ if (url.pathname.startsWith("/api/")) {
+ if (req.method === "OPTIONS") {
+ res.setHeader(
+ "Access-Control-Allow-Origin",
+ origin || `http://${host}`,
+ );
+ res.setHeader(
+ "Access-Control-Allow-Headers",
+ "Content-Type, X-Amp-Usage-Token",
+ );
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST");
+ res.setHeader("Vary", "Origin");
+ return send(res, 204, "", "text/plain");
+ }
+ const given = Buffer.from(
+ String(req.headers["x-amp-usage-token"] || ""),
+ );
+ const expected = Buffer.from(token);
+ if (
+ given.length !== expected.length ||
+ !timingSafeEqual(given, expected)
+ )
+ return send(res, 403, {
+ error: "Reopen the Amp usage page to reconnect.",
+ code: "reconnect",
+ });
+ res.setHeader(
+ "Access-Control-Allow-Origin",
+ origin || `http://${host}`,
+ );
+ res.setHeader("Vary", "Origin");
+ if (url.pathname === "/api/status" && req.method === "GET")
+ return send(res, 200, collector.view());
+ if (req.method !== "POST")
+ return send(res, 405, { error: "Method not allowed." });
+ if (
+ String(req.headers["content-type"]).split(";")[0] !==
+ "application/json"
+ )
+ return send(res, 415, { error: "Expected JSON." });
+ let raw = "";
+ for await (const chunk of req) {
+ raw += chunk;
+ if (Buffer.byteLength(raw) > 4096)
+ return send(res, 413, { error: "Request too large." });
+ }
+ try {
+ JSON.parse(raw);
+ } catch {
+ return send(res, 400, { error: "Invalid JSON." });
+ }
+ if (url.pathname === "/api/refresh") {
+ // The page polls status; a long cloud export never holds its HTTP request.
+ void collector.run().catch(() => {});
+ return send(res, 202, collector.view());
+ }
+ return send(res, 404, { error: "Not found." });
+ }
+ if (req.method !== "GET")
+ return send(res, 405, { error: "Method not allowed." });
+ const files = {
+ "/": ["index.html", "text/html; charset=utf-8"],
+ "/app.js": ["app.js", "text/javascript; charset=utf-8"],
+ "/words.js": ["words.js", "text/javascript; charset=utf-8"],
+ "/style.css": ["style.css", "text/css; charset=utf-8"],
+ };
+ const file = files[url.pathname];
+ if (!file) return send(res, 404, "Not found", "text/plain");
+ // The page carries the token, so only a navigation may read it.
+ const mode = req.headers["sec-fetch-mode"];
+ if (file[0] === "index.html" && mode && mode !== "navigate")
+ return send(res, 403, "Forbidden", "text/plain");
+ let text = await readFile(join(ui, file[0]), "utf8");
+ if (file[0] === "index.html")
+ text = text.replace("__SERVICE_TOKEN__", token);
+ const self = `http://127.0.0.1:${actualPort} http://localhost:${actualPort}`;
+ res.setHeader(
+ "Content-Security-Policy",
+ `default-src 'none'; script-src 'self' ${self}; style-src 'self' ${self}; connect-src 'self' ${self}; base-uri 'none'; form-action 'none'`,
+ );
+ return send(res, 200, text, file[1]);
+ } catch {
+ if (!res.headersSent)
+ send(res, 500, {
+ error: "Local service error. Check the plugin log.",
+ code: "serviceError",
+ });
+ else res.end();
+ }
+ });
+ try {
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(port, "127.0.0.1", resolve);
+ });
+ actualPort = server.address().port;
+ } catch (e) {
+ await collector.close();
+ await release();
+ throw e;
+ }
+ return {
+ port: actualPort,
+ collector,
+ async close() {
+ await collector.close();
+ await new Promise((resolve) => {
+ server.close(resolve);
+ server.closeAllConnections();
+ });
+ await release();
+ },
+ };
+}
diff --git a/packages/amp-usage/lib/sources.mjs b/packages/amp-usage/lib/sources.mjs
new file mode 100644
index 0000000..78e2390
--- /dev/null
+++ b/packages/amp-usage/lib/sources.mjs
@@ -0,0 +1,242 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { access, lstat, readdir, readFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join, delimiter, isAbsolute } from "node:path";
+import { projectThread, validThread } from "./parser.mjs";
+import { fail, reasonOf, readJSON, writeJSON } from "./storage.mjs";
+
+const exec = promisify(execFile);
+export async function findAmp(configured = "") {
+ const names = process.platform === "win32" ? ["amp.exe"] : ["amp"];
+ const paths = configured
+ ? [configured]
+ : [
+ ...(process.env.PATH || "").split(delimiter),
+ join(homedir(), ".amp", "bin"),
+ join(homedir(), ".local", "share", "amp", "bin"),
+ ].flatMap((d) => names.map((n) => join(d, n)));
+ for (const path of paths) {
+ try {
+ await access(path);
+ return path;
+ } catch {}
+ }
+ throw fail(
+ "ampNotFound",
+ "Amp CLI not found. Install Amp and run amp login, or set ampPath in plugin options.",
+ );
+}
+export async function runAmp(binary, args, timeout = 30_000) {
+ try {
+ const pending = exec(binary, args, {
+ timeout,
+ maxBuffer: 32 * 1024 * 1024,
+ windowsHide: true,
+ killSignal: "SIGKILL",
+ encoding: "utf8",
+ });
+ pending.child.stdin?.end();
+ const { stdout } = await pending;
+ return JSON.parse(stdout);
+ } catch (e) {
+ // The CLI's stderr may contain private server responses or credentials.
+ if (e instanceof SyntaxError)
+ throw fail(
+ "ampInvalidJSON",
+ "Amp returned invalid JSON. Update Amp and try again.",
+ );
+ throw e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
+ ? fail(
+ "ampTooLarge",
+ "An Amp thread export is too large to read; it was skipped.",
+ )
+ : e.killed
+ ? fail("ampTimeout", "Amp command timed out. Try syncing again.")
+ : fail(
+ "ampFailed",
+ "Amp command failed. Check amp login and network access in your terminal.",
+ );
+ }
+}
+export function localDirs() {
+ return [
+ join(
+ process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"),
+ "amp",
+ "threads",
+ ),
+ ];
+}
+export async function readLocal(dirs = localDirs(), { required = true } = {}) {
+ const threads = new Map();
+ const errors = [];
+ for (const dir of dirs) {
+ if (!isAbsolute(dir))
+ throw fail(
+ "localDirInvalid",
+ "Thread directories must be absolute paths.",
+ );
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch (e) {
+ // Amp's own legacy directory is optional; a configured one is not.
+ if (e.code !== "ENOENT") errors.push("localDirUnreadable");
+ else if (required) errors.push("localDirMissing");
+ continue;
+ }
+ for (const entry of entries) {
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
+ const path = join(dir, entry.name);
+ try {
+ const st = await lstat(path);
+ if (!st.isFile() || st.size > 32 * 1024 * 1024) throw new Error();
+ const t = JSON.parse(await readFile(path, "utf8"));
+ if (!validThread(t.id)) throw new Error();
+ const projected = projectThread(t);
+ if (
+ threads.has(t.id) &&
+ JSON.stringify(threads.get(t.id)) !== JSON.stringify(projected)
+ ) {
+ threads.set(t.id, null);
+ errors.push("localThreadConflict");
+ } else if (!threads.has(t.id)) threads.set(t.id, projected);
+ } catch {
+ errors.push("localThreadInvalid");
+ }
+ }
+ }
+ return {
+ threads: [...threads.values()].filter(Boolean),
+ errors,
+ remaining: 0,
+ };
+}
+
+export async function readCloud({
+ dataDir,
+ ampPath = "",
+ run,
+ maxExports = 20,
+ now = Date.now,
+} = {}) {
+ const binary = run ? "amp" : await findAmp(ampPath);
+ const invoke = run || ((args, ms) => runAmp(binary, args, ms));
+ const deadline = now() + 60_000;
+ const call = (args) => {
+ const ms = Math.min(30_000, deadline - now());
+ if (ms <= 0)
+ throw fail(
+ "ampBudget",
+ "Amp sync time budget reached. Sync again to continue.",
+ );
+ return invoke(args, ms);
+ };
+ const indexPath = join(dataDir, "cloud-index.json");
+ let index = await readJSON(indexPath, null);
+ // Version 1 projections carry no sent times; export those threads again.
+ if (index?.version !== 2 || typeof index.threads !== "object")
+ index = { version: 2, threads: {} };
+ // The last complete list, so a scan can stop paging at the first page with
+ // nothing new: Amp lists the most recently updated threads first. A full
+ // list once a day drops deleted threads.
+ const known =
+ typeof index.list?.threads === "object" &&
+ now() - index.list.at < 86_400_000
+ ? index.list.threads
+ : null;
+ const listed = new Map();
+ let complete = false;
+ for (let offset = 0; offset < 100_000; offset += 200) {
+ const page = await call([
+ "threads",
+ "list",
+ "--json",
+ "--include-archived",
+ "--limit",
+ "200",
+ "--offset",
+ String(offset),
+ ]);
+ if (!Array.isArray(page))
+ throw fail("ampListFormat", "Unexpected Amp thread list format.");
+ let added = 0,
+ changed = 0;
+ for (const t of page) {
+ if (
+ !validThread(t?.id) ||
+ typeof t.updated !== "string" ||
+ !Number.isFinite(Date.parse(t.updated))
+ )
+ throw fail("ampListFormat", "Unexpected Amp thread metadata.");
+ if (!listed.has(t.id)) added++;
+ if (known?.[t.id] !== t.updated) changed++;
+ listed.set(t.id, t.updated);
+ }
+ if (page.length < 200) {
+ complete = true;
+ break;
+ }
+ if (known && !changed) break;
+ if (!added || offset + 200 >= 100_000)
+ throw fail("ampListFormat", "Amp pagination did not finish.");
+ }
+ // A thread updated since it was last seen is newer than every one that was
+ // not, so the merged list stays a sound place to stop next time.
+ if (!complete)
+ for (const [id, updated] of Object.entries(known))
+ if (!listed.has(id)) listed.set(id, updated);
+ index.list = {
+ at: complete ? now() : index.list.at,
+ threads: Object.fromEntries(listed),
+ };
+ const threads = [],
+ errors = [];
+ let exported = 0,
+ remaining = 0;
+ // Oldest changed threads first; successful exports advance their own checkpoint.
+ const order = [...listed]
+ .map(([id, updated]) => ({ id, updated }))
+ .sort((a, b) => a.updated.localeCompare(b.updated));
+ for (const meta of order) {
+ const file = join(dataDir, "cloud", `${meta.id}.json`);
+ let cached = null;
+ try {
+ cached = await readJSON(file, null);
+ } catch {
+ /* Re-export a damaged projection. */
+ }
+ if (index.threads[meta.id] !== meta.updated || !cached) {
+ if (exported >= maxExports || now() >= deadline) remaining++;
+ else {
+ exported++;
+ try {
+ const raw = await call(["threads", "export", meta.id]);
+ if (raw?.id !== meta.id)
+ throw fail(
+ "ampExportMismatch",
+ "Amp export returned a different thread.",
+ );
+ cached = projectThread(raw);
+ await writeJSON(file, cached);
+ index.threads[meta.id] = meta.updated;
+ await writeJSON(indexPath, index);
+ } catch (e) {
+ errors.push(reasonOf(e));
+ }
+ }
+ }
+ // An export that failed or must wait still leaves the last good copy, so
+ // its records keep settling.
+ if (!cached) continue;
+ if (cached.id !== meta.id) {
+ errors.push("cacheMismatch");
+ delete index.threads[meta.id];
+ continue;
+ }
+ threads.push(cached);
+ }
+ await writeJSON(indexPath, index);
+ return { threads, errors, remaining, listed: listed.size, exported };
+}
diff --git a/packages/amp-usage/lib/storage.mjs b/packages/amp-usage/lib/storage.mjs
new file mode 100644
index 0000000..02a0b5f
--- /dev/null
+++ b/packages/amp-usage/lib/storage.mjs
@@ -0,0 +1,26 @@
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+import { randomUUID } from "node:crypto";
+
+// The page shows `reason`, a code it translates; the message is for the log.
+export const fail = (reason, message) =>
+ Object.assign(new Error(message), { reason });
+export const reasonOf = (e) => e?.reason || "unexpected";
+
+export async function readJSON(path, fallback) {
+ try {
+ return JSON.parse(await readFile(path, "utf8"));
+ } catch (e) {
+ if (e.code === "ENOENT") return fallback;
+ throw fail(
+ "fileUnreadable",
+ `Cannot read ${path}: ${e instanceof SyntaxError ? "invalid JSON" : e.code || "read failed"}`,
+ );
+ }
+}
+export async function writeJSON(path, value) {
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
+ const tmp = `${path}.${randomUUID()}.tmp`;
+ await writeFile(tmp, JSON.stringify(value), { mode: 0o600, flag: "wx" });
+ await rename(tmp, path);
+}
diff --git a/packages/amp-usage/lib/transport.mjs b/packages/amp-usage/lib/transport.mjs
new file mode 100644
index 0000000..dd1b81d
--- /dev/null
+++ b/packages/amp-usage/lib/transport.mjs
@@ -0,0 +1,36 @@
+import { request } from "node:http";
+
+// This is a host-side loopback request. Node fetch adds Sec-Fetch-Mode, which
+// Magpie correctly treats as a browser request and refuses without a key.
+export function sendUsage(url, init) {
+ return new Promise((resolve, reject) => {
+ const req = request(
+ url,
+ { method: init.method, headers: init.headers, signal: init.signal },
+ (res) => {
+ const chunks = [];
+ let size = 0;
+ res.on("data", (chunk) => {
+ size += chunk.length;
+ if (size > 1024 * 1024) {
+ res.destroy(new Error("Magpie acknowledgement is too large."));
+ return;
+ }
+ chunks.push(chunk);
+ });
+ res.on("error", reject);
+ res.on("end", () =>
+ resolve({
+ ok: res.statusCode >= 200 && res.statusCode < 300,
+ status: res.statusCode,
+ async json() {
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ },
+ }),
+ );
+ },
+ );
+ req.on("error", reject);
+ req.end(init.body);
+ });
+}
diff --git a/packages/amp-usage/package.json b/packages/amp-usage/package.json
new file mode 100644
index 0000000..f9d4061
--- /dev/null
+++ b/packages/amp-usage/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "@magpie-community/page-amp-usage",
+ "version": "0.1.0",
+ "description": "An Amp usage board in Magpie's window, with a local background service that can sync Amp usage into Magpie's usage ledger.",
+ "type": "module",
+ "main": "./index.mjs",
+ "files": [
+ "index.mjs",
+ "lib",
+ "page",
+ "ui",
+ "README.md",
+ "LICENSE",
+ "NOTICE"
+ ],
+ "scripts": {
+ "test": "node --test test/*.test.mjs"
+ },
+ "engines": {
+ "magpie": ">=0.1.3681",
+ "node": ">=20"
+ },
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/magpie-community/plugins.git",
+ "directory": "packages/amp-usage"
+ },
+ "keywords": [
+ "magpie",
+ "magpie-page",
+ "amp",
+ "usage"
+ ],
+ "magpie": {
+ "page": {
+ "title": "Amp usage",
+ "file": "page/index.html",
+ "icon": "page/icon.svg",
+ "service": {
+ "port": 3497,
+ "option": "port"
+ }
+ },
+ "permissions": [],
+ "options": {
+ "port": 3497,
+ "sync": true,
+ "gatewayURL": "http://127.0.0.1:3425",
+ "intervalSeconds": 300,
+ "settleSeconds": 120,
+ "ampPath": "",
+ "threadDirs": [],
+ "excludedThreadIds": [],
+ "excludedModels": []
+ }
+ }
+}
diff --git a/packages/amp-usage/page/boot.css b/packages/amp-usage/page/boot.css
new file mode 100644
index 0000000..17d4f19
--- /dev/null
+++ b/packages/amp-usage/page/boot.css
@@ -0,0 +1,13 @@
+body {
+ margin: 24px;
+ color: var(--magpie-fg, #242429);
+ background: var(--magpie-bg, #fff);
+ font: 14px/1.5 var(--magpie-font, system-ui);
+}
+h1 {
+ font-size: 20px;
+}
+button {
+ font: inherit;
+ padding: 8px 14px;
+}
diff --git a/packages/amp-usage/page/boot.js b/packages/amp-usage/page/boot.js
new file mode 100644
index 0000000..51cd4f2
--- /dev/null
+++ b/packages/amp-usage/page/boot.js
@@ -0,0 +1,68 @@
+(async () => {
+ const zh = (lang) =>
+ String(lang || navigator.language || "")
+ .toLowerCase()
+ .startsWith("zh");
+ const words = (lang) =>
+ zh(lang)
+ ? {
+ title: "Amp 用量",
+ connecting: "正在连接本地采集服务…",
+ stopped: "采集服务没有启动。请查看插件日志,并确认端口没有被占用。",
+ port: "插件选项中的服务端口无效。",
+ remote: "请更新 Magpie,才能从远程浏览器打开这个服务。",
+ retry: "重新连接",
+ }
+ : {
+ title: "Amp usage",
+ connecting: "Connecting to the local collector…",
+ stopped:
+ "The collector did not start. Check the plugin log and whether its port is already in use.",
+ port: "Invalid service port in plugin options.",
+ remote: "Update Magpie to open this service from a remote browser.",
+ retry: "Reconnect",
+ };
+ const message = document.getElementById("message");
+ const retry = document.getElementById("retry");
+ retry.addEventListener("click", () => location.reload());
+ let text = words();
+ const say = (key) => {
+ document.title = text.title;
+ document.getElementById("title").textContent = text.title;
+ retry.textContent = text.retry;
+ message.textContent = text[key];
+ };
+ say("connecting");
+ try {
+ const theme = await magpie.ready;
+ text = words(theme.lang);
+ say("connecting");
+ const options = await magpie.options.get();
+ const port = Number(options?.port ?? 3497);
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
+ throw new Error("port");
+ const target =
+ magpie.service ||
+ (["localhost", "127.0.0.1", ""].includes(location.hostname)
+ ? `http://127.0.0.1:${port}/`
+ : "");
+ if (!target) throw new Error("remote");
+ const url = new URL(target);
+ url.searchParams.set("theme", theme.dark ? "dark" : "light");
+ url.searchParams.set("lang", zh(theme.lang) ? "zh" : "en");
+ // The service's page wears the window's own colours.
+ const tokens = {};
+ for (const [k, v] of Object.entries(theme.tokens || {}))
+ if (/^[\x20-\x7e]{1,160}$/.test(String(v))) tokens[k] = String(v);
+ if (Object.keys(tokens).length)
+ url.searchParams.set("tokens", btoa(JSON.stringify(tokens)));
+ setTimeout(() => {
+ say("stopped");
+ retry.hidden = false;
+ }, 6000);
+ location.replace(url.href);
+ } catch (e) {
+ say(text[e.message] ? e.message : "stopped");
+ retry.hidden = false;
+ }
+})();
diff --git a/packages/amp-usage/page/icon.svg b/packages/amp-usage/page/icon.svg
new file mode 100644
index 0000000..850c9fa
--- /dev/null
+++ b/packages/amp-usage/page/icon.svg
@@ -0,0 +1,34 @@
+
diff --git a/packages/amp-usage/page/index.html b/packages/amp-usage/page/index.html
new file mode 100644
index 0000000..6447400
--- /dev/null
+++ b/packages/amp-usage/page/index.html
@@ -0,0 +1,18 @@
+
+
+
+
+
+ Amp usage
+
+
+
+
+ Amp usage
+
+
+
+
+
+
+
diff --git a/packages/amp-usage/test/collector.test.mjs b/packages/amp-usage/test/collector.test.mjs
new file mode 100644
index 0000000..8ae842c
--- /dev/null
+++ b/packages/amp-usage/test/collector.test.mjs
@@ -0,0 +1,353 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ appendFile,
+ mkdtemp,
+ mkdir,
+ open,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { createCollector, acquireLock, gatewayURL } from "../lib/collector.mjs";
+const at = "2026-01-01T00:00:00Z";
+const thread = () => ({
+ id: "T-example",
+ messages: [
+ {
+ messageId: 1,
+ role: "assistant",
+ state: { type: "complete" },
+ usage: {
+ model: "gpt-test",
+ timestamp: at,
+ inputTokens: 10,
+ outputTokens: 20,
+ },
+ },
+ ],
+});
+async function setup(t, extra = {}) {
+ const dir = await mkdtemp(join(tmpdir(), "amp-test-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ let now = Date.parse(at) + 1000000;
+ const sent = [],
+ rows = new Map();
+ const data = thread();
+ const opts = {
+ dataDir: join(dir, "state"),
+ configDir: dir,
+ options: { settleSeconds: 30 },
+ clock: () => now,
+ source: async () => ({ threads: [data], errors: [] }),
+ fetchImpl: async (_url, req) => {
+ const batch = JSON.parse(req.body);
+ sent.push(batch);
+ return Response.json({
+ records: batch.map((r, index) => {
+ const status = rows.has(r.rid) ? "skipped" : "accepted";
+ rows.set(r.rid, r);
+ return { index, rid: r.rid, status };
+ }),
+ });
+ },
+ ...extra,
+ };
+ let collector = await createCollector(opts);
+ t.after(() => collector.close());
+ return {
+ dir,
+ opts,
+ data,
+ sent,
+ rows,
+ get collector() {
+ return collector;
+ },
+ advance: () => {
+ now += 31000;
+ },
+ async restart() {
+ await collector.close();
+ collector = await createCollector(opts);
+ },
+ };
+}
+test("a record settles, is imported once, and survives restart", async (t) => {
+ const h = await setup(t);
+ const a = await h.collector.run();
+ assert.equal(a.pending, 1);
+ assert.equal(h.sent.length, 0);
+ h.advance();
+ const b = await h.collector.run();
+ assert.equal(b.imported, 1);
+ assert.equal(h.rows.size, 1);
+ await h.restart();
+ await h.collector.run();
+ assert.equal(h.sent.length, 1);
+});
+test("changed records are diagnosed without adding a second row", async (t) => {
+ const h = await setup(t);
+ await h.collector.run();
+ h.advance();
+ await h.collector.run();
+ h.data.messages[0].usage.outputTokens = 99;
+ const s = await h.collector.run();
+ assert.equal(s.issues.changedAfterImport, 1);
+ assert.equal(h.sent.length, 1);
+});
+test("a transport failure is retried with the same RID", async (t) => {
+ let fail = true,
+ first;
+ const h = await setup(t, {
+ fetchImpl: async (_u, req) => {
+ const batch = JSON.parse(req.body);
+ if (fail) {
+ first = batch[0].rid;
+ fail = false;
+ throw new Error("Network unavailable");
+ }
+ assert.equal(batch[0].rid, first);
+ return Response.json({
+ records: batch.map((r) => ({ rid: r.rid, status: "skipped" })),
+ });
+ },
+ });
+ await h.collector.run();
+ h.advance();
+ assert.ok((await h.collector.run()).errors.length);
+ assert.equal((await h.collector.run()).skipped, 1);
+});
+test("the gateway's matching usage is not imported again", async (t) => {
+ const h = await setup(t);
+ await writeFile(
+ join(h.dir, "usage.jsonl"),
+ JSON.stringify({
+ t: at,
+ model: "provider/gpt-test",
+ in: 10,
+ out: 20,
+ session: "T-example",
+ }) + "\n",
+ );
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, 1);
+ // Magpie rotates the ledger; the verdict must survive it.
+ await rm(join(h.dir, "usage.jsonl"));
+ h.advance();
+ await h.restart();
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, 1);
+ h.advance();
+ await h.collector.run();
+ assert.equal(h.sent.length, 0);
+});
+test("a batch Magpie refuses whole is split until the bad record stands alone", async (t) => {
+ const posts = [];
+ const h = await setup(t, {
+ fetchImpl: async (_u, req) => {
+ const batch = JSON.parse(req.body);
+ posts.push(batch.length);
+ if (batch.some((r) => r.out === 20))
+ return new Response("", { status: 400 });
+ return Response.json({
+ records: batch.map((r) => ({ rid: r.rid, status: "accepted" })),
+ });
+ },
+ });
+ for (let id = 2; id <= 5; id++)
+ h.data.messages.push({
+ ...h.data.messages[0],
+ messageId: id,
+ usage: { ...h.data.messages[0].usage, outputTokens: 20 + id },
+ });
+ await h.collector.run();
+ h.advance();
+ const s = await h.collector.run();
+ assert.deepEqual(s.errors, []);
+ assert.equal(s.imported, 4);
+ assert.equal(s.issues.rejected, 1);
+ assert.equal(posts[0], 5);
+ assert.ok(posts.length <= 7);
+});
+test("one malformed thread leaves the others' records", async (t) => {
+ const h = await setup(t, {
+ source: async () => ({ threads: [{ id: "bad" }, thread()], errors: [] }),
+ });
+ const s = await h.collector.run();
+ assert.equal(s.issues.invalidThread, 1);
+ assert.equal(s.usage[0].calls, 1);
+ assert.deepEqual(s.errors, []);
+});
+test("a gateway log line still being written waits", async (t) => {
+ const h = await setup(t, { options: { settleSeconds: 30, sync: false } });
+ const log = join(h.dir, "usage.jsonl");
+ const row = (patch) =>
+ JSON.stringify({ t: at, model: "gpt-test", in: 10, out: 20, ...patch });
+ await writeFile(log, row({ out: 21 }) + "\n");
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, undefined);
+ // A line still being written is not a row yet.
+ const line = row({ session: "T-example" });
+ await appendFile(log, line.slice(0, 20));
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, undefined);
+ await appendFile(log, line.slice(20) + "\n");
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, 1);
+});
+test("gateway log bytes before the offset are not read again", async (t) => {
+ const h = await setup(t, { options: { settleSeconds: 30, sync: false } });
+ const log = join(h.dir, "usage.jsonl");
+ const row = (patch) =>
+ JSON.stringify({ t: at, model: "gpt-test", in: 10, out: 20, ...patch });
+ await writeFile(log, row({ model: "gpt-tesx" }) + "\n");
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, undefined);
+ // Rewritten in place to a match, same length and inode: only a reader that
+ // starts over from byte 0 would see it.
+ const fh = await open(log, "r+");
+ await fh.write(row({}), 0);
+ await fh.close();
+ await appendFile(log, row({ out: 21 }) + "\n");
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, undefined);
+});
+test("a rotated gateway log is indexed afresh", async (t) => {
+ const h = await setup(t, { options: { settleSeconds: 30, sync: false } });
+ const log = join(h.dir, "usage.jsonl");
+ const row = (patch) =>
+ JSON.stringify({ t: at, model: "gpt-test", in: 10, out: 20, ...patch }) +
+ "\n";
+ await writeFile(log, row({ out: 21 }).repeat(3));
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, undefined);
+ // Shorter than what was read, so the offset cannot carry over.
+ await rm(log);
+ await writeFile(log, row({ session: "T-example" }));
+ assert.equal((await h.collector.run()).issues.gatewayDuplicate, 1);
+});
+test("a record Magpie rejects does not block the others", async (t) => {
+ const h = await setup(t, {
+ fetchImpl: async (_u, req) =>
+ Response.json({
+ records: JSON.parse(req.body).map((r) => ({
+ rid: r.rid,
+ status: r.out === 20 ? "rejected" : "accepted",
+ })),
+ }),
+ });
+ h.data.messages.push({
+ ...h.data.messages[0],
+ messageId: 2,
+ usage: { ...h.data.messages[0].usage, outputTokens: 21 },
+ });
+ await h.collector.run();
+ h.advance();
+ const s = await h.collector.run();
+ assert.equal(s.imported, 1);
+ assert.equal(s.issues.rejected, 1);
+ assert.equal(s.totalImported, 1);
+});
+test("with sync off the collector only reads", async (t) => {
+ const h = await setup(t, { options: { settleSeconds: 30, sync: false } });
+ await h.collector.run();
+ h.advance();
+ const s = await h.collector.run();
+ assert.equal(s.eligible, 1);
+ assert.equal(s.usage[0].calls, 1);
+ assert.equal(h.sent.length, 0);
+});
+test("corrupt state fails closed", async (t) => {
+ const h = await setup(t);
+ await h.collector.run();
+ await h.collector.close();
+ await writeFile(join(h.opts.dataDir, "state.json"), "{broken");
+ await assert.rejects(createCollector(h.opts), /invalid JSON/);
+});
+test("one service owns a data directory", async (t) => {
+ const dir = await mkdtemp(join(tmpdir(), "amp-lock-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ const release = await acquireLock(dir);
+ await assert.rejects(acquireLock(dir), /Another/);
+ await release();
+ const release2 = await acquireLock(dir);
+ await release2();
+});
+test("a torn or dead lock is taken over", async (t) => {
+ const dir = await mkdtemp(join(tmpdir(), "amp-lock-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ for (const left of ["", "{broken", '{"pid":2147483646}']) {
+ await writeFile(join(dir, "collector.lock"), left);
+ await (
+ await acquireLock(dir)
+ )();
+ }
+});
+test("gateway rows are read only for undecided records", async (t) => {
+ const h = await setup(t);
+ await h.collector.run();
+ h.advance();
+ assert.equal((await h.collector.run()).imported, 1);
+ // Unreadable now, but nothing is left to decide.
+ await mkdir(join(h.dir, "usage.jsonl"));
+ assert.deepEqual((await h.collector.run()).errors, []);
+});
+test("gateway destination is loopback-only", () => {
+ assert.equal(gatewayURL("http://127.0.0.1:3425/v1"), "http://127.0.0.1:3425");
+ for (const s of [
+ "https://example.com",
+ "http://127.0.0.1.evil.test",
+ "http://u:p@127.0.0.1",
+ "http://127.0.0.1/?token=x",
+ ])
+ assert.throws(() => gatewayURL(s));
+});
+test("a disappearing record must settle again before import", async (t) => {
+ const h = await setup(t);
+ await h.collector.run();
+ h.advance();
+ const m = h.data.messages.pop();
+ await h.collector.run();
+ h.data.messages.push(m);
+ const s = await h.collector.run();
+ assert.equal(s.pending, 1);
+ assert.equal(s.imported, 0);
+});
+test("identity changes with identical usage are held rather than duplicated", async (t) => {
+ const h = await setup(t);
+ await h.collector.run();
+ h.advance();
+ await h.collector.run();
+ h.data.messages[0].messageId = 2;
+ const s = await h.collector.run();
+ assert.equal(s.issues.identityChanged, 1);
+ assert.equal(h.sent.length, 1);
+});
+test("the page gets usage by local hour and model", async (t) => {
+ const h = await setup(t);
+ h.data.messages.push({
+ ...h.data.messages[0],
+ messageId: 2,
+ usage: { ...h.data.messages[0].usage, cacheReadInputTokens: 5 },
+ });
+ const row = (await h.collector.run()).usage;
+ assert.equal(row.length, 1);
+ assert.deepEqual(
+ { ...row[0], hour: undefined },
+ {
+ hour: undefined,
+ model: "gpt-test",
+ calls: 2,
+ in: 20,
+ out: 40,
+ cache_read: 5,
+ cache_write: 0,
+ },
+ );
+ assert.match(row[0].hour, /^\d{4}-\d\d-\d\dT\d\d$/);
+});
+test("a record held by two sources is counted once, from the first", async (t) => {
+ const copy = thread();
+ copy.messages[0].usage.outputTokens = 99;
+ const h = await setup(t, {
+ source: async () => ({ threads: [thread(), copy], errors: [] }),
+ });
+ const s = await h.collector.run();
+ assert.equal(s.scannedThreads, 1);
+ assert.equal(s.usage[0].calls, 1);
+ assert.equal(s.usage[0].out, 20);
+});
diff --git a/packages/amp-usage/test/fixtures/amp-local.json b/packages/amp-usage/test/fixtures/amp-local.json
new file mode 100644
index 0000000..d771c00
--- /dev/null
+++ b/packages/amp-usage/test/fixtures/amp-local.json
@@ -0,0 +1,20 @@
+{
+ "id": "T-redacted-local",
+ "messages": [
+ {
+ "role": "assistant",
+ "messageId": 1,
+ "state": {
+ "type": "complete"
+ },
+ "usage": {
+ "model": "claude-opus-4-6",
+ "timestamp": "2026-03-05T12:59:37.245Z",
+ "inputTokens": 10,
+ "outputTokens": 223,
+ "cacheReadInputTokens": 0,
+ "cacheCreationInputTokens": 19550
+ }
+ }
+ ]
+}
diff --git a/packages/amp-usage/test/host.integration.mjs b/packages/amp-usage/test/host.integration.mjs
new file mode 100644
index 0000000..661417b
--- /dev/null
+++ b/packages/amp-usage/test/host.integration.mjs
@@ -0,0 +1,97 @@
+// Optional real-host test. All config, usage and session paths are isolated.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createServer } from "node:net";
+import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { createCollector } from "../lib/collector.mjs";
+
+test(
+ "reports into an isolated real Magpie ledger without duplication",
+ { skip: !process.env.MAGPIE_BINARY, timeout: 30000 },
+ async (t) => {
+ const root = await mkdtemp(join(tmpdir(), "amp-magpie-"));
+ const config = join(root, ".config", "magpie");
+ await mkdir(config, { recursive: true });
+ const port = await new Promise((resolve) => {
+ const server = createServer();
+ server.listen(0, "127.0.0.1", () => {
+ const port = server.address().port;
+ server.close(() => resolve(port));
+ });
+ });
+ await writeFile(
+ join(config, "settings.json"),
+ JSON.stringify({ port, sessionReads: { asked: true, all: false } }),
+ );
+ const child = spawn(process.env.MAGPIE_BINARY, ["serve"], {
+ env: {
+ PATH: process.env.PATH,
+ HOME: root,
+ USERPROFILE: root,
+ XDG_CONFIG_HOME: join(root, ".config"),
+ XDG_CACHE_HOME: join(root, ".cache"),
+ XDG_DATA_HOME: join(root, ".local", "share"),
+ MAGPIE_ADDR: `127.0.0.1:${port}`,
+ },
+ stdio: "ignore",
+ });
+ const stopped = new Promise((resolve) => child.once("exit", resolve));
+ t.after(async () => {
+ child.kill("SIGTERM");
+ await stopped;
+ await rm(root, { recursive: true, force: true });
+ });
+ const base = `http://127.0.0.1:${port}`;
+ let up = false;
+ for (let i = 0; i < 100; i++) {
+ try {
+ if (
+ (
+ await fetch(`${base}/v1/models`, {
+ signal: AbortSignal.timeout(500),
+ })
+ ).ok
+ ) {
+ up = true;
+ break;
+ }
+ } catch {}
+ if (child.exitCode !== null) break;
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ assert.ok(up, "sandbox gateway starts");
+ const fixture = JSON.parse(
+ await readFile(new URL("fixtures/amp-local.json", import.meta.url)),
+ );
+ let now = Date.now();
+ const collector = await createCollector({
+ dataDir: join(config, "amp-usage"),
+ configDir: config,
+ options: { gatewayURL: base, settleSeconds: 30 },
+ clock: () => now,
+ source: async () => ({ threads: [fixture] }),
+ });
+ t.after(() => collector.close());
+ assert.equal((await collector.run()).pending, 1);
+ now += 31000;
+ const first = await collector.run();
+ assert.deepEqual(first.errors, []);
+ assert.equal(first.imported, 1);
+ assert.equal((await collector.run()).imported, 0);
+ const ledger = await (
+ await fetch(`${base}/v1/magpie/usage/requests?period=all&agent=amp`)
+ ).json();
+ assert.equal(ledger.total, 1);
+ assert.equal(ledger.rows[0].agent, "amp");
+ assert.equal(ledger.rows[0].source, "reported");
+ assert.equal(ledger.input, fixture.messages[0].usage.inputTokens);
+ assert.equal(ledger.output, fixture.messages[0].usage.outputTokens);
+ assert.equal(
+ ledger.cache_read,
+ fixture.messages[0].usage.cacheReadInputTokens || 0,
+ );
+ },
+);
diff --git a/packages/amp-usage/test/parser.test.mjs b/packages/amp-usage/test/parser.test.mjs
new file mode 100644
index 0000000..22ae72d
--- /dev/null
+++ b/packages/amp-usage/test/parser.test.mjs
@@ -0,0 +1,220 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { parseThread, projectThread } from "../lib/parser.mjs";
+const at = "2026-03-30T15:07:33.890Z";
+const usage = {
+ model: "claude-opus-4-6",
+ timestamp: at,
+ inputTokens: 1,
+ outputTokens: 189,
+ cacheCreationInputTokens: 661,
+ cacheReadInputTokens: 40653,
+};
+const message = (id = 1, patch = {}) => ({
+ role: "assistant",
+ messageId: id,
+ state: { type: "complete" },
+ usage: { ...usage, ...patch },
+});
+const thread = (messages = [message()], events = []) => ({
+ id: "T-test",
+ messages,
+ usageLedger: { events },
+});
+const event = (patch = {}) => ({
+ model: usage.model,
+ timestamp: at,
+ toMessageId: 1,
+ // Real Amp ledger events carry input/output only.
+ tokens: { input: 1, output: 189 },
+ ...patch,
+});
+
+test("real redacted Amp metadata maps cache separately and ignores credits", async () => {
+ const fixture = JSON.parse(
+ await readFile(new URL("fixtures/amp-local.json", import.meta.url)),
+ );
+ const { records } = parseThread(fixture);
+ assert.ok(records.length > 0);
+ const r = records[0];
+ const u = fixture.messages[0].usage;
+ assert.equal(r.in, u.inputTokens);
+ assert.equal(r.out, u.outputTokens);
+ assert.equal(r.cache_read, u.cacheReadInputTokens);
+ assert.equal(r.cache_write, u.cacheCreationInputTokens);
+ assert.equal(r.cost, undefined);
+ assert.equal(r.agent, "amp");
+});
+test("partial ledger and messages count each call once", () => {
+ const t = thread([message(), message(2, { outputTokens: 200 })], [event()]);
+ const r = parseThread(t).records;
+ assert.equal(r.length, 2);
+ assert.deepEqual(
+ r.map((x) => x.out),
+ [189, 200],
+ );
+});
+test("message ID match wins over token mismatch and remains stable as ledger appears", () => {
+ const a = parseThread(thread()).records[0];
+ const b = parseThread(
+ thread([message()], [event({ tokens: { input: 2, output: 190 } })]),
+ ).records[0];
+ assert.equal(a.rid, b.rid);
+ assert.equal(b.out, 190);
+});
+test("ledger missing timestamp uses matching message timestamp", () => {
+ assert.equal(
+ parseThread(thread([message()], [event({ timestamp: undefined })]))
+ .records[0].t,
+ at,
+ );
+});
+test("never uses file mtime or synthetic thread dates", () => {
+ const t = {
+ ...thread([message(1, { timestamp: undefined })]),
+ created: Date.now(),
+ };
+ assert.equal(parseThread(t).records.length, 0);
+ assert.equal(parseThread(t).issues.missingTimestamp, 1);
+});
+test("a call without a time takes the moment its turn was sent", () => {
+ const bare = (id) => message(id, { timestamp: undefined });
+ const t = thread([
+ bare(1),
+ { role: "user", sentAt: Date.parse(at) },
+ bare(2),
+ { role: "user" },
+ bare(3),
+ ]);
+ const r = parseThread(t);
+ assert.deepEqual(
+ r.records.map((x) => x.t),
+ [at, at],
+ );
+ assert.equal(r.issues.missingTimestamp, 1);
+ const raw = {
+ ...t,
+ messages: [{ role: "user", meta: { sentAt: Date.parse(at) } }, bare(2)],
+ };
+ assert.equal(parseThread(projectThread(raw)).records[0].t, at);
+});
+test("a time no Date can hold is no time, not a thrown scan", () => {
+ const r = parseThread(
+ thread([
+ { role: "user", sentAt: 1e20 },
+ message(1, { timestamp: undefined }),
+ message(2, { timestamp: "9999-99-99T00:00:00Z" }),
+ ]),
+ );
+ assert.equal(r.records.length, 0);
+ assert.equal(r.issues.missingTimestamp, 2);
+});
+test("identical token counts at different times are distinct calls", () => {
+ const t = thread(
+ [message(2, { timestamp: "2026-03-31T15:07:33.890Z" })],
+ [event({ id: "e1", operationType: "title-generation" })],
+ );
+ assert.equal(parseThread(t).records.length, 2);
+});
+test("equal ledger events are told apart by their own IDs, or held without one", () => {
+ const search = (id) => event({ id, operationType: "codebase-search" });
+ const r = parseThread(thread([], [search("e1"), search("e2"), search()]));
+ assert.equal(r.records.length, 2);
+ assert.notEqual(r.records[0].rid, r.records[1].rid);
+ assert.equal(r.issues.missingIdentity, 1);
+});
+test("a matched ledger event keeps the message's cache tokens", () => {
+ for (const events of [[event()], [event({ toMessageId: undefined })]]) {
+ const r = parseThread(thread([message()], events)).records;
+ assert.equal(r.length, 1);
+ assert.equal(r[0].cache_read, 40653);
+ assert.equal(r[0].cache_write, 661);
+ }
+});
+test("a subagent's calls are counted in its own thread only", () => {
+ const r = parseThread(
+ thread(
+ [],
+ [
+ event({
+ id: "e1",
+ operationType: "subagent",
+ subagentThreadID: "T-sub",
+ }),
+ ],
+ ),
+ );
+ assert.equal(r.records.length, 0);
+ assert.equal(r.issues.subagentThread, 1);
+});
+test("unfinished, fresh, invalid and zero usage do not reach the ledger", () => {
+ const t = thread([
+ { ...message(), state: { type: "streaming" } },
+ message(2, { timestamp: new Date().toISOString() }),
+ message(3, { inputTokens: -1 }),
+ message(4, {
+ inputTokens: 0,
+ outputTokens: 0,
+ cacheReadInputTokens: 0,
+ cacheCreationInputTokens: 0,
+ }),
+ ]);
+ const r = parseThread(t);
+ assert.equal(r.records.length, 0);
+ assert.deepEqual(r.issues, { invalidUsage: 1, unfinished: 1, settling: 1 });
+});
+test("conflicting repeated message IDs are held, even with three copies", () => {
+ const r = parseThread(
+ thread([
+ message(),
+ message(1, { inputTokens: 2 }),
+ message(1, { inputTokens: 3 }),
+ ]),
+ );
+ assert.equal(r.records.length, 0);
+ assert.ok(r.issues.conflictingIdentity);
+});
+test("projection excludes prompts, paths, identities and credits", () => {
+ const t = thread(
+ [
+ {
+ ...message(),
+ content: [{ text: "private" }],
+ usage: { ...usage, credits: 9 },
+ },
+ ],
+ [event({ secret: "private" })],
+ );
+ t.title = "private";
+ t.env = { path: "private" };
+ const s = JSON.stringify(projectThread(t));
+ assert.ok(!s.includes("private"));
+ assert.ok(!s.includes("credits"));
+});
+test("search and subagent ledger calls sharing a message boundary stay distinct", () => {
+ const r = parseThread(
+ thread(
+ [message()],
+ [
+ event({ operationType: "inference" }),
+ event({
+ id: "e2",
+ operationType: "codebase-search",
+ model: "gemini-3-flash-preview",
+ tokens: { input: 0, output: 415 },
+ timestamp: "2026-03-30T15:07:40Z",
+ }),
+ event({
+ id: "e3",
+ operationType: "subagent",
+ tokens: { input: 40, output: 497 },
+ timestamp: "2026-03-30T15:08:00Z",
+ }),
+ ],
+ ),
+ );
+ assert.equal(r.records.length, 3);
+ assert.equal(r.issues.conflictingIdentity, undefined);
+ assert.equal(new Set(r.records.map((x) => x.rid)).size, 3);
+});
diff --git a/packages/amp-usage/test/server.test.mjs b/packages/amp-usage/test/server.test.mjs
new file mode 100644
index 0000000..d230217
--- /dev/null
+++ b/packages/amp-usage/test/server.test.mjs
@@ -0,0 +1,104 @@
+import { request } from "node:http";
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { startServer } from "../lib/server.mjs";
+
+test("loopback service protects every API and accepts authenticated sandbox requests", async (t) => {
+ const dir = await mkdtemp(join(tmpdir(), "amp-service-"));
+ let scanned = 0;
+ const fake = {
+ view: () => ({ phase: "idle" }),
+ run: async () => {
+ scanned++;
+ },
+ close: async () => {},
+ };
+ const s = await startServer({
+ port: 0,
+ dataDir: dir,
+ configDir: dir,
+ collector: fake,
+ });
+ t.after(async () => {
+ await s.close();
+ await rm(dir, { recursive: true, force: true });
+ });
+ const base = `http://127.0.0.1:${s.port}`;
+ // Only a navigation reads the page that carries the token; Node's fetch
+ // always says cors.
+ const page = (mode) =>
+ new Promise((resolve, reject) => {
+ const req = request(
+ base,
+ { headers: { "sec-fetch-mode": mode } },
+ (res) => {
+ let body = "";
+ res.on("data", (c) => (body += c));
+ res.on("end", () =>
+ resolve({ status: res.statusCode, body, headers: res.headers }),
+ );
+ },
+ );
+ req.on("error", reject);
+ req.end();
+ });
+ assert.equal((await page("cors")).status, 403);
+ const root = await page("navigate");
+ assert.equal(root.headers["access-control-allow-origin"], undefined);
+ const token = root.body.match(
+ /name="service-token" content="([a-f0-9]+)"/,
+ )[1];
+ const denied = await fetch(base + "/api/status");
+ assert.equal(denied.status, 403);
+ assert.equal((await denied.json()).code, "reconnect");
+ assert.equal(
+ (
+ await fetch(base + "/api/status", {
+ headers: { "x-amp-usage-token": token, origin: "https://evil.test" },
+ })
+ ).status,
+ 403,
+ );
+ const badHost = await new Promise((resolve, reject) => {
+ const req = request(
+ base + "/api/status",
+ { headers: { "x-amp-usage-token": token, Host: "evil.test" } },
+ (res) => {
+ res.resume();
+ resolve(res.statusCode);
+ },
+ );
+ req.on("error", reject);
+ req.end();
+ });
+ assert.equal(badHost, 403);
+ const response = await fetch(base + "/api/refresh", {
+ method: "POST",
+ headers: {
+ "x-amp-usage-token": token,
+ origin: "null",
+ "content-type": "application/json",
+ },
+ body: "{}",
+ });
+ assert.equal(response.status, 202);
+ assert.equal(response.headers.get("access-control-allow-origin"), "null");
+ assert.equal(scanned, 1);
+ assert.equal(
+ (
+ await fetch(base + "/api/refresh", {
+ method: "POST",
+ headers: {
+ "x-amp-usage-token": token,
+ "content-type": "application/json",
+ },
+ body: "{",
+ })
+ ).status,
+ 400,
+ );
+ assert.equal((await fetch(base + "/unknown")).status, 404);
+});
diff --git a/packages/amp-usage/test/sources.test.mjs b/packages/amp-usage/test/sources.test.mjs
new file mode 100644
index 0000000..4110347
--- /dev/null
+++ b/packages/amp-usage/test/sources.test.mjs
@@ -0,0 +1,144 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { readCloud, readLocal } from "../lib/sources.mjs";
+const usage = {
+ model: "gpt-test",
+ timestamp: "2026-01-01T00:00:00Z",
+ inputTokens: 10,
+ outputTokens: 1,
+};
+async function dir(t) {
+ const d = await mkdtemp(join(tmpdir(), "amp-source-"));
+ t.after(() => rm(d, { recursive: true, force: true }));
+ return d;
+}
+test("cloud exports include archived threads, project private fields away, and reuse unchanged cache", async (t) => {
+ const dataDir = await dir(t),
+ calls = [];
+ const run = async (args) => {
+ calls.push(args);
+ if (args[1] === "list")
+ return [{ id: "T-cloud", updated: usage.timestamp }];
+ return {
+ id: "T-cloud",
+ title: "private",
+ messages: [
+ {
+ role: "assistant",
+ messageId: 1,
+ content: [{ text: "private" }],
+ usage,
+ },
+ ],
+ };
+ };
+ const first = await readCloud({ dataDir, run });
+ assert.equal(first.exported, 1);
+ assert.ok(calls[0].includes("--include-archived"));
+ const text = await readFile(join(dataDir, "cloud/T-cloud.json"), "utf8");
+ assert.ok(!text.includes("private"));
+ assert.equal((await readCloud({ dataDir, run })).exported, 0);
+});
+test("failed exports do not advance checkpoints", async (t) => {
+ const dataDir = await dir(t);
+ let fail = true;
+ const run = async (args) => {
+ if (args[1] === "list")
+ return [{ id: "T-cloud", updated: usage.timestamp }];
+ if (fail) throw new Error("Offline");
+ return { id: "T-cloud", messages: [] };
+ };
+ assert.equal((await readCloud({ dataDir, run })).errors.length, 1);
+ fail = false;
+ assert.equal((await readCloud({ dataDir, run })).exported, 1);
+});
+test("a changed thread keeps its last good copy while its export fails or waits", async (t) => {
+ const dataDir = await dir(t);
+ let updated = usage.timestamp,
+ fail = false;
+ const run = async (args) => {
+ if (args[1] === "list") return [{ id: "T-cloud", updated }];
+ if (fail) throw new Error("Offline");
+ return { id: "T-cloud", messages: [] };
+ };
+ await readCloud({ dataDir, run });
+ updated = "2026-01-02T00:00:00Z";
+ fail = true;
+ const failed = await readCloud({ dataDir, run });
+ assert.equal(failed.errors.length, 1);
+ assert.equal(failed.threads.length, 1);
+ const waiting = await readCloud({ dataDir, run, maxExports: 0 });
+ assert.equal(waiting.remaining, 1);
+ assert.equal(waiting.threads.length, 1);
+});
+test("bounded exports resume on the next run", async (t) => {
+ const dataDir = await dir(t);
+ const run = async (args) =>
+ args[1] === "list"
+ ? [
+ { id: "T-one", updated: usage.timestamp },
+ { id: "T-two", updated: usage.timestamp },
+ ]
+ : { id: args[2], messages: [] };
+ assert.equal((await readCloud({ dataDir, run, maxExports: 1 })).remaining, 1);
+ assert.equal((await readCloud({ dataDir, run, maxExports: 1 })).remaining, 0);
+});
+test("a missing configured directory is visible; Amp's own may be absent", async (t) => {
+ const missing = [join(await dir(t), "missing")];
+ assert.equal((await readLocal(missing)).errors.length, 1);
+ assert.equal(
+ (await readLocal(missing, { required: false })).errors.length,
+ 0,
+ );
+});
+test("projections from before sent times are exported again", async (t) => {
+ const dataDir = await dir(t);
+ const run = async (args) =>
+ args[1] === "list"
+ ? [{ id: "T-cloud", updated: usage.timestamp }]
+ : { id: "T-cloud", messages: [] };
+ await readCloud({ dataDir, run });
+ await writeFile(
+ join(dataDir, "cloud-index.json"),
+ JSON.stringify({ version: 1, threads: { "T-cloud": usage.timestamp } }),
+ );
+ assert.equal((await readCloud({ dataDir, run })).exported, 1);
+});
+test("listing stops at the first page with nothing new, yet keeps every thread", async (t) => {
+ const dataDir = await dir(t);
+ let clock = Date.parse(usage.timestamp);
+ const ids = Array.from({ length: 250 }, (_, i) => `T-${1000 + i}`);
+ const updated = Object.fromEntries(ids.map((id) => [id, usage.timestamp]));
+ const lists = [];
+ const run = async (args) => {
+ if (args[1] !== "list") return { id: args[2], messages: [] };
+ const offset = Number(args[args.indexOf("--offset") + 1]);
+ lists.push(offset);
+ // Newest first, as Amp lists them.
+ return ids
+ .map((id) => ({ id, updated: updated[id] }))
+ .sort((a, b) => b.updated.localeCompare(a.updated))
+ .slice(offset, offset + 200);
+ };
+ const read = () =>
+ readCloud({ dataDir, run, maxExports: 300, now: () => clock });
+ assert.equal((await read()).threads.length, 250);
+ assert.deepEqual(lists.splice(0), [0, 200]);
+ const again = await read();
+ assert.deepEqual(lists.splice(0), [0]);
+ assert.equal(again.threads.length, 250);
+ assert.equal(again.exported, 0);
+ // A thread from the second page changes: it moves to the first.
+ updated["T-1249"] = "2026-01-02T00:00:00Z";
+ const changed = await read();
+ assert.deepEqual(lists.splice(0), [0, 200]);
+ assert.equal(changed.exported, 1);
+ assert.equal(changed.threads.length, 250);
+ // A day on, the whole list is read again.
+ clock += 86_400_000;
+ await read();
+ assert.deepEqual(lists.splice(0), [0, 200]);
+});
diff --git a/packages/amp-usage/test/transport.test.mjs b/packages/amp-usage/test/transport.test.mjs
new file mode 100644
index 0000000..380f641
--- /dev/null
+++ b/packages/amp-usage/test/transport.test.mjs
@@ -0,0 +1,27 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { sendUsage } from "../lib/transport.mjs";
+test("host transport sends no browser headers and never follows redirects", async (t) => {
+ let headers;
+ const server = createServer((req, res) => {
+ headers = req.headers;
+ res.writeHead(302, { Location: "http://example.invalid" });
+ res.end("{}");
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ t.after(() => new Promise((r) => server.close(r)));
+ const response = await sendUsage(
+ `http://127.0.0.1:${server.address().port}/usage`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: "[]",
+ signal: AbortSignal.timeout(1000),
+ },
+ );
+ assert.equal(response.status, 302);
+ assert.equal(response.ok, false);
+ assert.equal(headers["sec-fetch-mode"], undefined);
+ assert.equal(headers.origin, undefined);
+});
diff --git a/packages/amp-usage/test/ui.test.mjs b/packages/amp-usage/test/ui.test.mjs
new file mode 100644
index 0000000..4447575
--- /dev/null
+++ b/packages/amp-usage/test/ui.test.mjs
@@ -0,0 +1,52 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFile, readdir } from "node:fs/promises";
+
+const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
+const scope = {};
+new Function("globalThis", await read("../ui/words.js"))(scope);
+const { words, error } = scope.AmpUsage;
+
+test("every error code the service can send reads in each language", async () => {
+ // The codes as the service writes them: fail("…"), errors.push("…") and
+ // the server's { code: "…" }; plus the page's own two.
+ const codes = new Set(["unreachable", "unexpected"]);
+ for (const f of await readdir(new URL("../lib/", import.meta.url))) {
+ const src = await read(`../lib/${f}`);
+ for (const re of [
+ /\bfail\(\s*"(\w+)"/g,
+ /errors\.push\("(\w+)"\)/g,
+ /\bcode: "(\w+)"/g,
+ ])
+ for (const m of src.matchAll(re)) codes.add(m[1]);
+ }
+ for (const c of [
+ "ampFailed",
+ "localDirMissing",
+ "magpieRefused",
+ "reconnect",
+ ])
+ assert.ok(codes.has(c), `the scan above no longer finds ${c}`);
+ for (const lang of ["en", "zh"])
+ for (const c of codes) {
+ assert.equal(typeof words[lang].err[c], "string", `${lang}: ${c}`);
+ assert.equal(error(words[lang], c), words[lang].err[c]);
+ }
+ assert.deepEqual(
+ Object.keys(words.zh.err).sort(),
+ Object.keys(words.en.err).sort(),
+ );
+});
+
+test("an unknown code reads as the generic message, never as the code", () => {
+ for (const lang of ["en", "zh"])
+ assert.equal(
+ error(words[lang], "fromANewerService"),
+ words[lang].err.unexpected,
+ );
+});
+
+test("the page loads its words before its script", async () => {
+ const html = await read("../ui/index.html");
+ assert.ok(html.indexOf('src="words.js"') < html.indexOf('src="app.js"'));
+});
diff --git a/packages/amp-usage/ui/app.js b/packages/amp-usage/ui/app.js
new file mode 100644
index 0000000..0884c97
--- /dev/null
+++ b/packages/amp-usage/ui/app.js
@@ -0,0 +1,375 @@
+const $ = (id) => document.getElementById(id);
+const query = new URL(location.href).searchParams;
+const root = document.documentElement;
+const theme = query.get("theme");
+root.dataset.theme =
+ theme === "dark" ||
+ (!theme && matchMedia("(prefers-color-scheme: dark)").matches)
+ ? "dark"
+ : "light";
+try {
+ // Magpie's own colours, handed over by the launcher.
+ const tokens = JSON.parse(atob(query.get("tokens") || ""));
+ for (const [k, v] of Object.entries(tokens))
+ if (/^[a-z0-9-]+$/.test(k)) root.style.setProperty(`--magpie-${k}`, v);
+} catch {
+ /* The fallbacks in style.css apply. */
+}
+const lang = (query.get("lang") || navigator.language || "")
+ .toLowerCase()
+ .startsWith("zh")
+ ? "zh"
+ : "en";
+root.lang = lang === "zh" ? "zh-CN" : "en";
+
+const W = AmpUsage.words[lang];
+document.title = W.title;
+for (const node of document.querySelectorAll("[data-t]"))
+ node.textContent = W[node.dataset.t];
+$("refresh").title = W.refresh;
+$("refresh").setAttribute("aria-label", W.refresh);
+$("auto").setAttribute("aria-label", W.auto);
+
+const groups = {
+ noTime: ["missingTimestamp"],
+ inProgress: ["unfinished", "settling"],
+ excluded: ["excludedThread", "excludedModel"],
+ held: [
+ "identityChanged",
+ "changedAfterImport",
+ "conflictingIdentity",
+ "invalidUsage",
+ "missingIdentity",
+ "invalidThread",
+ "rejected",
+ ],
+};
+const locale = lang === "zh" ? "zh-CN" : "en";
+const compact = new Intl.NumberFormat(locale, {
+ notation: "compact",
+ maximumFractionDigits: 1,
+});
+const full = new Intl.NumberFormat(locale);
+const two = (n) => String(n).padStart(2, "0");
+const dayOf = (d) =>
+ `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}`;
+const hourOf = (d) => `${dayOf(d)}T${two(d.getHours())}`;
+const dateOf = (key) => {
+ const [y, m, d, h = 0] = key.split(/[-T]/).map(Number);
+ return new Date(y, m - 1, d, h);
+};
+const el = (tag, text, cls) => {
+ const e = document.createElement(tag);
+ if (text !== undefined) e.textContent = text;
+ if (cls) e.className = cls;
+ return e;
+};
+const number = (tag, n) => {
+ const e = el(tag, compact.format(n));
+ e.title = full.format(n);
+ return e;
+};
+const share = (x) => (x > 0 && x < 0.01 ? "<1%" : `${Math.round(x * 100)}%`);
+const total = (r) => r.in + r.out + r.cache_read + r.cache_write;
+const sum = (rows) =>
+ rows.reduce(
+ (a, r) => {
+ for (const k of Object.keys(a)) a[k] += r[k];
+ return a;
+ },
+ { calls: 0, in: 0, out: 0, cache_read: 0, cache_write: 0 },
+ );
+
+// What the reader chose last time. A convenience: the page works without it.
+const kept = (key, fallback) => {
+ try {
+ return localStorage.getItem(key) ?? fallback;
+ } catch {
+ return fallback;
+ }
+};
+const keep = (key, value) => {
+ try {
+ localStorage.setItem(key, value);
+ } catch {
+ /* See above. */
+ }
+};
+const token = document.querySelector('meta[name="service-token"]').content;
+let state,
+ busy = false,
+ failure = "",
+ turn = 0,
+ period = kept("period", "30d"),
+ auto = Number(kept("auto", 300));
+const week = new Date();
+week.setDate(week.getDate() - 6);
+$("from").value = kept("from", dayOf(week));
+$("to").value = kept("to", dayOf(new Date()));
+$("auto").replaceChildren(
+ ...[0, 30, 60, 300].map((n) => {
+ const o = el(
+ "option",
+ !n ? W.off : n < 60 ? W.seconds(n) : W.minutes(n / 60),
+ );
+ o.value = n;
+ return o;
+ }),
+);
+$("auto").value = auto;
+
+async function api(path, body) {
+ let r, result;
+ // Errors are codes the page words itself; see W.err.
+ try {
+ r = await fetch(new URL(`api/${path}`, location.href), {
+ method: body === undefined ? "GET" : "POST",
+ headers: {
+ "X-Amp-Usage-Token": token,
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ result = await r.json();
+ } catch {
+ throw new Error("unreachable");
+ }
+ if (!r.ok) throw new Error(result.code || "unexpected");
+ return result;
+}
+function errors(codes) {
+ const lines = [...new Set(codes.map((c) => AmpUsage.error(W, c)))];
+ $("errors").replaceChildren(...lines.map((m) => el("p", m)));
+ $("errors").hidden = !lines.length;
+}
+
+// The span the reader asked for, as local hour keys, both ends included.
+function span(rows) {
+ const now = new Date();
+ const day = (back) =>
+ new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);
+ if (period === "24h")
+ return [hourOf(new Date(now.getTime() - 23 * 3600_000)), hourOf(now)];
+ if (period === "custom") {
+ const [a, b] = [$("from").value, $("to").value].sort();
+ return [`${a || dayOf(now)}T00`, `${b || dayOf(now)}T23`];
+ }
+ const back = { today: 0, "7d": 6, "30d": 29 }[period];
+ const first =
+ back === undefined
+ ? rows.reduce((a, r) => (r.hour < a ? r.hour : a), hourOf(now))
+ : hourOf(day(back));
+ return [`${first.slice(0, 10)}T00`, hourOf(now)];
+}
+
+function board(rows) {
+ const [from, to] = span(rows);
+ const shown = rows.filter((r) => r.hour >= from && r.hour <= to);
+ const all = sum(shown);
+ const prompt = all.in + all.cache_read + all.cache_write;
+ $("empty").textContent = rows.length ? W.emptyPeriod : W.empty;
+ $("empty").hidden = shown.length > 0;
+ $("board").hidden = !shown.length;
+ if (!shown.length) return;
+
+ $("tiles").replaceChildren(
+ ...[
+ [W.calls, all.calls],
+ [W.input, all.in],
+ [W.output, all.out],
+ [W.cacheRead, all.cache_read],
+ [W.cacheWrite, all.cache_write],
+ [W.hit, prompt ? all.cache_read / prompt : null],
+ ].map(([label, n], i) => {
+ const tile = el("div");
+ const value =
+ i < 5
+ ? number("dd", n)
+ : el("dd", n === null ? "–" : `${Math.floor(n * 1000) / 10}%`);
+ tile.append(el("dt", label), value);
+ return tile;
+ }),
+ );
+
+ // Hours for a day or two, days beyond that. Every step gets a bar, empty
+ // ones included, so gaps read as gaps.
+ const hourly = dateOf(to) - dateOf(from) < 48 * 3600_000;
+ const keyOf = hourly ? hourOf : dayOf;
+ const buckets = new Map();
+ for (const r of shown) {
+ const key = hourly ? r.hour : r.hour.slice(0, 10);
+ const b = buckets.get(key) || { calls: 0, tokens: 0 };
+ b.calls += r.calls;
+ b.tokens += total(r);
+ buckets.set(key, b);
+ }
+ const series = [];
+ const at = dateOf(from);
+ const end = dateOf(to);
+ while (at <= end) {
+ const key = keyOf(at);
+ series.push([key, buckets.get(key) || { calls: 0, tokens: 0 }]);
+ if (hourly) at.setHours(at.getHours() + 1);
+ else at.setDate(at.getDate() + 1);
+ }
+ const label = (key) =>
+ hourly ? `${key.slice(5, 10)} ${key.slice(11)}:00` : key;
+ $("chart-title").textContent = hourly ? W.hourly : W.daily;
+ $("chart").hidden = series.length < 2;
+ const peak = Math.max(...series.map(([, v]) => v.tokens));
+ const rest = `${full.format(total(all))} ${W.tokens}`;
+ $("readout").textContent = rest;
+ $("bars").classList.toggle("dense", series.length > 90);
+ $("bars").replaceChildren(
+ ...series.map(([key, v]) => {
+ const column = el("div", undefined, "bar");
+ column.tabIndex = 0;
+ const text = `${label(key)} · ${full.format(v.tokens)} ${W.tokens} · ${full.format(v.calls)} ${W.calls}`;
+ column.setAttribute("aria-label", text);
+ const fill = el("i");
+ fill.style.height = `${peak ? (v.tokens / peak) * 100 : 0}%`;
+ column.append(fill);
+ for (const on of ["pointerenter", "focus"])
+ column.addEventListener(on, () => ($("readout").textContent = text));
+ for (const off of ["pointerleave", "blur"])
+ column.addEventListener(off, () => ($("readout").textContent = rest));
+ return column;
+ }),
+ );
+ $("first-tick").textContent = label(series[0][0]);
+ $("last-tick").textContent = label(series.at(-1)[0]);
+
+ const models = new Map();
+ for (const r of shown)
+ models.set(r.model, sum([models.get(r.model) || sum([]), r]));
+ $("models").replaceChildren(
+ ...[...models]
+ .sort((a, b) => total(b[1]) - total(a[1]))
+ .map(([model, v]) => {
+ const tr = el("tr");
+ tr.append(
+ el("th", model),
+ number("td", v.calls),
+ number("td", v.in),
+ number("td", v.out),
+ number("td", v.cache_read),
+ number("td", v.cache_write),
+ el("td", share(total(v) / total(all))),
+ );
+ tr.firstChild.scope = "row";
+ return tr;
+ }),
+ );
+}
+
+// The poll repaints every two seconds; rebuilding the board then would drop
+// the hover and focus a reader has on a bar.
+let painted = "";
+function render(s) {
+ state = s;
+ const working = s.phase !== "idle";
+ $("refresh").disabled = working || busy;
+ $("refresh").classList.toggle("spin", working || busy);
+ for (const b of $("periods").children)
+ b.setAttribute("aria-pressed", String(b.dataset.period === period));
+ $("range").hidden = period !== "custom";
+ const paint = JSON.stringify([
+ period,
+ $("from").value,
+ $("to").value,
+ s.lastScan,
+ s.usage,
+ ]);
+ if (paint !== painted) {
+ painted = paint;
+ $("empty").hidden = true;
+ if (s.lastScan) board(s.usage || []);
+ else $("board").hidden = true;
+ }
+ if (!s.lastScan && working) {
+ $("empty").textContent = W.reading;
+ $("empty").hidden = false;
+ }
+ $("progress").textContent = [
+ s.lastScan &&
+ W.scanned(
+ new Date(s.lastScan).toLocaleTimeString(locale, {
+ hour: "2-digit",
+ minute: "2-digit",
+ }),
+ ),
+ s.remaining ? W.remaining(s.remaining) : "",
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+ const items = Object.entries(groups)
+ .map(([k, codes]) => [
+ k,
+ codes.reduce((n, c) => n + (s.issues?.[c] || 0), 0),
+ ])
+ .filter(([, n]) => n);
+ $("issues").replaceChildren(
+ ...items.map(([k, n]) => el("li", `${W[k]}: ${full.format(n)}`)),
+ );
+ $("issues-summary").textContent = W.issues(
+ full.format(items.reduce((n, [, c]) => n + c, 0)),
+ );
+ $("issues-box").hidden = !items.length;
+ errors([failure, ...(s.errors || [])].filter(Boolean));
+}
+
+async function act(fn) {
+ if (busy) return;
+ busy = true;
+ turn++;
+ failure = "";
+ if (state) render(state);
+ try {
+ const s = await fn();
+ busy = false;
+ render(s);
+ } catch (e) {
+ busy = false;
+ // Kept until the next action, so a status poll cannot erase it.
+ failure = e.message;
+ if (state) render(state);
+ else errors([failure]);
+ }
+}
+const read = () => api("refresh", {});
+$("refresh").onclick = () => act(read);
+$("auto").onchange = () => keep("auto", (auto = Number($("auto").value)));
+for (const b of $("periods").children)
+ b.onclick = () => {
+ keep("period", (period = b.dataset.period));
+ if (state) render(state);
+ };
+for (const id of ["from", "to"])
+ $(id).onchange = () => {
+ keep(id, $(id).value);
+ if (state) render(state);
+ };
+
+let left = Infinity;
+async function poll() {
+ const mine = turn;
+ try {
+ const s = await api("status");
+ // A reply that raced an action is older than what the action returned.
+ if (busy || mine !== turn) return;
+ render(s);
+ if (s.phase !== "idle") return;
+ const age = s.lastScan ? Date.now() - Date.parse(s.lastScan) : Infinity;
+ // A first export is bounded per read; keep going while it makes progress.
+ const more = s.remaining > 0 && s.remaining < left && !s.errors.length;
+ if (more || age === Infinity || (auto && age >= auto * 1000)) {
+ left = s.remaining || Infinity;
+ void act(read);
+ }
+ } catch (e) {
+ if (!busy) errors([e.message]);
+ }
+}
+void poll();
+setInterval(poll, 2000);
diff --git a/packages/amp-usage/ui/index.html b/packages/amp-usage/ui/index.html
new file mode 100644
index 0000000..5268dd9
--- /dev/null
+++ b/packages/amp-usage/ui/index.html
@@ -0,0 +1,109 @@
+
+
+
+
+
+
+ Amp usage
+
+
+
+
+
+
+
+
+
+ –
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/packages/amp-usage/ui/style.css b/packages/amp-usage/ui/style.css
new file mode 100644
index 0000000..0724348
--- /dev/null
+++ b/packages/amp-usage/ui/style.css
@@ -0,0 +1,293 @@
+/* Magpie's own look. The launcher passes the window's real colours as
+ --magpie-* variables; the values below are only fallbacks. */
+:root {
+ --magpie-bg: #f5f6f8;
+ --magpie-card: #ffffff;
+ --magpie-fg: #23262e;
+ --magpie-muted: #6b7280;
+ --magpie-line: #e2e4e9;
+ --magpie-accent: #5b5bd6;
+ --magpie-green: #1f7a4d;
+ --magpie-red: #b3352f;
+ color-scheme: light;
+}
+:root[data-theme="dark"] {
+ --magpie-bg: #15171c;
+ --magpie-card: #1c1f26;
+ --magpie-fg: #e8e9ee;
+ --magpie-muted: #9aa0aa;
+ --magpie-line: #2c3038;
+ --magpie-accent: #8f8ff0;
+ --magpie-green: #5ac08a;
+ --magpie-red: #e0716a;
+ color-scheme: dark;
+}
+* {
+ box-sizing: border-box;
+}
+body {
+ margin: 0;
+ background: var(--magpie-bg);
+ color: var(--magpie-fg);
+ font: 13px/1.5
+ var(
+ --magpie-font,
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ system-ui,
+ sans-serif
+ );
+ -webkit-font-smoothing: antialiased;
+}
+main {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ max-width: 960px;
+ margin: 0 auto;
+ padding: 20px 24px;
+}
+h1,
+h2,
+p {
+ margin: 0;
+}
+h1 {
+ font-size: 20px;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+}
+h2 {
+ font-size: 13px;
+ font-weight: 600;
+}
+.muted {
+ color: var(--magpie-muted);
+ font-size: 12px;
+}
+header,
+.tools,
+.range,
+.chart-head,
+.axis,
+footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+}
+.range {
+ justify-content: flex-start;
+}
+.card {
+ padding: 14px 16px;
+ border: 1px solid var(--magpie-line);
+ border-radius: 10px;
+ background: var(--magpie-card);
+}
+button,
+select,
+input {
+ min-height: 30px;
+ padding: 3px 10px;
+ border: 1px solid var(--magpie-line);
+ border-radius: 8px;
+ background: var(--magpie-card);
+ color: inherit;
+ font: inherit;
+}
+button,
+select {
+ cursor: pointer;
+}
+button:hover:not(:disabled) {
+ border-color: var(--magpie-muted);
+}
+button:disabled {
+ cursor: default;
+}
+:focus-visible {
+ outline: 2px solid var(--magpie-accent);
+ outline-offset: 1px;
+}
+svg {
+ width: 16px;
+ height: 16px;
+ vertical-align: -3px;
+}
+/* Magpie's own period control: one pill, the chosen period raised in it. */
+.segmented {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ padding: 3px;
+ border-radius: 10px;
+ background: var(--magpie-line);
+}
+.segmented button {
+ min-height: 26px;
+ padding: 2px 12px;
+ border: 0;
+ border-radius: 7px;
+ background: none;
+ color: var(--magpie-muted);
+}
+.segmented button:hover {
+ color: var(--magpie-fg);
+}
+.segmented button[aria-pressed="true"] {
+ background: var(--magpie-card);
+ color: var(--magpie-fg);
+ font-weight: 600;
+}
+button.icon {
+ padding: 3px 6px;
+ border-color: transparent;
+ background: none;
+ color: var(--magpie-muted);
+}
+button.icon.spin svg {
+ animation: spin 1s linear infinite;
+}
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ button.icon.spin svg {
+ animation: none;
+ }
+}
+.errors {
+ border-color: var(--magpie-red);
+ color: var(--magpie-red);
+ overflow-wrap: anywhere;
+}
+
+#board {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.tiles {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
+ gap: 12px;
+ margin: 0;
+}
+.tiles div {
+ padding: 12px 16px;
+ border: 1px solid var(--magpie-line);
+ border-radius: 10px;
+ background: var(--magpie-card);
+}
+dt {
+ color: var(--magpie-muted);
+ font-size: 12px;
+}
+dd {
+ margin: 2px 0 0;
+ font-size: 20px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+
+.chart-head {
+ margin-bottom: 12px;
+}
+#readout {
+ font-variant-numeric: tabular-nums;
+}
+.bars {
+ display: flex;
+ align-items: stretch;
+ gap: 2px;
+ height: 120px;
+ border-bottom: 1px solid var(--magpie-line);
+}
+/* The whole column is the hover target, not only the painted part. */
+.bar {
+ flex: 1 1 0;
+ display: flex;
+ align-items: flex-end;
+ min-width: 0;
+}
+.bar i {
+ width: 100%;
+ min-height: 0;
+ border-radius: 3px 3px 0 0;
+ background: var(--magpie-accent);
+}
+.bar:hover i,
+.bar:focus-visible i {
+ filter: brightness(1.25);
+}
+.bar:focus-visible {
+ outline-offset: -1px;
+}
+.bars.dense {
+ gap: 0;
+}
+.bars.dense .bar i {
+ border-radius: 0;
+}
+.axis {
+ margin-top: 6px;
+}
+
+.scroll {
+ overflow-x: auto;
+}
+table {
+ width: 100%;
+ margin-top: 8px;
+ border-collapse: collapse;
+ font-variant-numeric: tabular-nums;
+}
+th,
+td {
+ padding: 7px 0 7px 16px;
+ text-align: right;
+ white-space: nowrap;
+ font-weight: 400;
+}
+th:first-child {
+ padding-left: 0;
+ text-align: left;
+}
+thead th {
+ color: var(--magpie-muted);
+ font-size: 12px;
+}
+tbody tr {
+ border-top: 1px solid var(--magpie-line);
+}
+
+details {
+ color: var(--magpie-muted);
+}
+summary {
+ cursor: pointer;
+}
+details p,
+details ul {
+ max-width: 72ch;
+ margin: 8px 0 0;
+}
+ul {
+ padding-left: 18px;
+}
+footer {
+ overflow-wrap: anywhere;
+}
+[hidden] {
+ display: none !important;
+}
+@media (max-width: 520px) {
+ main {
+ padding: 16px;
+ }
+}
diff --git a/packages/amp-usage/ui/words.js b/packages/amp-usage/ui/words.js
new file mode 100644
index 0000000..8a812ea
--- /dev/null
+++ b/packages/amp-usage/ui/words.js
@@ -0,0 +1,153 @@
+// The page's words in each language, and how a service error code reads.
+// A classic script, so the page and the tests share one copy.
+globalThis.AmpUsage = {
+ words: {
+ en: {
+ title: "Amp usage",
+ today: "Today",
+ h24: "24 hours",
+ d7: "7 days",
+ d30: "30 days",
+ all: "All",
+ custom: "Custom",
+ refresh: "Refresh",
+ auto: "Refresh automatically",
+ off: "Off",
+ seconds: (n) => `${n} s`,
+ minutes: (n) => `${n} min`,
+ hourly: "Tokens per hour",
+ daily: "Tokens per day",
+ byModel: "By model",
+ model: "Model",
+ calls: "Requests",
+ input: "Input",
+ output: "Output",
+ cacheRead: "Cache read",
+ cacheWrite: "Cache write",
+ hit: "Cache hit rate",
+ share: "Share",
+ tokens: "tokens",
+ reading: "Reading Amp usage…",
+ scanned: (t) => `Read at ${t}`,
+ remaining: (n) => `${n} more threads to export`,
+ empty: "No Amp usage found yet.",
+ emptyPeriod: "No Amp usage in this period.",
+ issues: (n) => `${n} records left out`,
+ noTime: "No reliable time",
+ inProgress: "Still running or just changed",
+ excluded: "Excluded in plugin options",
+ held: "Inconsistent, held back rather than guessed",
+ howTitle: "How this is counted",
+ how1: "Input, output, cache reads and cache writes are kept apart. Amp credits are not turned into dollars; Magpie estimates the cost in its own usage pages.",
+ how2: "A request with no time of its own is dated by when its turn was sent, so a turn that runs past midnight counts on the day it began.",
+ credit: "Parser reference: Tokscale · MIT",
+ err: {
+ ampNotFound:
+ "Amp CLI not found. Install Amp and run amp login, or set ampPath in the plugin options.",
+ ampFailed:
+ "An Amp command failed. Check amp login and network access in your terminal.",
+ ampTimeout: "An Amp command timed out. Refresh to try again.",
+ ampTooLarge:
+ "An Amp thread export was too large to read; it was skipped.",
+ ampInvalidJSON:
+ "Amp returned output this plugin cannot read. Update Amp.",
+ ampListFormat:
+ "Amp's thread list changed format. Update Amp and this plugin.",
+ ampExportMismatch:
+ "Amp exported a different thread than asked; it was skipped.",
+ ampBudget: "Reading Amp took its time limit. Refresh to continue.",
+ cacheMismatch:
+ "A cached Amp thread did not match; it will be exported again.",
+ localDirInvalid:
+ "Thread directories in the plugin options must be absolute paths.",
+ localDirUnreadable: "A local thread directory cannot be read.",
+ localDirMissing:
+ "A local thread directory in the plugin options was not found.",
+ localThreadInvalid:
+ "A local thread was unreadable, oversized or invalid; it was left out.",
+ localThreadConflict:
+ "Two local copies of one thread disagree; it was left out.",
+ fileUnreadable:
+ "A file of this plugin's own cannot be read. Check the plugin log.",
+ magpieRefused:
+ "Magpie refused the usage records. Check the gateway address and Magpie version.",
+ magpieAck:
+ "Magpie answered in a way this plugin did not expect. Records will be sent again safely.",
+ magpieUnreachable:
+ "Magpie could not be reached. Check that it is running and the gateway address.",
+ reconnect: "Reopen the Amp usage page to reconnect.",
+ serviceError: "The local service failed. Check the plugin log.",
+ unreachable: "The local service is not answering. Reopen the page.",
+ unexpected: "Something went wrong. Check the plugin log.",
+ },
+ },
+ zh: {
+ title: "Amp 用量",
+ today: "今天",
+ h24: "24 小时",
+ d7: "7 天",
+ d30: "30 天",
+ all: "全部",
+ custom: "自定义",
+ refresh: "刷新",
+ auto: "自动刷新",
+ off: "关闭",
+ seconds: (n) => `${n} 秒`,
+ minutes: (n) => `${n} 分钟`,
+ hourly: "每小时 Token",
+ daily: "每日 Token",
+ byModel: "按模型",
+ model: "模型",
+ calls: "请求",
+ input: "输入",
+ output: "输出",
+ cacheRead: "缓存读取",
+ cacheWrite: "缓存写入",
+ hit: "缓存命中率",
+ share: "占比",
+ tokens: "token",
+ reading: "正在读取 Amp 用量…",
+ scanned: (t) => `读取于 ${t}`,
+ remaining: (n) => `还有 ${n} 个线程待导出`,
+ empty: "还没有读到 Amp 用量。",
+ emptyPeriod: "这个时间段没有 Amp 用量。",
+ issues: (n) => `${n} 条记录未计入`,
+ noTime: "没有可靠时间",
+ inProgress: "仍在生成或刚更新",
+ excluded: "已在插件选项中排除",
+ held: "数据前后不一致,保留不导入",
+ howTitle: "统计口径",
+ how1: "输入、输出、缓存读取、缓存写入分别统计。Amp credits 不折算成美元,费用由 Magpie 在自己的用量页估算。",
+ how2: "没有自身时间的请求,按所在轮次的发送时间计日;跨过午夜的一轮记在开始那天。",
+ credit: "解析参考:Tokscale · MIT",
+ err: {
+ ampNotFound:
+ "未找到 Amp CLI。请安装 Amp 并运行 amp login,或在插件选项中设置 ampPath。",
+ ampFailed: "Amp 命令执行失败。请在终端中检查 amp login 和网络连接。",
+ ampTimeout: "Amp 命令超时,请刷新重试。",
+ ampTooLarge: "有一个 Amp 线程导出过大,无法读取,已跳过。",
+ ampInvalidJSON: "Amp 返回了无法解析的内容,请更新 Amp。",
+ ampListFormat: "Amp 线程列表格式已变化,请更新 Amp 和本插件。",
+ ampExportMismatch: "Amp 导出的线程与请求不符,已跳过。",
+ ampBudget: "读取 Amp 已达单次时间上限,请刷新继续。",
+ cacheMismatch: "有一个缓存的 Amp 线程不一致,将重新导出。",
+ localDirInvalid: "插件选项中的线程目录必须是绝对路径。",
+ localDirUnreadable: "无法读取本地线程目录。",
+ localDirMissing: "插件选项中的本地线程目录不存在。",
+ localThreadInvalid: "有本地线程无法读取、过大或格式无效,已排除。",
+ localThreadConflict: "同一线程的两份本地副本不一致,已排除。",
+ fileUnreadable: "无法读取插件自身的文件,请查看插件日志。",
+ magpieRefused: "Magpie 拒绝了用量记录。请检查网关地址和 Magpie 版本。",
+ magpieAck: "Magpie 的回复不符合预期,记录稍后会安全重发。",
+ magpieUnreachable:
+ "无法连接 Magpie。请确认它正在运行,并检查网关地址。",
+ reconnect: "请重新打开 Amp 用量页面以重新连接。",
+ serviceError: "本地服务出错,请查看插件日志。",
+ unreachable: "本地服务没有响应,请重新打开页面。",
+ unexpected: "出现错误,请查看插件日志。",
+ },
+ },
+ },
+ // Unknown codes, such as one from a newer service, read as the generic one.
+ error: (w, code) => w.err[code] || w.err.unexpected,
+};
diff --git a/packages/day-card/NOTICE b/packages/day-card/NOTICE
new file mode 100644
index 0000000..b213235
--- /dev/null
+++ b/packages/day-card/NOTICE
@@ -0,0 +1,7 @@
+The Amp logo embedded in page/icons.js is an unmodified official brand asset:
+https://ampcode.com/logo-dark.svg
+https://ampcode.com/press-kit
+
+The logo is rendered in the receipt's ink without changing its proportions.
+Amp branding belongs to its respective owner and is not covered by this
+package's MIT license.
diff --git a/packages/day-card/day-card.test.mjs b/packages/day-card/day-card.test.mjs
index ece48e6..c0225e7 100644
--- a/packages/day-card/day-card.test.mjs
+++ b/packages/day-card/day-card.test.mjs
@@ -11,6 +11,7 @@ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
const scope = {}
new Function("globalThis", read("view.js"))(scope)
const V = scope.DayView
+new Function("globalThis", read("icons.js"))(scope)
// usage:day as magpie answers it (internal/gui/pageday.go, usageapi.DayOf)
const day = {
@@ -48,6 +49,27 @@ test("asks for one read, usage:day, and nothing else", () => {
expect([...reads]).toEqual(["usage:day"])
})
+test("Amp uses its bundled official logo only when the host supplies no Amp icon", () => {
+ const host = { src: "data:image/svg+xml;base64,PHN2Zy8+" }
+ const amp = (icon, icons = {}) =>
+ V.card({ ...day, icons, agents: [{ id: "amp", name: "Amp", icon, cost: 3.69, models: [] }] }, "en")
+ expect(amp("amp", { amp: host }).agents[0].icon).toBe("amp")
+ expect(amp("generic", { generic: host }).agents[0].icon).toBe("amp-official")
+ for (const icon of [undefined, "", "generic", "amp"]) {
+ const c = amp(icon)
+ expect(c.agents[0].icon).toBe("amp-official")
+ const mark = scope.DayIcons[c.agents[0].icon]
+ expect(mark.mono).toBe(true)
+ expect(mark.src).toStartWith("data:image/svg+xml;base64,")
+ const svg = Buffer.from(mark.src.split(",")[1], "base64").toString("utf8")
+ expect(svg).toContain('viewBox="0 0 281 144"')
+ expect(svg).toContain(" {
expect(pkg.main).toBeUndefined()
expect(pkg.exports).toBeUndefined()
diff --git a/packages/day-card/package.json b/packages/day-card/package.json
index cf03715..9b8ae32 100644
--- a/packages/day-card/package.json
+++ b/packages/day-card/package.json
@@ -1,8 +1,8 @@
{
"name": "@magpie-community/page-day-card",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "A page in magpie's window that draws a day, week, month or all of your AI usage as a card: tokens, cost, each agent and its models, your streak and your average day. Copy it as a picture or save it as a PNG",
- "files": ["page", "README.md"],
+ "files": ["page", "README.md", "NOTICE"],
"keywords": ["magpie", "magpie-page", "usage", "tokens", "cost", "card"],
"license": "MIT",
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/day-card" },
diff --git a/packages/day-card/page/app.js b/packages/day-card/page/app.js
index af340b4..e225387 100644
--- a/packages/day-card/page/app.js
+++ b/packages/day-card/page/app.js
@@ -49,7 +49,7 @@
// ---- logos: data: pictures from the read, each drawn in the ink ----
function picture(name) {
- const ic = state.day?.icons?.[name];
+ const ic = globalThis.DayIcons?.[name] || state.day?.icons?.[name];
if (!ic?.src) return Promise.resolve(null);
if (!state.icons.has(ic.src)) {
state.icons.set(ic.src, new Promise((ok) => {
@@ -77,7 +77,9 @@
const off = document.createElement("canvas");
off.width = off.height = px;
const o = off.getContext("2d");
- o.drawImage(ic.img, 0, 0, px, px);
+ const ratio = Math.min(px / ic.img.naturalWidth, px / ic.img.naturalHeight);
+ const w = ic.img.naturalWidth * ratio, h = ic.img.naturalHeight * ratio;
+ o.drawImage(ic.img, (px - w) / 2, (px - h) / 2, w, h);
let clear = ic.mono;
if (!clear) {
try {
diff --git a/packages/day-card/page/icons.js b/packages/day-card/page/icons.js
new file mode 100644
index 0000000..28c581b
--- /dev/null
+++ b/packages/day-card/page/icons.js
@@ -0,0 +1,8 @@
+// Official Amp logo from https://ampcode.com/logo-dark.svg (see ../NOTICE).
+// Inline bytes keep receipt export offline and its canvas readable.
+globalThis.DayIcons = {
+ "amp-official": {
+ "src": "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjgxIiBoZWlnaHQ9IjE0NCIgdmlld0JveD0iMCAwIDI4MSAxNDQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGQ9Ik0yMzYuMDE0IDIwQzI2MC40MzEgMjAuMDAwMSAyODAuNjAyIDM3LjQxMTUgMjgwLjYwMyA2NC43NDMyQzI4MC42MDIgOTMuNTMzNyAyNjAuMDY1IDExNC4xNjYgMjMzLjUyIDExNC4xNjZDMjI0LjE1OCAxMTQuMTY2IDIxNS42MzkgMTEyLjQyMiAyMDguNjMgMTA4LjQ5QzIwMi44ODYgMTA1LjI3IDE5OC4yMDMgMTAwLjYwNSAxOTQuOTE5IDk0LjMzNzlMMTg4LjExNSAxNDEuODIyTDE4Ny45NDYgMTQzLjAxNkgxNzQuMjE0TDE3NC40NDggMTQxLjQyM0wxOTEuNzcyIDIyLjQ5NDFIMjA1LjM3MkwyMDMuOTM3IDMxLjMzNjlDMjEyLjE0MyAyMy44NjA4IDIyMy4yIDIwLjAwMDIgMjM2LjAxNCAyMFpNNDcuMDgyIDIwLjE1NDNDNTYuNDQzNSAyMC4xNTQzIDY1LjAwMTIgMjEuODk5MSA3Mi4wNDg4IDI1Ljg0ODZDNzcuODIyMiAyOS4wODMxIDgyLjUzMjMgMzMuNzcxMyA4NS44MjcxIDQwLjA4NUw4OC4xMjAxIDIzLjY5MjRMODguMjg2MSAyMi40OTMySDEwMS44NjNMODkuMTYxMSAxMTAuNjMzTDg4Ljk4NzMgMTExLjgyNkg3NS40MDkyTDc2LjcyMjcgMTAyLjg1NUM2OC41ODU0IDExMC40NTYgNTcuMzk4MSAxMTQuMzIzIDQ0LjU4ODkgMTE0LjMyM0MyMC4xNzA5IDExNC4zMjMgMC4wMDAxNjcyMjMgOTYuOTA4NyAwIDY5LjU3NzFDMC4wMDAxNDk3NDUgNDAuNzg1NCAyMC41NCAyMC4xNTQ5IDQ3LjA4MiAyMC4xNTQzWk0xMTYuMjM0IDExMC42MzZMMTE2LjA2MSAxMTEuODI3SDEwMi40ODVMMTE1LjM1MSAyMy42ODU1TDExNS41MjEgMjIuNDk0MUgxMjkuMDgzTDExNi4yMzQgMTEwLjYzNlpNMTQwLjY3MyAxMTAuNjM2TDE0MC40OTkgMTExLjgyN0gxMjYuOTI0TDEzOS43ODkgMjMuNjg1NUwxMzkuOTYgMjIuNDk0MUgxNTMuNTIxTDE0MC42NzMgMTEwLjYzNlpNMTc3Ljk1OCAyMi40OTQxTDE2NS4xMDggMTEwLjYzNkwxNjQuOTM1IDExMS44MjdIMTUxLjM2TDE2NC4yMjUgMjMuNjg1NUwxNjQuMzk2IDIyLjQ5NDFIMTc3Ljk1OFpNNDguNDg1NCAzMS45ODQ0QzI3Ljg2MzggMzEuOTg1IDE0LjAxMzMgNDguMzc5OSAxNC4wMTI3IDY4Ljk1MjFDMTQuMDEyNyA3Ny43OTA3IDE2LjgwOTQgODYuMTc3MSAyMi4zMTQ1IDkyLjMzNEMyNy43OTczIDk4LjQ2NTcgMzYuMDYzMSAxMDIuNDkzIDQ3LjI0MDIgMTAyLjQ5M0M2Ny44NTM0IDEwMi40OTMgODEuNzEyMiA4NS45NDg3IDgxLjcxMjkgNjUuMzY4MkM4MS43MTI5IDU1LjQwNzYgNzguMjQ5MyA0Ny4wNzkyIDcyLjQxMzEgNDEuMjQ0MUM2Ni41Nzk0IDM1LjQwODggNTguMjg3MSAzMS45ODQ0IDQ4LjQ4NTQgMzEuOTg0NFpNMjMzLjM2MiAzMS44MjkxQzIxMi43NDkgMzEuODI5NyAxOTguODkgNDguMzcxNiAxOTguODkgNjguOTUyMUMxOTguODkgNzguOTEyMyAyMDIuMzU2IDg3LjI0MDMgMjA4LjE4OSA5My4wNzQyQzIxNC4wMjMgOTguOTEwNyAyMjIuMzE1IDEwMi4zMzYgMjMyLjExNiAxMDIuMzM2QzI1Mi43MzggMTAyLjMzNSAyNjYuNTg5IDg1Ljk0MDcgMjY2LjU5IDY1LjM2ODJDMjY2LjU5IDU2LjUyOTYgMjYzLjc5NSA0OC4xNDI0IDI1OC4yOSA0MS45ODYzQzI1Mi44MDcgMzUuODU1MSAyNDQuNTQyIDMxLjgyOTEgMjMzLjM2MiAzMS44MjkxWiIgZmlsbD0iI0ZGRkZGRiIvPgo8L3N2Zz4K",
+ "mono": true
+ }
+};
diff --git a/packages/day-card/page/index.html b/packages/day-card/page/index.html
index d352784..af0564c 100644
--- a/packages/day-card/page/index.html
+++ b/packages/day-card/page/index.html
@@ -7,6 +7,7 @@
+
diff --git a/packages/day-card/page/view.js b/packages/day-card/page/view.js
index a91a5d2..97eac39 100644
--- a/packages/day-card/page/view.js
+++ b/packages/day-card/page/view.js
@@ -273,7 +273,9 @@
const hidden = Math.max(0, models.length - maxModels) + (Number(a.moreModels) || 0);
return {
name: upper(a.id ? a.name || a.id : t.noAgent),
- icon: a.icon || "",
+ // Amp's own logo stands in only when the host has no Amp picture to
+ // give: none, a missing one, or its generic dot.
+ icon: a.id === "amp" && (a.icon === "generic" || !day.icons?.[a.icon]?.src) ? "amp-official" : a.icon || "",
value: money(a.cost, cur, rate),
models: models.slice(0, maxModels).map((m) => ({ name: upper(m.model || "?"), icon: m.icon || "", value: money(m.cost, cur, rate) })),
more: hidden ? t.more(hidden) : "",
diff --git a/registry.json b/registry.json
index efe251b..76428a5 100644
--- a/registry.json
+++ b/registry.json
@@ -151,6 +151,7 @@
{"package": "@magpie-community/tools-layerfs", "name": "LayerFS", "kind": "tools", "community": true, "summary": {"en": "LayerFS workspaces for every agent: deduplicated checkpoints and branches behind stable filesystem paths, instead of a fresh copy of the tree for every agent.", "zh": "给每个 agent 的 LayerFS 工作区:稳定的文件系统路径背后是可去重的检查点与分支,而不是每个 agent 各复制一棵项目树。"}},
{ "package": "@magpie-community/page-usage", "name": "Usage Glance", "kind": "page", "community": true,
"summary": { "en": "A page in magpie's window with calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them. Reads only your usage summary.", "zh": "在 magpie 窗口里一眼看到今天、7 天或 30 天的调用、错误、token、费用和对应模型。只读取用量汇总。" } },
+ {"package": "@magpie-community/page-amp-usage", "name": "Amp Usage", "kind": "page", "community": true, "summary": {"en": "An Amp usage board: requests, tokens and cache hit rate by hour, day and model, read from your Amp account and legacy local threads. Its background service syncs that usage into Magpie requests and Day card, with duplicate checks; set sync to false to only view it.", "zh": "Amp \u7528\u91cf\u770b\u677f\uff1a\u8bf7\u6c42\u6570\u3001Token\u3001\u7f13\u5b58\u547d\u4e2d\u7387\uff0c\u6309\u5c0f\u65f6\u3001\u6309\u65e5\u548c\u6309\u6a21\u578b\u67e5\u770b\uff0c\u6570\u636e\u6765\u81ea Amp \u8d26\u53f7\u548c\u65e7\u7248\u672c\u5730\u7ebf\u7a0b\u3002\u540e\u53f0\u670d\u52a1\u628a\u8fd9\u4e9b\u7528\u91cf\u540c\u6b65\u8fdb Magpie \u8bf7\u6c42\u7edf\u8ba1\u548c\u6bcf\u65e5\u5361\u7247\uff0c\u5e26\u53bb\u91cd\u68c0\u67e5\uff1b\u628a sync \u8bbe\u4e3a false \u5219\u53ea\u67e5\u770b\u3002"}},
{ "package": "@magpie-community/page-day-card", "name": "Day Card", "kind": "page", "community": true,
"summary": { "en": "A day of your AI usage printed as a receipt: its cost, requests and streak, the day against your average day, each agent and its models, and its tokens. Copy it as a picture or save it as a PNG. Reads only your usage by day.", "zh": "把一天的 AI 用量打印成一张小票:费用、请求数、连续使用天数、与日均的倍数、每个 Agent 和它用的模型,以及 token 用量。可复制为图片或保存为 PNG。只读取按天的用量。" } },
{ "package": "@magpie-community/page-fingerprint", "name": "Fingerprint", "kind": "page", "community": true,