magpie-multi-usage 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,32 +2,12 @@
2
2
 
3
3
  **English** | [简体中文](README.zh-CN.md)
4
4
 
5
- An open-source, zero-dependency multi-device token usage dashboard plugin for [Magpie](https://github.com/yetone/magpie), using a dedicated private GitHub repository as a sanitized stats-only relay — with zero Magpie backup decryption keys, zero writes to `~/.config/magpie`, and zero external cron jobs.
5
+ An open-source, zero-dependency multi-device token usage dashboard plugin for [Magpie](https://github.com/yetone/magpie). Built for running Magpie on multiple machines with independent configs — a primary workstation, headless servers, intermittently online laptops: each device publishes sanitized usage counters to a dedicated private GitHub repository, and any machine can view the combined dashboard without merging configs, exposing gateway ports, or handing Magpie's backup decryption passphrase to a plugin.
6
6
 
7
7
  ## Highlights
8
8
 
9
- - **Works immediately out of the box**: Displays your local machine's usage (both gateway requests and Magpie-discovered native agent sessions such as Claude Code, OpenCode, Codex, and Antigravity) even before configuring a GitHub relay.
10
- - **Magpie-native UI**: Matches Magpie's built-in Usage page layout, light/dark themes, and `--magpie-*` host tokens, with English and Chinese (`auto` / `en` / `zh`) language selection in Settings.
11
- - **Independent multi-device aggregation**: Combines workstations, laptops, and headless `magpie serve` nodes without merging configs, providers, or sync targets.
12
- - **Zero decryption passphrase**: Never touches Magpie backups, credentials, or sync keys; relays only sanitized aggregate counters via conflict-free per-device JSON files.
13
- - **Pure ESM, zero runtime dependencies**: Runs cleanly on Magpie's bundled Bun host and Node.js 22+.
14
-
15
- ## Why this plugin exists
16
-
17
- Magpie's built-in sync supports sharing usage across machines, but ties every machine to a single sync target and shares one encryption passphrase between full configuration backups (`.magpie-backup`) and usage files (`.magpie-usage`).
18
-
19
- When you run Magpie across multiple machines with independent configurations — such as a primary workstation, headless servers, and intermittently online laptops — this plugin gives you a unified token usage dashboard without:
20
-
21
- - Merging configs, providers, or sync targets across machines;
22
- - Exposing Magpie gateway ports or requiring Tailscale, public IPs, or SSH access;
23
- - Providing Magpie's backup decryption passphrase to a third-party plugin.
24
-
25
- ## How it works
26
-
27
- 1. **Reads local usage from Magpie**: Incrementally pulls this machine's own usage feed from Magpie's loopback gateway API (`GET /v1/magpie/usage/requests?computer=this&cursor=...`), including both gateway traffic and native agent sessions discovered by Magpie.
28
- 2. **Syncs headless servers automatically**: Uses Magpie's read-only async `magpie.hooks` (`onResponse`, debounced) so headless `magpie serve` nodes publish updates automatically without external cron jobs.
29
- 3. **Publishes atomically to a dedicated private GitHub repo**: Writes sanitized monthly snapshots and a manifest into conflict-free per-device folders using the Git Data API (single atomic commit with compare-and-swap ref updates), strictly refusing public repositories before any read or write.
30
- 4. **Aggregates on read inside Magpie**: Renders combined and per-device totals, two-tone daily usage bars, clickable device filter rows, and tabbed **Agents / Models / Providers** breakdowns. When a remote device fails or is offline, its last hash-verified cached snapshot is preserved and flagged as cached.
9
+ - **Works out of the box**: local usage (gateway requests plus Magpie-discovered Claude Code, OpenCode, Codex, and Antigravity sessions) renders with zero setup.
10
+ - **Independent multi-device aggregation**: workstations, laptops, and headless `magpie serve` nodes publish automatically via Magpie's read-only hooks — no external cron jobs.
31
11
 
32
12
  ## Installation
33
13
 
@@ -50,30 +30,30 @@ Open **Multi-Device Usage** (**多端用量**) in the Magpie sidebar — local u
50
30
 
51
31
  ### 1. Create a dedicated private GitHub repository
52
32
 
53
- Create a new **Private** GitHub repository dedicated solely to sanitized usage stats (for example, `<you>/magpie-usage-stats`) and initialize its default branch (such as `main` with a README).
33
+ Create a new **Private** repository solely for sanitized usage stats (for example, `<you>/magpie-usage-stats`) and initialize its default branch (such as `main` with a README).
54
34
 
55
35
  > [!IMPORTANT]
56
36
  > Do **not** reuse your Magpie configuration sync repository, and do **not** use a public repository. This plugin verifies `private === true` before every read and ref update, and refuses public repositories (`PUBLIC_REPO_REFUSED`).
57
37
 
58
- ### 2. Create a Fine-grained GitHub PAT
38
+ ### 2. Create a fine-grained PAT
59
39
 
60
- Create a GitHub **Fine-grained personal access token** scoped strictly to **Only select repositories → your dedicated stats repo**:
40
+ Create a GitHub **fine-grained personal access token** scoped strictly to **Only select repositories → your dedicated stats repo**, choosing permissions by what each machine will do:
61
41
 
62
- - **Publishing machine** (workstation or headless server): `Contents: Read and write` (GitHub automatically includes `Metadata: Read-only`).
63
- - **View-only machine** (optional read-only dashboard): `Contents: Read-only` (uncheck **Publish this machine's usage** in Settings).
42
+ - Machines that publish their own usage: `Contents: Read and write`.
43
+ - Machines that only view the combined dashboard: `Contents: Read-only`, and turn off **Publish this machine's usage** in Settings.
64
44
 
65
45
  ### 3. Configure each machine
66
46
 
67
- - **Magpie Desktop / `magpie web`**:
68
- 1. Open **Multi-Device Usage** in the Magpie sidebar and click the **Settings** gear icon.
69
- 2. Set **Device display name** (optional), **Private GitHub repository** (`owner/repo`), and **GitHub Fine-grained PAT**.
70
- 3. Click **Test connection**, then **Save and sync**.
71
- - **Headless `magpie serve` node**:
72
- 1. Set non-sensitive options (`repo`, `deviceName`, `pushEnabled`, `pushIntervalSec`) via `magpie plugin options`.
73
- 2. Supply the GitHub PAT via the environment variable `MAGPIE_MULTI_USAGE_GITHUB_TOKEN` (or store `{"githubToken":"..."}` in `<dataDir>/credentials.json` with strict mode `0600`). Never place a PAT in plaintext `plugins.json`.
47
+ - **Magpie Desktop / `magpie web`**: open **Multi-Device Usage** → **Settings** gear → set **Device display name** (optional), **Private GitHub repository** (`owner/repo`), and **PAT** → **Test connection** → **Save and sync**.
48
+ - **Headless `magpie serve` node**: set non-sensitive options (`repo`, `deviceName`, `pushEnabled`, `pushIntervalSec`) via `magpie plugin options`, and supply the PAT via `MAGPIE_MULTI_USAGE_GITHUB_TOKEN` (or a `0600`-mode `<dataDir>/credentials.json`) — never in plaintext `plugins.json`.
74
49
 
75
50
  > [!NOTE]
76
- > Automatic background publishing on headless servers is triggered after completed gateway requests. If a headless machine routes zero traffic through Magpie's gateway (100% direct native agent sessions only), open the plugin page or trigger a refresh to publish those sessions.
51
+ > Background publishing on headless servers triggers after completed gateway requests. If a node routes zero traffic through the gateway, open the plugin page or trigger a refresh once to publish those sessions.
52
+
53
+ ## How it works
54
+
55
+ 1. Each device incrementally pulls its own usage from Magpie's loopback API and publishes sanitized monthly snapshots into its own `<prefix>/<device-id>/` folder — one atomic commit per device, no cross-machine conflicts.
56
+ 2. Any machine aggregates on read: combined and per-device totals, two-tone daily bars, clickable device filters, and tabbed **Agents / Models / Providers** breakdowns. Offline devices keep their last hash-verified cached snapshot, flagged as cached.
77
57
 
78
58
  ## Configuration reference
79
59
 
@@ -121,21 +101,18 @@ Only aggregate counters (`calls`, `errors`, `excludedForwarded`, `input`, `outpu
121
101
  - **Cache hit rate**: `cacheRead / (input + cacheRead + cacheWrite)`, matching Magpie's `Totals.HitRate()`.
122
102
  - **Forwarding deduplication**: Calls with a non-empty `via` field are excluded by default (`filterForwarded: true`) and reported in the `forwarded excluded` counter.
123
103
 
124
- ## Privacy and security guarantees
104
+ ## Privacy and security
125
105
 
126
- - Never asks for or reads Magpie's backup decryption passphrase, `.magpie-backup`, `.magpie-usage`, `providers.json`, `logins.json`, `sync.json`, or `plugin-auth.json`.
127
- - Never writes to `~/.config/magpie/*`; all plugin state, caches, and credentials live in an isolated data directory outside Magpie's configuration folder.
128
- - Never uploads prompts, model responses, provider keys, account emails, or client IPs.
129
- - Re-verifies `private === true` and immutable `repoId` before reads and ref updates, refusing public repositories (`PUBLIC_REPO_REFUSED`).
130
- - Stores GitHub PATs only in `0600` `<dataDir>/credentials.json` (refusing group/world-readable files on POSIX) or `MAGPIE_MULTI_USAGE_GITHUB_TOKEN`, never in `plugins.json`, logs, or API responses.
131
- - Binds the local page service strictly to `127.0.0.1` with loopback `Host`/`Origin`/navigation checks, scoped `Origin: null` sandbox CORS, and a random per-process `X-Multi-Usage-Token` header.
106
+ - Never reads or asks for Magpie's backup decryption passphrase or any credentials, and never writes to `~/.config/magpie`; plugin data lives in its own directory.
107
+ - The relay repository stores only aggregate counters and dimension labels — never prompts, responses, keys, emails, or IPs.
108
+ - PATs are stored only in an environment variable or a `0600`-mode `credentials.json`; the local page listens only on `127.0.0.1`.
132
109
 
133
- ## Troubleshooting
110
+ ## FAQ
134
111
 
135
- - **`PUBLIC_REPO_REFUSED`**: The configured repository is public. Switch to a dedicated private repository.
136
- - **`BRANCH_NOT_FOUND` on Test connection**: Initialize the target branch on GitHub first (for example, add an initial README when creating the repo).
137
- - **Device name shows hostname (e.g. `dev`)**: Set a friendly name in **Settings → Device display name** and click **Save and sync**.
138
- - **Reset local plugin state**: Remove `<dataDir>` (`~/.local/share/magpie-multi-usage` by default); your Magpie history in `~/.config/magpie` is untouched and will re-ingest cleanly on next open.
112
+ - **`PUBLIC_REPO_REFUSED`**: the configured repository is public; switch to a dedicated private one.
113
+ - **`BRANCH_NOT_FOUND` on Test connection**: the target branch isn't initialized yet; create it on GitHub first (for example, add a README when creating the repo).
114
+ - **Device name shows the hostname**: set a friendly name in **Settings → Device display name**, then save and sync.
115
+ - **Want to reset local plugin state**: remove `<dataDir>` (default `~/.local/share/magpie-multi-usage`); Magpie's own data is untouched and re-ingests cleanly on next open.
139
116
 
140
117
  ## Documentation & development
141
118
 
package/README.zh-CN.md CHANGED
@@ -2,32 +2,12 @@
2
2
 
3
3
  [English](README.md) | **简体中文**
4
4
 
5
- 一个面向 [Magpie](https://github.com/yetone/magpie) 的开源、零依赖多端 Token 用量仪表盘插件,以专用私有 GitHub 仓库作为仅承载脱敏统计数据的「中继」——全程不持有 Magpie 备份解密密钥、不写入 `~/.config/magpie`、也不依赖任何外部定时任务。
5
+ 一个面向 [Magpie](https://github.com/yetone/magpie) 的开源、零依赖多端 Token 用量仪表盘插件。适用于在多台配置彼此独立的机器上运行 Magpie 的场景——主工作站、无头服务器、时常离线的笔记本:每台设备将脱敏后的用量计数发布到专用私有 GitHub 仓库,任意一台机器都能查看合并仪表盘,且无需合并配置、暴露网关端口,也不必将 Magpie 的备份解密口令交给第三方插件。
6
6
 
7
7
  ## 特性亮点
8
8
 
9
- - **开箱即用**:即使尚未配置 GitHub 中继,也能立即展示本机的用量数据(包括网关请求,以及 Magpie 发现的原生代理会话,如 Claude Code、OpenCode、Codex 与 Antigravity)。
10
- - **Magpie 原生界面**:与 Magpie 内置 Usage 页面的布局、亮/暗主题及 `--magpie-*` 宿主样式令牌保持一致,并支持在设置中选择英文或中文(`auto` / `en` / `zh`)。
11
- - **独立的多端聚合**:聚合工作站、笔记本与无头 `magpie serve` 节点的数据,且无需跨机器合并配置、提供商或同步目标。
12
- - **零解密口令**:绝不接触 Magpie 备份、凭据或同步密钥;仅通过按设备隔离、互不冲突的 JSON 文件中继脱敏后的聚合计数。
13
- - **纯 ESM、零运行时依赖**:在 Magpie 内置的 Bun 宿主与 Node.js 22+ 上均可干净运行。
14
-
15
- ## 为什么需要这个插件
16
-
17
- Magpie 内置的同步功能支持跨机器共享用量,但要求每台机器绑定同一个同步目标,并在完整配置备份(`.magpie-backup`)与用量文件(`.magpie-usage`)之间共用同一个加密口令。
18
-
19
- 当你在多台配置彼此独立的机器上运行 Magpie —— 例如主工作站、无头服务器以及时常离线的笔记本 —— 本插件可以在完全避免以下事项的前提下,为你提供统一的 Token 用量仪表盘:
20
-
21
- - 跨机器合并配置、提供商或同步目标;
22
- - 暴露 Magpie 网关端口,或依赖 Tailscale、公网 IP、SSH 访问;
23
- - 将 Magpie 的备份解密口令交给第三方插件。
24
-
25
- ## 工作原理
26
-
27
- 1. **从 Magpie 读取本地用量**:增量拉取本机自身的用量数据流,数据来自 Magpie 的回环网关 API(`GET /v1/magpie/usage/requests?computer=this&cursor=...`),同时涵盖网关流量与 Magpie 发现的原生代理会话。
28
- 2. **自动同步无头服务器**:借助 Magpie 的只读异步 `magpie.hooks`(`onResponse`,带防抖),无头 `magpie serve` 节点无需外部定时任务即可自动发布更新。
29
- 3. **原子化发布到专用私有 GitHub 仓库**:通过 Git Data API(带比较交换 ref 更新的单一原子提交),将脱敏后的每月快照与清单写入互不冲突的按设备目录,并在任何读写之前严格拒绝公共仓库。
30
- 4. **在 Magpie 内按读取聚合**:渲染合并与按设备的总量、双色每日用量条形图、可点击的设备筛选行,以及带标签页的 **Agents / Models / Providers** 明细。当远程设备故障或离线时,保留其最后一次通过哈希校验的缓存快照,并标记为缓存数据。
9
+ - **开箱即用**:无需任何配置即可展示本机用量(包括网关请求,以及 Magpie 发现的 Claude Code、OpenCode、Codex 与 Antigravity 会话)。
10
+ - **独立多端聚合**:工作站、笔记本与无头 `magpie serve` 节点借助 Magpie 只读钩子自动发布,无需外部定时任务。
31
11
 
32
12
  ## 安装
33
13
 
@@ -50,30 +30,30 @@ magpie plugin add /path/to/magpie-multi-usage
50
30
 
51
31
  ### 1. 创建专用私有 GitHub 仓库
52
32
 
53
- 新建一个仅用于存放脱敏用量统计的 **Private** GitHub 仓库(例如 `<you>/magpie-usage-stats`),并初始化其默认分支(如附带 README 的 `main`)。
33
+ 新建一个仅用于存放脱敏用量统计的 **Private** 仓库(例如 `<you>/magpie-usage-stats`),并初始化默认分支(如附带 README 的 `main`)。
54
34
 
55
35
  > [!IMPORTANT]
56
36
  > 请**不要**复用 Magpie 配置同步仓库,也**不要**使用公共仓库。本插件在每次读取和 ref 更新前都会校验 `private === true`,并拒绝公共仓库(`PUBLIC_REPO_REFUSED`)。
57
37
 
58
- ### 2. 创建 Fine-grained PAT(细粒度个人访问令牌)
38
+ ### 2. 创建 Fine-grained PAT
59
39
 
60
- 创建一个 GitHub **Fine-grained personal access token**,并将其作用域严格限定为 **Only select repositories → 你的专用统计仓库**:
40
+ 创建 GitHub **细粒度个人访问令牌**,作用域严格限定为 **Only select repositories → 你的专用统计仓库**,权限按用途选择:
61
41
 
62
- - **发布端机器**(工作站或无头服务器):`Contents: Read and write`(GitHub 会自动附带 `Metadata: Read-only`)。
63
- - **只读机器**(可选的只读仪表盘):`Contents: Read-only`(并在设置中取消勾选 **上报本机用量**)。
42
+ - 要上报本机用量的机器:`Contents: Read and write`。
43
+ - 只看汇总、不上报的机器:`Contents: Read-only`,并在设置中关闭 **发布本机用量**。
64
44
 
65
45
  ### 3. 配置每台机器
66
46
 
67
- - **Magpie Desktop / `magpie web`**:
68
- 1. 在 Magpie 侧边栏打开 **Multi-Device Usage**,点击 **设置**(Settings)齿轮图标。
69
- 2. 填写 **本机名称**(Device display name,可选)、**专用私有 GitHub 仓库**(`owner/repo`)与 **GitHub Fine-grained PAT**。
70
- 3. 点击 **测试连接**(Test connection),再点击 **保存并同步**(Save and sync)。
71
- - **无头 `magpie serve` 节点**:
72
- 1. 通过 `magpie plugin options` 设置非敏感选项(`repo`、`deviceName`、`pushEnabled`、`pushIntervalSec`)。
73
- 2. 通过环境变量 `MAGPIE_MULTI_USAGE_GITHUB_TOKEN` 提供 GitHub PAT(或将 `{"githubToken":"..."}` 以严格权限 `0600` 存入 `<dataDir>/credentials.json`)。切勿将 PAT 以明文形式写入 `plugins.json`。
47
+ - **Magpie 桌面 / `magpie web`**:打开 **多端用量** → **设置**齿轮 → 填写 **设备显示名**(可选)、**私有 GitHub 仓库**(`owner/repo`)与 **PAT** → **测试连接** → **保存并同步**。
48
+ - **无头 `magpie serve` 节点**:通过 `magpie plugin options` 设置非敏感项(`repo`、`deviceName`、`pushEnabled`、`pushIntervalSec`),PAT 通过环境变量 `MAGPIE_MULTI_USAGE_GITHUB_TOKEN`(或 `0600` 权限的 `<dataDir>/credentials.json`)提供——绝不写入明文 `plugins.json`。
74
49
 
75
50
  > [!NOTE]
76
- > 无头服务器上的自动后台发布由已完成的网关请求触发。如果某台无头机器没有任何流量经过 Magpie 网关(100% 为直接的原生代理会话),请打开插件页面或手动触发刷新来发布这些会话。
51
+ > 无头服务器的后台发布由完成的网关请求触发。若某节点没有任何流量经过网关,打开插件页面或手动刷新一次即可发布这些会话。
52
+
53
+ ## 工作原理
54
+
55
+ 1. 每台设备增量拉取自身用量(Magpie 回环 API),并将脱敏后的每月快照发布到仓库中自己的 `<prefix>/<device-id>/` 目录——每设备一次原子提交,互不冲突。
56
+ 2. 任意机器按读取聚合:合并与按设备总量、双色每日条形图、可点击的设备筛选、**Agents / Models / Providers** 标签页明细;离线设备保留最后一次通过哈希校验的缓存快照并标记为缓存。
77
57
 
78
58
  ## 配置参考
79
59
 
@@ -82,67 +62,64 @@ magpie plugin add /path/to/magpie-multi-usage
82
62
  | 字段 | 默认值 | 说明 |
83
63
  | --- | --- | --- |
84
64
  | `lang` | `"auto"` | 界面语言(`auto`、`en` 或 `zh`),持久化于 `<dataDir>/config.json`。 |
85
- | `deviceName` | `""` | 本机的自定义显示名称。未设置时依次回退到 Magpie 的 `usage-computer.json` 名称、操作系统主机名、设备 ID。 |
65
+ | `deviceName` | `""` | 本机自定义标签。缺省时依次回退到 Magpie `usage-computer.json` 的名称、OS 主机名、设备 ID。 |
86
66
  | `repo` | `""` | 专用私有 GitHub 仓库,`owner/repo` 格式。 |
87
- | `branch` | `""` | 可选的目标分支(默认使用仓库的默认分支)。 |
88
- | `prefix` | `"devices"` | 仓库内的文件夹前缀(`<prefix>/<device-id>/...`)。 |
89
- | `pushEnabled` | `true` | 将本机的脱敏快照发布到中继仓库。禁用后即为只读查看模式。 |
90
- | `pushIntervalSec` | `300` | 自动 hook 触发推送之间的最小防抖间隔(秒,`30`–`86400`)。 |
91
- | `filterForwarded` | `true` | 排除跨 Magpie 转发的调用(`via !== ""`),避免两端同时上报时重复计数。 |
67
+ | `branch` | `""` | 可选目标分支(默认为仓库默认分支)。 |
68
+ | `prefix` | `"devices"` | 仓库内目录前缀(`<prefix>/<device-id>/...`)。 |
69
+ | `pushEnabled` | `true` | 将本机脱敏快照发布到中继仓库。关闭即为只读查看模式。 |
70
+ | `pushIntervalSec` | `300` | 钩子触发的自动推送之间的最小防抖间隔(秒,`30`–`86400`)。 |
71
+ | `filterForwarded` | `true` | 排除跨 Magpie 转发的调用(`via !== ""`),防止双端同时上报时重复计数。 |
92
72
  | `port` | `18792` | 本地页面服务的回环端口(`127.0.0.1`)。 |
93
- | `dataDir` | `""` | 可选的插件隔离数据目录覆盖项。 |
73
+ | `dataDir` | `""` | 可选:覆盖插件独立数据目录。 |
94
74
 
95
75
  ### 环境变量
96
76
 
97
77
  | 变量 | 说明 |
98
78
  | --- | --- |
99
- | `MAGPIE_MULTI_USAGE_GITHUB_TOKEN` | Fine-grained GitHub PAT(优先级高于 `<dataDir>/credentials.json`)。 |
100
- | `MAGPIE_MULTI_USAGE_DATA_DIR` | 覆盖插件数据目录(默认:POSIX 下为 `$XDG_DATA_HOME/magpie-multi-usage` 或 `~/.local/share/magpie-multi-usage`;Windows 下为 `%LOCALAPPDATA%\magpie-multi-usage`)。 |
101
- | `MAGPIE_ADDR` | 可选的 Magpie 网关回环地址(依次回退到只读的 `<magpieConfigDir>/settings.json`、`http://127.0.0.1:3425`)。 |
79
+ | `MAGPIE_MULTI_USAGE_GITHUB_TOKEN` | 细粒度 GitHub PAT(优先级高于 `<dataDir>/credentials.json`)。 |
80
+ | `MAGPIE_MULTI_USAGE_DATA_DIR` | 覆盖插件数据目录(默认:POSIX 为 `$XDG_DATA_HOME/magpie-multi-usage` 或 `~/.local/share/magpie-multi-usage`;Windows 为 `%LOCALAPPDATA%\magpie-multi-usage`)。 |
81
+ | `MAGPIE_ADDR` | 可选的回环 Magpie 网关地址(缺省时依次读取只读的 `<magpieConfigDir>/settings.json`,再回退 `http://127.0.0.1:3425`)。 |
102
82
  | `MAGPIE_CONFIG_DIR` | 可选的只读 Magpie 配置目录路径。 |
103
83
 
104
- ## 中继仓库结构
84
+ ## 中继仓库布局
105
85
 
106
- 每台设备在单一原子提交中只写入自己的 `<prefix>/<device-id>/` 目录,从根源上消除跨机器的合并冲突:
86
+ 每台设备只写入自己专属的 `<prefix>/<device-id>/` 目录(单一原子提交),互不冲突:
107
87
 
108
88
  ```text
109
89
  devices/
110
90
  └── <device-id>/
111
- ├── manifest.json # device metadata, coverage window, and SHA-256 hash per month
112
- ├── 2026-10.json # sanitized daily & model/agent/provider aggregate counters
91
+ ├── manifest.json # 设备元数据、覆盖窗口与每月 SHA-256 哈希
92
+ ├── 2026-10.json # 脱敏后的每日与 model/agent/provider 聚合计数
113
93
  └── 2026-11.json
114
94
  ```
115
95
 
116
- 仅存储聚合计数(`calls`、`errors`、`excludedForwarded`、`input`、`output`、`cacheRead`、`cacheWrite`、`cost`)与维度标签(`model`、`agent`、`provider`)——绝不存储提示词、响应、请求头、密钥或 IP 地址。
96
+ 仅存储聚合计数(`calls`、`errors`、`excludedForwarded`、`input`、`output`、`cacheRead`、`cacheWrite`、`cost`)与维度标签(`model`、`agent`、`provider`)——绝不存储提示词、响应、请求头、密钥或 IP。
117
97
 
118
- ## Token 计量
98
+ ## Token 计算
119
99
 
120
- - **总 Token 数**:`input + output + cacheRead + cacheWrite`(缓存 Token 不会在 `input` 中重复计入)。
121
- - **缓存命中率**:`cacheRead / (input + cacheRead + cacheWrite)`,与 Magpie 的 `Totals.HitRate()` 保持一致。
122
- - **转发去重**:默认排除 `via` 字段非空的调用(`filterForwarded: true`),并在 `forwarded excluded` 计数器中报告。
100
+ - **总 Token**:`input + output + cacheRead + cacheWrite`(缓存 Token 不会在 `input` 中重复计入)。
101
+ - **缓存命中率**:`cacheRead / (input + cacheRead + cacheWrite)`,与 Magpie 的 `Totals.HitRate()` 一致。
102
+ - **转发去重**:默认排除 `via` 字段非空的调用(`filterForwarded: true`),并在 `forwarded excluded` 计数中体现。
123
103
 
124
- ## 隐私与安全保证
104
+ ## 隐私与安全
125
105
 
126
- - 绝不请求或读取 Magpie 的备份解密口令、`.magpie-backup`、`.magpie-usage`、`providers.json`、`logins.json`、`sync.json` 或 `plugin-auth.json`。
127
- - 绝不写入 `~/.config/magpie/*`;所有插件状态、缓存与凭据均存放在 Magpie 配置目录之外的隔离数据目录中。
128
- - 绝不上传提示词、模型响应、提供商密钥、账户邮箱或客户端 IP。
129
- - 在读取和 ref 更新前重新校验 `private === true` 与不可变的 `repoId`,拒绝公共仓库(`PUBLIC_REPO_REFUSED`)。
130
- - GitHub PAT 仅存储于权限为 `0600` 的 `<dataDir>/credentials.json`(POSIX 下拒绝组/其他用户可读的文件)或 `MAGPIE_MULTI_USAGE_GITHUB_TOKEN`,绝不进入 `plugins.json`、日志或 API 响应。
131
- - 本地页面服务严格绑定 `127.0.0.1`,执行回环 `Host`/`Origin`/导航校验、限定范围的 `Origin: null` 沙箱 CORS,以及每进程随机的 `X-Multi-Usage-Token` 请求头。
106
+ - 不读取、也不索要 Magpie 的备份解密口令或任何凭据,不写 `~/.config/magpie`;插件数据存放在独立目录。
107
+ - 中继仓库只存聚合计数与维度标签,不含提示词、响应、密钥、邮箱或 IP。
108
+ - PAT 只存于环境变量或 `0600` 权限的 `credentials.json`;本地页面仅监听 `127.0.0.1`。
132
109
 
133
- ## 故障排查
110
+ ## 常见问题
134
111
 
135
- - **`PUBLIC_REPO_REFUSED`**:配置的仓库为公共仓库。请改用专用私有仓库。
136
- - **测试连接(Test connection)时报 `BRANCH_NOT_FOUND`**:请先在 GitHub 上初始化目标分支(例如建仓库时附带初始 README)。
137
- - **设备名显示为主机名(如 `dev`)**:在 **设置 → 本机名称**(Settings → Device display name)中设置友好名称,然后点击 **保存并同步**(Save and sync)。
138
- - **重置本地插件状态**:删除 `<dataDir>`(默认为 `~/.local/share/magpie-multi-usage`);`~/.config/magpie` 中的 Magpie 历史记录不受影响,下次打开时会干净地重新导入。
112
+ - **提示 `PUBLIC_REPO_REFUSED`**:配置的是公共仓库,请改用专用私有仓库。
113
+ - **测试连接提示 `BRANCH_NOT_FOUND`**:目标分支还没初始化,请先在 GitHub 上建好(例如建仓时附带 README)。
114
+ - **设备名显示成主机名**:在 **设置 → 设备显示名** 里填一个名字,再保存并同步。
115
+ - **想清空插件本地数据重来**:删除 `<dataDir>`(默认 `~/.local/share/magpie-multi-usage`)即可,Magpie 自身数据不受影响。
139
116
 
140
117
  ## 文档与开发
141
118
 
142
119
  - 架构与文件索引:[docs/code-map.md](docs/code-map.md)
143
120
  - 工程与安全规范:[docs/code-standards.md](docs/code-standards.md)
144
121
 
145
- 所有测试完全离线运行,基于隔离的临时目录与本地 HTTP 固定测试数据:
122
+ 所有测试完全离线运行,基于隔离的临时目录与本地 HTTP fixtures:
146
123
 
147
124
  ```bash
148
125
  HOME=$(mktemp -d) node --test test/*.test.mjs
@@ -151,4 +128,4 @@ HOME=$(mktemp -d) bun test test/
151
128
 
152
129
  ## 许可证
153
130
 
154
- MIT 许可证 —— 详见 [LICENSE](LICENSE)。
131
+ MIT 许可证——见 [LICENSE](LICENSE)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magpie-multi-usage",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Multi-device token usage dashboard plugin for Magpie using a dedicated private GitHub repository relay (no decryption passphrase required).",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -361,7 +361,7 @@ export function buildDeviceManifest({
361
361
  deviceId,
362
362
  displayName,
363
363
  platform = process.platform,
364
- pluginVersion = "0.1.0",
364
+ pluginVersion = "0.1.2",
365
365
  revision = 1,
366
366
  updatedAt = new Date().toISOString(),
367
367
  snapshots = [],
@@ -224,7 +224,7 @@ export function createGitHubRelayStore({
224
224
  apiBaseUrl = DEFAULT_API_BASE_URL,
225
225
  fetchImpl = globalThis.fetch,
226
226
  timeoutMs = 15000,
227
- pluginVersion = "0.1.0",
227
+ pluginVersion = "0.1.2",
228
228
  } = {}) {
229
229
  const normalizedRepo = normalizeRepo(repo);
230
230
  if (!normalizedRepo) {
@@ -19,7 +19,7 @@ import { createSyncEngine } from "./sync-engine.mjs";
19
19
 
20
20
  export const TOKEN_HEADER = "x-multi-usage-token";
21
21
  export const DEFAULT_PORT = DEFAULT_CONFIG.port;
22
- export const PLUGIN_VERSION = "0.1.0";
22
+ export const PLUGIN_VERSION = "0.1.2";
23
23
 
24
24
  const MAX_JSON_BODY_BYTES = 256 * 1024;
25
25
  const ALLOWED_RANGES = new Set(["today", "7d", "30d", "all"]);
@@ -385,8 +385,17 @@ export async function startHttpServer({
385
385
  ? template.replace("<!--MULTI_USAGE_BOOTSTRAP-->", bootstrapTag)
386
386
  : template.replace("</head>", `${bootstrapTag}\n</head>`);
387
387
 
388
+ // WebKit can fail to match 'self' inside Magpie's opaque-origin iframe.
389
+ // The Host header has already passed the loopback host allowlist.
390
+ const loopbackOrigin = `http://${req.headers.host.trim().toLowerCase()}`;
388
391
  sendResponse(res, 200, "text/html; charset=utf-8", html, {
389
- "Content-Security-Policy": `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'`,
392
+ "Content-Security-Policy": [
393
+ "default-src 'self'",
394
+ `script-src 'self' ${loopbackOrigin} 'nonce-${nonce}'`,
395
+ `style-src 'self' ${loopbackOrigin} 'unsafe-inline'`,
396
+ "img-src 'self' data:",
397
+ `connect-src 'self' ${loopbackOrigin}`,
398
+ ].join("; "),
390
399
  });
391
400
  return;
392
401
  }
@@ -160,7 +160,7 @@ export function createSyncEngine({
160
160
  fetchImpl = globalThis.fetch,
161
161
  apiBaseUrl,
162
162
  gatewayBaseUrl,
163
- pluginVersion = "0.1.0",
163
+ pluginVersion = "0.1.2",
164
164
  timeZone,
165
165
  now = () => Date.now(),
166
166
  storeFactory = createGitHubRelayStore,