Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions src/collectors/hermes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { DatabaseSync } from 'node:sqlite';
import { basename } from 'node:path';
import { createHash } from 'node:crypto';
import { normalizeModel } from '../models.js';

/**
* Hermes Agent 采集器:只读 `~/.hermes/state.db`(可与其 WAL 并发)。
*
* 数据形态(实测 2026-11-16,Hermes profile=default)——与其它源都不同,接入前必读:
*
* 1. `session_model_usage` 不是逐请求事件,而是**按 (session, model, provider, task,
* billing_mode, billing_base_url) 聚合、原地累加更新**的行:api_call_count 与各 token
* 列都是"该聚合自首次以来的累计值",每次新请求把对应行 UPDATE 上去(last_seen 前移)。
* 实测 175 行、messages.token_count 全 0、逐请求粒度在库里不存在。
* → 因此本源粒度诚实标注为**会话×模型×任务级聚合**,无法 drill 到单次请求。
* 这不是实现缺陷,是上游只暴露到这个粒度(与 Qoder 只报 credits 同理:如实呈现,不造假)。
*
* 2. 正因为"先插后改、原地累加",必须按 **last_seen 时间水位**增量,不能用 rowid
* (同 OpenCode message 表的教训:rowid 水位会越过"已插入未完成"的行)。
* 每轮回看 LOOKBACK 兜住乱序提交。
*
* 3. 稳定哈希标识同一聚合。store 保留已观测到的历史,在 last_seen 的本地自然日
* 只入账余量。首次扫描或间隔多天时,上游没有逐日明细,未观测的增量只能归到
* 最后一次更新日;无法还原两次观测之间逐日或逐请求的用量。
*
* 口径:与库内统一公式一致 —— total = input + cached_input + cache_write + output,
* reasoning_tokens 只作信息列**不再加进 total**(Hermes 单列 reasoning,已含在 output 内)。
* input_tokens 取 Anthropic 口径(不含 cache_read);这是接入时唯一需对账验证的假设,
* 若某 provider 的 input 已含缓存,应在本文件按 billing_provider 分支扣减(暂未发现)。
*/

const LOOKBACK_MS = 60_000; // last_seen 回看窗,兜多写入方乱序提交(同 OpenCode)

/** 聚合身份 → 稳定键;同一聚合的所有日用量共用此前缀。 */
function aggKey(r) {
const id = [r.session_id, r.model, r.billing_provider, r.task, r.billing_mode, r.billing_base_url]
.map(x => (x == null ? '' : String(x))).join('\u0000');
return 'hermes:smu:' + createHash('sha1').update(id).digest('hex').slice(0, 20);
}

