@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.
@@ -0,0 +1,192 @@
1
+ /**
2
+ * aiti-ai-usage — tool/skill usage stats tests (borrow plan §2.7A/B).
3
+ *
4
+ * Covers:
5
+ * 1) parseSessionJsonl extracts ToolUsageRow / SkillUsageRow from assistant toolCall blocks /
6
+ * toolResult messages / user <skill> blocks (incl. anon call_id fallback and multi-skill messages);
7
+ * 2) insertToolRows merge semantics: call row (ok=NULL) ← result row fills ok/duration/tool by key;
8
+ * 3) idempotency: repeated parse+insert of the same file never inflates counts;
9
+ * 4) catalog pure functions: estimateTokens (chars/4) + toolEstTokens + buildCatalog merge.
10
+ *
11
+ * Run: node --experimental-strip-types --test pi-web-ext/aiti-ai-usage/tool-usage.test.mjs
12
+ */
13
+ import assert from "node:assert/strict";
14
+ import test from "node:test";
15
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { openUsageDb } from "./lib/db.ts";
19
+ import { parseSessionJsonl, insertToolRows, insertSkillRows } from "./lib/ingest.ts";
20
+ import { buildCatalog, estimateTokens, readMcpCatalog, toolEstTokens } from "./lib/catalog.ts";
21
+
22
+ const NOW = Date.now();
23
+
24
+ /** Fixture session JSONL: one tool call (call+result), one failing call, one skill message, one plain assistant */
25
+ function fixtureJsonl() {
26
+ const lines = [
27
+ JSON.stringify({ type: "session", id: "sess-tu", cwd: "/tmp/proj", timestamp: new Date(NOW).toISOString() }),
28
+ // assistant: two toolCall blocks + usage
29
+ JSON.stringify({
30
+ id: "m1", timestamp: new Date(NOW).toISOString(), type: "message",
31
+ message: {
32
+ role: "assistant", provider: "openai", model: "gpt-4o", timestamp: NOW,
33
+ content: [
34
+ { type: "text", text: "let me check" },
35
+ { type: "toolCall", toolCallId: "call_1", toolName: "read", input: { path: "/tmp/a" } },
36
+ { type: "toolCall", toolCallId: "call_2", toolName: "bash", input: { cmd: "ls" } },
37
+ ],
38
+ usage: { input: 100, output: 50, totalTokens: 150, cost: { total: 0.01 } },
39
+ },
40
+ }),
41
+ // toolResult: call_1 ok (with toolName + duration), call_2 failed
42
+ JSON.stringify({
43
+ id: "m2", timestamp: new Date(NOW + 1000).toISOString(), type: "message",
44
+ message: { role: "toolResult", toolCallId: "call_1", toolName: "read", isError: false, durationMs: 120, timestamp: NOW + 1000, content: [{ type: "text", text: "ok" }] },
45
+ }),
46
+ JSON.stringify({
47
+ id: "m3", timestamp: new Date(NOW + 2000).toISOString(), type: "message",
48
+ message: { role: "toolResult", toolCallId: "call_2", toolName: "bash", isError: true, durationMs: 30, timestamp: NOW + 2000, content: [{ type: "text", text: "boom" }] },
49
+ }),
50
+ // user: skill block prepended (pi skill invocation shape)
51
+ JSON.stringify({
52
+ id: "m4", timestamp: new Date(NOW + 3000).toISOString(), type: "message",
53
+ message: {
54
+ role: "user", timestamp: NOW + 3000,
55
+ content: [{ type: "text", text: '<skill name="usage-report" location="/x/SKILL.md">\nReferences are relative to the skill dir.\n\n帮我出报表' }],
56
+ },
57
+ }),
58
+ // assistant without usage (its toolCall block must still record a call row)
59
+ JSON.stringify({
60
+ id: "m5", timestamp: new Date(NOW + 4000).toISOString(), type: "message",
61
+ message: { role: "assistant", timestamp: NOW + 4000, content: [{ type: "toolCall", toolCallId: "call_3", toolName: "edit", input: {} }] },
62
+ }),
63
+ ];
64
+ return lines.join("\n") + "\n";
65
+ }
66
+
67
+ function openTmpDb(root) {
68
+ const usage = openUsageDb(join(root, "usage.sqlite"));
69
+ usage.ensure();
70
+ return usage;
71
+ }
72
+
73
+ test("parseSessionJsonl:toolCall/toolResult/<skill> 提取正确", async () => {
74
+ const parsed = await parseSessionJsonl(fixtureJsonl(), "fallback");
75
+ assert.equal(parsed.id, "sess-tu");
76
+ // 3 tool call rows (2 calls + 1 call-only) + 2 result rows = 5 raw rows
77
+ assert.equal(parsed.toolRows.length, 5);
78
+ const calls = Object.fromEntries(parsed.toolRows.map((r) => [r.call_id, r]));
79
+ assert.equal(calls.call_1.tool, "read");
80
+ assert.equal(calls.call_2.tool, "bash");
81
+ assert.equal(calls.call_3.tool, "edit");
82
+ assert.equal(calls.call_1.ok, 1);
83
+ assert.equal(calls.call_1.duration_ms, 120);
84
+ assert.equal(calls.call_2.ok, 0);
85
+ assert.equal(calls.call_2.duration_ms, 30);
86
+ assert.equal(calls.call_3.ok, null); // no result yet → placeholder row
87
+ // skill: 1 row (multiple skill blocks in one message would yield multiple rows)
88
+ assert.equal(parsed.skillRows.length, 1);
89
+ assert.equal(parsed.skillRows[0].skill, "usage-report");
90
+ assert.equal(parsed.skillRows[0].session_id, "sess-tu");
91
+ });
92
+
93
+ test("insert 合并语义:call 行(ok=NULL) ← result 行同键补 ok/duration;重复重放幂等", async () => {
94
+ const root = mkdtempSync(join(tmpdir(), "ai-usage-tu-"));
95
+ const usage = openTmpDb(root);
96
+ const parsed = await parseSessionJsonl(fixtureJsonl(), "fallback");
97
+ insertToolRows(usage, parsed.toolRows);
98
+ insertSkillRows(usage, parsed.skillRows);
99
+ // after merge: 3 rows (call_1/call_2/call_3) with ok/duration filled in
100
+ const rows = usage.db.prepare("SELECT * FROM tool_usage ORDER BY call_id").all();
101
+ assert.equal(rows.length, 3);
102
+ const byId = Object.fromEntries(rows.map((r) => [r.call_id, r]));
103
+ assert.equal(byId.call_1.ok, 1);
104
+ assert.equal(byId.call_1.duration_ms, 120);
105
+ assert.equal(byId.call_1.tool, "read");
106
+ assert.equal(byId.call_3.ok, null);
107
+ assert.equal(usage.db.prepare("SELECT COUNT(*) n FROM skill_usage").get().n, 1);
108
+ // replay (re-parse + re-insert of the same file) → counts not inflated, values stable
109
+ const again = await parseSessionJsonl(fixtureJsonl(), "fallback");
110
+ insertToolRows(usage, again.toolRows);
111
+ insertSkillRows(usage, again.skillRows);
112
+ assert.equal(usage.db.prepare("SELECT COUNT(*) n FROM tool_usage").get().n, 3);
113
+ assert.equal(usage.db.prepare("SELECT COUNT(*) n FROM skill_usage").get().n, 1);
114
+ const rows2 = usage.db.prepare("SELECT * FROM tool_usage WHERE call_id='call_1'").get();
115
+ assert.equal(rows2.ok, 1);
116
+ assert.equal(rows2.duration_ms, 120);
117
+ });
118
+
119
+ test("result 行缺 toolName 时保留 call 行的 tool(COALESCE 语义)", async () => {
120
+ const root = mkdtempSync(join(tmpdir(), "ai-usage-tu-"));
121
+ const usage = openTmpDb(root);
122
+ insertToolRows(usage, [
123
+ { session_id: "s", call_id: "c1", ts: NOW, day: "2026-11-20", tool: "read", ok: null, duration_ms: null },
124
+ { session_id: "s", call_id: "c1", ts: NOW + 1, day: "2026-11-20", tool: "", ok: 1, duration_ms: 5 },
125
+ ]);
126
+ const row = usage.db.prepare("SELECT * FROM tool_usage WHERE call_id='c1'").get();
127
+ assert.equal(row.tool, "read");
128
+ assert.equal(row.ok, 1);
129
+ assert.equal(row.duration_ms, 5);
130
+ });
131
+
132
+ test("30 天计数口径:buildCatalog 归因(tool 级精确名 + MCP server 级 mcp__ 前缀)", () => {
133
+ const servers = [
134
+ {
135
+ name: "big-server", enabled: true, toolCount: 2, estTokens: 0, cachedAt: null,
136
+ tools: [
137
+ { name: "search_docs", estTokens: 200, calls30d: 0 },
138
+ { name: "never_used", estTokens: 300, calls30d: 0 },
139
+ ],
140
+ },
141
+ {
142
+ name: "chrome-devtools", enabled: true, toolCount: 1, estTokens: 0, cachedAt: null,
143
+ tools: [{ name: "click", estTokens: 100, calls30d: 0 }],
144
+ },
145
+ ];
146
+ const skills = [{ name: "usage-report", filePath: "/s/SKILL.md", disabled: false, calls30d: 0 }];
147
+ const cat = buildCatalog(
148
+ servers, skills,
149
+ { search_docs: 7, never_used: 0, mcp__chrome_devtools: 428 },
150
+ { "usage-report": 2 },
151
+ );
152
+ assert.equal(cat.mcp[0].tools[0].calls30d, 7); // bare-name exact match (built-in/extension tools)
153
+ assert.equal(cat.mcp[0].calls30d, 7);
154
+ assert.equal(cat.mcp[1].calls30d, 428); // server-level attribution: mcp__chrome_devtools (dash→underscore)
155
+ assert.equal(cat.mcp[1].tools[0].calls30d, 0); // per-tool stays 0 for MCP (no apportioning in phase 1)
156
+ assert.equal(cat.mcpTotalTools, 3);
157
+ assert.equal(cat.skills[0].calls30d, 2);
158
+ });
159
+
160
+ test("token 估算口径:bytes/4(pi estimateTokens 同源)+ schema JSON 计入", () => {
161
+ assert.equal(estimateTokens("abcdefgh"), 2); // 8 chars / 4
162
+ assert.equal(estimateTokens(""), 0);
163
+ const t1 = toolEstTokens({ name: "search", description: "d".repeat(40), inputSchema: { type: "object", properties: { q: { type: "string" } } } });
164
+ const t2 = toolEstTokens({ name: "search", description: "", inputSchema: {} });
165
+ assert.ok(t1 > t2, "schema+description add tokens");
166
+ assert.ok(t2 >= 1);
167
+ });
168
+
169
+ test("readMcpCatalog: excludeTools 标记 + 幻影行(缓存中已消失的排除名单)", () => {
170
+ const root = mkdtempSync(join(tmpdir(), "ai-usage-cat-"));
171
+ const agentDir = join(root, "agent");
172
+ mkdirSync(agentDir, { recursive: true });
173
+ writeFileSync(join(agentDir, "mcp-cache.json"), JSON.stringify({
174
+ version: 1,
175
+ servers: { big: { configHash: "x", cachedAt: Date.now(), tools: [
176
+ { name: "click", description: "click it", inputSchema: { type: "object" } },
177
+ { name: "search", description: "search", inputSchema: {} },
178
+ ] } },
179
+ }));
180
+ writeFileSync(join(agentDir, "mcp.json"), JSON.stringify({ mcpServers: { big: { command: "x", excludeTools: ["click", "gone_tool", "get_*"], enabled: false } } }));
181
+ const servers = readMcpCatalog(agentDir, []);
182
+ assert.equal(servers.length, 1);
183
+ const srv = servers[0];
184
+ assert.equal(srv.enabled, false);
185
+ assert.deepEqual(srv.excludedPatterns, ["click", "gone_tool", "get_*"]);
186
+ const byName = Object.fromEntries(srv.tools.map((t) => [t.name, t]));
187
+ assert.equal(byName.click.excluded, true); // cache row hit by a pattern → marked excluded
188
+ assert.ok(!byName.search.excluded);
189
+ assert.equal(byName.gone_tool.phantom, true); // non-cache list row → phantom (restorable)
190
+ assert.equal(byName.gone_tool.excluded, true);
191
+ rmSync(root, { recursive: true, force: true });
192
+ });
@@ -6,6 +6,7 @@
6
6
  * 用法:node tools/build-client.mjs (或 npm run watch 自动重建)
