@aiti-ai/aiti-ai-usage 0.1.9 → 0.1.10

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/index.ts CHANGED
@@ -16,7 +16,6 @@ let initialized = false;
16
16
  export default {
17
17
  id: "aiti-ai-usage",
18
18
  name: "AI Usage",
19
- version: "0.1.0",
20
19
  icon: "icon.svg",
21
20
  client: "dist/aiti-ai-usage.mjs",
22
21
 
@@ -62,6 +61,7 @@ export default {
62
61
  try { cur = runtime(); } catch { return; } // runtime 未初始化(shutdown 窗口)→ 跳过该条
63
62
  try {
64
63
  liveIngest(cur, info.sessionId, event.message);
64
+ recordLiveToolCalls(cur.usage, info.sessionId, event.message); // borrow plan §2.7A: tool calls recorded live in passing (file scans fill in ok/duration)
65
65
  } catch (e) {
66
66
  console.error("[aiti-ai-usage] live ingest:", e instanceof Error ? e.message : e);
67
67
  }
@@ -88,11 +88,17 @@ export default {
88
88
  // [懒加载 v2] 纯报表面板:开页不拉 client bundle(82KB)——toolbar 静态按钮点击经
89
89
  // meta.onClick 物化打开;sessionStats 是交互插槽(打开会话信息时自动物化)。
90
90
  clientImmediately: false,
91
- toolbar: [{ id: "usage", label: "用量", title: "AI 用量报表", icon: "icons/chart-column.svg" }],
91
+ toolbar: [{ id: "usage", label: "i18n:au.app.label", title: "i18n:au.app.title", icon: "icons/chart-column.svg" }],
92
92
  sessionStats: [{ id: "report-entry", label: "用量报表按钮", title: "会话统计下拉内「用量报表」入口" }],
93
- dialogs: [{ id: "report", label: "AI 用量报表" }],
93
+ dialogs: [{ id: "report", label: "i18n:it.report.label" }],
94
94
  i18n: {
95
95
  en: {
96
+ "it.report.title": "Usage report",
97
+ "it.report.label": "AI usage report",
98
+ "ext.displayName": "AI Usage", "feat.report-entry": "Usage report button",
99
+ "feat.report": "AI usage report",
100
+ "au.app.label": "Usage",
101
+ "au.app.title": "AI usage report",
96
102
  "au.title": "AI Usage Report",
97
103
  "au.entry": "Usage Report",
98
104
  "au.tabOverview": "Overview",
@@ -101,6 +107,31 @@ export default {
101
107
  "au.tabPivot": "Pivot",
102
108
  "au.tabTrend": "Trend",
103
109
  "au.tabSessions": "Sessions",
110
+ "au.tabCatalog": "Catalog",
111
+ "au.catalog.intro": "Fixed per-session injection cost: MCP schema ≈{tok} tokens across {n} tools, repeated with every API request. Paired with 30-day call counts (MCP calls attributed at server level — pi's recording caliber) — cost × usage shows the waste at a glance.",
112
+ "au.catalog.mcp": "MCP servers",
113
+ "au.catalog.server": "Server",
114
+ "au.catalog.state": "State",
115
+ "au.catalog.tools": "Tools",
116
+ "au.catalog.estTok": "Est. tokens",
117
+ "au.catalog.used30d": "Calls 30d",
118
+ "au.catalog.noMcp": "No MCP cache found (pi generates it on first session)",
119
+ "au.catalog.skills": "Skills",
120
+ "au.catalog.skillName": "Skill",
121
+ "au.catalog.enable": "Enable",
122
+ "au.catalog.disable": "Disable",
123
+ "au.catalog.disabledNote": "hidden from the model",
124
+ "au.catalog.noSkills": "No skills found",
125
+ "au.catalog.toolMeta": "~{tok} tok · {n} calls in 30d",
126
+ "au.catalog.patterns": "Exclude patterns",
127
+ "au.catalog.dropPattern": "Drop this pattern (restores matching tools)",
128
+ "au.catalog.exclude": "Exclude",
129
+ "au.catalog.restore": "Restore",
130
+ "au.catalog.excludedBadge": "excluded",
131
+ "au.catalog.excludeNote": "Hide this tool from the model's tool list (writes mcp.json excludeTools; effective next session; model visibility only)",
132
+ "au.catalog.restoreNote": "Remove this tool from the exclusion list (effective next session)",
133
+ "au.catalog.phantomNote": "Already excluded and absent from the current cache (list row kept for restore)",
134
+ "au.catalog.rules": "Governance notes: toggles only affect model visibility (manual slash/mention paths stay); give newly installed servers/skills a ~7-day trial before judging usage; never auto-disable — evidence first.",
104
135
  "au.range.today": "Today",
105
136
  "au.range.7d": "7 days",
106
137
  "au.range.30d": "30 days",
@@ -222,6 +253,10 @@ export default {
222
253
  "au.quote.fileref": "@file mention",
223
254
  },
224
255
  "zh-CN": {
256
+ "it.report.title": "用量",
257
+ "it.report.label": "AI 用量报表",
258
+ "ext.displayName": "AI 用量统计", "au.app.label": "用量",
259
+ "au.app.title": "AI 用量报表",
225
260
  "au.title": "AI 用量报表",
226
261
  "au.entry": "用量报表",
227
262
  "au.tabOverview": "总览",
@@ -230,6 +265,31 @@ export default {
230
265
  "au.tabPivot": "维度",
231
266
  "au.tabTrend": "趋势",
232
267
  "au.tabSessions": "会话",
268
+ "au.tabCatalog": "目录账单",
269
+ "au.catalog.intro": "会话固定注入成本:MCP schema ≈{tok} tokens / {n} 个工具,随每次 API 请求重复发送。与最近 30 天调用次数并排(MCP 调用按 server 级归因——pi 记录口径)——成本 × 使用率一眼看出浪费项。",
270
+ "au.catalog.mcp": "MCP servers",
271
+ "au.catalog.server": "Server",
272
+ "au.catalog.state": "状态",
273
+ "au.catalog.tools": "工具数",
274
+ "au.catalog.estTok": "估算 tokens",
275
+ "au.catalog.used30d": "30 天调用",
276
+ "au.catalog.noMcp": "未发现 MCP 缓存(pi 首次会话后生成)",
277
+ "au.catalog.skills": "Skills",
278
+ "au.catalog.skillName": "Skill",
279
+ "au.catalog.enable": "启用",
280
+ "au.catalog.disable": "禁用",
281
+ "au.catalog.disabledNote": "模型不可见",
282
+ "au.catalog.noSkills": "未发现 skills",
283
+ "au.catalog.toolMeta": "≈{tok} tok · 30 天 {n} 次",
284
+ "au.catalog.patterns": "排除规则",
285
+ "au.catalog.dropPattern": "删除此规则(恢复匹配的工具)",
286
+ "au.catalog.exclude": "排除",
287
+ "au.catalog.restore": "恢复",
288
+ "au.catalog.excludedBadge": "已排除",
289
+ "au.catalog.excludeNote": "从模型工具清单排除此工具(写 mcp.json excludeTools;下次会话生效,只影响模型可见性)",
290
+ "au.catalog.restoreNote": "从排除名单移除此工具(下次会话生效)",
291
+ "au.catalog.phantomNote": "此工具已被排除且不在当前缓存中(名单行,供恢复)",
292
+ "au.catalog.rules": "治理纪律:开关只影响模型可见性(人工 slash/引用路径保留);新装 server/skill 先给约 7 天试用期再判使用率;绝不自动禁用——证据先行。",
233
293
  "au.range.today": "今天",
234
294
  "au.range.7d": "近7天",
235
295
  "au.range.30d": "近30天",
@@ -357,7 +417,7 @@ export default {
357
417
  // ---------------------------------------------------------------- live ingest
358
418
 
359
419
  import { localDay } from "./lib/db.ts";
360
- import { noteDirtyDay, scheduleFlush } from "./lib/ingest.ts";
420
+ import { noteDirtyDay, scheduleFlush, recordLiveToolCalls } from "./lib/ingest.ts";
361
421
 
362
422
  function liveIngest(rt: ReturnType<typeof init>, sessionId: string, msg: Record<string, any>): void {
363
423
  const u = msg.usage;
package/lib/catalog.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * catalog.ts — tool/skill catalog billing data layer (borrow plan §2.7B/C)
3
+ *
4
+ * Catalog billing = fixed injection-cost inventory: MCP servers × tools × schema tokens (bytes/4
5
+ * caliber, same as pi's estimateTokens in lib/subagent-input.ts) + skills (the formatSkillsForPrompt
6
+ * surface) side-by-side with 30-day call counts — cost × usage exposes the waste at a glance.
7
+ *
8
+ * Pure functions (buildCatalog/estimateTokens) are directly testable; collectCatalog assembles on the
9
+ * server (bounded mcp-cache.json read ≤8MB, mcp.json enabled states, same-origin /api/skills surface).
10
+ */
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+
14
+ /** pi's own estimate caliber (estimateTokens in its compaction module): ~4 chars/token. */
15
+ export function estimateTokens(s: string): number {
16
+ return Math.ceil((s || "").length / 4);
17
+ }
18
+
19
+ /** Estimated tokens for a tool's schema + description (§2.7 caliber: inputSchema JSON bytes + description) */
20
+ export function toolEstTokens(tool: { name?: string; description?: string; inputSchema?: unknown }): number {
21
+ let chars = 0;
22
+ try { chars += JSON.stringify(tool.inputSchema ?? {}).length; } catch { chars += 2; }
23
+ chars += (tool.description || "").length;
24
+ chars += (tool.name || "").length;
25
+ return estimateTokens(chars === 0 ? "" : "x".repeat(chars));
26
+ }
27
+
28
+ export interface CatalogTool { name: string; estTokens: number; calls30d: number; excluded?: boolean; phantom?: boolean }
29
+ export interface CatalogMcpServer {
30
+ name: string;
31
+ enabled: boolean;
32
+ toolCount: number;
33
+ estTokens: number;
34
+ calls30d: number;
35
+ cachedAt: string | null;
36
+ /** mcp.json excludeTools patterns (adapter honors globs at tool-registration time) */
37
+ excludedPatterns: string[];
38
+ tools: CatalogTool[];
39
+ }
40
+
41
+ /** Glob → RegExp (`*` wildcard, everything else literal); used for excludeTools display matching. */
42
+ export function globToRegExp(pattern: string): RegExp {
43
+ const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[\\s\\S]*");
44
+ return new RegExp("^" + escaped + "$", "i");
45
+ }
46
+
47
+ export function toolMatchesPatterns(toolName: string, patterns: string[]): boolean {
48
+ return patterns.some((p) => p && globToRegExp(p).test(toolName));
49
+ }
50
+ export interface CatalogSkill { name: string; filePath: string; disabled: boolean; calls30d: number }
51
+ export interface Catalog {
52
+ mcp: CatalogMcpServer[];
53
+ mcpTotalTools: number;
54
+ mcpTotalTokens: number;
55
+ skills: CatalogSkill[];
56
+ skillCalls30d: number;
57
+ notes: string[];
58
+ }
59
+
60
+ /** Assemble the MCP catalog from mcp-cache.json + mcp.json (bounded reads; missing/corrupt → empty + note). */
61
+ export function readMcpCatalog(agentDir: string, notes: string[]): Array<{ name: string; enabled: boolean; toolCount: number; estTokens: number; cachedAt: string | null; excludedPatterns: string[]; tools: CatalogTool[] }> {
62
+ const cachePath = path.join(agentDir, "mcp-cache.json");
63
+ const cfgPath = path.join(agentDir, "mcp.json");
64
+ // enabled/excludeTools come from mcp.json (enabled:false key = off, absent = on; excludeTools =
65
+ // adapter-side filtering by original/prefixed name + glob at registration — excluded tools never
66
+ // reach mcp-cache, so the UI adds phantom list rows from the patterns to keep restore possible)
67
+ const disabledSet = new Set<string>();
68
+ const excludePatterns = new Map<string, string[]>();
69
+ try {
70
+ const st = fs.statSync(cfgPath);
71
+ if (st.size <= 8 * 1024 * 1024) {
72
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, "utf8"));
73
+ for (const [name, srv] of Object.entries<any>(cfg?.mcpServers ?? {})) {
74
+ if (srv?.enabled === false) disabledSet.add(name);
75
+ if (Array.isArray(srv?.excludeTools)) excludePatterns.set(name, srv.excludeTools.map(String));
76
+ }
77
+ } else notes.push("mcp.json 超 8MB,enabled 状态跳过");
78
+ } catch { /* no mcp.json: everything defaults to enabled */ }
79
+ let cache: any = null;
80
+ try {
81
+ const st = fs.statSync(cachePath);
82
+ if (st.size > 8 * 1024 * 1024) {
83
+ notes.push("mcp-cache.json 超 8MB,跳过(有界读纪律)");
84
+ return [];
85
+ }
86
+ cache = JSON.parse(fs.readFileSync(cachePath, "utf8"));
87
+ } catch { notes.push("mcp-cache.json 不可读(pi 尚未生成缓存?)"); return []; }
88
+ const out: Array<{ name: string; enabled: boolean; toolCount: number; estTokens: number; cachedAt: string | null; excludedPatterns: string[]; tools: CatalogTool[] }> = [];
89
+ for (const [name, srv] of Object.entries<any>(cache?.servers ?? {})) {
90
+ const patterns = excludePatterns.get(name) || [];
91
+ const tools: CatalogTool[] = (Array.isArray(srv?.tools) ? srv.tools : []).map((t: any) => ({
92
+ name: String(t?.name || "?"),
93
+ estTokens: toolEstTokens(t),
94
+ calls30d: 0,
95
+ excluded: toolMatchesPatterns(String(t?.name || "?"), patterns) || undefined,
96
+ }));
97
+ // phantom rows: non-glob exclude patterns whose tool no longer appears in the cache
98
+ // (already filtered out by the adapter) — name-only rows so the UI can restore them.
99
+ const known = new Set(tools.map((t) => t.name.toLowerCase()));
100
+ for (const p of patterns) {
101
+ if (p.includes("*")) continue;
102
+ if (!known.has(p.toLowerCase())) {
103
+ tools.push({ name: p, estTokens: 0, calls30d: 0, excluded: true, phantom: true });
104
+ }
105
+ }
106
+ out.push({
107
+ name,
108
+ enabled: !disabledSet.has(name),
109
+ toolCount: tools.length,
110
+ estTokens: tools.reduce((a, b) => a + b.estTokens, 0),
111
+ cachedAt: srv?.cachedAt ? new Date(Number(srv.cachedAt)).toISOString() : null,
112
+ excludedPatterns: patterns,
113
+ tools,
114
+ });
115
+ }
116
+ out.sort((a, b) => b.estTokens - a.estTokens);
117
+ return out;
118
+ }
119
+
120
+ /** Pure merge: catalog surface × 30-day call counts → Catalog (directly testable).
121
+ * Attribution caliber: pi records MCP calls at server level (toolName = `mcp__<server>`, dash→underscore);
122
+ * exact-name matching only covers built-in/extension bare names, so per-tool counts stay 0 for MCP
123
+ * tools (no cost apportioning in phase 1). */
124
+ export function buildCatalog(
125
+ mcpServers: Array<{ name: string; enabled: boolean; toolCount: number; estTokens: number; cachedAt: string | null; excludedPatterns: string[]; tools: CatalogTool[] }>,
126
+ skills: CatalogSkill[],
127
+ toolCounts: Record<string, number>,
128
+ skillCounts: Record<string, number>,
129
+ ): Catalog {
130
+ const notes: string[] = [];
131
+ const serverCalls = (name: string): number => {
132
+ const variants = [name, name.replace(/-/g, "_")];
133
+ let n = 0;
134
+ for (const [k, c] of Object.entries(toolCounts)) {
135
+ for (const v of variants) {
136
+ if (k === `mcp__${v}` || k.startsWith(`mcp__${v}__`)) { n += c; break; }
137
+ }
138
+ }
139
+ return n;
140
+ };
141
+ for (const s of mcpServers) {
142
+ let bare = 0;
143
+ for (const t of s.tools) {
144
+ t.calls30d = toolCounts[t.name] || 0;
145
+ bare += t.calls30d;
146
+ }
147
+ s.calls30d = bare + serverCalls(s.name); // bare-name tools + the mcp__<server> wrapper caliber
148
+ }
149
+ for (const sk of skills) sk.calls30d = skillCounts[sk.name] || 0;
150
+ return {
151
+ mcp: mcpServers,
152
+ mcpTotalTools: mcpServers.reduce((a, s) => a + s.toolCount, 0),
153
+ mcpTotalTokens: mcpServers.reduce((a, s) => a + s.estTokens, 0),
154
+ skills,
155
+ skillCalls30d: skills.reduce((a, s) => a + s.calls30d, 0),
156
+ notes,
157
+ };
158
+ }
159
+
160
+ /** Server-side assembly (called from api.ts /catalog): read catalog + query 30-day usage + fetch skills surface same-origin. */
161
+ export async function collectCatalog(usage: { db: { prepare: (sql: string) => { all: (...a: unknown[]) => unknown[] } } }, opts: { agentDir: string; sameOrigin?: (p: string) => string }): Promise<Catalog> {
162
+ const notes: string[] = [];
163
+ const servers = readMcpCatalog(opts.agentDir, notes);
164
+ const since = Date.now() - 30 * 24 * 3600 * 1000;
165
+ const toolCounts: Record<string, number> = {};
166
+ try {
167
+ for (const r of usage.db.prepare("SELECT tool, COUNT(*) c FROM tool_usage WHERE ts >= ? GROUP BY tool").all(since) as Array<{ tool: string; c: number }>) {
168
+ toolCounts[r.tool] = r.c;
169
+ }
170
+ } catch { notes.push("tool_usage 表不可读(旧库未升级?)"); }
171
+ const skillCounts: Record<string, number> = {};
172
+ try {
173
+ for (const r of usage.db.prepare("SELECT skill, COUNT(*) c FROM skill_usage WHERE ts >= ? GROUP BY skill").all(since) as Array<{ skill: string; c: number }>) {
174
+ skillCounts[r.skill] = r.c;
175
+ }
176
+ } catch { notes.push("skill_usage 表不可读(旧库未升级?)"); }
177
+ // effective skills surface: same-origin host /api/skills (loadSkillsWithInstallInfo includes disableModelInvocation)
178
+ const skills: CatalogSkill[] = [];
179
+ if (opts.sameOrigin) {
180
+ try {
181
+ const res = await fetch(opts.sameOrigin("/api/skills"));
182
+ const d = (await res.json()) as any;
183
+ for (const s of Array.isArray(d?.skills) ? d.skills : []) {
184
+ skills.push({
185
+ name: String(s?.name || path.basename(String(s?.filePath || ""), ".md")),
186
+ filePath: String(s?.filePath || ""),
187
+ disabled: s?.disableModelInvocation === true,
188
+ calls30d: 0,
189
+ });
190
+ }
191
+ skills.sort((a, b) => a.name.localeCompare(b.name));
192
+ } catch (e) {
193
+ notes.push("skills 面拉取失败:" + (e instanceof Error ? e.message : String(e)));
194
+ }
195
+ } else {
196
+ notes.push("sameOrigin 未配置,skills 面跳过");
197
+ }
198
+ return buildCatalog(servers, skills, toolCounts, skillCounts);
199
+ }
package/lib/db.ts CHANGED
@@ -200,6 +200,33 @@ export function openUsageDb(dbPath: string): UsageDb {
200
200
  SELECT agent, session_id, ts, day, provider, model, input, output,
201
201
  cache_read, cache_write, reasoning, total_tokens, cost_total, credits
202
202
  FROM ext_usage;
203
+
204
+ -- tool 调用明细(borrow plan §2.7A:ingest 顺带增量统计,不重扫)。
205
+ -- 行粒度 = 一次工具调用;PK=(session_id, call_id) 幂等重放安全。
206
+ -- assistant toolCall 块先记 call(ok=NULL 占位),toolResult 结果消息按同键 UPSERT 补 ok/duration。
207
+ CREATE TABLE IF NOT EXISTS tool_usage (
208
+ session_id TEXT NOT NULL,
209
+ call_id TEXT NOT NULL,
210
+ ts INTEGER NOT NULL,
211
+ day TEXT NOT NULL,
212
+ tool TEXT NOT NULL,
213
+ ok INTEGER,
214
+ duration_ms INTEGER,
215
+ PRIMARY KEY (session_id, call_id)
216
+ );
217
+ CREATE INDEX IF NOT EXISTS idx_tool_usage_day ON tool_usage(day, tool);
218
+
219
+ -- skill 唤起明细:user 消息 text 内嵌 <skill name="…"> 块(pi skill invocation)。
220
+ -- PK=(session_id, msg_id, skill) 幂等;calls 统计 = 行计数。
221
+ CREATE TABLE IF NOT EXISTS skill_usage (
222
+ session_id TEXT NOT NULL,
223
+ msg_id TEXT NOT NULL,
224
+ ts INTEGER NOT NULL,
225
+ day TEXT NOT NULL,
226
+ skill TEXT NOT NULL,
227
+ PRIMARY KEY (session_id, msg_id, skill)
228
+ );
229
+ CREATE INDEX IF NOT EXISTS idx_skill_usage_day ON skill_usage(day, skill);
203
230
  `);
204
231
 
205
232
  // daily_model 旧 schema 迁移(2026-09-12 外部 agent 摄入):缺 agent 列 → 重建含 agent 的新表
package/lib/ingest.ts CHANGED
@@ -44,6 +44,38 @@ export function withTx<T>(db: DatabaseSync, fn: () => T): T {
44
44
 
45
45
  // ---------------------------------------------------------------- JSONL 解析
46
46
 
47
+ /** Tool usage row (tool_usage table; borrow plan §2.7A). ok=NULL = call recorded only (result message fills it in by key) */
48
+ export interface ToolUsageRow {
49
+ session_id: string;
50
+ call_id: string;
51
+ ts: number;
52
+ day: string;
53
+ tool: string;
54
+ ok: number | null;
55
+ duration_ms: number | null;
56
+ }
57
+
58
+ /** Skill invocation row (skill_usage table) */
59
+ export interface SkillUsageRow {
60
+ session_id: string;
61
+ msg_id: string;
62
+ ts: number;
63
+ day: string;
64
+ skill: string;
65
+ }
66
+
67
+ /** pi skill invocation discriminator: <skill name="…"> blocks embedded in user text (possibly several) */
68
+ const SKILL_BLOCK_RE = /<skill name="([^"\n]+)"[^>]*>/g;
69
+ function skillNamesIn(text: string): string[] {
70
+ const out: string[] = [];
71
+ SKILL_BLOCK_RE.lastIndex = 0;
72
+ let m: RegExpExecArray | null;
73
+ while ((m = SKILL_BLOCK_RE.exec(text)) !== null) {
74
+ if (m[1]) out.push(m[1]);
75
+ }
76
+ return out;
77
+ }
78
+
47
79
  interface ParsedRow {
48
80
  session_id: string;
49
81
  ts: number;
@@ -76,7 +108,8 @@ export interface UserMsgRow {
76
108
 
77
109
  export async function parseSessionJsonl(text: string, fallbackId: string): Promise<{
78
110
  id: string; cwd: string; title: string;
79
- rows: ParsedRow[]; userRows: UserMsgRow[]; firstTs: number; lastTs: number;
111
+ rows: ParsedRow[]; userRows: UserMsgRow[]; toolRows: ToolUsageRow[]; skillRows: SkillUsageRow[];
112
+ firstTs: number; lastTs: number;
80
113
  }> {
81
114
  let id = fallbackId;
82
115
  let cwd = "";
@@ -86,6 +119,9 @@ export async function parseSessionJsonl(text: string, fallbackId: string): Promi
86
119
  let lastTs = 0;
87
120
  // 用户输入消息暂存(末尾会话上下文齐备后统一判定 kind)
88
121
  const pendingUser: Array<{ msgId: string; ts: number; text: string; image: boolean }> = [];
122
+ // tool/skill usage rows (borrow plan §2.7A: stats collected in passing during ingest)
123
+ const toolRows: ToolUsageRow[] = [];
124
+ const skillRows: SkillUsageRow[] = [];
89
125
  // 会话级归因:session_info(外部导入会话 / subagent 子会话名)
90
126
  let infoName = "";
91
127
  let infoExternal = false;
@@ -96,13 +132,28 @@ export async function parseSessionJsonl(text: string, fallbackId: string): Promi
96
132
  const ts = Number(m.timestamp) || Date.parse(String(e?.timestamp ?? "")) || 0;
97
133
  const msgId = String(e?.id ?? "") || `anon:${fallbackId}:${ts}:${userSeq}`;
98
134
  pendingUser.push({ msgId, ts, text, image });
135
+ // skill invocation: pi prepends skill content to the user message as a <skill name="…"> block (same discriminator as slash-display)
136
+ for (const sm of skillNamesIn(text)) {
137
+ skillRows.push({ session_id: id, msg_id: msgId, ts, day: localDay(ts), skill: sm });
138
+ }
99
139
  userSeq++;
100
140
  };
101
141
 
102
142
  const pushAssistant = (m: Record<string, any>) => {
143
+ const ts = Number(m.timestamp) || 0;
144
+ // toolCall blocks: record the call row first (ok=NULL placeholder; the toolResult message fills ok/duration by key)
145
+ if (Array.isArray(m.content)) {
146
+ for (const c of m.content) {
147
+ if (c?.type === "toolCall" && c.toolName) {
148
+ toolRows.push({
149
+ session_id: id, call_id: String(c.toolCallId || `anon:${ts}:${toolRows.length}`),
150
+ ts, day: localDay(ts), tool: String(c.toolName), ok: null, duration_ms: null,
151
+ });
152
+ }
153
+ }
154
+ }
103
155
  const u = m.usage;
104
156
  if (!u || !m.model) return;
105
- const ts = Number(m.timestamp) || 0;
106
157
  rows.push({
107
158
  session_id: id,
108
159
  ts,
@@ -121,6 +172,18 @@ export async function parseSessionJsonl(text: string, fallbackId: string): Promi
121
172
  if (ts > lastTs) lastTs = ts;
122
173
  };
123
174
 
175
+ const pushToolResult = (m: Record<string, any>, e: Record<string, any>) => {
176
+ const callId = String(m.toolCallId || "");
177
+ if (!callId) return;
178
+ const ts = Number(m.timestamp) || Date.parse(String(e?.timestamp ?? "")) || 0;
179
+ toolRows.push({
180
+ session_id: id, call_id: callId, ts, day: localDay(ts),
181
+ tool: m.toolName ? String(m.toolName) : "",
182
+ ok: m.isError === true ? 0 : 1,
183
+ duration_ms: Number.isFinite(Number(m.durationMs)) ? Math.round(Number(m.durationMs)) : null,
184
+ });
185
+ };
186
+
124
187
  let scanned = 0;
125
188
  for (const line of text.split("\n")) {
126
189
  if (!line) continue;
@@ -140,6 +203,7 @@ export async function parseSessionJsonl(text: string, fallbackId: string): Promi
140
203
  if (e.type === "message") {
141
204
  const m = e.message;
142
205
  if (m?.role === "assistant") pushAssistant(m);
206
+ else if (m?.role === "toolResult") pushToolResult(m, e);
143
207
  else if (m?.role === "user") {
144
208
  pushUser(m, e);
145
209
  if (!title) {
@@ -183,7 +247,7 @@ export async function parseSessionJsonl(text: string, fallbackId: string): Promi
183
247
  quote_kinds: st.kinds.join(","),
184
248
  };
185
249
  });
186
- return { id, cwd, title, rows, userRows, firstTs, lastTs };
250
+ return { id, cwd, title, rows, userRows, toolRows, skillRows, firstTs, lastTs };
187
251
  }
188
252
 
189
253
  // ---------------------------------------------------------------- 写入 + 汇总
@@ -228,6 +292,55 @@ export function insertUserRows(usage: UsageDb, rows: UserMsgRow[]): void {
228
292
  }
229
293
  }
230
294
 
295
+ /**
296
+ * Tool usage rows (borrow plan §2.7A): PK=(session_id, call_id), safe under replay.
297
+ * call rows (ok=NULL) land first; the toolResult message UPSERTs the same key and only fills
298
+ * ok/duration/tool — repeated rescans overwrite with identical values, never inflating counts.
299
+ */
300
+ export function insertToolRows(usage: UsageDb, rows: ToolUsageRow[]): void {
301
+ if (rows.length === 0) return;
302
+ const ins = usage.db.prepare(`
303
+ INSERT INTO tool_usage (session_id, call_id, ts, day, tool, ok, duration_ms)
304
+ VALUES (?, ?, ?, ?, ?, ?, ?)
305
+ ON CONFLICT(session_id, call_id) DO UPDATE SET
306
+ ok=COALESCE(excluded.ok, tool_usage.ok),
307
+ duration_ms=COALESCE(excluded.duration_ms, tool_usage.duration_ms),
308
+ tool=CASE WHEN excluded.tool != '' THEN excluded.tool ELSE tool_usage.tool END`);
309
+ for (const r of rows) {
310
+ ins.run(r.session_id, r.call_id, r.ts, r.day, r.tool, r.ok, r.duration_ms);
311
+ }
312
+ }
313
+
314
+ /** Skill invocations: PK=(session_id, msg_id, skill), idempotent. */
315
+ export function insertSkillRows(usage: UsageDb, rows: SkillUsageRow[]): void {
316
+ if (rows.length === 0) return;
317
+ const ins = usage.db.prepare(`
318
+ INSERT OR IGNORE INTO skill_usage (session_id, msg_id, ts, day, skill)
319
+ VALUES (?, ?, ?, ?, ?)`);
320
+ for (const r of rows) {
321
+ ins.run(r.session_id, r.msg_id, r.ts, r.day, r.skill);
322
+ }
323
+ }
324
+
325
+ /** Live toolCall blocks (from message_end assistant events): call rows only; file scans fill in results. */
326
+ export function recordLiveToolCalls(usage: UsageDb, sessionId: string, msg: Record<string, any>): void {
327
+ if (!Array.isArray(msg.content)) return;
328
+ const ts = Number(msg.timestamp) || Date.now();
329
+ const day = localDay(ts);
330
+ const rows: ToolUsageRow[] = [];
331
+ for (const c of msg.content) {
332
+ if (c?.type === "toolCall" && c.toolName) {
333
+ rows.push({
334
+ session_id: sessionId, call_id: String(c.toolCallId || `anon:${ts}:${rows.length}`),
335
+ ts, day, tool: String(c.toolName), ok: null, duration_ms: null,
336
+ });
337
+ }
338
+ }
339
+ if (rows.length) {
340
+ withTx(usage.db, () => insertToolRows(usage, rows));
341
+ }
342
+ }
343
+
231
344
  /** 实时单条(message_end 事件):幂等写明细 + 刷新会话聚合。 */
232
345
  export function ingestLiveMessage(usage: UsageDb, sessionId: string, msg: Record<string, any>): void {
233
346
  const u = msg.usage;
@@ -403,6 +516,8 @@ export async function syncLiveSessions(ctx: IngestCtx, opts: { force?: boolean }
403
516
  }
404
517
  insertMsgRows(usage, parsed.rows);
405
518
  insertUserRows(usage, parsed.userRows);
519
+ insertToolRows(usage, parsed.toolRows);
520
+ insertSkillRows(usage, parsed.skillRows);
406
521
  // 会话行:保留实时状态字段(state),只覆盖内容字段
407
522
  db.prepare(`
408
523
  INSERT INTO sessions (id, cwd, title, started_at, last_ts, msgs, total_tokens, cost_total, archived, state, source_file)
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@aiti-ai/aiti-ai-usage",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "type": "module",
5
5
  "homepage": "https://aiti.pw/extensions/session-manager.html",
6
- "description": "AI token 用量统计扩展(provider/model/key/session 四维报表,日/月双粒度)",
6
+ "description": "AI token usage statistics — multi-dimensional reports by workspace/provider/model/key/time-slot, pivot over any dimension combination + sankey diagram + CSV export, event-driven with zero polling, standalone SQLite storage",
7
7
  "scripts": {
8
8
  "build:client": "vite build --config vite.config.ts",
9
9
  "build:server": "esbuild server/ingest-worker.ts --bundle --platform=node --format=esm --outfile=dist/ingest-worker.mjs --log-level=warning",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "aitiExtProtocol": "1.0",
21
21
  "license": "MIT",
22
- "contentHash": "a97edddfdd732a68",
22
+ "contentHash": "321da7cdb20a1930",
23
23
  "repository": {
24
24
  "type": "git",
25
25
  "url": "git+https://github.com/aiti-ai/aiti-ai.git",
package/server/api.ts CHANGED
@@ -546,6 +546,30 @@ export async function handleApi(req: Request, ctx: ExtApiCtx): Promise<Response
546
546
  case "sessions": return sessionsList(sp);
547
547
  case "userstat": return userStat(sp);
548
548
  case "session-keys": return rest.length ? sessionKeys(rest[0]) : null;
549
+ case "catalog": return catalog(sp);
549
550
  default: return null;
550
551
  }
551
552
  }
553
+
554
+ /** Catalog billing (borrow plan §2.7B/C): MCP catalog (mcp-cache × mcp.json enabled) × 30-day calls
555
+ * + skills surface (same-origin /api/skills needs cwd → forwarded from the client's selectedCwd). */
556
+ async function catalog(sp: URLSearchParams): Promise<Response> {
557
+ const { collectCatalog } = await import("../lib/catalog.ts");
558
+ const rt = runtime();
559
+ const agentDir = process.env.PI_CODING_AGENT_DIR || (process.env.HOME ? process.env.HOME + "/.pi/agent" : "");
560
+ const origin = process.env.AITI_AI_SCHEDULE_API_ORIGIN || "http://127.0.0.1:" + (process.env.PORT || "3000");
561
+ const basePath = process.env.PI_WEB_BASE_PATH || "";
562
+ // cwd fallback: when the client sends none (new-session page with empty selectedCwd) use the most recent session's cwd
563
+ let cwd = sp.get("cwd") || "";
564
+ if (!cwd) {
565
+ try {
566
+ const row = rt.usage.db.prepare("SELECT cwd FROM sessions WHERE cwd != '' ORDER BY last_ts DESC LIMIT 1").get() as { cwd?: string } | undefined;
567
+ if (row?.cwd) cwd = row.cwd;
568
+ } catch { /* sessions table unreadable: skip the fallback */ }
569
+ }
570
+ const cat = await collectCatalog(rt.usage, {
571
+ agentDir,
572
+ sameOrigin: (p: string) => origin + basePath + p + (cwd && p.startsWith("/api/skills") ? (p.includes("?") ? "&" : "?") + "cwd=" + encodeURIComponent(cwd) : ""),
573
+ });
574
+ return json({ ok: true, ...cat, generatedAt: new Date().toISOString() });
575
+ }
@@ -1,7 +1,9 @@
1
1
  ---
2
2
  name: usage-report
3
3
  title: AI 帮我解读 AI 用量统计
4
+ title.en: "AI: interpret AI usage stats"
4
5
  placeholder: 想了解什么?如:这个月哪个模型花钱最多 / 最近 7 天 token 趋势…
6
+ placeholder.en: "What to know? e.g. which model cost the most this month / last-7-day token trend…"
5
7
  ---
6
8
 
7
9
  # usage-report · 解读 AI 用量数据