export async function collectHermesDb(store, { tool, path, state, version }) {
const st = { smuLastSeen: 0, msgMaxRowid: 0, ...(state ?? {}), _v: version };
let inserted = 0;
let db;
try {
db = new DatabaseSync(path, { readOnly: true });
} catch {
return { inserted, state: st, skip: true }; // 库不存在/被锁:跳过本轮(用户没装 Hermes)
}
try {
// 项目名来自 sessions.cwd(实测覆盖率约半数;缺失则 null,不靠目录名猜)
const sessCwd = db.prepare('SELECT cwd FROM sessions WHERE id = ?');

// Node 22.13 的 iterator 需持有 statement 强引用,防 GC 提前释放(同 OpenCode)
const iterate = (sql, ...params) => {
const statement = db.prepare(sql);
const rows = statement.iterate(...params);
Object.defineProperty(rows, 'statementRef', { value: statement });
return rows;
};

// ---- 用量事件:session_model_usage 按 last_seen 水位增量 ----
// last_seen 是 epoch 秒(real);events.ts 是毫秒整数。
const since = Math.max(0, (st.smuLastSeen || 0) - LOOKBACK_MS / 1000);
const rows = iterate(`
SELECT session_id, model, billing_provider, billing_mode, billing_base_url, task,
api_call_count, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
reasoning_tokens, last_seen
FROM session_model_usage
WHERE last_seen > ? ORDER BY last_seen`, since);
for (const r of rows) {
const lastSeen = Number(r.last_seen) || 0;
if (lastSeen > st.smuLastSeen) st.smuLastSeen = lastSeen;

const input = r.input_tokens || 0;
const cached = r.cache_read_tokens || 0;
const cacheWrite = r.cache_write_tokens || 0;
const output = r.output_tokens || 0;
const reasoning = r.reasoning_tokens || 0;
const total = input + cached + cacheWrite + output; // reasoning 不重复计入
if (total <= 0) continue; // 空调用/中断行不入事件

const cwd = sessCwd.get(r.session_id)?.cwd;
inserted += store.upsertHermesEvent({
ts: Math.round(lastSeen * 1000),
tool,
model: normalizeModel(r.model),
session_id: r.session_id,
project: cwd ? basename(cwd) : null,
input_tokens: input,
cached_input: cached,
cache_write: cacheWrite,
output_tokens: output,
reasoning_tokens: reasoning, // 信息列
total_tokens: total,
dedup_key: aggKey(r),
});
}

// ---- 工具调用:messages.tool_name 非空行,按 rowid 水位 + 删行检测 ----
// messages.id == rowid(实测 0 不一致),但 id 稀疏(max 45918 / 17723 行)说明会删行:
// 删掉最大 rowid 后号会被复用,纯 rowid 水位会静默漏掉复用的新行(同 OpenCode part 教训)。
// 表变短即删过行 → 水位退回 0 整表重读,dedup 保证幂等。
const msgTop = db.prepare('SELECT MAX(rowid) AS m FROM messages').get()?.m ?? 0;
if (msgTop < st.msgMaxRowid) st.msgMaxRowid = 0;
const tools = iterate(`
SELECT rowid AS rid, id, session_id, tool_name, timestamp
FROM messages
WHERE rowid > ? AND rowid <= ? AND tool_name IS NOT NULL AND tool_name <> ''
ORDER BY rowid`, st.msgMaxRowid, msgTop);
for (const t of tools) {
const ts = Math.round((Number(t.timestamp) || 0) * 1000);
if (!ts || !t.tool_name) continue;
store.insertToolCall({
ts, tool, name: t.tool_name, session_id: t.session_id,
dedup_key: `hermes:tc:${t.id}`,
});
}
st.msgMaxRowid = Math.max(st.msgMaxRowid, msgTop);
} finally {
db.close();
}
return { inserted, state: st };
}
12 changes: 12 additions & 0 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,18 @@ export const SOURCES = [
version: 1,
subscription: true,
},
{
tool: 'hermes',
label: 'Hermes',
// Hermes Agent(Nous Research):~/.hermes/state.db 的 session_model_usage(用量,原地累加,
// 按 last_seen 水位)+ messages.tool_name(工具调用)。粒度为会话×模型×任务级聚合,
// 上游不暴露逐请求明细(messages.token_count 全 0),如实呈现不造假。
roots: [join(HOME, '.hermes/state.db')],
kind: 'sqlite',
collector: 'hermes',
version: 1,
watchRecursive: false, // ~/.hermes 顶层含 venv/缓存等数 GB 内容,只监听直接子项(-wal 在内)
},
];