7
7
  */
8
8
  import { spawnSync } from "node:child_process";
9
+ import { createRequire } from "node:module";
9
10
  import { resolve } from "node:path";
10
11
  import { fileURLToPath } from "node:url";
11
12
  import { existsSync } from "node:fs";
@@ -13,7 +14,7 @@ import { existsSync } from "node:fs";
13
14
  const root = resolve(fileURLToPath(new URL("..", import.meta.url)));
14
15
 
15
16
  const viteJs = resolve(root, "node_modules", "vite", "bin", "vite.js");
16
- const viteBin = existsSync(viteJs) ? viteJs : "vite";
17
+ const viteBin = existsSync(viteJs) ? viteJs : resolve(createRequire(import.meta.url).resolve("vite/package.json"), "..", "bin", "vite.js");
17
18
 
18
19
  const r = spawnSync(process.execPath, [viteBin, "build", "--config", resolve(root, "vite.config.ts")], {
19
20
  cwd: root,
package/tools/deploy.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * aiti-ai-usage · 部署到 ~/.pi/web/extensions/ 和 ~/.pi/web-dev/extensions/
4
4
  *
5
- * 源码已迁入 pi-work pi-web-ext/aiti-ai-usage/(本目录为权威源码位置);
5
+ * Sources live in extensions/aiti-ai-usage/(this directory is authoritative);
6
6
  * 部署 = client bundle 构建(vite)→ 整目录同步到两个扩展根 + git 提交部署状态。
7
7
  * 用法:node tools/deploy.mjs
8
8
  * 生效:POST /api/extensions/reload(或重启 pi-web);client no-store 刷新页面即新