@sleep2agi/commhub-server 0.9.0-preview.270 → 0.9.0-preview.273
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/node-permissions.ts +2 -0
- package/src/node-token-usage.test.ts +99 -0
- package/src/node-token-usage.ts +178 -0
- package/src/server.ts +35 -0
- package/src/tool-audience.ts +3 -0
- package/src/tools.ts +34 -0
package/build-info.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.9.0-preview.
|
|
3
|
+
"version": "0.9.0-preview.273",
|
|
4
4
|
"description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
package/src/node-permissions.ts
CHANGED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// #3952 —— 节点 Token 审计:记账能累加、读账按节点聚合、且**只收计数不收内容**。
|
|
2
|
+
//
|
|
3
|
+
// admin 原话:「要对节点进行 Token 审计了,能看到节点消耗了多少 Token」。
|
|
4
|
+
// 现状是 Hub 里一行都没有(api_tokens 是鉴权令牌 id,不是用量),
|
|
5
|
+
// 而节点侧其实看得到(claude/codex 每轮都有 input/output tokens,只是打进了日志)。
|
|
6
|
+
//
|
|
7
|
+
// 判据四格:
|
|
8
|
+
// ① 累加:同一小时同一 model 报两次 ⇒ 相加(一轮一报是常态,不是覆盖)
|
|
9
|
+
// ② 读账:按节点聚合、按 total 降序(审计第一眼看"谁最多")
|
|
10
|
+
// ③ 口径:hour 是 UTC 小时桶;sinceHours 用它比较,与写入同口径
|
|
11
|
+
// ④ 形状:表里**没有**任何内容列(prompt / message / credential)—— 由列清单钉住
|
|
12
|
+
import { describe, expect, test } from 'bun:test';
|
|
13
|
+
import './require-explicit-test-db';
|
|
14
|
+
import { db } from './db';
|
|
15
|
+
import {
|
|
16
|
+
currentHourUtc,
|
|
17
|
+
normalizeUsage,
|
|
18
|
+
readTokenUsage,
|
|
19
|
+
reportTokenUsage,
|
|
20
|
+
NODE_TOKEN_USAGE_COLUMNS,
|
|
21
|
+
} from './node-token-usage';
|
|
22
|
+
|
|
23
|
+
const net = 'net_tok_usage';
|
|
24
|
+
const nodeA = 'n_tok_a';
|
|
25
|
+
const nodeB = 'n_tok_b';
|
|
26
|
+
|
|
27
|
+
function cleanup() {
|
|
28
|
+
db.run('DELETE FROM node_token_usage WHERE network_id = ?1', [net]);
|
|
29
|
+
db.run('DELETE FROM nodes WHERE network_id = ?1', [net]);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe("#3952 节点 Token 审计", () => {
|
|
33
|
+
test("① 同一小时同一 model 报两次 ⇒ 累加", () => {
|
|
34
|
+
cleanup();
|
|
35
|
+
const hour = '2026-11-05T10';
|
|
36
|
+
expect(reportTokenUsage({ networkId: net, nodeId: nodeA, hour, model: 'deepseek/flash', inputTokens: 100, outputTokens: 20 }).ok).toBe(true);
|
|
37
|
+
expect(reportTokenUsage({ networkId: net, nodeId: nodeA, hour, model: 'deepseek/flash', inputTokens: 50, outputTokens: 10 }).ok).toBe(true);
|
|
38
|
+
const row = db.get<any>('SELECT input_tokens, output_tokens FROM node_token_usage WHERE network_id=?1 AND node_id=?2 AND hour=?3', net, nodeA, hour);
|
|
39
|
+
expect(row.input_tokens).toBe(150);
|
|
40
|
+
expect(row.output_tokens).toBe(30);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("② 读账按节点聚合、按 total 降序", () => {
|
|
44
|
+
cleanup();
|
|
45
|
+
const hour = currentHourUtc();
|
|
46
|
+
db.run('INSERT INTO nodes(node_id,node_name,alias,network_id) VALUES(?1,?2,?2,?3)', [nodeA, 'aliasA', net]);
|
|
47
|
+
db.run('INSERT INTO nodes(node_id,node_name,alias,network_id) VALUES(?1,?2,?2,?3)', [nodeB, 'aliasB', net]);
|
|
48
|
+
reportTokenUsage({ networkId: net, nodeId: nodeA, hour, model: 'm', inputTokens: 10, outputTokens: 5 });
|
|
49
|
+
reportTokenUsage({ networkId: net, nodeId: nodeB, hour, model: 'm', inputTokens: 900, outputTokens: 100 });
|
|
50
|
+
const rows = readTokenUsage(net, 24);
|
|
51
|
+
expect(rows.map((r) => r.node_id)).toEqual([nodeB, nodeA]);
|
|
52
|
+
expect(rows[0].total_tokens).toBe(1000);
|
|
53
|
+
expect(rows[0].alias).toBe('aliasB');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("③ 口径:窗口外的行不出现(hour 是 UTC 小时桶)", () => {
|
|
57
|
+
cleanup();
|
|
58
|
+
const now = currentHourUtc();
|
|
59
|
+
const old = currentHourUtc(Date.now() - 48 * 3600_000);
|
|
60
|
+
reportTokenUsage({ networkId: net, nodeId: nodeA, hour: now, model: 'm', inputTokens: 1, outputTokens: 1 });
|
|
61
|
+
reportTokenUsage({ networkId: net, nodeId: nodeA, hour: old, model: 'm', inputTokens: 999, outputTokens: 999 });
|
|
62
|
+
const rows = readTokenUsage(net, 24);
|
|
63
|
+
expect(rows.length).toBe(1);
|
|
64
|
+
expect(rows[0].total_tokens).toBe(2);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("cache 单列:报进去不进 total(它是 input 的几百倍,混算会把排行变成「谁最老」)", () => {
|
|
68
|
+
cleanup();
|
|
69
|
+
const hour = currentHourUtc();
|
|
70
|
+
reportTokenUsage({ networkId: net, nodeId: nodeA, hour, model: 'm', inputTokens: 100, outputTokens: 10, cacheReadTokens: 50_000 });
|
|
71
|
+
const rows = readTokenUsage(net, 24);
|
|
72
|
+
expect(rows[0].total_tokens).toBe(110);
|
|
73
|
+
expect(rows[0].cache_read_tokens).toBe(50_000);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("④ 形状:表里没有任何内容列(prompt / message / credential 一律不存在)", () => {
|
|
77
|
+
const shape = [...NODE_TOKEN_USAGE_COLUMNS].join(",");
|
|
78
|
+
expect(shape).not.toMatch(/prompt|message|content|credential|secret|token_value/i);
|
|
79
|
+
const cols = db.all<{ name: string }>("PRAGMA table_info(node_token_usage)").map((c) => c.name);
|
|
80
|
+
expect(cols.sort()).toEqual([...NODE_TOKEN_USAGE_COLUMNS].sort());
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("什么都不报 ⇒ 拒绝,且不写全 0 行(0 与「没上报」不能同形)", () => {
|
|
84
|
+
cleanup();
|
|
85
|
+
expect(reportTokenUsage({ networkId: net, nodeId: nodeA }).ok).toBe(false);
|
|
86
|
+
const n = db.get<{ c: number }>('SELECT COUNT(*) AS c FROM node_token_usage WHERE network_id=?1', net)?.c;
|
|
87
|
+
expect(n).toBe(0);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("hour 形状不对 ⇒ 拒绝(不做「猜一个」)", () => {
|
|
91
|
+
expect(normalizeUsage({ networkId: net, nodeId: nodeA, hour: '2026-11-05 10:00:00', inputTokens: 1 })).toBeNull();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("镜像:turns / cost 没给就留空(不填 0 冒充「知道」)", () => {
|
|
95
|
+
const norm = normalizeUsage({ networkId: net, nodeId: nodeA, hour: '2026-11-05T10', inputTokens: 5 });
|
|
96
|
+
expect(norm?.turns).toBeNull();
|
|
97
|
+
expect(norm?.costUsd).toBeNull();
|
|
98
|
+
});
|
|
99
|
+
});
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// #3952(admin 2026-11-05「要对节点进行 Token 审计,能看到节点消耗了多少 Token」)
|
|
2
|
+
//
|
|
3
|
+
// 现状:Hub 里**没有任何** token 用量记账 —— 只有 api_tokens(那是鉴权用的令牌 id,
|
|
4
|
+
// 和"消耗了多少 token"是两回事)。节点侧其实**看得到**用量(claude/codex 的每轮结果里
|
|
5
|
+
// 都有 input_tokens / output_tokens,只是打进了日志),但从来没有上报。
|
|
6
|
+
//
|
|
7
|
+
// 本模块只做「记账 + 读账」,不做采集:
|
|
8
|
+
// 写 reportTokenUsage() 节点令牌专用,按 (network, node, hour, model) 累加
|
|
9
|
+
// 读 readTokenUsage() 人(成员/owner/admin)按节点聚合
|
|
10
|
+
//
|
|
11
|
+
// 已知边界:turns / cost_usd 列 NOT NULL DEFAULT 0 ⇒ 「没报」与「报了 0」在存储上同形。
|
|
12
|
+
// 要区分得再加一列 has_turns;当前不值这个复杂度(谁要区分,读 normalizeUsage 的返回值)。
|
|
13
|
+
//
|
|
14
|
+
// 三条口径(写死,避免以后各说各话):
|
|
15
|
+
// ① hour 是 **UTC 小时桶**('YYYY-MM-DDTHH'),与 node_tool_calls 同口径。
|
|
16
|
+
// ② 累加而不是覆盖:同一小时同一 model 多次上报要相加 —— 一轮一报是常态。
|
|
17
|
+
// ③ **只收计数,不收内容**:没有 prompt、没有消息 id、没有凭据。
|
|
18
|
+
// 这一点由 schema 的形状保证(列就那几个),也由测试钉住。
|
|
19
|
+
|
|
20
|
+
import { db } from './db';
|
|
21
|
+
|
|
22
|
+
// 建表放在**本模块**而不是别处的 schema 大块:那样只要 import 了本模块,表就一定在。
|
|
23
|
+
// (2026-11-05 踩过:放 node-permissions.ts 的 exec 块里,单测没 import 它 ⇒ no such table。)
|
|
24
|
+
db.exec(`
|
|
25
|
+
CREATE TABLE IF NOT EXISTS node_token_usage (
|
|
26
|
+
network_id TEXT NOT NULL,
|
|
27
|
+
node_id TEXT NOT NULL,
|
|
28
|
+
hour TEXT NOT NULL,
|
|
29
|
+
model TEXT NOT NULL DEFAULT 'unknown',
|
|
30
|
+
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
31
|
+
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
32
|
+
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
turns INTEGER NOT NULL DEFAULT 0,
|
|
34
|
+
cost_usd REAL NOT NULL DEFAULT 0,
|
|
35
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
36
|
+
PRIMARY KEY (network_id, node_id, hour, model)
|
|
37
|
+
);
|
|
38
|
+
CREATE INDEX IF NOT EXISTS idx_node_token_usage_hour ON node_token_usage(network_id, hour);
|
|
39
|
+
`);
|
|
40
|
+
// 已存在的库补列(SQLite 没有 IF NOT EXISTS for ADD COLUMN)
|
|
41
|
+
try { db.exec("ALTER TABLE node_token_usage ADD COLUMN cache_read_tokens INTEGER NOT NULL DEFAULT 0"); } catch {}
|
|
42
|
+
|
|
43
|
+
export interface TokenUsageInput {
|
|
44
|
+
networkId: string;
|
|
45
|
+
nodeId: string;
|
|
46
|
+
/** 'YYYY-MM-DDTHH'(UTC);缺省 = 现在这一小时 */
|
|
47
|
+
hour?: string | null;
|
|
48
|
+
/** provider/model 或运行时的自有标识;缺省 'unknown' —— 不假装知道 */
|
|
49
|
+
model?: string | null;
|
|
50
|
+
inputTokens?: number | null;
|
|
51
|
+
outputTokens?: number | null;
|
|
52
|
+
/** 缓存命中的读入量。**必须单列**:opencode 实测 cache.read 是 input+output 的 289 倍,
|
|
53
|
+
* 混进去算会让「谁用得多」变成「谁用得久」。 */
|
|
54
|
+
cacheReadTokens?: number | null;
|
|
55
|
+
/** 有的运行时只给总轮数/费用;没有就留空,**不填 0**(0 与"不知道"是两件事) */
|
|
56
|
+
turns?: number | null;
|
|
57
|
+
costUsd?: number | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const HOUR_RE = /^\d{4}-\d{2}-\d{2}T\d{2}$/;
|
|
61
|
+
const MODEL_MAX = 100;
|
|
62
|
+
|
|
63
|
+
export function currentHourUtc(now = Date.now()): string {
|
|
64
|
+
return new Date(now).toISOString().slice(0, 13);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function nonNegativeInt(value: unknown): number | null {
|
|
68
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return null;
|
|
69
|
+
if (!Number.isSafeInteger(Math.round(value))) return null;
|
|
70
|
+
return Math.round(value);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 校验 + 归一。返回 null 表示「这一份上报不合规」——调用方负责拒绝,不静默丢。 */
|
|
74
|
+
export function normalizeUsage(input: TokenUsageInput): {
|
|
75
|
+
hour: string; model: string;
|
|
76
|
+
inputTokens: number; outputTokens: number; cacheReadTokens: number;
|
|
77
|
+
turns: number | null; costUsd: number | null;
|
|
78
|
+
} | null {
|
|
79
|
+
const hour = typeof input.hour === 'string' && input.hour ? input.hour : currentHourUtc();
|
|
80
|
+
if (!HOUR_RE.test(hour)) return null;
|
|
81
|
+
const rawModel = typeof input.model === 'string' ? input.model.trim() : '';
|
|
82
|
+
if (rawModel.length > MODEL_MAX) return null;
|
|
83
|
+
const model = rawModel || 'unknown';
|
|
84
|
+
const inputTokens = nonNegativeInt(input.inputTokens) ?? 0;
|
|
85
|
+
const outputTokens = nonNegativeInt(input.outputTokens) ?? 0;
|
|
86
|
+
const cacheReadTokens = nonNegativeInt(input.cacheReadTokens) ?? 0;
|
|
87
|
+
if (inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && input.turns == null && input.costUsd == null) {
|
|
88
|
+
// 什么都没报:不写一行全 0 的记录(那会让"没有用量"和"没上报"在报表上同形)。
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const turns = nonNegativeInt(input.turns);
|
|
92
|
+
const costRaw = input.costUsd;
|
|
93
|
+
const costUsd = typeof costRaw === 'number' && Number.isFinite(costRaw) && costRaw >= 0 ? costRaw : null;
|
|
94
|
+
return { hour, model, inputTokens, outputTokens, cacheReadTokens, turns, costUsd };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 记账:同一 (network, node, hour, model) 累加。turns/cost 可空,空则保持原值。 */
|
|
98
|
+
export function reportTokenUsage(input: TokenUsageInput): { ok: true; hour: string; model: string } | { ok: false; error: string } {
|
|
99
|
+
const norm = normalizeUsage(input);
|
|
100
|
+
if (!norm) return { ok: false, error: 'invalid_token_usage' };
|
|
101
|
+
db.run(
|
|
102
|
+
`INSERT INTO node_token_usage(network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens, turns, cost_usd, updated_at)
|
|
103
|
+
VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, COALESCE(?8, 0), COALESCE(?9, 0), datetime('now'))
|
|
104
|
+
ON CONFLICT(network_id, node_id, hour, model) DO UPDATE SET
|
|
105
|
+
input_tokens = input_tokens + excluded.input_tokens,
|
|
106
|
+
output_tokens = output_tokens + excluded.output_tokens,
|
|
107
|
+
cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
|
|
108
|
+
turns = COALESCE(turns, 0) + COALESCE(excluded.turns, 0),
|
|
109
|
+
cost_usd = COALESCE(cost_usd, 0) + COALESCE(excluded.cost_usd, 0),
|
|
110
|
+
updated_at = datetime('now')`,
|
|
111
|
+
// turns / cost_usd 这里存 0 = 「没有这一项」。**存储层不区分「0 轮」与「没报轮数」**,
|
|
112
|
+
// 这是已知偏差(见文件头「已知边界」);要区分得加一列 has_turns,成本不值。
|
|
113
|
+
[input.networkId, input.nodeId, norm.hour, norm.model, norm.inputTokens, norm.outputTokens,
|
|
114
|
+
norm.cacheReadTokens, norm.turns, norm.costUsd],
|
|
115
|
+
);
|
|
116
|
+
return { ok: true, hour: norm.hour, model: norm.model };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface NodeTokenUsageRow {
|
|
120
|
+
node_id: string;
|
|
121
|
+
alias: string | null;
|
|
122
|
+
input_tokens: number;
|
|
123
|
+
output_tokens: number;
|
|
124
|
+
/** input+output(**不含 cache**)—— 报表默认看这个 */
|
|
125
|
+
total_tokens: number;
|
|
126
|
+
/** 单列;opencode 上它可能是 total 的几百倍 */
|
|
127
|
+
cache_read_tokens: number;
|
|
128
|
+
turns: number;
|
|
129
|
+
cost_usd: number;
|
|
130
|
+
models: number;
|
|
131
|
+
first_hour: string | null;
|
|
132
|
+
last_hour: string | null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 读账:按节点聚合。`sinceHours` 用 UTC 小时桶比较(与写入同口径)。
|
|
137
|
+
*
|
|
138
|
+
* 排序:total_tokens 降序 —— 审计第一眼要看"谁最多",而不是按名字排。
|
|
139
|
+
*/
|
|
140
|
+
export function readTokenUsage(networkId: string, sinceHours = 24): NodeTokenUsageRow[] {
|
|
141
|
+
const hours = Math.max(1, Math.min(24 * 90, Math.floor(sinceHours)));
|
|
142
|
+
const since = currentHourUtc(Date.now() - hours * 3600_000);
|
|
143
|
+
const rows = db.all<{
|
|
144
|
+
node_id: string; alias: string | null;
|
|
145
|
+
input_tokens: number; output_tokens: number;
|
|
146
|
+
turns: number; cost_usd: number; models: number;
|
|
147
|
+
first_hour: string | null; last_hour: string | null;
|
|
148
|
+
}>(
|
|
149
|
+
`SELECT u.node_id,
|
|
150
|
+
COALESCE(n.alias, s.alias) AS alias,
|
|
151
|
+
SUM(u.input_tokens) AS input_tokens,
|
|
152
|
+
SUM(u.output_tokens) AS output_tokens,
|
|
153
|
+
SUM(u.cache_read_tokens) AS cache_read_tokens,
|
|
154
|
+
SUM(u.turns) AS turns,
|
|
155
|
+
SUM(u.cost_usd) AS cost_usd,
|
|
156
|
+
COUNT(DISTINCT u.model) AS models,
|
|
157
|
+
MIN(u.hour) AS first_hour,
|
|
158
|
+
MAX(u.hour) AS last_hour
|
|
159
|
+
FROM node_token_usage u
|
|
160
|
+
LEFT JOIN nodes n ON n.node_id = u.node_id AND n.network_id = u.network_id
|
|
161
|
+
LEFT JOIN sessions s ON s.node_id = u.node_id AND s.network_id = u.network_id
|
|
162
|
+
WHERE u.network_id = ?1 AND u.hour >= ?2
|
|
163
|
+
GROUP BY u.node_id
|
|
164
|
+
ORDER BY (SUM(u.input_tokens) + SUM(u.output_tokens)) DESC`,
|
|
165
|
+
networkId, since,
|
|
166
|
+
);
|
|
167
|
+
return rows.map((r) => ({
|
|
168
|
+
...r,
|
|
169
|
+
cache_read_tokens: r.cache_read_tokens ?? 0,
|
|
170
|
+
total_tokens: (r.input_tokens ?? 0) + (r.output_tokens ?? 0),
|
|
171
|
+
}));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 记账表与读账口径都只认这几个列 —— 形状就是「不收内容」的保证。 */
|
|
175
|
+
export const NODE_TOKEN_USAGE_COLUMNS = [
|
|
176
|
+
'network_id', 'node_id', 'hour', 'model',
|
|
177
|
+
'input_tokens', 'output_tokens', 'cache_read_tokens', 'turns', 'cost_usd', 'updated_at',
|
|
178
|
+
] as const;
|
package/src/server.ts
CHANGED
|
@@ -108,6 +108,7 @@ import { startDueReminderTimer } from "./requirement-due-reminders.js";
|
|
|
108
108
|
import { clearNodeFromRequirements, handleRequirementsRequest } from "./requirements.js";
|
|
109
109
|
import { readHubProviders, putHubProvider, providerWriteStatus } from "./hub-provider-config.js";
|
|
110
110
|
import { readLastConfigUpdate } from "./node-config-last-update.js";
|
|
111
|
+
import { readTokenUsage } from "./node-token-usage.js";
|
|
111
112
|
import { readBuildInfo } from "./build-info.js";
|
|
112
113
|
import { requestProviderApplication } from "./daemon-provider-snapshots.js";
|
|
113
114
|
import { requestNodeSecrets, getScopedSecrets } from "./scoped-secrets.js";
|
|
@@ -6393,6 +6394,40 @@ return Bun.serve({
|
|
|
6393
6394
|
// {model, flags, config_revision} the node last posted via
|
|
6394
6395
|
// report_status (B6). NEVER reads per-node files. Network-scoped
|
|
6395
6396
|
// via addNetworkScope so a netA viewer can't read a netB node.
|
|
6397
|
+
// ── #3952 Token 审计(admin 2026-11-05)──
|
|
6398
|
+
// GET /api/token-usage?network_id=…&since_hours=24
|
|
6399
|
+
// 人(成员/owner/admin)读本网络各节点的 LLM token 计数聚合;节点令牌不给(user_token_required)。
|
|
6400
|
+
// 为什么走 REST 而不是 MCP 工具:tools/list 的 user 预算只剩 ~500 B,
|
|
6401
|
+
// 而一个带 schema 的新工具要 ~900 B —— 审计页本来就是人看的表,REST 更合适。
|
|
6402
|
+
// 只回计数:没有 prompt、没有消息 id、没有凭据(表形状决定的)。
|
|
6403
|
+
if (url.pathname === "/api/token-usage" && req.method === "GET") {
|
|
6404
|
+
const token = requestToken(req, { allowQueryToken: false });
|
|
6405
|
+
const resolved = token ? resolveToken(token) : null;
|
|
6406
|
+
if (!resolved) return withCors(req, Response.json({ ok: false, error: "auth required" }, { status: 401 }));
|
|
6407
|
+
if (isNodeCredential(resolved)) return withCors(req, Response.json({ ok: false, error: "user_token_required" }, { status: 403 }));
|
|
6408
|
+
const netId = getNetworkId(url.searchParams.get("network_id") ?? undefined);
|
|
6409
|
+
if (!netId) return withCors(req, Response.json({ ok: false, error: "network_required" }, { status: 400 }));
|
|
6410
|
+
const role = resolved.user.role === "admin" ? "admin" : getUserNetworkRole(resolved.user.user_id, netId);
|
|
6411
|
+
if (!role) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
|
|
6412
|
+
const raw = Number(url.searchParams.get("since_hours") ?? 24);
|
|
6413
|
+
const sinceHours = Number.isFinite(raw) ? Math.max(1, Math.min(24 * 90, Math.floor(raw))) : 24;
|
|
6414
|
+
const nodes = readTokenUsage(netId, sinceHours);
|
|
6415
|
+
const totals = nodes.reduce((acc, r) => ({
|
|
6416
|
+
input_tokens: acc.input_tokens + r.input_tokens,
|
|
6417
|
+
output_tokens: acc.output_tokens + r.output_tokens,
|
|
6418
|
+
// cache 单列:它可能是 total 的几百倍,绝不能加进 total
|
|
6419
|
+
cache_read_tokens: acc.cache_read_tokens + r.cache_read_tokens,
|
|
6420
|
+
total_tokens: acc.total_tokens + r.total_tokens,
|
|
6421
|
+
cost_usd: Number((acc.cost_usd + r.cost_usd).toFixed(6)),
|
|
6422
|
+
}), { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, total_tokens: 0, cost_usd: 0 });
|
|
6423
|
+
return withCors(req, Response.json({
|
|
6424
|
+
ok: true, network_id: netId, since_hours: sinceHours,
|
|
6425
|
+
// 空表也要说清口径:0 行可能因为「没人上报」,也可能因为「窗口里没用量」。
|
|
6426
|
+
note: nodes.length ? undefined : "这个窗口里没有任何节点上报过 token 用量(不是「用量为 0」)",
|
|
6427
|
+
nodes, totals,
|
|
6428
|
+
}));
|
|
6429
|
+
}
|
|
6430
|
+
|
|
6396
6431
|
const nodeConfigMatch = url.pathname.match(/^\/api\/nodes\/([^/]+)\/config$/);
|
|
6397
6432
|
if (nodeConfigMatch && req.method === "GET") {
|
|
6398
6433
|
const nodeId = decodeURIComponent(nodeConfigMatch[1] ?? "");
|
package/src/tool-audience.ts
CHANGED
|
@@ -50,6 +50,9 @@ export const TOOL_AUDIENCE: Readonly<Record<string, ToolAudience>> = {
|
|
|
50
50
|
submit_skill: "both", list_skills: "both", get_skill: "both", review_skill: "both",
|
|
51
51
|
report_completion: "both", get_inbox: "both", ack_inbox: "both",
|
|
52
52
|
get_all_status: "both", get_session_status: "both",
|
|
53
|
+
// #3952 —— Token 审计:节点上报走 protocol(默认不列,agent-node 按名直调);
|
|
54
|
+
// 人的审计视图走 REST `/api/nodes/token-usage`,**不占 tools/list 预算**。
|
|
55
|
+
report_token_usage: "protocol",
|
|
53
56
|
send_task: "both", send_message: "both", send_reply: "both", send_peer_reply: "both", send_ack: "both",
|
|
54
57
|
retry_task: "both", get_task: "both", list_tasks: "both", cancel_task: "both", reassign_task: "both",
|
|
55
58
|
send_desktop_message: "both", broadcast: "both", get_completions: "both",
|
package/src/tools.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { clearNodeFromAgentTeams, agentTeamWhoami } from "./agent-teams.js";
|
|
|
16
16
|
import { parseDbTimestampMs } from "./db-timestamp.js";
|
|
17
17
|
import { z } from "zod/v4";
|
|
18
18
|
import { nodeHealthSchema, normalizeNodeHealth, recordNodeHealth } from "./node-health-store.js";
|
|
19
|
+
import { readTokenUsage, reportTokenUsage } from "./node-token-usage.js";
|
|
19
20
|
import { assertNodeHealthy } from "./node-health-guard.js";
|
|
20
21
|
import { noteModelAuthHealth } from "./model-auth-notify.js";
|
|
21
22
|
import { numberedAliasInClause, parseAliasFilter } from "./alias-filter.js";
|
|
@@ -3295,6 +3296,39 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
3295
3296
|
}
|
|
3296
3297
|
);
|
|
3297
3298
|
|
|
3299
|
+
// ── #3952 Token 审计(admin 2026-11-05)──
|
|
3300
|
+
// ── #3952 Token 审计(admin 2026-11-05)──
|
|
3301
|
+
// audience=protocol:agent-node 按名字直接调、从不 list,所以它**不进 tools/list**,
|
|
3302
|
+
// 也就不吃那个只剩 3 B 的 node 预算。这不是偷懒,是那条预算的实际约束推出来的唯一合理归类。
|
|
3303
|
+
server.tool(
|
|
3304
|
+
"report_token_usage",
|
|
3305
|
+
"Node reports its own LLM token counts (never content).",
|
|
3306
|
+
{
|
|
3307
|
+
hour: z.string().max(13).optional(),
|
|
3308
|
+
model: z.string().max(100).optional(),
|
|
3309
|
+
input_tokens: z.number().int().min(0).optional(),
|
|
3310
|
+
output_tokens: z.number().int().min(0).optional(),
|
|
3311
|
+
cache_read_tokens: z.number().int().min(0).optional(),
|
|
3312
|
+
turns: z.number().int().min(0).optional(),
|
|
3313
|
+
cost_usd: z.number().min(0).optional(),
|
|
3314
|
+
},
|
|
3315
|
+
async ({ hour, model, input_tokens, output_tokens, cache_read_tokens, turns, cost_usd }) => {
|
|
3316
|
+
if (!callerTokenIsNetwork || !enforceNetworkId || !callerAlias) {
|
|
3317
|
+
return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "network_token_required" }) }] };
|
|
3318
|
+
}
|
|
3319
|
+
const node = resolveCallerNode();
|
|
3320
|
+
if (!node) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "alias_unknown" }) }] };
|
|
3321
|
+
const r = reportTokenUsage({
|
|
3322
|
+
networkId: enforceNetworkId, nodeId: node.node_id,
|
|
3323
|
+
hour: hour ?? null, model: model ?? null,
|
|
3324
|
+
inputTokens: input_tokens ?? null, outputTokens: output_tokens ?? null,
|
|
3325
|
+
cacheReadTokens: cache_read_tokens ?? null,
|
|
3326
|
+
turns: turns ?? null, costUsd: cost_usd ?? null,
|
|
3327
|
+
});
|
|
3328
|
+
return { content: [{ type: "text" as const, text: JSON.stringify(r) }] };
|
|
3329
|
+
},
|
|
3330
|
+
);
|
|
3331
|
+
|
|
3298
3332
|
// ── V2: cancel_task (取消任务) ──
|
|
3299
3333
|
server.tool(
|
|
3300
3334
|
"cancel_task",
|