magpie-tokentracker 0.0.0-stage → 0.2.1
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 +21 -0
- package/README.md +143 -2
- package/index.mjs +57 -0
- package/lib/official.mjs +47 -0
- package/lib/tokentracker.mjs +172 -0
- package/lib/usage.mjs +476 -0
- package/package.json +67 -4
- package/page/app.js +591 -0
- package/page/board.html +115 -0
- package/page/boot.js +177 -0
- package/page/icon.svg +8 -0
- package/page/index.html +40 -0
- package/page/style.css +481 -0
- package/server.mjs +570 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 jerryjiao
|
|
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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# magpie-tokentracker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/magpie-tokentracker)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
[](https://www.npmjs.com/package/magpie-tokentracker)
|
|
6
|
+
|
|
7
|
+
在 magpie 窗口里追踪本机 [TokenTracker](https://github.com/xiufengsun/TokenTracker) 的 AI 用量:今天 / 7 天 / 30 天的 token 用量、花费、缓存命中、会话数,按编程工具和模型拆分,带小时级与每日趋势;另有订阅配额、近一年活动热力图、成就徽章,以及官方账号 / 云同步入口。零依赖。
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
## 安装(发布后,从 npm)
|
|
12
|
+
|
|
13
|
+
npm 包发布后,一条命令安装:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
magpie plugin add magpie-tokentracker
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
> 截至本文更新,npm 包尚未发布。当前本地开发安装方式见下文[「本地安装(开发中)」](#本地安装开发中)。
|
|
20
|
+
|
|
21
|
+
## 结构
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
index.mjs magpie 宿主入口:server(input, options),懒启动服务
|
|
25
|
+
server.mjs 零依赖 node:http 服务(只绑 127.0.0.1)
|
|
26
|
+
lib/usage.mjs 纯函数:周期换算、卡片/拆分/序列整理
|
|
27
|
+
lib/tokentracker.mjs TokenTracker 探活、自动拉起、API 调用
|
|
28
|
+
page/index.html magpie 托管的带路页(bridge → 导航到本机服务)
|
|
29
|
+
page/boot.js 读 bridge(语言/主题/端口/magpie.service)后跳转
|
|
30
|
+
page/board.html|app.js|style.css 看板本体(服务端拼成全内联单页,见「注意」)
|
|
31
|
+
test/*.test.mjs 28 个测试(node --test)
|
|
32
|
+
test/fixtures/ 从真实 TokenTracker 接口抓的样例
|
|
33
|
+
docs/ 设计规范、发布文档(不进 npm 包)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## 本地安装(开发中)
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
magpie plugin add /Users/mac/Documents/projects/magpie-tokentracker
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
装完后 magpie 窗口侧栏的 Plugins 组里出现「TokenTracker」页。
|
|
43
|
+
|
|
44
|
+
**本地路径安装的坑(2026-11-17 白屏事故)**:magpie 的页面文件(`magpie.page.file`)只从插件库 `~/.config/magpie/plugins/node_modules/<name>/` 下发;`plugin add <本地路径>` 只注册 spec、执行服务代码,但不拷 page 文件 → 页面 tab 永远白屏(服务其实是活的)。本地开发二选一:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
# A. 软链进插件库(本机用的就是这种)
|
|
48
|
+
ln -sfn "$PWD" ~/.config/magpie/plugins/node_modules/magpie-tokentracker
|
|
49
|
+
|
|
50
|
+
# B. 发 npm 包后 `magpie plugin add magpie-tokentracker`
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
装完(或第一次建好软链后)**要重启 magpie app**:桌面 app 只在启动时索引插件库,不重启它认不到新 page。验证:重启后 app.log 里出现 `plugin: [magpie-tokentracker] board on ...`。
|
|
54
|
+
|
|
55
|
+
## 依赖
|
|
56
|
+
|
|
57
|
+
本机要有 TokenTracker 在 `127.0.0.1:7680`(官方 CLI 的 `serve`)。没有也没关系:服务第一次被问到用量时会自动拉起(见下面的选项),拉不起来时页面显示离线提示和命令。
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
npx tokentracker serve # 或 tokentracker serve
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## 选项(magpie → Plugins → TokenTracker 的 options)
|
|
64
|
+
|
|
65
|
+
| 键 | 默认 | 说明 |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `port` | `3491` | 看板服务的端口(`0` = 随机,测试用) |
|
|
68
|
+
| `tokentrackerPort` | `7680` | TokenTracker 的端口 |
|
|
69
|
+
| `autoStart` | `true` | 探活失败时自动 `spawn` TokenTracker |
|
|
70
|
+
| `command` | `""` | 拉起用的命令;空 = PATH 里的 `tokentracker`,再退到 `npx -y tokentracker-cli` |
|
|
71
|
+
| `timeZone` | `""` | 「今天」的时区;空 = `Asia/Shanghai` |
|
|
72
|
+
|
|
73
|
+
环境变量同名大写(`MAGPIE_TOKENTRACKER_PORT` 等)也能喂,手动跑服务时方便。
|
|
74
|
+
|
|
75
|
+
## 服务接口(全部只读,只对 127.0.0.1 开)
|
|
76
|
+
|
|
77
|
+
| 路由 | 说明 |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `GET /` | 看板 HTML(全内联单页;CSP `unsafe-inline` + 显式回环 connect-src,见「注意」) |
|
|
80
|
+
| `GET /api/usage?period=today\|7d\|30d[&force=1]` | 整理好的 JSON:卡片、按工具、按模型、小时/日序列 |
|
|
81
|
+
| `GET /api/status` | 服务端口 + TokenTracker 探活结果 |
|
|
82
|
+
| `GET /api/healthz` | 存活检查 |
|
|
83
|
+
|
|
84
|
+
- 数据 8 秒缓存,`force=1` 跳过;同周期并发请求合并。
|
|
85
|
+
- TokenTracker 不在时回 503,payload 里带 `hint.command`;自动拉起失败后有 60 秒冷却,避免每 20 秒的自动刷新反复 spawn。
|
|
86
|
+
- magpie 的页面 frame 是 opaque origin(`Origin: null`),所以 `/api/*` 对它回 `Access-Control-Allow-Origin: null`;其它 Origin 一律 403。数据本身不是秘密(TokenTracker 自己的读接口就是回环裸奔的),不加鉴权。
|
|
87
|
+
- 拉起的 TokenTracker 用独立进程组(`detached: true`),服务退出时整组 SIGTERM,不留孤儿占着 7680。
|
|
88
|
+
|
|
89
|
+
## TokenTracker 接口约定(实测 1.5.22)
|
|
90
|
+
|
|
91
|
+
- `GET /api/local-auth` → 探活 + 版本。
|
|
92
|
+
- `tokentracker-usage-summary?from&to&tz&rolling=1`:总量、花费、缓存、会话、`rolling.last_7d/last_30d`。
|
|
93
|
+
- `tokentracker-usage-daily` / `-usage-hourly`:日/小时序列。
|
|
94
|
+
- `tokentracker-usage-model-breakdown`:按工具(source)→ 模型的拆分和定价。
|
|
95
|
+
- 花费不在 `queue.jsonl` 里,是按定价表算的,所以必须走 HTTP 接口,不能直接读文件。
|
|
96
|
+
|
|
97
|
+
## 官方云同步与排行榜(可选)
|
|
98
|
+
|
|
99
|
+
看板之外,[TokenTracker](https://github.com/xiufengsun/TokenTracker) 官方还提供两项云上能力:
|
|
100
|
+
|
|
101
|
+
- **全球排行榜**:登录官方账号即可参加,免费。
|
|
102
|
+
- **官方 Cloud 云同步**(付费,[tokentracker.cc/cloud](https://tokentracker.cc/cloud)):多设备用量聚合与网页历史。
|
|
103
|
+
|
|
104
|
+
本插件看板会显示官方账号的登录状态与对应入口;不登录也不影响本地功能——看板的全部本地能力(读取、展示、按工具/模型拆分、趋势)只走本机回环接口,不需要任何账号。
|
|
105
|
+
|
|
106
|
+
## 常见问题
|
|
107
|
+
|
|
108
|
+
### 本机没装 TokenTracker,怎么办?
|
|
109
|
+
|
|
110
|
+
不用提前装。服务第一次被问到用量时会探活 `127.0.0.1:<tokentrackerPort>`(默认 7680);失败且 `autoStart` 开着(默认开)就自动拉起:优先 PATH 里的 `tokentracker`,退到 `npx -y tokentracker-cli`,都可以用 `command` 选项自定义。拉不起来时页面显示离线提示和可直接复制的命令;拉起失败后有 60 秒冷却,避免自动刷新反复 spawn(细节见「依赖」「选项」「服务接口」三节)。
|
|
111
|
+
|
|
112
|
+
### 没登录官方账号?
|
|
113
|
+
|
|
114
|
+
本地看板全功能可用——它只读本机 TokenTracker 的回环接口,不需要任何账号。网页历史、全球排行榜、官方 Cloud 云同步(付费)才需要登录官方账号:在官方看板 Settings → Account 里登录,或执行 `tokentracker device-login`。
|
|
115
|
+
|
|
116
|
+
### 数据上传了什么?
|
|
117
|
+
|
|
118
|
+
插件看板本身不向任何地方上传数据——它只读本机 TokenTracker 的回环接口。这些接口暴露的也只是聚合用量数字:tokens 数、按定价表估算的费用、模型名、编程工具名、小时/日时间桶,不含任何代码、提示词、对话内容或文件内容(见「TokenTracker 接口约定」)。只有当你主动使用官方 Cloud 云同步(付费)时,数据才会同步到官方云端,内容同样是用量数字,不是代码与对话。
|
|
119
|
+
<!-- TODO(发布前): 到 TokenTracker 官方仓库(https://github.com/xiufengsun/TokenTracker)核对官方隐私说明的准确表述与链接后,替换本行。 -->
|
|
120
|
+
|
|
121
|
+
## 开发
|
|
122
|
+
|
|
123
|
+
```sh
|
|
124
|
+
npm test # node --test test/*.test.mjs
|
|
125
|
+
node index.mjs # 手动跑服务(默认 3491),Ctrl-C 会带走拉起的 TokenTracker
|
|
126
|
+
open http://127.0.0.1:3491/
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
改完代码要再 `magpie plugin add <路径>` 一次,magpie 的 Bun 宿主才会重新加载(宿主进程 magpie-bu 会换 pid)。
|
|
130
|
+
|
|
131
|
+
发布流程(GitHub repo / npm publish / magpie 收录)见 [`docs/publish-checklist.md`](./docs/publish-checklist.md)。
|
|
132
|
+
|
|
133
|
+
## 注意
|
|
134
|
+
|
|
135
|
+
- TokenTracker CLI 第一次 `serve` 会做初始化:给 Claude Code 写 hooks、改 Codex CLI 配置、装 Opencode 插件。都是可逆的,但要知情。
|
|
136
|
+
- 端口 3491 是挑过的:magpie 里 loop-guard 插件占了 3477/3478,避开。
|
|
137
|
+
- 端口被占时不再硬失败(magpie 自升级交接的真实事故修出来的):同款服务连续两次探活成功 → 复用;否则每秒重试绑定,最多 20 秒,等旧实例退出;外来占用者等满 20 秒才报错。`/api/healthz` 带指纹 `{service, build}`(复用按服务名判,不按 build —— 多实例共存的稳定优先;升级代码后想让老 build 退位,`magpie plugin rm <路径> && magpie plugin add <路径>` 走一遍,宿主整个换进程)。
|
|
138
|
+
- 已知边界:同一台机器同时跑桌面 app 和 `magpie web` 时,第二个实例会复用桌面侧的服务(同款指纹),页面照常跳本机服务。
|
|
139
|
+
- 看板是全内联单页(服务端把 style.css/app.js 内联进 board.html,并把 `__SERVICE_BASE__` 注入成 `http://127.0.0.1:<port>`):magpie 的页面 frame 是 `sandbox="allow-scripts"` 的 opaque origin,CSP 里 `'self'` 匹配不到任何来源,外链 css/js 和相对 fetch 全会被拦;所以 CSP 用 `'unsafe-inline'` + 显式回环 connect-src,fetch 一律走绝对地址。
|
|
140
|
+
- 改了 `server.mjs` 记得 `BUILD` +1(healthz 里看得见);改了 page 文件不用,内联是每次请求现拼的。
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
[MIT](./LICENSE)
|
package/index.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// magpie 窗口里的「TokenTracker」页面。
|
|
2
|
+
//
|
|
3
|
+
// 两层结构(跟 page-usage-board / page-usage-tree 同一套契约):
|
|
4
|
+
// 1. 本文件被 magpie 的 Bun 宿主当 OpenCode v1 插件加载。模块导入必须零副作用:
|
|
5
|
+
// 服务只在 magpie 调 server(input, options) 时启动,且等真正监听后才返回。
|
|
6
|
+
// 2. page/index.html + page/boot.js 是 magpie 托管的带路页,把框架导航到本机服务
|
|
7
|
+
// (桌面窗口)或 magpie.web 的 service 转发路径(留在 magpie origin 里)。
|
|
8
|
+
//
|
|
9
|
+
// 服务自己只绑 127.0.0.1,只读本机 TokenTracker 的回环接口。
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
let starting = null;
|
|
15
|
+
|
|
16
|
+
const plugin = {
|
|
17
|
+
id: "magpie-tokentracker",
|
|
18
|
+
server: async (_input, options) => {
|
|
19
|
+
if (!starting) {
|
|
20
|
+
starting = import(pathToFileURL(path.join(here, "server.mjs")).href)
|
|
21
|
+
.then((mod) => mod.startServer({
|
|
22
|
+
port: options?.port,
|
|
23
|
+
tokentrackerPort: options?.tokentrackerPort,
|
|
24
|
+
autoStart: options?.autoStart,
|
|
25
|
+
command: options?.command,
|
|
26
|
+
timeZone: options?.timeZone,
|
|
27
|
+
}))
|
|
28
|
+
.then(({ port }) => ({ ok: true, port }))
|
|
29
|
+
.catch((error) => {
|
|
30
|
+
starting = null; // 允许 magpie 下次调用重试
|
|
31
|
+
console.error("[magpie-tokentracker] server not started:", error?.message || error);
|
|
32
|
+
throw error;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
await starting;
|
|
36
|
+
return await starting;
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export default plugin;
|
|
41
|
+
|
|
42
|
+
// 手动启动入口:node index.mjs
|
|
43
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
44
|
+
plugin.server().then(async (started) => {
|
|
45
|
+
// 手动跑的时候,Ctrl-C / kill 也要顺手带走拉起来的 TokenTracker 子进程
|
|
46
|
+
const { killActiveTokenTracker } = await import("./lib/tokentracker.mjs");
|
|
47
|
+
const stop = () => {
|
|
48
|
+
killActiveTokenTracker();
|
|
49
|
+
process.exit(0);
|
|
50
|
+
};
|
|
51
|
+
process.once("SIGINT", stop);
|
|
52
|
+
process.once("SIGTERM", stop);
|
|
53
|
+
}).catch((error) => {
|
|
54
|
+
console.error(`[magpie-tokentracker] not started: ${error?.message || error}`);
|
|
55
|
+
process.exit(1);
|
|
56
|
+
});
|
|
57
|
+
}
|
package/lib/official.mjs
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// TokenTracker 官方云(tokentracker.cc)登录态的纯函数:读本机配置 + userId 掩码。
|
|
2
|
+
//
|
|
3
|
+
// 官方登录信息写在本机 ~/.tokentracker/tracker/config.json(1.5.22 未登录时只有
|
|
4
|
+
// installedAt / baseUrl / machineId 三个字段;machineId 是装机就有的设备标识,不算登录)。
|
|
5
|
+
// 路径由调用方传入,测试用临时文件喂「已登录 / 未登录」两种状态。
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
|
|
8
|
+
// 登录后可能写入 config.json 的用户标识字段(按常见命名逐一试)。
|
|
9
|
+
const USER_ID_KEYS = ["userId", "user_id", "uid", "accountId", "account_id", "email", "username"];
|
|
10
|
+
|
|
11
|
+
// 掩码:前 6 位 + … + 后 4 位;太短(≤10)掩不住就直接原样返回;空给空串。
|
|
12
|
+
export function maskUserId(id) {
|
|
13
|
+
const text = String(id ?? "").trim();
|
|
14
|
+
if (!text) return "";
|
|
15
|
+
if (text.length <= 10) return text;
|
|
16
|
+
return `${text.slice(0, 6)}…${text.slice(-4)}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 从配置对象里挑出用户标识;挑不出给空串。
|
|
20
|
+
export function pickUserId(config) {
|
|
21
|
+
if (!config || typeof config !== "object") return "";
|
|
22
|
+
for (const key of USER_ID_KEYS) {
|
|
23
|
+
const value = config[key];
|
|
24
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
25
|
+
if (Number.isFinite(value) && value > 0) return String(value);
|
|
26
|
+
}
|
|
27
|
+
return "";
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 读官方配置 → 登录态。读不到 / 解析失败都算未登录:
|
|
31
|
+
// 配置文件损坏不该拖垮看板,云面板降级成「未登录」即可。
|
|
32
|
+
export async function readOfficialStatus(filePath) {
|
|
33
|
+
let text = "";
|
|
34
|
+
try {
|
|
35
|
+
text = await readFile(filePath, "utf8");
|
|
36
|
+
} catch {
|
|
37
|
+
return { loggedIn: false, userId: "" };
|
|
38
|
+
}
|
|
39
|
+
let config = null;
|
|
40
|
+
try {
|
|
41
|
+
config = JSON.parse(text);
|
|
42
|
+
} catch {
|
|
43
|
+
return { loggedIn: false, userId: "" };
|
|
44
|
+
}
|
|
45
|
+
const id = pickUserId(config);
|
|
46
|
+
return { loggedIn: Boolean(id), userId: maskUserId(id) };
|
|
47
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// 和本机 TokenTracker 打交道:探测、必要时拉起、读它的回环接口。
|
|
2
|
+
//
|
|
3
|
+
// TokenTracker(github.com/xiufengsun/TokenTracker,npm 包 tokentracker-cli)在
|
|
4
|
+
// `tokentracker serve` 时于 127.0.0.1:7680 提供一套本机接口:
|
|
5
|
+
// GET /api/local-auth → { token, serverVersion? }
|
|
6
|
+
// GET /functions/tokentracker-usage-summary?from&to&tz
|
|
7
|
+
// GET /functions/tokentracker-usage-model-breakdown?from&to&tz
|
|
8
|
+
// GET /functions/tokentracker-usage-daily?from&to&tz
|
|
9
|
+
// GET /functions/tokentracker-usage-hourly?from&to&tz
|
|
10
|
+
// 读接口对回环地址开放(不校验 token),写接口才要 token;我们只读,所以不拿 token。
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { accessSync, constants } from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_PORT = 7680;
|
|
16
|
+
|
|
17
|
+
// 最近一次由 ensureRunning 拉起的 TokenTracker 子进程;手动跑服务时退出要带走它
|
|
18
|
+
let activeChild = null;
|
|
19
|
+
|
|
20
|
+
export function killActiveTokenTracker() {
|
|
21
|
+
const child = activeChild;
|
|
22
|
+
activeChild = null;
|
|
23
|
+
try {
|
|
24
|
+
child?.kill();
|
|
25
|
+
} catch {
|
|
26
|
+
// 已经退了
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const PROBE_TIMEOUT_MS = 1500;
|
|
30
|
+
|
|
31
|
+
export function resolvePort(value) {
|
|
32
|
+
const n = Number(value);
|
|
33
|
+
return Number.isInteger(n) && n > 0 && n < 65536 ? n : DEFAULT_PORT;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function baseUrl(port) {
|
|
37
|
+
return `http://127.0.0.1:${resolvePort(port)}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function withTimeout(ms) {
|
|
41
|
+
const controller = new AbortController();
|
|
42
|
+
const timer = setTimeout(() => controller.abort(), ms);
|
|
43
|
+
return { signal: controller.signal, done: () => clearTimeout(timer) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 探测:能拿到 /api/local-auth 的 JSON 就算 TokenTracker 在跑。
|
|
47
|
+
export async function probe(base, { timeoutMs = PROBE_TIMEOUT_MS } = {}) {
|
|
48
|
+
const timeout = withTimeout(timeoutMs);
|
|
49
|
+
try {
|
|
50
|
+
const res = await fetch(`${base}/api/local-auth`, {
|
|
51
|
+
headers: { Accept: "application/json" },
|
|
52
|
+
signal: timeout.signal,
|
|
53
|
+
});
|
|
54
|
+
if (!res.ok) return { reachable: false, error: `HTTP ${res.status}` };
|
|
55
|
+
const data = await res.json().catch(() => null);
|
|
56
|
+
return {
|
|
57
|
+
reachable: true,
|
|
58
|
+
version: typeof data?.serverVersion === "string" ? data.serverVersion : "",
|
|
59
|
+
};
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const code = error?.cause?.code || error?.code || "";
|
|
62
|
+
return {
|
|
63
|
+
reachable: false,
|
|
64
|
+
error: code || (error?.name === "AbortError" ? "timeout" : String(error?.message || error)),
|
|
65
|
+
};
|
|
66
|
+
} finally {
|
|
67
|
+
timeout.done();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function onPath(bin) {
|
|
72
|
+
const dirs = String(process.env.PATH || "").split(path.delimiter).filter(Boolean);
|
|
73
|
+
for (const dir of dirs) {
|
|
74
|
+
try {
|
|
75
|
+
accessSync(path.join(dir, bin), constants.X_OK);
|
|
76
|
+
return path.join(dir, bin);
|
|
77
|
+
} catch {
|
|
78
|
+
// 继续找
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return "";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 拉起命令:优先用户配置(command),其次 PATH 里的 tokentracker,最后 npx。
|
|
85
|
+
export function resolveCommand(command, port) {
|
|
86
|
+
const args = ["serve", "--no-open", "--port", String(resolvePort(port))];
|
|
87
|
+
const custom = String(command || "").trim();
|
|
88
|
+
if (custom) {
|
|
89
|
+
const parts = custom.split(/\s+/);
|
|
90
|
+
return { bin: parts[0], args: [...parts.slice(1), ...args] };
|
|
91
|
+
}
|
|
92
|
+
const local = onPath("tokentracker");
|
|
93
|
+
if (local) return { bin: local, args };
|
|
94
|
+
const npx = onPath("npx");
|
|
95
|
+
if (npx) return { bin: npx, args: ["-y", "tokentracker-cli", ...args] };
|
|
96
|
+
return { bin: "", args: [] };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 确保有一个可用的 TokenTracker:先探测;不行且允许自动拉起时,起一个子进程等它就绪。
|
|
100
|
+
export async function ensureRunning({
|
|
101
|
+
port,
|
|
102
|
+
autoStart = true,
|
|
103
|
+
command = "",
|
|
104
|
+
log = () => {},
|
|
105
|
+
waitMs = 25000,
|
|
106
|
+
probeFn = probe,
|
|
107
|
+
spawnFn = spawn,
|
|
108
|
+
} = {}) {
|
|
109
|
+
const base = baseUrl(port);
|
|
110
|
+
const first = await probeFn(base);
|
|
111
|
+
if (first.reachable) return { reachable: true, base, started: false, version: first.version || "" };
|
|
112
|
+
|
|
113
|
+
if (!autoStart) return { reachable: false, base, started: false, error: first.error || "unreachable" };
|
|
114
|
+
|
|
115
|
+
const cmd = resolveCommand(command, port);
|
|
116
|
+
if (!cmd.bin) {
|
|
117
|
+
return { reachable: false, base, started: false, error: "tokentracker command not found" };
|
|
118
|
+
}
|
|
119
|
+
log(`starting TokenTracker: ${cmd.bin} ${cmd.args.join(" ")}`);
|
|
120
|
+
let child;
|
|
121
|
+
activeChild = null;
|
|
122
|
+
try {
|
|
123
|
+
// detached: true 让 tokentracker 自己成组:它还会再 fork 一个真正监听端口的
|
|
124
|
+
// node 子进程,只有整组杀才能带走,不然留下孤儿服务占着端口。
|
|
125
|
+
child = spawnFn(cmd.bin, cmd.args, { stdio: "ignore", detached: true });
|
|
126
|
+
} catch (error) {
|
|
127
|
+
return { reachable: false, base, started: false, error: `spawn failed: ${error?.message || error}` };
|
|
128
|
+
}
|
|
129
|
+
child.on?.("error", (error) => log(`TokenTracker start failed: ${error?.message || error}`));
|
|
130
|
+
// 退出时顺手带走整组子进程,别在 magpie 关掉后留一个孤儿服务。
|
|
131
|
+
activeChild = child;
|
|
132
|
+
const killChild = () => {
|
|
133
|
+
if (activeChild === child) activeChild = null;
|
|
134
|
+
try {
|
|
135
|
+
if (process.platform !== "win32") process.kill(-child.pid, "SIGTERM");
|
|
136
|
+
else child.kill();
|
|
137
|
+
} catch {
|
|
138
|
+
// 已经退了
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
child.once?.("exit", killChild);
|
|
142
|
+
process.once("exit", killChild);
|
|
143
|
+
|
|
144
|
+
const deadline = Date.now() + waitMs;
|
|
145
|
+
while (Date.now() < deadline) {
|
|
146
|
+
await new Promise((r) => setTimeout(r, 600));
|
|
147
|
+
const now = await probeFn(base);
|
|
148
|
+
if (now.reachable) {
|
|
149
|
+
return { reachable: true, base, started: true, version: now.version || "" };
|
|
150
|
+
}
|
|
151
|
+
if (child.exitCode !== null && child.exitCode !== undefined) {
|
|
152
|
+
return { reachable: false, base, started: false, error: `TokenTracker exited (${child.exitCode})` };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { reachable: false, base, started: false, error: "TokenTracker did not answer in time" };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function apiGet(base, slug, params = {}, { timeoutMs = 8000 } = {}) {
|
|
159
|
+
const url = new URL(`/functions/${slug}`, base);
|
|
160
|
+
for (const [key, value] of Object.entries(params)) {
|
|
161
|
+
if (value !== undefined && value !== null && value !== "") url.searchParams.set(key, String(value));
|
|
162
|
+
}
|
|
163
|
+
const timeout = withTimeout(timeoutMs);
|
|
164
|
+
try {
|
|
165
|
+
const res = await fetch(url, { headers: { Accept: "application/json" }, signal: timeout.signal });
|
|
166
|
+
const text = await res.text();
|
|
167
|
+
if (!res.ok) throw new Error(`${slug} answered HTTP ${res.status}`);
|
|
168
|
+
return JSON.parse(text);
|
|
169
|
+
} finally {
|
|
170
|
+
timeout.done();
|
|
171
|
+
}
|
|
172
|
+
}
|