/**
Expand Down
2 changes: 1 addition & 1 deletion src/deviceTracking.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function installDeviceTracking(store) {
migrateDevices(store.db);
store._deviceTracking = true;
store._deviceContext = 'local';
for (const [table, methods] of [['events', ['insertEvent', 'insertDshEvent', 'upsertClaudeEvent', 'upsertAntigravityEvent']],
for (const [table, methods] of [['events', ['insertEvent', 'insertDshEvent', 'upsertClaudeEvent', 'upsertAntigravityEvent', 'upsertHermesEvent']],
['tool_calls', ['insertToolCall']], ['credit_usage', ['insertCredit']]]) {
const tag = store.db.prepare(`UPDATE ${table} SET device = ? WHERE dedup_key = ? AND device = 'unknown'`);
for (const name of methods) {
Expand Down
8 changes: 7 additions & 1 deletion src/scanner.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { collectOpencodeDb } from './collectors/opencode.js';
import { collectAntigravityFile } from './collectors/antigravity.js';
import { collectKimiFile } from './collectors/kimi.js';
import { collectQoderFile } from './collectors/qoder.js';
import { collectHermesDb } from './collectors/hermes.js';

const COLLECTORS = {
claude: async (store, args) => ({ ...(await collectClaudeFile(store, args)), state: { _v: args.version } }),
Expand All @@ -28,6 +29,7 @@ const COLLECTORS = {
antigravity: collectAntigravityFile, // 自带 state:上下文累计 + 模型 + 待补正事件
kimi: collectKimiFile, // 自带 state:config.update 的模型别名
qoder: async (store, args) => ({ ...(await collectQoderFile(store, args)), state: { _v: args.version } }),
hermes: collectHermesDb, // 自带 state:session_model_usage last_seen 水位 + messages rowid 水位
};

/**
Expand Down Expand Up @@ -296,8 +298,12 @@ export class Scanner extends EventEmitter {
const watchDir = src.kind === 'sqlite' ? dirname(root) : root;
// 目录不存在 = 用户没装这个工具,属正常情况,不该刷一行 watch failed 吓人
if (!existsSync(watchDir)) continue;
// watchRecursive=false 的源(如 hermes:父目录 ~/.hermes 含 venv/缓存/日志达数 GB)
// 只监听父目录直接子项——其 -wal 文件本就是直接子项,无需递归整棵树(避免无关
// FSEvent 触发全源扫描)。周期性兜底扫描仍覆盖它。
const recursive = src.watchRecursive !== false;
try {
const w = watchCb(watchDir, { recursive: true }, () => this._scheduleScan());
const w = watchCb(watchDir, { recursive }, () => this._scheduleScan());
this._watchers.push(w);
} catch {
try {
Expand Down
51 changes: 49 additions & 2 deletions src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { canonicalCodexKey, migrateCodexKeys, offloadCodexKeyArchive } from './c
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { installDeviceTracking } from './deviceTracking.js';
import { localDayStart } from './timeRange.js';

/**
* 归一化事件模型:
Expand Down Expand Up @@ -118,7 +119,10 @@ function migrate(db, dbPath) {

/** 采集器可能调用的全部写方法:stageWrites() 代理这些,其余(读)直通 */
const STAGED_WRITES = ['insertEvent', 'insertDshEvent', 'insertToolCall', 'insertCredit',
'saveQuota', 'dropStaleCodexRows', 'correctEventInput', 'upsertAntigravityEvent', 'upsertClaudeEvent'];
'saveQuota', 'dropStaleCodexRows', 'correctEventInput', 'upsertAntigravityEvent', 'upsertClaudeEvent',
'upsertHermesEvent'];

const HERMES_TOKEN_FIELDS = ['input_tokens', 'cached_input', 'cache_write', 'output_tokens', 'reasoning_tokens'];

