@koinzhang/paseo-plugin-activity 0.1.0

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.
Files changed (52) hide show
  1. package/client/activity-heatmap.tsx +138 -0
  2. package/client/global-surface.tsx +689 -0
  3. package/client/panel.tsx +423 -0
  4. package/client/pending-skill.ts +50 -0
  5. package/client/pill-data-cache.test.ts +68 -0
  6. package/client/pill-data-cache.ts +37 -0
  7. package/client/pill.tsx +211 -0
  8. package/client/provider-filter.test.ts +95 -0
  9. package/client/provider-filter.ts +44 -0
  10. package/client/rank-color.test.ts +35 -0
  11. package/client/rank-color.ts +69 -0
  12. package/client/usage-popover.tsx +383 -0
  13. package/client/usage-query.tsx +54 -0
  14. package/client/usage-stats.tsx +18 -0
  15. package/client/use-app-language.ts +14 -0
  16. package/client/web.ts +28 -0
  17. package/index.client.tsx +62 -0
  18. package/index.server.ts +128 -0
  19. package/package.json +31 -0
  20. package/paseo-plugin.json +6 -0
  21. package/server/agents.test.ts +67 -0
  22. package/server/agents.ts +75 -0
  23. package/server/background-sync.test.ts +143 -0
  24. package/server/background-sync.ts +105 -0
  25. package/server/handlers-query.test.ts +91 -0
  26. package/server/handlers.ts +531 -0
  27. package/server/host-types.ts +14 -0
  28. package/server/ingest.test.ts +233 -0
  29. package/server/ingest.ts +277 -0
  30. package/server/mcp-servers.test.ts +70 -0
  31. package/server/mcp-servers.ts +212 -0
  32. package/server/messages.test.ts +150 -0
  33. package/server/migrate-data.test.ts +65 -0
  34. package/server/migrate-data.ts +54 -0
  35. package/server/resolve-model.test.ts +11 -0
  36. package/server/resolve-model.ts +30 -0
  37. package/server/skill-path.test.ts +56 -0
  38. package/server/skill-path.ts +85 -0
  39. package/server/store.test.ts +221 -0
  40. package/server/store.ts +909 -0
  41. package/server/ttl-cache.ts +34 -0
  42. package/shared/activity.test.ts +86 -0
  43. package/shared/activity.ts +185 -0
  44. package/shared/classify.test.ts +306 -0
  45. package/shared/classify.ts +378 -0
  46. package/shared/format.test.ts +48 -0
  47. package/shared/format.ts +45 -0
  48. package/shared/insights.test.ts +122 -0
  49. package/shared/insights.ts +188 -0
  50. package/shared/plugin-id.ts +7 -0
  51. package/shared/usage.test.ts +668 -0
  52. package/shared/usage.ts +726 -0
