@anthonyhan/token-pilot 0.0.0-stage → 0.2.4
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 +146 -2
- package/bin/token-pilot.js +18 -0
- package/dist/adapters/claude-code.js +251 -0
- package/dist/adapters/codex.js +163 -0
- package/dist/adapters/dsh.js +163 -0
- package/dist/adapters/kimi-code.js +165 -0
- package/dist/adapters/opencode.js +126 -0
- package/dist/adapters/pi.js +119 -0
- package/dist/adapters/qoder.js +51 -0
- package/dist/adapters/types.js +7 -0
- package/dist/adapters/volc-ark.js +92 -0
- package/dist/adapters/workbuddy.js +144 -0
- package/dist/cli/index.js +278 -0
- package/dist/cli/serve.js +200 -0
- package/dist/core/aggregate.js +821 -0
- package/dist/core/alert.js +32 -0
- package/dist/core/autocompact.js +40 -0
- package/dist/core/budget.js +23 -0
- package/dist/core/collector.js +213 -0
- package/dist/core/compression.js +129 -0
- package/dist/core/config.js +41 -0
- package/dist/core/contract.js +4 -0
- package/dist/core/metrics.js +53 -0
- package/dist/core/price-fetch.js +128 -0
- package/dist/core/pricing.js +156 -0
- package/dist/core/registry.js +144 -0
- package/dist/core/retry-detector.js +41 -0
- package/dist/core/rtk.js +58 -0
- package/dist/core/savings.js +43 -0
- package/dist/core/schema.js +3 -0
- package/dist/core/unknown-models.js +50 -0
- package/package.json +30 -3
- package/pricing/models.json +311 -0
package/README.md
CHANGED
|
@@ -1,3 +1,147 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="docs/assets/icon.png" width="96" alt="token-pilot —— 所有 AI 工具的本地账单,本月实测 ¥2,546 / 810M tokens">
|
|
4
|
+
|
|
5
|
+
# token-pilot ⚡
|
|
6
|
+
|
|
7
|
+
### 所有 AI 工具的本地账单,一抬头就看见
|
|
8
|
+
|
|
9
|
+
同时用 Claude Code / Codex / Kimi Code 跑国产模型的人,终于能答上「这个月给 AI 烧了多少钱」——只读本地日志,数据不出本机。
|
|
10
|
+
|
|
11
|
+
[](LICENSE)
|
|
12
|
+
[](#-状态栏应用)
|
|
13
|
+
[](tests/)
|
|
14
|
+
[](#-数据准确性)
|
|
15
|
+
|
|
16
|
+
[快速开始](#-快速开始) · [状态栏应用](#-状态栏应用) · [数据准确性](#-数据准确性) · [什么时候别用它](#-什么时候别用它) · [TODO](#-todo-list) · [English](README-en.md) · [llms.txt](llms.txt)
|
|
17
|
+
|
|
18
|
+
</div>
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+

|
|
23
|
+
|
|
24
|
+
> 状态栏常驻 `⚡ ¥今日 · 预算%`。左键弹面板,「打开完整看板」看全部。我的真实 10 月:**810M tokens · ¥2,546 · 12,685 次调用**([怎么算的](#-数据准确性))。
|
|
25
|
+
|
|
26
|
+
> ⚠️ **注意**:npm 上的 \`token-pilot\` 是别人的同名包(MCP 代码导航工具,会往 Claude Code 写 hooks)。**我们的包叫 \`@anthonyhan/token-pilot\`**,别装错:
|
|
27
|
+
|
|
28
|
+
## 🚀 快速开始
|
|
29
|
+
|
|
30
|
+
**For Humans:**
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install -g @anthonyhan/token-pilot
|
|
34
|
+
token-pilot month # 本月账单 + 月底预测 + 打转检测 + 省钱建议
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**For AI Agents:**(把这句粘贴给你的 Agent)
|
|
38
|
+
|
|
39
|
+
> 帮我安装 token-pilot:`npm install -g @anthonyhan/token-pilot`,然后跑 `token-pilot month` 告诉我这个月 AI 花了多少钱、哪里在浪费。
|
|
40
|
+
|
|
41
|
+
### 状态栏应用
|
|
42
|
+
|
|
43
|
+
[Releases](../../releases) 下载 `.dmg`(macOS Apple Silicon)/ `.msi`(Windows x64)。安装启动后**只在状态栏显示一个闪电图标**——无 Dock 图标、无启动窗口;左键弹面板,右键出菜单。
|
|
44
|
+
|
|
45
|
+
> 未签名:macOS 首次打开需右键 → 打开;Windows SmartScreen 选「仍要运行」。自己构建:`cd menubar && npm install && npx tauri build`
|
|
46
|
+
|
|
47
|
+
## ✨ 它能做什么
|
|
48
|
+
|
|
49
|
+
| 场景 | 你说 | 它做 |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| 看账单 | `token-pilot month` | 按宿主/按模型双维度月账单 + 月底预测 |
|
|
52
|
+
| 怕超支 | 设个月度预算 | 进度条 + 超支系统通知 + 托盘常驻 `¥今日 · 预算%` |
|
|
53
|
+
| Agent 打转 | 不用说话 | 自动揪出「单会话 ≥30 次调用」的死循环,算出浪费金额 |
|
|
54
|
+
| 想省钱 | 看「省钱建议」卡 | 贵模型干轻活 → 迁移建议+每月省多少;低缓存命中 → 优化空间;本月缓存帮你省了多少 |
|
|
55
|
+
| 上下文太长 | 自动提醒 / 点徽标 | 会话超 100K 上下文标记「该压缩」,可写 Claude Code autoCompact / 一键装 RTK 输出压缩层 |
|
|
56
|
+
| 核对价格 | `token-pilot prices` | 每个在用模型的单价来源(目录价/人工覆写/自动补价待核对) |
|
|
57
|
+
| 谁在烧 | 看「宿主/模型/项目榜」 | 哪个工具、哪个模型、哪个项目花最多,一目了然 |
|
|
58
|
+
| 国产模型 | 不用配置 | DeepSeek/GLM/Kimi/Qwen 走宿主日志 model 字段自动归一 |
|
|
59
|
+
|
|
60
|
+
**兼容你的工具链:** Claude Code ✅ · Codex ✅ · Kimi Code ✅ · OpenCode ✅(全量 token)· DeepSeek/GLM/Kimi/Qwen/MiniMax/混元/MiMo/LongCat/Doubao ✅(模型归一)· 其余 12 款仅检测 · 桌面订阅端记固定月费
|
|
61
|
+
|
|
62
|
+
## 📈 数据准确性
|
|
63
|
+
|
|
64
|
+
账单工具不准就是误导。所以准确性**可验证**:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
python3 scripts/reconcile.py month # 第三方视角独立重算原始日志,与 CLI 逐项对账
|
|
68
|
+
python3 scripts/verify-dashboard.py # 看板 36 项算法不变量校验
|
|
69
|
+
npm test # 40 个单元测试(定价/采集口径/聚合/注入)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
实测修过的口径坑(2026-10-21,本机 4787 个日志文件):
|
|
73
|
+
|
|
74
|
+
| 坑 | 影响 | 修复 |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| Claude 流式快照重复行 | 某会话 169 行 usage 实为 79 次调用 | 按 `message.id` 去重取最大 |
|
|
77
|
+
| Codex `input` 含 `cached` 子集 | 缓存被按全价+缓存价计两次 | 拆分 `input − cached` |
|
|
78
|
+
| Kimi `inputOther` 才是新输入 | 同上 | 只认 `usage.record` 且不并入缓存 |
|
|
79
|
+
|
|
80
|
+
## 📊 凭什么信我
|
|
81
|
+
|
|
82
|
+
- 我自己的 AI 账单就是它管的:本月 **¥2,546 / 810M tokens**(2026-10-21,上方截图即本机实时数据)
|
|
83
|
+
- 36 项看板算法不变量 + 22 个单测 + 独立对账脚本,全部开箱可跑
|
|
84
|
+
- 诚实披露速率口径:日志按「调用完成时刻」记账,生成中的调用完成前不计入(看板内有注明)
|
|
85
|
+
|
|
86
|
+
## ⚠️ 什么时候别用它
|
|
87
|
+
|
|
88
|
+
- **你想管的工具不写本地用量日志**(Antigravity / Copilot / Cursor 等 12 款)——只能检测到装没装,读不到 token
|
|
89
|
+
- **桌面订阅 App**(Kimi.app / ChatGPT.app)——不按 token 计费,只能登记固定月费
|
|
90
|
+
- **想拦在请求前面节流**——它是事后分析,不拦截请求(拦截需要代理层,在 Roadmap)
|
|
91
|
+
|
|
92
|
+
## 💰 支持这个项目
|
|
93
|
+
|
|
94
|
+
token-pilot 免费且 MIT。如果它帮你省下了 AI 账单,可以请我喝杯咖啡:
|
|
95
|
+
|
|
96
|
+
| 支付宝 | 微信 |
|
|
97
|
+
|---|---|
|
|
98
|
+
| <img src="docs/assets/sponsor-alipay.png" width="260" alt="支付宝赞赏码"> | <img src="docs/assets/sponsor-wechat.png" width="260" alt="微信赞赏码"> |
|
|
99
|
+
|
|
100
|
+
也想出现在这里?→ [bmomhan@gmail.com](mailto:bmomhan@gmail.com)(赞助位招租)
|
|
101
|
+
|
|
102
|
+
⭐ Star 本仓库 = 告诉我你在用哪个宿主——下一个 adapter 优先做 Star 用户提名最多的那个。
|
|
103
|
+
|
|
104
|
+
## 🙋 关于我
|
|
105
|
+
|
|
106
|
+
一个人 + 几个 AI Agent 在做产品实验(西安远程)。token-pilot 是我自己每天真在用的工具——它先抓出了我 kimi-code 里一个打了 120 次调用的打转会话,又告诉我这个月缓存帮我省了 ¥3,048。
|
|
107
|
+
|
|
108
|
+
**保持联系:** [X @AnthonyHan_](https://x.com/AnthonyHan_) · [bmomhan@gmail.com](mailto:bmomhan@gmail.com)
|
|
109
|
+
|
|
110
|
+
## 📝 更新日志
|
|
111
|
+
|
|
112
|
+
- **2026-10-21** v0.1.0:首版 → CLI 账单 + 本地看板 + macOS/Windows 状态栏应用,三形态一次给齐
|
|
113
|
+
|
|
114
|
+
## ✅ TODO LIST
|
|
115
|
+
|
|
116
|
+
**采集覆盖**
|
|
117
|
+
- [x] OpenCode adapter(SQLite)
|
|
118
|
+
- [x] Qoder adapter(仅会话数,model 全为 auto——诚实标注)
|
|
119
|
+
- [x] pi adapter
|
|
120
|
+
- [x] Cursor spike(结论:无 token 用量数据,ai-code-tracking 是代码追踪非用量 → 诚实归「仅检测」)
|
|
121
|
+
- [x] 云端用量 API:Doubao 火山(arkcli usage stats,日粒度)
|
|
122
|
+
- [ ] 云端用量 API:OpenAI / Kimi 开放平台(需用户配 API key)
|
|
123
|
+
|
|
124
|
+
**节流(Step 2)**
|
|
125
|
+
- [x] 2A 压缩潜力量化(规则引擎:陈旧输出/重复读取/超长输出 → 本月可省多少,实测 $63-95)
|
|
126
|
+
- [x] 2B 压缩执行第一层:自动压缩提醒 + Claude autoCompact 写入 + RTK 一键安装
|
|
127
|
+
- [ ] 2B 压缩执行第二层:代理网关(LiteLLM/自研,视数据再定)
|
|
128
|
+
- [ ] 低价模型路由(本地代理层,可选开启,默认不动你任何配置)
|
|
129
|
+
- [ ] 异常重试自动熔断提醒(已有检测,加主动通知策略)
|
|
130
|
+
|
|
131
|
+
**平台与工程**
|
|
132
|
+
- [x] macOS 状态栏应用(arm64 .app/.dmg)
|
|
133
|
+
- [x] Windows 核查 + 分平台图标 + CI
|
|
134
|
+
- [ ] Windows .msi 实机验证(Actions 产物)
|
|
135
|
+
- [ ] Intel Mac 包(universal2)
|
|
136
|
+
- [ ] 自动更新(tauri-updater)
|
|
137
|
+
- [ ] 签名与公证(Apple Developer $99/年,有赞助再开)
|
|
138
|
+
|
|
139
|
+
## English
|
|
140
|
+
|
|
141
|
+
**[README in English → README-en.md](README-en.md)**
|
|
142
|
+
|
|
143
|
+
*token-pilot* — local billing + budget control for all your AI coding tools. Reads local logs only (no hooks, no telemetry). CLI + local dashboard + menubar app (macOS/Windows). Chinese models (DeepSeek/GLM/Kimi…) auto-normalized via host-log `model` field.
|
|
144
|
+
|
|
145
|
+
## License
|
|
146
|
+
|
|
147
|
+
MIT © anthonyhann
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// token-pilot 全局入口:优先跑编译产物 dist/(npm 包形态);仓库内开发回退 tsx
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const distEntry = path.resolve(__dirname, '../dist/cli/index.js');
|
|
10
|
+
const srcEntry = path.resolve(__dirname, '../src/cli/index.ts');
|
|
11
|
+
|
|
12
|
+
let r;
|
|
13
|
+
if (existsSync(distEntry)) {
|
|
14
|
+
r = spawnSync(process.execPath, [distEntry, ...process.argv.slice(2)], { stdio: 'inherit' });
|
|
15
|
+
} else {
|
|
16
|
+
r = spawnSync('npx', ['tsx', srcEntry, ...process.argv.slice(2)], { stdio: 'inherit', shell: process.platform === 'win32' });
|
|
17
|
+
}
|
|
18
|
+
process.exit(r.status ?? 0);
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// Claude Code adapter — 只读解析 ~/.claude/projects/**/*.jsonl
|
|
2
|
+
// 参考 ccusage 路线:不注入 hook,不改配置,纯只读
|
|
3
|
+
import { promises as fs } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
const HOME = os.homedir();
|
|
7
|
+
const PROJECTS_DIR = path.join(HOME, '.claude', 'projects');
|
|
8
|
+
async function* walkJsonl(dir) {
|
|
9
|
+
let entries;
|
|
10
|
+
try {
|
|
11
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
for (const e of entries) {
|
|
17
|
+
const full = path.join(dir, e.name);
|
|
18
|
+
if (e.isDirectory()) {
|
|
19
|
+
yield* walkJsonl(full);
|
|
20
|
+
}
|
|
21
|
+
else if (e.isFile() && e.name.endsWith('.jsonl')) {
|
|
22
|
+
yield full;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function parseLine(line, file, lineNo) {
|
|
27
|
+
if (!line.includes('"usage"'))
|
|
28
|
+
return null;
|
|
29
|
+
let d;
|
|
30
|
+
try {
|
|
31
|
+
d = JSON.parse(line);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
const usage = d.message?.usage;
|
|
37
|
+
const model = d.message?.model;
|
|
38
|
+
if (!usage || !model || model === '<synthetic>' || model === 'error')
|
|
39
|
+
return null;
|
|
40
|
+
const input = usage.input_tokens ?? 0;
|
|
41
|
+
const output = usage.output_tokens ?? 0;
|
|
42
|
+
const cacheRead = usage.cache_read_input_tokens ?? 0;
|
|
43
|
+
const cacheCreation = usage.cache_creation_input_tokens ?? 0;
|
|
44
|
+
// eventId 用 message.id 做去重键;缺 id 时退化为 文件+行号(不参与去重)
|
|
45
|
+
const msgId = d.message?.id;
|
|
46
|
+
const eventId = msgId ?? `${path.basename(file, '.jsonl')}#${lineNo}`;
|
|
47
|
+
return {
|
|
48
|
+
agent: 'claude-code',
|
|
49
|
+
sessionId: d.sessionId ?? path.basename(file, '.jsonl'),
|
|
50
|
+
eventId,
|
|
51
|
+
timestamp: d.timestamp ? new Date(d.timestamp).getTime() : 0,
|
|
52
|
+
provider: providerFromModel(model),
|
|
53
|
+
model,
|
|
54
|
+
usage: {
|
|
55
|
+
inputTokens: input,
|
|
56
|
+
outputTokens: output,
|
|
57
|
+
cacheReadTokens: cacheRead,
|
|
58
|
+
cacheCreationTokens: cacheCreation,
|
|
59
|
+
totalTokens: input + output + cacheRead + cacheCreation,
|
|
60
|
+
},
|
|
61
|
+
workspace: d.cwd,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
// 从 model 名推 provider(国产模型识别在这)
|
|
65
|
+
function providerFromModel(model) {
|
|
66
|
+
const m = model.toLowerCase();
|
|
67
|
+
if (m.includes('claude'))
|
|
68
|
+
return 'anthropic';
|
|
69
|
+
if (m.includes('deepseek'))
|
|
70
|
+
return 'deepseek';
|
|
71
|
+
if (m.includes('glm'))
|
|
72
|
+
return 'glm';
|
|
73
|
+
if (m.includes('kimi'))
|
|
74
|
+
return 'kimi';
|
|
75
|
+
if (m.includes('qwen'))
|
|
76
|
+
return 'qwen';
|
|
77
|
+
if (m.includes('doubao') || m.includes('seed'))
|
|
78
|
+
return 'doubao';
|
|
79
|
+
if (m.includes('minimax'))
|
|
80
|
+
return 'minimax';
|
|
81
|
+
if (m.includes('hunyuan') || m.includes('hy'))
|
|
82
|
+
return 'hunyuan';
|
|
83
|
+
if (m.includes('mimo'))
|
|
84
|
+
return 'mimo';
|
|
85
|
+
if (m.includes('longcat'))
|
|
86
|
+
return 'longcat';
|
|
87
|
+
if (m.includes('gpt'))
|
|
88
|
+
return 'openai';
|
|
89
|
+
return 'unknown';
|
|
90
|
+
}
|
|
91
|
+
// 抓会话标题:首条用户文本消息,截 40 字符
|
|
92
|
+
function grabTitle(line, out) {
|
|
93
|
+
try {
|
|
94
|
+
const d = JSON.parse(line);
|
|
95
|
+
if (d?.type !== 'user' || !d?.sessionId)
|
|
96
|
+
return;
|
|
97
|
+
if (out.has(d.sessionId))
|
|
98
|
+
return;
|
|
99
|
+
const c = d.message?.content;
|
|
100
|
+
let text = '';
|
|
101
|
+
if (typeof c === 'string')
|
|
102
|
+
text = c;
|
|
103
|
+
else if (Array.isArray(c)) {
|
|
104
|
+
const t = c.find((b) => b?.type === 'text' && typeof b.text === 'string');
|
|
105
|
+
text = t?.text ?? '';
|
|
106
|
+
}
|
|
107
|
+
text = text.replace(/\s+/g, ' ').trim();
|
|
108
|
+
// 跳过系统注入块:xml 标签、[SYSTEM]/[MESSAGE FROM...] 等方括号标签
|
|
109
|
+
if (!text || text.startsWith('<') || text.startsWith('['))
|
|
110
|
+
return;
|
|
111
|
+
out.set(d.sessionId, text.slice(0, 40));
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// 非 JSON 行忽略
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// 解析单个 jsonl 文件:文件内按 message.id 去重(取 totalTokens 最大),附会话标题
|
|
118
|
+
async function readFileEvents(file, sinceMs = 0) {
|
|
119
|
+
let content;
|
|
120
|
+
try {
|
|
121
|
+
content = await fs.readFile(file, 'utf8');
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
const byId = new Map();
|
|
127
|
+
const titleBySession = new Map();
|
|
128
|
+
const lines = content.split('\n');
|
|
129
|
+
for (let i = 0; i < lines.length; i++) {
|
|
130
|
+
const line = lines[i];
|
|
131
|
+
if (!line.trim())
|
|
132
|
+
continue;
|
|
133
|
+
// 顺手抓会话标题(首条用户文本消息),成本只是一次子串判断
|
|
134
|
+
if (line.includes('"type":"user"') && line.includes('"content"')) {
|
|
135
|
+
grabTitle(line, titleBySession);
|
|
136
|
+
}
|
|
137
|
+
const ev = parseLine(line, file, i);
|
|
138
|
+
if (!ev || ev.timestamp < sinceMs)
|
|
139
|
+
continue;
|
|
140
|
+
const prev = byId.get(ev.eventId);
|
|
141
|
+
if (!prev || ev.usage.totalTokens > prev.usage.totalTokens) {
|
|
142
|
+
byId.set(ev.eventId, ev);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const events = [...byId.values()];
|
|
146
|
+
for (const ev of events) {
|
|
147
|
+
const t = titleBySession.get(ev.sessionId);
|
|
148
|
+
if (t)
|
|
149
|
+
ev.sessionTitle = t;
|
|
150
|
+
}
|
|
151
|
+
return events;
|
|
152
|
+
}
|
|
153
|
+
async function listFiles() {
|
|
154
|
+
const out = [];
|
|
155
|
+
for await (const f of walkJsonl(PROJECTS_DIR))
|
|
156
|
+
out.push(f);
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
// 内容流:tool_use(assistant)与 tool_result(user)只取尺寸与目标路径,不落内容
|
|
160
|
+
async function readFileContentEvents(file, sinceMs = 0) {
|
|
161
|
+
let content;
|
|
162
|
+
try {
|
|
163
|
+
content = await fs.readFile(file, 'utf8');
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return [];
|
|
167
|
+
}
|
|
168
|
+
const events = [];
|
|
169
|
+
const sessionId = path.basename(file, '.jsonl');
|
|
170
|
+
for (const line of content.split('\n')) {
|
|
171
|
+
if (!line.includes('tool_use') && !line.includes('tool_result'))
|
|
172
|
+
continue;
|
|
173
|
+
let d;
|
|
174
|
+
try {
|
|
175
|
+
d = JSON.parse(line);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
|
|
181
|
+
if (ts < sinceMs)
|
|
182
|
+
continue;
|
|
183
|
+
const items = d.message?.content;
|
|
184
|
+
if (!Array.isArray(items))
|
|
185
|
+
continue;
|
|
186
|
+
for (const c of items) {
|
|
187
|
+
if (!c || typeof c !== 'object')
|
|
188
|
+
continue;
|
|
189
|
+
const cc = c;
|
|
190
|
+
if (d.type === 'assistant' && cc.type === 'tool_use') {
|
|
191
|
+
const input = cc.input;
|
|
192
|
+
events.push({
|
|
193
|
+
agent: 'claude-code',
|
|
194
|
+
sessionId,
|
|
195
|
+
timestamp: ts,
|
|
196
|
+
kind: 'tool_use',
|
|
197
|
+
tool: cc.name,
|
|
198
|
+
targetPath: input?.file_path ?? input?.path,
|
|
199
|
+
sizeBytes: cc.input ? JSON.stringify(cc.input).length : 0,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
else if (d.type === 'user' && cc.type === 'tool_result') {
|
|
203
|
+
events.push({
|
|
204
|
+
agent: 'claude-code',
|
|
205
|
+
sessionId,
|
|
206
|
+
timestamp: ts,
|
|
207
|
+
kind: 'tool_result',
|
|
208
|
+
sizeBytes: cc.content ? JSON.stringify(cc.content).length : 0,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return events;
|
|
214
|
+
}
|
|
215
|
+
export const claudeCodeAdapter = {
|
|
216
|
+
meta: {
|
|
217
|
+
id: 'claude-code',
|
|
218
|
+
displayName: 'Claude Code',
|
|
219
|
+
detectPaths: ['~/.claude'],
|
|
220
|
+
detectCommands: ['claude'],
|
|
221
|
+
},
|
|
222
|
+
async detect() {
|
|
223
|
+
try {
|
|
224
|
+
await fs.access(PROJECTS_DIR);
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
},
|
|
231
|
+
listFiles,
|
|
232
|
+
readFileEvents,
|
|
233
|
+
readFileContentEvents,
|
|
234
|
+
async readEvents(sinceMs = 0) {
|
|
235
|
+
// 同一 message.id 只可能出现在一个会话文件里,按文件合并即可
|
|
236
|
+
const events = [];
|
|
237
|
+
for (const file of await listFiles()) {
|
|
238
|
+
// 文件 mtime 早于 since 就整个跳过(快计算)
|
|
239
|
+
try {
|
|
240
|
+
const st = await fs.stat(file);
|
|
241
|
+
if (st.mtimeMs < sinceMs)
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
events.push(...(await readFileEvents(file, sinceMs)));
|
|
248
|
+
}
|
|
249
|
+
return events;
|
|
250
|
+
},
|
|
251
|
+
};
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Codex adapter — 只读解析 ~/.codex/sessions/**/*.jsonl
|
|
2
|
+
// 格式:rollout jsonl,token 在 type=token_usage_record 事件的 payload.usage
|
|
3
|
+
import { promises as fs } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
const HOME = os.homedir();
|
|
7
|
+
const SESSIONS_DIR = path.join(HOME, '.codex', 'sessions');
|
|
8
|
+
async function* walkJsonl(dir) {
|
|
9
|
+
let entries;
|
|
10
|
+
try {
|
|
11
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
for (const e of entries) {
|
|
17
|
+
const full = path.join(dir, e.name);
|
|
18
|
+
if (e.isDirectory())
|
|
19
|
+
yield* walkJsonl(full);
|
|
20
|
+
else if (e.isFile() && e.name.endsWith('.jsonl'))
|
|
21
|
+
yield full;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function parseLine(line, file, lineNo) {
|
|
25
|
+
if (!line.includes('"token_usage_record"'))
|
|
26
|
+
return null;
|
|
27
|
+
let d;
|
|
28
|
+
try {
|
|
29
|
+
d = JSON.parse(line);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
if (d.type !== 'token_usage_record')
|
|
35
|
+
return null;
|
|
36
|
+
const u = d.payload?.usage;
|
|
37
|
+
if (!u)
|
|
38
|
+
return null;
|
|
39
|
+
// OpenAI 语义实测:input_tokens 包含 cached_input_tokens(cached 是子集),
|
|
40
|
+
// total_tokens = input_tokens + output_tokens。
|
|
41
|
+
// 新输入 = input − cached,缓存部分走 cacheRead 单价,不重复计费。
|
|
42
|
+
const inputRaw = u.input_tokens ?? 0;
|
|
43
|
+
const cacheRead = u.cached_input_tokens ?? 0;
|
|
44
|
+
const cacheCreation = u.cache_write_input_tokens ?? 0;
|
|
45
|
+
const output = u.output_tokens ?? 0;
|
|
46
|
+
const input = Math.max(inputRaw - cacheRead, 0);
|
|
47
|
+
return {
|
|
48
|
+
agent: 'codex',
|
|
49
|
+
sessionId: d.payload?.session_id ?? path.basename(file, '.jsonl'),
|
|
50
|
+
eventId: `${path.basename(file, '.jsonl')}#${lineNo}`,
|
|
51
|
+
timestamp: d.timestamp ? new Date(d.timestamp).getTime() : 0,
|
|
52
|
+
provider: 'openai',
|
|
53
|
+
model: 'codex', // rollout 里 model 名不稳定,先标 codex
|
|
54
|
+
usage: {
|
|
55
|
+
inputTokens: input,
|
|
56
|
+
outputTokens: output,
|
|
57
|
+
cacheReadTokens: cacheRead,
|
|
58
|
+
cacheCreationTokens: cacheCreation,
|
|
59
|
+
totalTokens: input + output + cacheRead + cacheCreation,
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
async function readFileEvents(file, sinceMs = 0) {
|
|
64
|
+
let content;
|
|
65
|
+
try {
|
|
66
|
+
content = await fs.readFile(file, 'utf8');
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
const events = [];
|
|
72
|
+
const lines = content.split('\n');
|
|
73
|
+
for (let i = 0; i < lines.length; i++) {
|
|
74
|
+
const line = lines[i];
|
|
75
|
+
if (!line.trim())
|
|
76
|
+
continue;
|
|
77
|
+
const ev = parseLine(line, file, i);
|
|
78
|
+
if (ev && ev.timestamp >= sinceMs)
|
|
79
|
+
events.push(ev);
|
|
80
|
+
}
|
|
81
|
+
return events;
|
|
82
|
+
}
|
|
83
|
+
async function listFiles() {
|
|
84
|
+
const out = [];
|
|
85
|
+
for await (const f of walkJsonl(SESSIONS_DIR))
|
|
86
|
+
out.push(f);
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
export const codexAdapter = {
|
|
90
|
+
meta: {
|
|
91
|
+
id: 'codex',
|
|
92
|
+
displayName: 'Codex',
|
|
93
|
+
detectPaths: ['~/.codex'],
|
|
94
|
+
detectCommands: ['codex'],
|
|
95
|
+
},
|
|
96
|
+
async detect() {
|
|
97
|
+
try {
|
|
98
|
+
await fs.access(SESSIONS_DIR);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
listFiles,
|
|
106
|
+
readFileEvents,
|
|
107
|
+
readFileContentEvents: readCodexContentEvents,
|
|
108
|
+
async readEvents(sinceMs = 0) {
|
|
109
|
+
const events = [];
|
|
110
|
+
for (const file of await listFiles()) {
|
|
111
|
+
try {
|
|
112
|
+
const st = await fs.stat(file);
|
|
113
|
+
if (st.mtimeMs < sinceMs)
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
events.push(...(await readFileEvents(file, sinceMs)));
|
|
120
|
+
}
|
|
121
|
+
return events;
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
// 内容流:response_item 的 function_call / function_call_output,只取尺寸
|
|
125
|
+
export async function readCodexContentEvents(file, sinceMs = 0) {
|
|
126
|
+
let content;
|
|
127
|
+
try {
|
|
128
|
+
content = await fs.readFile(file, 'utf8');
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
const events = [];
|
|
134
|
+
const sessionId = path.basename(file, '.jsonl');
|
|
135
|
+
for (const line of content.split('\n')) {
|
|
136
|
+
if (!line.includes('function_call'))
|
|
137
|
+
continue;
|
|
138
|
+
let d;
|
|
139
|
+
try {
|
|
140
|
+
d = JSON.parse(line);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
|
|
146
|
+
if (ts < sinceMs)
|
|
147
|
+
continue;
|
|
148
|
+
const p = d.payload;
|
|
149
|
+
if (p?.type === 'function_call') {
|
|
150
|
+
events.push({
|
|
151
|
+
agent: 'codex', sessionId, timestamp: ts, kind: 'tool_use',
|
|
152
|
+
tool: p.name, sizeBytes: (p.arguments ?? '').length,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
else if (p?.type === 'function_call_output') {
|
|
156
|
+
events.push({
|
|
157
|
+
agent: 'codex', sessionId, timestamp: ts, kind: 'tool_result',
|
|
158
|
+
sizeBytes: (p.output ?? '').length,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return events;
|
|
163
|
+
}
|