export class Store {
constructor(dbPath) {
Expand Down Expand Up @@ -155,6 +159,16 @@ export class Store {
ts = ?, model = ?, session_id = ?, project = ?, input_tokens = ?, cached_input = ?,
cache_write = ?, output_tokens = ?, reasoning_tokens = ?, total_tokens = ?, usage_quality = ?
WHERE dedup_key = ? AND tool = 'claude-code'`);
// The fixed-length aggregate key also matches the first (including legacy) bucket.
// ':' starts its daily suffixes; ';' is the exclusive upper bound in the unique key index.
this._hermesBuckets = this.db.prepare(`SELECT dedup_key, ts, model, project,
input_tokens, cached_input, cache_write, output_tokens, reasoning_tokens
FROM events WHERE dedup_key >= ? AND dedup_key < ? AND +tool = 'hermes'
ORDER BY ts DESC`);
this._updateHermesEvent = this.db.prepare(`UPDATE events SET
ts = ?, model = ?, session_id = ?, project = ?, input_tokens = ?, cached_input = ?,
cache_write = ?, output_tokens = ?, reasoning_tokens = ?, total_tokens = ?
WHERE dedup_key = ? AND tool = 'hermes'`);
this._insertToolCall = this.db.prepare(`
INSERT OR IGNORE INTO tool_calls (ts, tool, name, session_id, dedup_key)
VALUES (?, ?, ?, ?, ?)`);
Expand Down Expand Up @@ -310,6 +324,39 @@ export class Store {
return n;
}

/** Attribute newly observed Hermes usage to the local day of the source snapshot. */
upsertHermesEvent(e) {
if (e.tool !== 'hermes') throw new Error('invalid Hermes event');
const buckets = this._hermesBuckets.all(e.dedup_key, e.dedup_key + ';');
const latest = buckets[0];
if (latest && latest.ts > e.ts) return 0; // an older scan can finish replaying later

const dayStart = localDayStart(e.ts);
const today = latest && latest.ts >= dayStart ? latest : null;
const earlier = today ? buckets.slice(1) : buckets;
const daily = { ...e };
for (const field of HERMES_TOKEN_FIELDS) {
const booked = earlier.reduce((sum, bucket) => sum + bucket[field], 0);
// last_seen is rounded to milliseconds; equal timestamps may replay out of order.
const floor = today?.ts === e.ts ? today[field] : 0;
daily[field] = Math.max(floor, (e[field] ?? 0) - booked);
}
daily.total_tokens = daily.input_tokens + daily.cached_input + daily.cache_write + daily.output_tokens;

if (!today) {
if (!daily.total_tokens && !daily.reasoning_tokens) return 0;
if (latest) daily.dedup_key = e.dedup_key + ':' + dayStart;
return this.insertEvent(daily); // tags the actual daily key with the source device
}
if (today.ts === e.ts && today.model === e.model && today.project === e.project &&
HERMES_TOKEN_FIELDS.every(field => today[field] === daily[field])) return 0;
this._updateHermesEvent.run(
e.ts, e.model ?? null, e.session_id ?? null, e.project ?? null, daily.input_tokens, daily.cached_input,
daily.cache_write, daily.output_tokens, daily.reasoning_tokens, daily.total_tokens, today.dedup_key,
);
return 0;
}

/**
* 采集器专用的写入代理:写操作先按顺序记下,解析(含异步读文件、解压)结束后由扫描器
* 在一个同步事务里 replay()。事务因此从不跨 await——同一连接上的轮询器 / 设置写入
Expand All @@ -329,7 +376,7 @@ export class Store {
const before = this.db.prepare('SELECT total_changes() n').get().n;
for (const [name, args] of ops) {
const r = this[name](...args);
if (['insertEvent', 'insertDshEvent', 'upsertAntigravityEvent', 'upsertClaudeEvent'].includes(name)) inserted += r;
if (['insertEvent', 'insertDshEvent', 'upsertAntigravityEvent', 'upsertClaudeEvent', 'upsertHermesEvent'].includes(name)) inserted += r;
}
changed = this.db.prepare('SELECT total_changes() n').get().n > before;
return inserted;
Expand Down
42 changes: 42 additions & 0 deletions test/date-ranges.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,48 @@ export async function testDateRanges(ok) {
assert.equal(sum((await buildSummary(store, {}, 0, { now })).by_day), 155);
});

await check('Hermes 跨午夜后保留首日 1000,次日只计新增 500,重放幂等', async () => {
const store = makeStore('hermes-days');
const midnight = new Date(2026, 10, 18).getTime();
const first = {
tool: 'hermes', session_id: 'overnight', model: 'kimi-k3', project: 'fixture',
dedup_key: 'hermes:smu:0123456789abcdef0123', ts: midnight - 1,
input_tokens: 600, cached_input: 200, cache_write: 100, output_tokens: 100,
reasoning_tokens: 40, total_tokens: 1000,
};
const replay = snapshot => {
const stage = store.stageWrites({ device: 'windows' });
stage.store.upsertHermesEvent(snapshot);
return stage.replay();
};
// The previous collector stored a single, unsuffixed cumulative event.
const seed = store.stageWrites({ device: 'windows' });
seed.store.insertEvent(first);
seed.replay();
assert.equal(replay(first), 0);
const next = { ...first, ts: midnight, input_tokens: 800, total_tokens: 1200 };
assert.equal(replay(next), 1);
const final = { ...next, ts: midnight + 1000, cached_input: 350, cache_write: 150,
output_tokens: 200, reasoning_tokens: 60, total_tokens: 1500 };
assert.equal(replay(final), 0);
assert.equal(replay(final), 0); // collector lookback
assert.equal(replay(next), 0); // an older staged scan finishes later
assert.equal(replay({ ...next, ts: final.ts }), 0); // same millisecond, smaller counters
assert.equal(replay({ ...final, ts: new Date(2026, 10, 19).getTime() }), 0);

const summary = await buildSummary(store, {}, 2, { now: midnight + 2000, device: 'windows' });
assert.deepEqual(summary.by_day_all, [
{ d: '2026-11-17', total: 1000 }, { d: '2026-11-18', total: 500 },
]);
assert.equal(summary.totals.today_tokens, 500);
assert.equal(summary.totals.all_time_tokens, 1500);
assert.equal(summary.totals.all_time_events, 2);
const secondDay = store.db.prepare(`SELECT input_tokens, cached_input, cache_write,
output_tokens, reasoning_tokens FROM events WHERE ts >= ?`).get(midnight);
assert.deepEqual({ ...secondDay }, { input_tokens: 200, cached_input: 150, cache_write: 50,
output_tokens: 100, reasoning_tokens: 20 });
});

await check('排行榜上报按含今天的 UTC 7/30 自然日聚合,用量及主力模型不混入前一天', async () => {
const store = makeStore('utc');
const now = Date.parse('2026-10-10T13:00:00Z');
Expand Down
Loading
Loading