magpie-multi-usage 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 haoyuqi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,154 @@
1
- # Temporary Holding Version
1
+ # magpie-multi-usage
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **English** | [简体中文](README.zh-CN.md)
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.
6
+
7
+ ## Highlights
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.
31
+
32
+ ## Installation
33
+
34
+ Install directly from GitHub via Magpie's CLI:
35
+
36
+ ```bash
37
+ magpie plugin add github:haoyuqi/magpie-multi-usage
38
+ ```
39
+
40
+ Or install from a local clone:
41
+
42
+ ```bash
43
+ git clone https://github.com/haoyuqi/magpie-multi-usage.git
44
+ magpie plugin add /path/to/magpie-multi-usage
45
+ ```
46
+
47
+ Open **Multi-Device Usage** (**多端用量**) in the Magpie sidebar — local usage loads automatically with zero setup.
48
+
49
+ ## Multi-device relay setup
50
+
51
+ ### 1. Create a dedicated private GitHub repository
52
+
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).
54
+
55
+ > [!IMPORTANT]
56
+ > 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
+
58
+ ### 2. Create a Fine-grained GitHub PAT
59
+
60
+ Create a GitHub **Fine-grained personal access token** scoped strictly to **Only select repositories → your dedicated stats repo**:
61
+
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).
64
+
65
+ ### 3. Configure each machine
66
+
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`.
74
+
75
+ > [!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.
77
+
78
+ ## Configuration reference
79
+
80
+ ### Settings & plugin options
81
+
82
+ | Field | Default | Description |
83
+ | --- | --- | --- |
84
+ | `lang` | `"auto"` | UI language (`auto`, `en`, or `zh`), persisted in `<dataDir>/config.json`. |
85
+ | `deviceName` | `""` | Custom label for this machine. Falls back to Magpie's `usage-computer.json` name, then OS hostname, then device ID. |
86
+ | `repo` | `""` | Dedicated private GitHub repository in `owner/repo` format. |
87
+ | `branch` | `""` | Optional target branch (defaults to the repository's default branch). |
88
+ | `prefix` | `"devices"` | Folder prefix inside the repository (`<prefix>/<device-id>/...`). |
89
+ | `pushEnabled` | `true` | Publish this machine's sanitized snapshots to the relay repo. Disable for read-only viewer mode. |
90
+ | `pushIntervalSec` | `300` | Minimum debounce interval (seconds, `30`–`86400`) between automatic hook-triggered pushes. |
91
+ | `filterForwarded` | `true` | Exclude cross-Magpie forwarded calls (`via !== ""`) to prevent double-counting when both nodes report. |
92
+ | `port` | `18792` | Loopback port for the local page service (`127.0.0.1`). |
93
+ | `dataDir` | `""` | Optional override for the plugin's isolated data directory. |
94
+
95
+ ### Environment variables
96
+
97
+ | Variable | Description |
98
+ | --- | --- |
99
+ | `MAGPIE_MULTI_USAGE_GITHUB_TOKEN` | Fine-grained GitHub PAT (takes precedence over `<dataDir>/credentials.json`). |
100
+ | `MAGPIE_MULTI_USAGE_DATA_DIR` | Override plugin data directory (default: `$XDG_DATA_HOME/magpie-multi-usage` or `~/.local/share/magpie-multi-usage` on POSIX; `%LOCALAPPDATA%\magpie-multi-usage` on Windows). |
101
+ | `MAGPIE_ADDR` | Optional loopback Magpie gateway address (falls back to read-only `<magpieConfigDir>/settings.json`, then `http://127.0.0.1:3425`). |
102
+ | `MAGPIE_CONFIG_DIR` | Optional read-only Magpie configuration directory path. |
103
+
104
+ ## Relay repository layout
105
+
106
+ Each device writes exclusively under its own `<prefix>/<device-id>/` folder in a single atomic commit, eliminating cross-machine merge conflicts:
107
+
108
+ ```text
109
+ devices/
110
+ └── <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
113
+ └── 2026-11.json
114
+ ```
115
+
116
+ Only aggregate counters (`calls`, `errors`, `excludedForwarded`, `input`, `output`, `cacheRead`, `cacheWrite`, `cost`) and dimension labels (`model`, `agent`, `provider`) are stored — never prompts, responses, headers, keys, or IPs.
117
+
118
+ ## Token accounting
119
+
120
+ - **Total tokens**: `input + output + cacheRead + cacheWrite` (cache tokens are never double-counted inside `input`).
121
+ - **Cache hit rate**: `cacheRead / (input + cacheRead + cacheWrite)`, matching Magpie's `Totals.HitRate()`.
122
+ - **Forwarding deduplication**: Calls with a non-empty `via` field are excluded by default (`filterForwarded: true`) and reported in the `forwarded excluded` counter.
123
+
124
+ ## Privacy and security guarantees
125
+
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.
132
+
133
+ ## Troubleshooting
134
+
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.
139
+
140
+ ## Documentation & development
141
+
142
+ - Architecture and file index: [docs/code-map.md](docs/code-map.md)
143
+ - Engineering and security standards: [docs/code-standards.md](docs/code-standards.md)
144
+
145
+ All tests run completely offline against isolated temporary directories and local HTTP fixtures:
146
+
147
+ ```bash
148
+ HOME=$(mktemp -d) node --test test/*.test.mjs
149
+ HOME=$(mktemp -d) bun test test/
150
+ ```
151
+
152
+ ## License
153
+
154
+ MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,154 @@
1
+ # magpie-multi-usage
2
+
3
+ [English](README.md) | **简体中文**
4
+
5
+ 一个面向 [Magpie](https://github.com/yetone/magpie) 的开源、零依赖多端 Token 用量仪表盘插件,以专用私有 GitHub 仓库作为仅承载脱敏统计数据的「中继」——全程不持有 Magpie 备份解密密钥、不写入 `~/.config/magpie`、也不依赖任何外部定时任务。
6
+
7
+ ## 特性亮点
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** 明细。当远程设备故障或离线时,保留其最后一次通过哈希校验的缓存快照,并标记为缓存数据。
31
+
32
+ ## 安装
33
+
34
+ 通过 Magpie 的 CLI 直接从 GitHub 安装:
35
+
36
+ ```bash
37
+ magpie plugin add github:haoyuqi/magpie-multi-usage
38
+ ```
39
+
40
+ 或从本地克隆安装:
41
+
42
+ ```bash
43
+ git clone https://github.com/haoyuqi/magpie-multi-usage.git
44
+ magpie plugin add /path/to/magpie-multi-usage
45
+ ```
46
+
47
+ 在 Magpie 侧边栏打开 **Multi-Device Usage**(**多端用量**)——本地用量零配置自动加载。
48
+
49
+ ## 多端中继配置
50
+
51
+ ### 1. 创建专用私有 GitHub 仓库
52
+
53
+ 新建一个仅用于存放脱敏用量统计的 **Private** GitHub 仓库(例如 `<you>/magpie-usage-stats`),并初始化其默认分支(如附带 README 的 `main`)。
54
+
55
+ > [!IMPORTANT]
56
+ > 请**不要**复用 Magpie 配置同步仓库,也**不要**使用公共仓库。本插件在每次读取和 ref 更新前都会校验 `private === true`,并拒绝公共仓库(`PUBLIC_REPO_REFUSED`)。
57
+
58
+ ### 2. 创建 Fine-grained PAT(细粒度个人访问令牌)
59
+
60
+ 创建一个 GitHub **Fine-grained personal access token**,并将其作用域严格限定为 **Only select repositories → 你的专用统计仓库**:
61
+
62
+ - **发布端机器**(工作站或无头服务器):`Contents: Read and write`(GitHub 会自动附带 `Metadata: Read-only`)。
63
+ - **只读机器**(可选的只读仪表盘):`Contents: Read-only`(并在设置中取消勾选 **上报本机用量**)。
64
+
65
+ ### 3. 配置每台机器
66
+
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`。
74
+
75
+ > [!NOTE]
76
+ > 无头服务器上的自动后台发布由已完成的网关请求触发。如果某台无头机器没有任何流量经过 Magpie 网关(100% 为直接的原生代理会话),请打开插件页面或手动触发刷新来发布这些会话。
77
+
78
+ ## 配置参考
79
+
80
+ ### 设置与插件选项
81
+
82
+ | 字段 | 默认值 | 说明 |
83
+ | --- | --- | --- |
84
+ | `lang` | `"auto"` | 界面语言(`auto`、`en` 或 `zh`),持久化于 `<dataDir>/config.json`。 |
85
+ | `deviceName` | `""` | 本机的自定义显示名称。未设置时依次回退到 Magpie 的 `usage-computer.json` 名称、操作系统主机名、设备 ID。 |
86
+ | `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 !== ""`),避免两端同时上报时重复计数。 |
92
+ | `port` | `18792` | 本地页面服务的回环端口(`127.0.0.1`)。 |
93
+ | `dataDir` | `""` | 可选的插件隔离数据目录覆盖项。 |
94
+
95
+ ### 环境变量
96
+
97
+ | 变量 | 说明 |
98
+ | --- | --- |
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`)。 |
102
+ | `MAGPIE_CONFIG_DIR` | 可选的只读 Magpie 配置目录路径。 |
103
+
104
+ ## 中继仓库结构
105
+
106
+ 每台设备在单一原子提交中只写入自己的 `<prefix>/<device-id>/` 目录,从根源上消除跨机器的合并冲突:
107
+
108
+ ```text
109
+ devices/
110
+ └── <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
113
+ └── 2026-11.json
114
+ ```
115
+
116
+ 仅存储聚合计数(`calls`、`errors`、`excludedForwarded`、`input`、`output`、`cacheRead`、`cacheWrite`、`cost`)与维度标签(`model`、`agent`、`provider`)——绝不存储提示词、响应、请求头、密钥或 IP 地址。
117
+
118
+ ## Token 计量
119
+
120
+ - **总 Token 数**:`input + output + cacheRead + cacheWrite`(缓存 Token 不会在 `input` 中重复计入)。
121
+ - **缓存命中率**:`cacheRead / (input + cacheRead + cacheWrite)`,与 Magpie 的 `Totals.HitRate()` 保持一致。
122
+ - **转发去重**:默认排除 `via` 字段非空的调用(`filterForwarded: true`),并在 `forwarded excluded` 计数器中报告。
123
+
124
+ ## 隐私与安全保证
125
+
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` 请求头。
132
+
133
+ ## 故障排查
134
+
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 历史记录不受影响,下次打开时会干净地重新导入。
139
+
140
+ ## 文档与开发
141
+
142
+ - 架构与文件索引:[docs/code-map.md](docs/code-map.md)
143
+ - 工程与安全规范:[docs/code-standards.md](docs/code-standards.md)
144
+
145
+ 所有测试完全离线运行,基于隔离的临时目录与本地 HTTP 固定测试数据:
146
+
147
+ ```bash
148
+ HOME=$(mktemp -d) node --test test/*.test.mjs
149
+ HOME=$(mktemp -d) bun test test/
150
+ ```
151
+
152
+ ## 许可证
153
+
154
+ MIT 许可证 —— 详见 [LICENSE](LICENSE)。
package/hooks.mjs ADDED
@@ -0,0 +1,31 @@
1
+ import { getSharedSyncEngine } from "./src/sync-engine.mjs";
2
+
3
+ /**
4
+ * Strict no-op pass-through request hook.
5
+ *
6
+ * Magpie's Bun plugin host requires magpie.hooks modules to export onRequest
7
+ * (or onSignIn) in order to load the plugin and register it for onResponse
8
+ * notifications. Returning undefined preserves the request untouched with zero
9
+ * mutation and zero added latency.
10
+ */
11
+ export function onRequest() {
12
+ return undefined;
13
+ }
14
+
15
+ /**
16
+ * Read-only asynchronous Magpie gateway hook for headless auto-sync.
17
+ *
18
+ * Triggers a debounced background push via the shared SyncEngine without
19
+ * requiring the local HTTP server to have been started. Never throws or blocks.
20
+ */
21
+ export async function onResponse(_completedReply, ctx = {}) {
22
+ try {
23
+ const engine = getSharedSyncEngine({
24
+ optionDataDir: ctx?.options?.dataDir || "",
25
+ defaults: ctx?.options || {},
26
+ });
27
+ engine.scheduleDebouncedPush();
28
+ } catch {
29
+ // Never throw from a read-only response hook.
30
+ }
31
+ }
package/index.mjs ADDED
@@ -0,0 +1,103 @@
1
+ import { DEFAULT_CONFIG, resolveDataDir } from "./src/config.mjs";
2
+ import { DEFAULT_PORT, startHttpServer } from "./src/http-server.mjs";
3
+ import { getSharedSyncEngine } from "./src/sync-engine.mjs";
4
+
5
+ let startedPromise = null;
6
+ let activeHandle = null;
7
+
8
+ function resolveServicePort(options) {
9
+ const candidate = Number(options?.port);
10
+ if (Number.isInteger(candidate) && candidate >= 0 && candidate <= 65535) {
11
+ return candidate;
12
+ }
13
+ return DEFAULT_PORT;
14
+ }
15
+
16
+ /**
17
+ * Lazily start the local loopback HTTP service once when invoked by Magpie's
18
+ * plugin host. Importing this module never opens a listening socket.
19
+ *
20
+ * Note: Magpie passes settings.Dir() (e.g. ~/.config/magpie) as input.directory.
21
+ * We treat input.directory strictly as read-only magpieConfigDir and keep all
22
+ * plugin writes inside the dedicated isolated dataDir shared with hooks.mjs.
23
+ */
24
+ export function startPluginServer(input = {}, options = {}) {
25
+ if (!startedPromise) {
26
+ startedPromise = (async () => {
27
+ const magpieConfigDir = typeof input?.directory === "string" && input.directory.trim()
28
+ ? input.directory.trim()
29
+ : undefined;
30
+ const dataDir = resolveDataDir({
31
+ optionDataDir: options?.dataDir || "",
32
+ });
33
+ const port = resolveServicePort(options);
34
+ const { port: _optPort, dataDir: _optDataDir, ...nonServiceOptions } = options || {};
35
+ const mergedDefaults = {
36
+ ...DEFAULT_CONFIG,
37
+ ...nonServiceOptions,
38
+ ...(port >= 1024 && port <= 65535 ? { port } : {}),
39
+ };
40
+ const engine = getSharedSyncEngine({
41
+ dataDir,
42
+ magpieConfigDir,
43
+ defaults: mergedDefaults,
44
+ });
45
+ const handle = await startHttpServer({
46
+ port,
47
+ dataDir,
48
+ magpieConfigDir,
49
+ defaults: mergedDefaults,
50
+ engine,
51
+ });
52
+ activeHandle = handle;
53
+
54
+ // Observe terminal background bind failures so they never become
55
+ // unhandled rejections and never leave a dead singleton handle cached.
56
+ handle.ready.then(
57
+ (boundPort) => {
58
+ if (boundPort === null && activeHandle === handle) {
59
+ activeHandle = null;
60
+ startedPromise = null;
61
+ }
62
+ },
63
+ () => {
64
+ if (activeHandle === handle) {
65
+ activeHandle = null;
66
+ startedPromise = null;
67
+ }
68
+ },
69
+ );
70
+
71
+ return handle;
72
+ })().catch((err) => {
73
+ activeHandle = null;
74
+ startedPromise = null;
75
+ throw err;
76
+ });
77
+ }
78
+ return startedPromise;
79
+ }
80
+
81
+ /**
82
+ * Stop any active plugin HTTP server (used by tests for clean teardown).
83
+ */
84
+ export async function stopPluginServerForTests() {
85
+ const handle = activeHandle;
86
+ activeHandle = null;
87
+ startedPromise = null;
88
+ if (handle) {
89
+ await handle.close();
90
+ }
91
+ }
92
+
93
+ export default {
94
+ id: "magpie-multi-usage",
95
+ server: async (input = {}, options = {}) => {
96
+ try {
97
+ await startPluginServer(input, options);
98
+ } catch {
99
+ // Never crash Magpie plugin host on startup failure.
100
+ }
101
+ return {};
102
+ },
103
+ };
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "magpie-multi-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Multi-device token usage dashboard plugin for Magpie using a dedicated private GitHub repository relay (no decryption passphrase required).",
5
+ "type": "module",
6
+ "main": "./index.mjs",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/haoyuqi/magpie-multi-usage.git"
11
+ },
12
+ "homepage": "https://github.com/haoyuqi/magpie-multi-usage#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/haoyuqi/magpie-multi-usage/issues"
15
+ },
16
+ "keywords": [
17
+ "magpie",
18
+ "magpie-plugin",
19
+ "magpie-page",
20
+ "token-usage",
21
+ "multi-device",
22
+ "usage-dashboard"
23
+ ],
24
+ "files": [
25
+ "index.mjs",
26
+ "hooks.mjs",
27
+ "page",
28
+ "src",
29
+ "README.md",
30
+ "README.zh-CN.md",
31
+ "LICENSE"
32
+ ],
33
+ "magpie": {
34
+ "name": "Multi-Device Usage",
35
+ "summary": {
36
+ "en": "Aggregate token usage across multiple Magpie machines via a dedicated private GitHub stats repository — no backup decryption passphrase, no config merging, headless-friendly.",
37
+ "zh": "通过专用私有 GitHub 统计仓库汇总多台 Magpie 设备的 Token 用量——无需备份解密口令、不合并配置、支持无头服务器与离线多端。"
38
+ },
39
+ "hooks": "./hooks.mjs",
40
+ "page": {
41
+ "title": "Multi-Device Usage",
42
+ "titles": {
43
+ "en": "Multi-Device Usage",
44
+ "zh": "多端用量",
45
+ "zh-TW": "多端用量"
46
+ },
47
+ "file": "page/index.html",
48
+ "icon": "page/icon.svg",
49
+ "service": {
50
+ "port": 18792,
51
+ "option": "port"
52
+ }
53
+ },
54
+ "permissions": [],
55
+ "options": {
56
+ "port": 18792,
57
+ "dataDir": "",
58
+ "deviceName": "",
59
+ "repo": "",
60
+ "branch": "",
61
+ "prefix": "devices",
62
+ "pushEnabled": true,
63
+ "pushIntervalSec": 300,
64
+ "filterForwarded": true
65
+ }
66
+ },
67
+ "scripts": {
68
+ "test": "node --test test/*.test.mjs"
69
+ }
70
+ }