@@ -0,0 +1,909 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import type { Category, Confidence } from "../shared/classify.ts";
4
+ import { normalizeProvider } from "../shared/classify.ts";
5
+ import { LOG_PREFIX } from "../shared/plugin-id.ts";
6
+ import { resolveActivityDataDir } from "./migrate-data.ts";
7
+
8
+ export interface ToolCallRow {
9
+ agentId: string;
10
+ callId: string;
11
+ workspaceId: string | null;
12
+ provider: string;
13
+ turnId: string | null;
14
+ name: string;
15
+ detailType: string | null;
16
+ category: Category;
17
+ confidence: Confidence | null;
18
+ skillName: string | null;
19
+ mcpServer: string | null;
20
+ mcpTool: string | null;
21
+ command: string | null;
22
+ filePath: string | null;
23
+ status: string | null;
24
+ errorMessage: string | null;
25
+ seq: number | null;
26
+ ts: string | null;
27
+ ingestedAt: string;
28
+ }
29
+
30
+ export type UserMessageRow = {
31
+ agentId: string;
32
+ messageId: string;
33
+ workspaceId: string | null;
34
+ provider: string;
35
+ /** Agent snapshot model when the message was ingested; null if unknown. */
36
+ model: string | null;
37
+ turnId: string | null;
38
+ seq: number | null;
39
+ ts: string | null;
40
+ ingestedAt: string;
41
+ };
42
+
43
+ export type UserMessageFilter = AgentQueryFilter & { agentId?: string };
44
+
45
+ export type UsageStoreDriver = "sqlite" | "jsonl";
46
+
47
+ export type SyncState = {
48
+ agentId: string;
49
+ epoch: string;
50
+ lastSeq: number;
51
+ updatedAt: string;
52
+ };
53
+
54
+ export type QueryFilter = {
55
+ agentId?: string;
56
+ workspaceId?: string;
57
+ category?: Category;
58
+ confidence?: Confidence | null;
59
+ skillName?: string;
60
+ mcpServer?: string;
61
+ from?: string;
62
+ to?: string;
63
+ };
64
+
65
+ /** Persisted agent registry row (005). */
66
+ export type AgentRow = {
67
+ agentId: string;
68
+ workspaceId: string | null;
69
+ parentAgentId: string | null;
70
+ provider: string;
71
+ title: string | null;
72
+ createdAt: string;
73
+ archivedAt: string | null;
74
+ updatedAt: string;
75
+ };
76
+
77
+ export type AgentQueryFilter = {
78
+ workspaceId?: string;
79
+ /** Raw or normalized; compared after normalizeProvider at call site if needed. */
80
+ provider?: string;
81
+ from?: string;
82
+ to?: string;
83
+ };
84
+
85
+ export interface UsageStore {
86
+ readonly driver: UsageStoreDriver;
87
+ upsertMany(rows: readonly ToolCallRow[]): number;
88
+ count(): number;
89
+ getRow(agentId: string, callId: string): ToolCallRow | null;
90
+ select(filter?: QueryFilter): ToolCallRow[];
91
+ upsertUserMessages(rows: readonly UserMessageRow[]): number;
92
+ selectUserMessages(filter?: UserMessageFilter): UserMessageRow[];
93
+ upsertAgents(rows: readonly AgentRow[]): number;
94
+ getAgent(agentId: string): AgentRow | null;
95
+ selectAgents(filter?: AgentQueryFilter): AgentRow[];
96
+ getSyncState(agentId: string): SyncState | null;
97
+ setSyncState(agentId: string, epoch: string, lastSeq: number): void;
98
+ /** Drop hash-keyed (`canonical:…`) user messages for an agent (timeline epoch replace). */
99
+ deleteCanonicalUserMessages(agentId: string): number;
100
+ close(): void;
101
+ }
102
+
103
+ export interface CreateUsageStoreOptions {
104
+ dir?: string;
105
+ fileName?: string;
106
+ driver?: UsageStoreDriver;
107
+ }
108
+
109
+ export const SCHEMA_SQL = `
110
+ CREATE TABLE IF NOT EXISTS tool_calls (
111
+ agent_id TEXT NOT NULL,
112
+ call_id TEXT NOT NULL,
113
+ workspace_id TEXT,
114
+ provider TEXT NOT NULL,
115
+ turn_id TEXT,
116
+ name TEXT NOT NULL,
117
+ detail_type TEXT,
118
+ category TEXT NOT NULL,
119
+ confidence TEXT,
120
+ skill_name TEXT,
121
+ mcp_server TEXT,
122
+ mcp_tool TEXT,
123
+ command TEXT,
124
+ file_path TEXT,
125
+ status TEXT,
126
+ error_message TEXT,
127
+ seq INTEGER,
128
+ ts TEXT,
129
+ ingested_at TEXT NOT NULL,
130
+ PRIMARY KEY (agent_id, call_id)
131
+ );
132
+
133
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_ts ON tool_calls(ts, ingested_at);
134
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_skill ON tool_calls(skill_name);
135
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_mcp ON tool_calls(mcp_server, mcp_tool);
136
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_agent ON tool_calls(agent_id, workspace_id);
137
+
138
+ -- 006: user_messages (turns the user sent; message body is not stored)
139
+ -- Merged into store SCHEMA_SQL; file: ~/.paseo/plugin-data/activity/usage.db
140
+
141
+ CREATE TABLE IF NOT EXISTS user_messages (
142
+ agent_id TEXT NOT NULL,
143
+ message_id TEXT NOT NULL,
144
+ workspace_id TEXT,
145
+ provider TEXT NOT NULL,
146
+ model TEXT, -- 015: snapshot model at ingest; nullable
147
+ turn_id TEXT,
148
+ seq INTEGER,
149
+ ts TEXT, -- backfilled exact time; nullable for live rows
150
+ ingested_at TEXT NOT NULL,
151
+ PRIMARY KEY (agent_id, message_id)
152
+ );
153
+
154
+ CREATE INDEX IF NOT EXISTS idx_user_messages_ts ON user_messages(ts, ingested_at);
155
+ CREATE INDEX IF NOT EXISTS idx_user_messages_agent ON user_messages(agent_id, workspace_id);
156
+
157
+ CREATE TABLE IF NOT EXISTS sync_state (
158
+ agent_id TEXT PRIMARY KEY,
159
+ epoch TEXT NOT NULL,
160
+ last_seq INTEGER NOT NULL,
161
+ updated_at TEXT NOT NULL
162
+ );
163
+
164
+ CREATE TABLE IF NOT EXISTS agents (
165
+ agent_id TEXT PRIMARY KEY,
166
+ workspace_id TEXT,
167
+ parent_agent_id TEXT,
168
+ provider TEXT NOT NULL,
169
+ title TEXT,
170
+ created_at TEXT NOT NULL,
171
+ archived_at TEXT,
172
+ updated_at TEXT NOT NULL
173
+ );
174
+
175
+ CREATE INDEX IF NOT EXISTS idx_agents_created ON agents(created_at);
176
+ CREATE INDEX IF NOT EXISTS idx_agents_provider ON agents(provider);
177
+ `;
178
+
179
+ const UPSERT_SQL = `
180
+ INSERT INTO tool_calls (
181
+ agent_id, call_id, workspace_id, provider, turn_id, name, detail_type,
182
+ category, confidence, skill_name, mcp_server, mcp_tool, command, file_path,
183
+ status, error_message, seq, ts, ingested_at
184
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
185
+ ON CONFLICT(agent_id, call_id) DO UPDATE SET
186
+ workspace_id = COALESCE(excluded.workspace_id, tool_calls.workspace_id),
187
+ turn_id = COALESCE(excluded.turn_id, tool_calls.turn_id),
188
+ detail_type = COALESCE(excluded.detail_type, tool_calls.detail_type),
189
+ category = excluded.category,
190
+ confidence = CASE
191
+ WHEN excluded.category IS NOT tool_calls.category
192
+ THEN excluded.confidence
193
+ ELSE COALESCE(excluded.confidence, tool_calls.confidence)
194
+ END,
195
+ skill_name = CASE
196
+ WHEN excluded.category IS NOT tool_calls.category
197
+ THEN excluded.skill_name
198
+ ELSE COALESCE(excluded.skill_name, tool_calls.skill_name)
199
+ END,
200
+ mcp_server = CASE
201
+ WHEN excluded.category IS NOT tool_calls.category
202
+ THEN excluded.mcp_server
203
+ ELSE COALESCE(excluded.mcp_server, tool_calls.mcp_server)
204
+ END,
205
+ mcp_tool = CASE
206
+ WHEN excluded.category IS NOT tool_calls.category
207
+ THEN excluded.mcp_tool
208
+ ELSE COALESCE(excluded.mcp_tool, tool_calls.mcp_tool)
209
+ END,
210
+ command = CASE
211
+ WHEN excluded.category IS NOT tool_calls.category
212
+ THEN excluded.command
213
+ ELSE COALESCE(excluded.command, tool_calls.command)
214
+ END,
215
+ file_path = CASE
216
+ WHEN excluded.category IS NOT tool_calls.category
217
+ THEN excluded.file_path
218
+ ELSE COALESCE(excluded.file_path, tool_calls.file_path)
219
+ END,
220
+ status = CASE
221
+ WHEN excluded.status = 'running'
222
+ AND tool_calls.status IN ('completed', 'failed', 'canceled')
223
+ THEN tool_calls.status
224
+ ELSE COALESCE(excluded.status, tool_calls.status)
225
+ END,
226
+ error_message = COALESCE(excluded.error_message, tool_calls.error_message),
227
+ seq = COALESCE(excluded.seq, tool_calls.seq),
228
+ ts = COALESCE(excluded.ts, tool_calls.ts)
229
+ `;
230
+
231
+ const UPSERT_MESSAGE_SQL = `
232
+ INSERT INTO user_messages (agent_id, message_id, workspace_id, provider, model, turn_id, seq, ts, ingested_at)
233
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
234
+ ON CONFLICT(agent_id, message_id) DO UPDATE SET
235
+ workspace_id = COALESCE(excluded.workspace_id, user_messages.workspace_id),
236
+ provider = excluded.provider,
237
+ model = COALESCE(user_messages.model, excluded.model),
238
+ turn_id = COALESCE(excluded.turn_id, user_messages.turn_id),
239
+ seq = COALESCE(excluded.seq, user_messages.seq),
240
+ ts = COALESCE(excluded.ts, user_messages.ts)
241
+ `;
242
+
243
+ function messageMatchesFilter(row: UserMessageRow, filter: UserMessageFilter): boolean {
244
+ if (filter.agentId && row.agentId !== filter.agentId) return false;
245
+ if (filter.workspaceId && row.workspaceId !== filter.workspaceId) return false;
246
+ if (filter.provider && normalizeProvider(row.provider) !== normalizeProvider(filter.provider)) return false;
247
+ const time = row.ts ?? row.ingestedAt;
248
+ return (!filter.from || time >= filter.from) && (!filter.to || time <= filter.to);
249
+ }
250
+
251
+ function mergeMessage(previous: UserMessageRow, next: UserMessageRow): UserMessageRow {
252
+ return {
253
+ ...next,
254
+ workspaceId: next.workspaceId ?? previous.workspaceId,
255
+ model: previous.model ?? next.model,
256
+ turnId: next.turnId ?? previous.turnId,
257
+ seq: next.seq ?? previous.seq,
258
+ ts: next.ts ?? previous.ts,
259
+ ingestedAt: previous.ingestedAt,
260
+ };
261
+ }
262
+
263
+ function normalizeStoredModel(value: unknown): string | null {
264
+ if (typeof value !== "string") return null;
265
+ const trimmed = value.trim();
266
+ return trimmed ? trimmed : null;
267
+ }
268
+
269
+ const SELECT_ROW_SQL = `
270
+ SELECT agent_id, call_id, workspace_id, provider, turn_id, name, detail_type,
271
+ category, confidence, skill_name, mcp_server, mcp_tool, command, file_path,
272
+ status, error_message, seq, ts, ingested_at
273
+ FROM tool_calls
274
+ WHERE agent_id = ? AND call_id = ?
275
+ `;
276
+
277
+ const TERMINAL_STATUSES = new Set(["completed", "failed", "canceled"]);
278
+
279
+ type SqliteModule = typeof import("node:sqlite");
280
+
281
+ /** Ensure upgraded DBs gain `user_messages.model` (CREATE TABLE IF NOT EXISTS will not alter). */
282
+ export function ensureUserMessageModelColumn(
283
+ db: InstanceType<SqliteModule["DatabaseSync"]>,
284
+ ): void {
285
+ const cols = db.prepare("PRAGMA table_info(user_messages)").all() as Array<{ name?: string }>;
286
+ if (cols.some((col) => col.name === "model")) return;
287
+ db.exec("ALTER TABLE user_messages ADD COLUMN model TEXT");
288
+ }
289
+
290
+ export function defaultDataDir(): string {
291
+ return resolveActivityDataDir().dir;
292
+ }
293
+
294
+ export function createUsageStore(options: CreateUsageStoreOptions = {}): UsageStore {
295
+ const dir = options.dir ?? defaultDataDir();
296
+ mkdirSync(dir, { recursive: true });
297
+ if (options.driver !== "jsonl") {
298
+ const sqlite = loadSqlite();
299
+ if (sqlite) {
300
+ try {
301
+ return new SqliteUsageStore(join(dir, options.fileName ?? "usage.db"), sqlite);
302
+ } catch (error) {
303
+ console.error(`${LOG_PREFIX} node:sqlite unavailable, falling back to JSONL`, error);
304
+ }
305
+ } else if (options.driver === "sqlite") {
306
+ throw new Error("node:sqlite is not available in this runtime");
307
+ }
308
+ }
309
+ return new JsonlUsageStore(join(dir, "usage.jsonl"));
310
+ }
311
+
312
+ function loadSqlite(): SqliteModule | null {
313
+ try {
314
+ const module = process.getBuiltinModule("node:sqlite") as unknown as
315
+ | SqliteModule
316
+ | undefined;
317
+ return module && typeof module.DatabaseSync === "function" ? module : null;
318
+ } catch {
319
+ return null;
320
+ }
321
+ }
322
+
323
+ function rowEffectiveTime(row: ToolCallRow): string {
324
+ return row.ts ?? row.ingestedAt;
325
+ }
326
+
327
+ export function rowMatchesFilter(row: ToolCallRow, filter: QueryFilter = {}): boolean {
328
+ if (filter.agentId && row.agentId !== filter.agentId) return false;
329
+ if (filter.workspaceId && row.workspaceId !== filter.workspaceId) return false;
330
+ if (filter.category && row.category !== filter.category) return false;
331
+ if (filter.confidence !== undefined) {
332
+ if (filter.confidence === null) {
333
+ if (row.confidence !== null) return false;
334
+ } else if (row.confidence !== filter.confidence) return false;
335
+ }
336
+ if (filter.skillName && row.skillName !== filter.skillName) return false;
337
+ if (filter.mcpServer && row.mcpServer !== filter.mcpServer) return false;
338
+ const t = rowEffectiveTime(row);
339
+ if (filter.from && t < filter.from) return false;
340
+ if (filter.to && t > filter.to) return false;
341
+ return true;
342
+ }
343
+
344
+ export function agentMatchesFilter(row: AgentRow, filter: AgentQueryFilter = {}): boolean {
345
+ if (filter.workspaceId && row.workspaceId !== filter.workspaceId) return false;
346
+ if (filter.provider && normalizeProvider(row.provider) !== normalizeProvider(filter.provider)) {
347
+ return false;
348
+ }
349
+ if (filter.from && row.createdAt < filter.from) return false;
350
+ if (filter.to && row.createdAt > filter.to) return false;
351
+ return true;
352
+ }
353
+
354
+ /** Keep earlier createdAt; prefer non-null metadata from next. */
355
+ export function mergeAgentRow(previous: AgentRow, next: AgentRow): AgentRow {
356
+ return {
357
+ agentId: previous.agentId,
358
+ workspaceId: next.workspaceId ?? previous.workspaceId,
359
+ parentAgentId: next.parentAgentId ?? previous.parentAgentId,
360
+ provider: next.provider || previous.provider,
361
+ title: next.title ?? previous.title,
362
+ createdAt: previous.createdAt <= next.createdAt ? previous.createdAt : next.createdAt,
363
+ archivedAt: next.archivedAt ?? previous.archivedAt,
364
+ updatedAt: next.updatedAt >= previous.updatedAt ? next.updatedAt : previous.updatedAt,
365
+ };
366
+ }
367
+
368
+ function rowValues(row: ToolCallRow): Array<string | number | null> {
369
+ return [
370
+ row.agentId,
371
+ row.callId,
372
+ row.workspaceId,
373
+ row.provider,
374
+ row.turnId,
375
+ row.name,
376
+ row.detailType,
377
+ row.category,
378
+ row.confidence,
379
+ row.skillName,
380
+ row.mcpServer,
381
+ row.mcpTool,
382
+ row.command,
383
+ row.filePath,
384
+ row.status,
385
+ row.errorMessage,
386
+ row.seq,
387
+ row.ts,
388
+ row.ingestedAt,
389
+ ];
390
+ }
391
+
392
+ function rowFromRecord(record: Record<string, unknown>): ToolCallRow {
393
+ return {
394
+ agentId: String(record.agent_id),
395
+ callId: String(record.call_id),
396
+ workspaceId: record.workspace_id == null ? null : String(record.workspace_id),
397
+ provider: String(record.provider),
398
+ turnId: record.turn_id == null ? null : String(record.turn_id),
399
+ name: String(record.name),
400
+ detailType: record.detail_type == null ? null : String(record.detail_type),
401
+ category: String(record.category) as Category,
402
+ confidence: record.confidence == null ? null : (String(record.confidence) as Confidence),
403
+ skillName: record.skill_name == null ? null : String(record.skill_name),
404
+ mcpServer: record.mcp_server == null ? null : String(record.mcp_server),
405
+ mcpTool: record.mcp_tool == null ? null : String(record.mcp_tool),
406
+ command: record.command == null ? null : String(record.command),
407
+ filePath: record.file_path == null ? null : String(record.file_path),
408
+ status: record.status == null ? null : String(record.status),
409
+ errorMessage: record.error_message == null ? null : String(record.error_message),
410
+ seq: record.seq == null ? null : Number(record.seq),
411
+ ts: record.ts == null ? null : String(record.ts),
412
+ ingestedAt: String(record.ingested_at),
413
+ };
414
+ }
415
+
416
+ function rowKey(agentId: string, callId: string): string {
417
+ return `${agentId}\u0000${callId}`;
418
+ }
419
+
420
+ const UPSERT_AGENT_SQL = `
421
+ INSERT INTO agents (
422
+ agent_id, workspace_id, parent_agent_id, provider, title,
423
+ created_at, archived_at, updated_at
424
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
425
+ ON CONFLICT(agent_id) DO UPDATE SET
426
+ workspace_id = COALESCE(excluded.workspace_id, agents.workspace_id),
427
+ parent_agent_id = COALESCE(excluded.parent_agent_id, agents.parent_agent_id),
428
+ provider = excluded.provider,
429
+ title = COALESCE(excluded.title, agents.title),
430
+ created_at = CASE
431
+ WHEN excluded.created_at < agents.created_at THEN excluded.created_at
432
+ ELSE agents.created_at
433
+ END,
434
+ archived_at = COALESCE(excluded.archived_at, agents.archived_at),
435
+ updated_at = excluded.updated_at
436
+ `;
437
+
438
+ function agentValues(row: AgentRow): Array<string | null> {
439
+ return [
440
+ row.agentId,
441
+ row.workspaceId,
442
+ row.parentAgentId,
443
+ row.provider,
444
+ row.title,
445
+ row.createdAt,
446
+ row.archivedAt,
447
+ row.updatedAt,
448
+ ];
449
+ }
450
+
451
+ function agentFromRecord(record: Record<string, unknown>): AgentRow {
452
+ return {
453
+ agentId: String(record.agent_id),
454
+ workspaceId: record.workspace_id == null ? null : String(record.workspace_id),
455
+ parentAgentId: record.parent_agent_id == null ? null : String(record.parent_agent_id),
456
+ provider: String(record.provider),
457
+ title: record.title == null ? null : String(record.title),
458
+ createdAt: String(record.created_at),
459
+ archivedAt: record.archived_at == null ? null : String(record.archived_at),
460
+ updatedAt: String(record.updated_at),
461
+ };
462
+ }
463
+
464
+ function mergeRow(previous: ToolCallRow, next: ToolCallRow): ToolCallRow {
465
+ const status =
466
+ next.status === "running" && previous.status && TERMINAL_STATUSES.has(previous.status)
467
+ ? previous.status
468
+ : (next.status ?? previous.status);
469
+ const categoryChanged = next.category !== previous.category;
470
+ return {
471
+ ...previous,
472
+ ...next,
473
+ workspaceId: next.workspaceId ?? previous.workspaceId,
474
+ turnId: next.turnId ?? previous.turnId,
475
+ detailType: next.detailType ?? previous.detailType,
476
+ confidence: categoryChanged ? next.confidence : (next.confidence ?? previous.confidence),
477
+ skillName: categoryChanged ? next.skillName : (next.skillName ?? previous.skillName),
478
+ mcpServer: categoryChanged ? next.mcpServer : (next.mcpServer ?? previous.mcpServer),
479
+ mcpTool: categoryChanged ? next.mcpTool : (next.mcpTool ?? previous.mcpTool),
480
+ command: categoryChanged ? next.command : (next.command ?? previous.command),
481
+ filePath: categoryChanged ? next.filePath : (next.filePath ?? previous.filePath),
482
+ status,
483
+ errorMessage: next.errorMessage ?? previous.errorMessage,
484
+ seq: next.seq ?? previous.seq,
485
+ ts: next.ts ?? previous.ts,
486
+ ingestedAt: previous.ingestedAt,
487
+ };
488
+ }
489
+
490
+ function toolCallSelectSql(filter: QueryFilter): { sql: string; params: Array<string | number | null> } {
491
+ const clauses: string[] = [];
492
+ const params: Array<string | number | null> = [];
493
+ if (filter.agentId) {
494
+ clauses.push("agent_id = ?");
495
+ params.push(filter.agentId);
496
+ }
497
+ if (filter.workspaceId) {
498
+ clauses.push("workspace_id = ?");
499
+ params.push(filter.workspaceId);
500
+ }
501
+ if (filter.category) {
502
+ clauses.push("category = ?");
503
+ params.push(filter.category);
504
+ }
505
+ if (filter.skillName) {
506
+ clauses.push("skill_name = ?");
507
+ params.push(filter.skillName);
508
+ }
509
+ if (filter.mcpServer) {
510
+ clauses.push("mcp_server = ?");
511
+ params.push(filter.mcpServer);
512
+ }
513
+ if (filter.confidence !== undefined) {
514
+ if (filter.confidence === null) clauses.push("confidence IS NULL");
515
+ else {
516
+ clauses.push("confidence = ?");
517
+ params.push(filter.confidence);
518
+ }
519
+ }
520
+ if (filter.from) {
521
+ clauses.push("COALESCE(ts, ingested_at) >= ?");
522
+ params.push(filter.from);
523
+ }
524
+ if (filter.to) {
525
+ clauses.push("COALESCE(ts, ingested_at) <= ?");
526
+ params.push(filter.to);
527
+ }
528
+ const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
529
+ return { sql: `SELECT * FROM tool_calls${where}`, params };
530
+ }
531
+
532
+ function userMessageSelectSql(filter: UserMessageFilter): { sql: string; params: Array<string | number | null> } {
533
+ const clauses: string[] = [];
534
+ const params: Array<string | number | null> = [];
535
+ if (filter.agentId) {
536
+ clauses.push("agent_id = ?");
537
+ params.push(filter.agentId);
538
+ }
539
+ if (filter.workspaceId) {
540
+ clauses.push("workspace_id = ?");
541
+ params.push(filter.workspaceId);
542
+ }
543
+ if (filter.from) {
544
+ clauses.push("COALESCE(ts, ingested_at) >= ?");
545
+ params.push(filter.from);
546
+ }
547
+ if (filter.to) {
548
+ clauses.push("COALESCE(ts, ingested_at) <= ?");
549
+ params.push(filter.to);
550
+ }
551
+ const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
552
+ return {
553
+ sql: `SELECT agent_id AS agentId, message_id AS messageId,
554
+ workspace_id AS workspaceId, provider, model, turn_id AS turnId, seq, ts,
555
+ ingested_at AS ingestedAt FROM user_messages${where}`,
556
+ params,
557
+ };
558
+ }
559
+
560
+ function agentSelectSql(filter: AgentQueryFilter): { sql: string; params: Array<string | number | null> } {
561
+ const clauses: string[] = [];
562
+ const params: Array<string | number | null> = [];
563
+ if (filter.workspaceId) {
564
+ clauses.push("workspace_id = ?");
565
+ params.push(filter.workspaceId);
566
+ }
567
+ if (filter.from) {
568
+ clauses.push("created_at >= ?");
569
+ params.push(filter.from);
570
+ }
571
+ if (filter.to) {
572
+ clauses.push("created_at <= ?");
573
+ params.push(filter.to);
574
+ }
575
+ const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
576
+ return { sql: `SELECT * FROM agents${where}`, params };
577
+ }
578
+
579
+ class SqliteUsageStore implements UsageStore {
580
+ readonly driver = "sqlite" as const;
581
+ private readonly db: InstanceType<SqliteModule["DatabaseSync"]>;
582
+ private readonly insert: ReturnType<InstanceType<SqliteModule["DatabaseSync"]>["prepare"]>;
583
+ private readonly insertAgent: ReturnType<InstanceType<SqliteModule["DatabaseSync"]>["prepare"]>;
584
+ private readonly insertMessage: ReturnType<InstanceType<SqliteModule["DatabaseSync"]>["prepare"]>;
585
+
586
+ constructor(filePath: string, sqlite: SqliteModule) {
587
+ this.db = new sqlite.DatabaseSync(filePath);
588
+ this.db.exec(SCHEMA_SQL);
589
+ ensureUserMessageModelColumn(this.db);
590
+ this.insert = this.db.prepare(UPSERT_SQL);
591
+ this.insertAgent = this.db.prepare(UPSERT_AGENT_SQL);
592
+ this.insertMessage = this.db.prepare(UPSERT_MESSAGE_SQL);
593
+ }
594
+
595
+ upsertMany(rows: readonly ToolCallRow[]): number {
596
+ if (rows.length === 0) return 0;
597
+ this.db.exec("BEGIN");
598
+ try {
599
+ for (const row of rows) {
600
+ this.insert.run(...rowValues(row));
601
+ }
602
+ this.db.exec("COMMIT");
603
+ } catch (error) {
604
+ this.db.exec("ROLLBACK");
605
+ throw error;
606
+ }
607
+ return rows.length;
608
+ }
609
+
610
+ count(): number {
611
+ const record = this.db.prepare("SELECT COUNT(*) AS count FROM tool_calls").get() as
612
+ | Record<string, unknown>
613
+ | undefined;
614
+ return record ? Number(record.count) : 0;
615
+ }
616
+
617
+ getRow(agentId: string, callId: string): ToolCallRow | null {
618
+ const record = this.db.prepare(SELECT_ROW_SQL).get(agentId, callId) as
619
+ | Record<string, unknown>
620
+ | undefined;
621
+ return record ? rowFromRecord(record) : null;
622
+ }
623
+
624
+ select(filter: QueryFilter = {}): ToolCallRow[] {
625
+ const { sql, params } = toolCallSelectSql(filter);
626
+ const records = this.db.prepare(sql).all(...params) as Record<string, unknown>[];
627
+ return records.map(rowFromRecord).filter((row) => rowMatchesFilter(row, filter));
628
+ }
629
+
630
+ upsertAgents(rows: readonly AgentRow[]): number {
631
+ if (rows.length === 0) return 0;
632
+ this.db.exec("BEGIN");
633
+ try {
634
+ for (const row of rows) {
635
+ this.insertAgent.run(...agentValues(row));
636
+ }
637
+ this.db.exec("COMMIT");
638
+ } catch (error) {
639
+ this.db.exec("ROLLBACK");
640
+ throw error;
641
+ }
642
+ return rows.length;
643
+ }
644
+
645
+ upsertUserMessages(rows: readonly UserMessageRow[]): number {
646
+ if (!rows.length) return 0;
647
+ this.db.exec("BEGIN");
648
+ try {
649
+ for (const row of rows) {
650
+ this.insertMessage.run(
651
+ row.agentId,
652
+ row.messageId,
653
+ row.workspaceId,
654
+ row.provider,
655
+ row.model,
656
+ row.turnId,
657
+ row.seq,
658
+ row.ts,
659
+ row.ingestedAt,
660
+ );
661
+ }
662
+ this.db.exec("COMMIT");
663
+ } catch (error) {
664
+ this.db.exec("ROLLBACK");
665
+ throw error;
666
+ }
667
+ return rows.length;
668
+ }
669
+
670
+ selectUserMessages(filter: UserMessageFilter = {}): UserMessageRow[] {
671
+ const { sql, params } = userMessageSelectSql(filter);
672
+ const rows = this.db.prepare(sql).all(...params) as Array<Record<string, unknown>>;
673
+ return rows
674
+ .map((row) => ({
675
+ agentId: String(row.agentId),
676
+ messageId: String(row.messageId),
677
+ workspaceId: row.workspaceId == null ? null : String(row.workspaceId),
678
+ provider: String(row.provider),
679
+ model: normalizeStoredModel(row.model),
680
+ turnId: row.turnId == null ? null : String(row.turnId),
681
+ seq: row.seq == null ? null : Number(row.seq),
682
+ ts: row.ts == null ? null : String(row.ts),
683
+ ingestedAt: String(row.ingestedAt),
684
+ }))
685
+ .filter((row) => messageMatchesFilter(row, filter));
686
+ }
687
+
688
+ getAgent(agentId: string): AgentRow | null {
689
+ const record = this.db
690
+ .prepare("SELECT * FROM agents WHERE agent_id = ?")
691
+ .get(agentId) as Record<string, unknown> | undefined;
692
+ return record ? agentFromRecord(record) : null;
693
+ }
694
+
695
+ selectAgents(filter: AgentQueryFilter = {}): AgentRow[] {
696
+ const { sql, params } = agentSelectSql(filter);
697
+ const records = this.db.prepare(sql).all(...params) as Record<string, unknown>[];
698
+ return records.map(agentFromRecord).filter((row) => agentMatchesFilter(row, filter));
699
+ }
700
+
701
+ getSyncState(agentId: string): SyncState | null {
702
+ const record = this.db
703
+ .prepare("SELECT agent_id, epoch, last_seq, updated_at FROM sync_state WHERE agent_id = ?")
704
+ .get(agentId) as Record<string, unknown> | undefined;
705
+ if (!record) return null;
706
+ return {
707
+ agentId: String(record.agent_id),
708
+ epoch: String(record.epoch),
709
+ lastSeq: Number(record.last_seq),
710
+ updatedAt: String(record.updated_at),
711
+ };
712
+ }
713
+
714
+ setSyncState(agentId: string, epoch: string, lastSeq: number): void {
715
+ this.db
716
+ .prepare(
717
+ `INSERT INTO sync_state (agent_id, epoch, last_seq, updated_at)
718
+ VALUES (?, ?, ?, ?)
719
+ ON CONFLICT(agent_id) DO UPDATE SET
720
+ epoch = excluded.epoch,
721
+ last_seq = excluded.last_seq,
722
+ updated_at = excluded.updated_at`,
723
+ )
724
+ .run(agentId, epoch, lastSeq, new Date().toISOString());
725
+ }
726
+
727
+ deleteCanonicalUserMessages(agentId: string): number {
728
+ const result = this.db
729
+ .prepare(`DELETE FROM user_messages WHERE agent_id = ? AND message_id LIKE 'canonical:%'`)
730
+ .run(agentId) as { changes?: number };
731
+ return Number(result.changes ?? 0);
732
+ }
733
+
734
+ close(): void {
735
+ this.db.close();
736
+ }
737
+ }
738
+
739
+ class JsonlUsageStore implements UsageStore {
740
+ readonly driver = "jsonl" as const;
741
+ private readonly rows = new Map<string, ToolCallRow>();
742
+ private readonly agents = new Map<string, AgentRow>();
743
+ private readonly sync = new Map<string, SyncState>();
744
+ private readonly filePath: string;
745
+ private readonly agentsPath: string;
746
+ private readonly messagesPath: string;
747
+ private readonly messages = new Map<string, UserMessageRow>();
748
+
749
+ constructor(filePath: string) {
750
+ this.filePath = filePath;
751
+ this.messagesPath = join(dirname(filePath), "user_messages.jsonl");
752
+ if (existsSync(this.messagesPath)) {
753
+ for (const line of readFileSync(this.messagesPath, "utf8").split("\n")) {
754
+ if (!line.trim()) continue;
755
+ try {
756
+ const parsed = JSON.parse(line) as UserMessageRow | {
757
+ __delete_canonical_messages?: { agentId: string };
758
+ };
759
+ if (parsed && "__delete_canonical_messages" in parsed && parsed.__delete_canonical_messages) {
760
+ const agentId = parsed.__delete_canonical_messages.agentId;
761
+ for (const [key, row] of this.messages) {
762
+ if (row.agentId === agentId && row.messageId.startsWith("canonical:")) {
763
+ this.messages.delete(key);
764
+ }
765
+ }
766
+ continue;
767
+ }
768
+ const row = parsed as UserMessageRow;
769
+ if (row.agentId && row.messageId) {
770
+ this.messages.set(rowKey(row.agentId, row.messageId), {
771
+ ...row,
772
+ model: normalizeStoredModel(row.model),
773
+ });
774
+ }
775
+ } catch { /* Ignore incomplete lines, as with the other JSONL stores. */ }
776
+ }
777
+ }
778
+ this.agentsPath = join(dirname(filePath), "agents.jsonl");
779
+ if (existsSync(filePath)) {
780
+ for (const line of readFileSync(filePath, "utf8").split("\n")) {
781
+ if (!line.trim()) continue;
782
+ try {
783
+ const parsed = JSON.parse(line) as ToolCallRow | { __sync: SyncState };
784
+ if ("__sync" in parsed && parsed.__sync) {
785
+ this.sync.set(parsed.__sync.agentId, parsed.__sync);
786
+ continue;
787
+ }
788
+ const row = parsed as ToolCallRow;
789
+ if (!row.agentId || !row.callId) continue;
790
+ this.rows.set(rowKey(row.agentId, row.callId), row);
791
+ } catch {
792
+ continue;
793
+ }
794
+ }
795
+ }
796
+ if (existsSync(this.agentsPath)) {
797
+ for (const line of readFileSync(this.agentsPath, "utf8").split("\n")) {
798
+ if (!line.trim()) continue;
799
+ try {
800
+ const row = JSON.parse(line) as AgentRow;
801
+ if (!row.agentId) continue;
802
+ const previous = this.agents.get(row.agentId);
803
+ this.agents.set(row.agentId, previous ? mergeAgentRow(previous, row) : row);
804
+ } catch {
805
+ continue;
806
+ }
807
+ }
808
+ }
809
+ }
810
+
811
+ upsertMany(rows: readonly ToolCallRow[]): number {
812
+ if (rows.length === 0) return 0;
813
+ const lines: string[] = [];
814
+ for (const row of rows) {
815
+ const key = rowKey(row.agentId, row.callId);
816
+ const previous = this.rows.get(key);
817
+ const merged = previous ? mergeRow(previous, row) : row;
818
+ this.rows.set(key, merged);
819
+ lines.push(JSON.stringify(merged));
820
+ }
821
+ appendFileSync(this.filePath, `${lines.join("\n")}\n`);
822
+ return rows.length;
823
+ }
824
+
825
+ count(): number {
826
+ return this.rows.size;
827
+ }
828
+
829
+ getRow(agentId: string, callId: string): ToolCallRow | null {
830
+ return this.rows.get(rowKey(agentId, callId)) ?? null;
831
+ }
832
+
833
+ select(filter: QueryFilter = {}): ToolCallRow[] {
834
+ return [...this.rows.values()].filter((row) => rowMatchesFilter(row, filter));
835
+ }
836
+
837
+ upsertAgents(rows: readonly AgentRow[]): number {
838
+ if (rows.length === 0) return 0;
839
+ const lines: string[] = [];
840
+ for (const row of rows) {
841
+ const previous = this.agents.get(row.agentId);
842
+ const merged = previous ? mergeAgentRow(previous, row) : row;
843
+ this.agents.set(row.agentId, merged);
844
+ lines.push(JSON.stringify(merged));
845
+ }
846
+ appendFileSync(this.agentsPath, `${lines.join("\n")}\n`);
847
+ return rows.length;
848
+ }
849
+
850
+ upsertUserMessages(rows: readonly UserMessageRow[]): number {
851
+ if (!rows.length) return 0;
852
+ const lines: string[] = [];
853
+ for (const row of rows) {
854
+ const key = rowKey(row.agentId, row.messageId);
855
+ const previous = this.messages.get(key);
856
+ const merged = previous ? mergeMessage(previous, row) : row;
857
+ this.messages.set(key, merged);
858
+ lines.push(JSON.stringify(merged));
859
+ }
860
+ appendFileSync(this.messagesPath, `${lines.join("\n")}\n`);
861
+ return rows.length;
862
+ }
863
+
864
+ selectUserMessages(filter: UserMessageFilter = {}): UserMessageRow[] {
865
+ return [...this.messages.values()].filter(row => messageMatchesFilter(row, filter));
866
+ }
867
+
868
+ getAgent(agentId: string): AgentRow | null {
869
+ return this.agents.get(agentId) ?? null;
870
+ }
871
+
872
+ selectAgents(filter: AgentQueryFilter = {}): AgentRow[] {
873
+ return [...this.agents.values()].filter((row) => agentMatchesFilter(row, filter));
874
+ }
875
+
876
+ getSyncState(agentId: string): SyncState | null {
877
+ return this.sync.get(agentId) ?? null;
878
+ }
879
+
880
+ setSyncState(agentId: string, epoch: string, lastSeq: number): void {
881
+ const state: SyncState = {
882
+ agentId,
883
+ epoch,
884
+ lastSeq,
885
+ updatedAt: new Date().toISOString(),
886
+ };
887
+ this.sync.set(agentId, state);
888
+ appendFileSync(this.filePath, `${JSON.stringify({ __sync: state })}\n`);
889
+ }
890
+
891
+ deleteCanonicalUserMessages(agentId: string): number {
892
+ let removed = 0;
893
+ for (const [key, row] of this.messages) {
894
+ if (row.agentId === agentId && row.messageId.startsWith("canonical:")) {
895
+ this.messages.delete(key);
896
+ removed += 1;
897
+ }
898
+ }
899
+ if (removed > 0) {
900
+ appendFileSync(
901
+ this.messagesPath,
902
+ `${JSON.stringify({ __delete_canonical_messages: { agentId, removed } })}\n`,
903
+ );
904
+ }
905
+ return removed;
906
+ }
907
+
908
+ close(): void {}
909
+ }