@koinzhang/paseo-plugin-activity 0.6.0 → 0.8.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 (68) hide show
  1. package/CHANGELOG.md +50 -1
  2. package/README.md +18 -11
  3. package/client/activity-heatmap.tsx +115 -74
  4. package/client/agent-creations.tsx +100 -90
  5. package/client/attention-pill.tsx +17 -6
  6. package/client/attention-popover.tsx +19 -23
  7. package/client/design-tokens.test.ts +39 -0
  8. package/client/design-tokens.ts +180 -0
  9. package/client/formatted-time.tsx +4 -4
  10. package/client/global-surface.tsx +243 -268
  11. package/client/header-button.ts +136 -0
  12. package/client/hourly-activity-timeline.tsx +153 -103
  13. package/client/panel-visibility.test.ts +25 -0
  14. package/client/panel-visibility.ts +45 -0
  15. package/client/panel.tsx +94 -111
  16. package/client/pill.tsx +1 -1
  17. package/client/provider-dropdown.tsx +134 -0
  18. package/client/provider-filter.test.ts +17 -13
  19. package/client/provider-filter.ts +5 -7
  20. package/client/rank-color.ts +3 -3
  21. package/client/ranking-bars.tsx +294 -0
  22. package/client/sidebar-item.tsx +15 -0
  23. package/client/ui.tsx +351 -0
  24. package/client/usage-popover.tsx +72 -137
  25. package/client/usage-stats.tsx +29 -11
  26. package/client/use-agent-turn-end.ts +2 -1
  27. package/client/use-app-language.ts +17 -0
  28. package/client/web.ts +73 -18
  29. package/client/workspace/agent-row.tsx +28 -28
  30. package/client/workspace/agents-section.tsx +42 -57
  31. package/client/workspace/constants.ts +8 -6
  32. package/client/workspace/display-menu.tsx +6 -5
  33. package/client/workspace/filters.test.ts +1 -1
  34. package/client/workspace/filters.ts +4 -2
  35. package/client/workspace/panel.tsx +96 -104
  36. package/client/workspace/rank-section.tsx +40 -65
  37. package/client/workspace/running-indicator.tsx +1 -1
  38. package/client/workspace/terminals-section.tsx +24 -12
  39. package/index.client.tsx +53 -31
  40. package/index.server.ts +55 -73
  41. package/package.json +3 -3
  42. package/paseo-plugin.json +2 -1
  43. package/server/agents.ts +20 -2
  44. package/server/background-sync.ts +34 -4
  45. package/server/handlers-query.test.ts +27 -1
  46. package/server/handlers.ts +75 -31
  47. package/server/host-types.ts +6 -6
  48. package/server/ingest.test.ts +8 -0
  49. package/server/messages.test.ts +96 -1
  50. package/server/prompt-dedupe.ts +52 -0
  51. package/server/rpc-cache.test.ts +74 -0
  52. package/server/rpc-cache.ts +48 -0
  53. package/server/store.test.ts +122 -0
  54. package/server/store.ts +313 -19
  55. package/server/ttl-cache.ts +3 -0
  56. package/server/turn-ingest.test.ts +180 -0
  57. package/server/turn-ingest.ts +71 -0
  58. package/shared/activity.test.ts +36 -0
  59. package/shared/activity.ts +37 -0
  60. package/shared/classify.test.ts +1 -10
  61. package/shared/classify.ts +3 -10
  62. package/shared/format.ts +10 -7
  63. package/shared/i18n.test.ts +34 -0
  64. package/shared/i18n.ts +363 -0
  65. package/shared/insights.test.ts +120 -81
  66. package/shared/insights.ts +125 -64
  67. package/shared/usage.test.ts +121 -0
  68. package/shared/usage.ts +191 -2
package/server/store.ts CHANGED
@@ -4,6 +4,7 @@ import type { Category, Confidence } from "../shared/classify.ts";
4
4
  import { normalizeProvider } from "../shared/classify.ts";
5
5
  import { LOG_PREFIX } from "../shared/plugin-id.ts";
6
6
  import { resolveActivityDataDir } from "./migrate-data.ts";
7
+ import { replayDuplicateMessageIds } from "./prompt-dedupe.ts";
7
8
 
8
9
  export interface ToolCallRow {
9
10
  agentId: string;
@@ -72,6 +73,10 @@ export type AgentRow = {
72
73
  createdAt: string;
73
74
  archivedAt: string | null;
74
75
  updatedAt: string;
76
+ /** Agent working directory (070); null when never observed. */
77
+ cwd?: string | null;
78
+ /** Project root of the agent's workspace while it was listed (070); covers worktrees. */
79
+ projectRoot?: string | null;
75
80
  };
76
81
 
77
82
  export type AgentQueryFilter = {
@@ -82,12 +87,38 @@ export type AgentQueryFilter = {
82
87
  to?: string;
83
88
  };
84
89
 
90
+ /** Controlled extra predicates for `selectRecent` (not free-form SQL). */
91
+ export type RecentRowScope = "skill-named" | "mcp-named";
92
+
93
+ export type RecentRowOptions = {
94
+ limit: number;
95
+ offset?: number;
96
+ scope?: RecentRowScope;
97
+ };
98
+
99
+ /** Earliest / latest tool activity per agent (registry fallback for unknown agents). */
100
+ export type AgentActivitySpan = {
101
+ agentId: string;
102
+ provider: string;
103
+ workspaceId: string | null;
104
+ firstAt: string;
105
+ lastAt: string;
106
+ };
107
+
85
108
  export interface UsageStore {
86
109
  readonly driver: UsageStoreDriver;
110
+ /** Increments on every write; read caches compare against it. */
111
+ generation(): number;
87
112
  upsertMany(rows: readonly ToolCallRow[]): number;
88
113
  count(): number;
89
114
  getRow(agentId: string, callId: string): ToolCallRow | null;
90
115
  select(filter?: QueryFilter): ToolCallRow[];
116
+ /** Newest first (effective time, then call_id), paged in the store. */
117
+ selectRecent(filter: QueryFilter, options: RecentRowOptions): ToolCallRow[];
118
+ countRows(filter?: QueryFilter): number;
119
+ agentActivitySpans(): AgentActivitySpan[];
120
+ /** call_ids already stored in a terminal status for this agent. */
121
+ terminalCallIds(agentId: string): Set<string>;
91
122
  upsertUserMessages(rows: readonly UserMessageRow[]): number;
92
123
  selectUserMessages(filter?: UserMessageFilter): UserMessageRow[];
93
124
  upsertAgents(rows: readonly AgentRow[]): number;
@@ -97,6 +128,8 @@ export interface UsageStore {
97
128
  setSyncState(agentId: string, epoch: string, lastSeq: number): void;
98
129
  /** Drop hash-keyed (`canonical:…`) user messages for an agent (timeline epoch replace). */
99
130
  deleteCanonicalUserMessages(agentId: string): number;
131
+ /** Drop replayed copies of live prompts (075); all agents when agentId is omitted. */
132
+ pruneReplayDuplicateMessages(agentId?: string): number;
100
133
  close(): void;
101
134
  }
102
135
 
@@ -134,6 +167,9 @@ CREATE INDEX IF NOT EXISTS idx_tool_calls_ts ON tool_calls(ts, ingested_at)
134
167
  CREATE INDEX IF NOT EXISTS idx_tool_calls_skill ON tool_calls(skill_name);
135
168
  CREATE INDEX IF NOT EXISTS idx_tool_calls_mcp ON tool_calls(mcp_server, mcp_tool);
136
169
  CREATE INDEX IF NOT EXISTS idx_tool_calls_agent ON tool_calls(agent_id, workspace_id);
170
+ -- 064: workspace-scoped reads and COALESCE(ts, ingested_at) window filters / ordering
171
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_workspace ON tool_calls(workspace_id, category);
172
+ CREATE INDEX IF NOT EXISTS idx_tool_calls_time ON tool_calls(COALESCE(ts, ingested_at));
137
173
 
138
174
  -- 006: user_messages (turns the user sent; message body is not stored)
139
175
  -- Merged into store SCHEMA_SQL; file: ~/.paseo/plugin-data/activity/usage.db
@@ -153,6 +189,7 @@ CREATE TABLE IF NOT EXISTS user_messages (
153
189
 
154
190
  CREATE INDEX IF NOT EXISTS idx_user_messages_ts ON user_messages(ts, ingested_at);
155
191
  CREATE INDEX IF NOT EXISTS idx_user_messages_agent ON user_messages(agent_id, workspace_id);
192
+ CREATE INDEX IF NOT EXISTS idx_user_messages_time ON user_messages(COALESCE(ts, ingested_at));
156
193
 
157
194
  CREATE TABLE IF NOT EXISTS sync_state (
158
195
  agent_id TEXT PRIMARY KEY,
@@ -169,13 +206,43 @@ CREATE TABLE IF NOT EXISTS agents (
169
206
  title TEXT,
170
207
  created_at TEXT NOT NULL,
171
208
  archived_at TEXT,
172
- updated_at TEXT NOT NULL
209
+ updated_at TEXT NOT NULL,
210
+ cwd TEXT,
211
+ project_root TEXT
173
212
  );
174
213
 
175
214
  CREATE INDEX IF NOT EXISTS idx_agents_created ON agents(created_at);
176
215
  CREATE INDEX IF NOT EXISTS idx_agents_provider ON agents(provider);
177
216
  `;
178
217
 
218
+ // Replayed history (ACP / OpenCode / Pi) is stamped at replay time, which is never
219
+ // earlier than the real event, and no event happens after it was first ingested (074).
220
+ function mergedTsSql(table: string): string {
221
+ return `CASE
222
+ WHEN julianday(excluded.ts) IS NULL THEN ${table}.ts
223
+ WHEN ${table}.ts IS NULL THEN
224
+ CASE WHEN julianday(excluded.ts) <= julianday(${table}.ingested_at)
225
+ THEN excluded.ts END
226
+ WHEN julianday(excluded.ts) < julianday(${table}.ts) THEN excluded.ts
227
+ ELSE ${table}.ts
228
+ END`;
229
+ }
230
+
231
+ function mergeTs(previous: string | null, next: string | null, ingestedAt: string): string | null {
232
+ const nextTime = next == null ? Number.NaN : Date.parse(next);
233
+ if (Number.isNaN(nextTime)) return previous;
234
+ if (previous == null) return nextTime <= Date.parse(ingestedAt) ? next : null;
235
+ return nextTime < Date.parse(previous) ? next : previous;
236
+ }
237
+
238
+ function clampTs(ts: string | null, ingestedAt: string): string | null {
239
+ return ts != null && Date.parse(ts) > Date.parse(ingestedAt) ? null : ts;
240
+ }
241
+
242
+ const CLAMP_TS_SQL = ["tool_calls", "user_messages"].map(table =>
243
+ `UPDATE ${table} SET ts = NULL WHERE ts IS NOT NULL AND julianday(ts) > julianday(ingested_at);`,
244
+ ).join("\n");
245
+
179
246
  const UPSERT_SQL = `
180
247
  INSERT INTO tool_calls (
181
248
  agent_id, call_id, workspace_id, provider, turn_id, name, detail_type,
@@ -225,7 +292,7 @@ ON CONFLICT(agent_id, call_id) DO UPDATE SET
225
292
  END,
226
293
  error_message = COALESCE(excluded.error_message, tool_calls.error_message),
227
294
  seq = COALESCE(excluded.seq, tool_calls.seq),
228
- ts = COALESCE(excluded.ts, tool_calls.ts)
295
+ ts = ${mergedTsSql("tool_calls")}
229
296
  `;
230
297
 
231
298
  const UPSERT_MESSAGE_SQL = `
@@ -237,7 +304,7 @@ ON CONFLICT(agent_id, message_id) DO UPDATE SET
237
304
  model = COALESCE(user_messages.model, excluded.model),
238
305
  turn_id = COALESCE(excluded.turn_id, user_messages.turn_id),
239
306
  seq = COALESCE(excluded.seq, user_messages.seq),
240
- ts = COALESCE(excluded.ts, user_messages.ts)
307
+ ts = ${mergedTsSql("user_messages")}
241
308
  `;
242
309
 
243
310
  function messageMatchesFilter(row: UserMessageRow, filter: UserMessageFilter): boolean {
@@ -255,7 +322,7 @@ function mergeMessage(previous: UserMessageRow, next: UserMessageRow): UserMessa
255
322
  model: previous.model ?? next.model,
256
323
  turnId: next.turnId ?? previous.turnId,
257
324
  seq: next.seq ?? previous.seq,
258
- ts: next.ts ?? previous.ts,
325
+ ts: mergeTs(previous.ts, next.ts, previous.ingestedAt),
259
326
  ingestedAt: previous.ingestedAt,
260
327
  };
261
328
  }
@@ -287,6 +354,17 @@ export function ensureUserMessageModelColumn(
287
354
  db.exec("ALTER TABLE user_messages ADD COLUMN model TEXT");
288
355
  }
289
356
 
357
+ /** Ensure upgraded DBs gain `agents.cwd` / `agents.project_root` (070). */
358
+ export function ensureAgentProjectColumns(
359
+ db: InstanceType<SqliteModule["DatabaseSync"]>,
360
+ ): void {
361
+ const cols = new Set(
362
+ (db.prepare("PRAGMA table_info(agents)").all() as Array<{ name?: string }>).map((col) => col.name),
363
+ );
364
+ if (!cols.has("cwd")) db.exec("ALTER TABLE agents ADD COLUMN cwd TEXT");
365
+ if (!cols.has("project_root")) db.exec("ALTER TABLE agents ADD COLUMN project_root TEXT");
366
+ }
367
+
290
368
  export function defaultDataDir(): string {
291
369
  return resolveActivityDataDir().dir;
292
370
  }
@@ -320,6 +398,21 @@ function loadSqlite(): SqliteModule | null {
320
398
  }
321
399
  }
322
400
 
401
+ function replayDuplicatesByAgent(rows: readonly UserMessageRow[]): Array<[string, string[]]> {
402
+ const byAgent = new Map<string, UserMessageRow[]>();
403
+ for (const row of rows) {
404
+ const list = byAgent.get(row.agentId);
405
+ if (list) list.push(row);
406
+ else byAgent.set(row.agentId, [row]);
407
+ }
408
+ const result: Array<[string, string[]]> = [];
409
+ for (const [agentId, list] of byAgent) {
410
+ const ids = replayDuplicateMessageIds(list);
411
+ if (ids.size > 0) result.push([agentId, [...ids]]);
412
+ }
413
+ return result;
414
+ }
415
+
323
416
  function rowEffectiveTime(row: ToolCallRow): string {
324
417
  return row.ts ?? row.ingestedAt;
325
418
  }
@@ -362,6 +455,8 @@ export function mergeAgentRow(previous: AgentRow, next: AgentRow): AgentRow {
362
455
  createdAt: previous.createdAt <= next.createdAt ? previous.createdAt : next.createdAt,
363
456
  archivedAt: next.archivedAt,
364
457
  updatedAt: next.updatedAt >= previous.updatedAt ? next.updatedAt : previous.updatedAt,
458
+ cwd: next.cwd ?? previous.cwd ?? null,
459
+ projectRoot: next.projectRoot ?? previous.projectRoot ?? null,
365
460
  };
366
461
  }
367
462
 
@@ -420,8 +515,8 @@ function rowKey(agentId: string, callId: string): string {
420
515
  const UPSERT_AGENT_SQL = `
421
516
  INSERT INTO agents (
422
517
  agent_id, workspace_id, parent_agent_id, provider, title,
423
- created_at, archived_at, updated_at
424
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
518
+ created_at, archived_at, updated_at, cwd, project_root
519
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
425
520
  ON CONFLICT(agent_id) DO UPDATE SET
426
521
  workspace_id = COALESCE(excluded.workspace_id, agents.workspace_id),
427
522
  parent_agent_id = COALESCE(excluded.parent_agent_id, agents.parent_agent_id),
@@ -432,7 +527,9 @@ ON CONFLICT(agent_id) DO UPDATE SET
432
527
  ELSE agents.created_at
433
528
  END,
434
529
  archived_at = excluded.archived_at,
435
- updated_at = excluded.updated_at
530
+ updated_at = excluded.updated_at,
531
+ cwd = COALESCE(excluded.cwd, agents.cwd),
532
+ project_root = COALESCE(excluded.project_root, agents.project_root)
436
533
  `;
437
534
 
438
535
  function agentValues(row: AgentRow): Array<string | null> {
@@ -445,6 +542,8 @@ function agentValues(row: AgentRow): Array<string | null> {
445
542
  row.createdAt,
446
543
  row.archivedAt,
447
544
  row.updatedAt,
545
+ row.cwd ?? null,
546
+ row.projectRoot ?? null,
448
547
  ];
449
548
  }
450
549
 
@@ -458,6 +557,8 @@ function agentFromRecord(record: Record<string, unknown>): AgentRow {
458
557
  createdAt: String(record.created_at),
459
558
  archivedAt: record.archived_at == null ? null : String(record.archived_at),
460
559
  updatedAt: String(record.updated_at),
560
+ cwd: record.cwd == null ? null : String(record.cwd),
561
+ projectRoot: record.project_root == null ? null : String(record.project_root),
461
562
  };
462
563
  }
463
564
 
@@ -482,12 +583,33 @@ function mergeRow(previous: ToolCallRow, next: ToolCallRow): ToolCallRow {
482
583
  status,
483
584
  errorMessage: next.errorMessage ?? previous.errorMessage,
484
585
  seq: next.seq ?? previous.seq,
485
- ts: next.ts ?? previous.ts,
586
+ ts: mergeTs(previous.ts, next.ts, previous.ingestedAt),
486
587
  ingestedAt: previous.ingestedAt,
487
588
  };
488
589
  }
489
590
 
490
- function toolCallSelectSql(filter: QueryFilter): { sql: string; params: Array<string | number | null> } {
591
+ export function rowMatchesRecentScope(row: ToolCallRow, scope: RecentRowScope | undefined): boolean {
592
+ if (scope === "skill-named") return row.confidence !== "low" && !!row.skillName?.trim();
593
+ if (scope === "mcp-named") return !!row.mcpServer?.trim() && !!row.mcpTool?.trim();
594
+ return true;
595
+ }
596
+
597
+ function compareRecent(a: ToolCallRow, b: ToolCallRow): number {
598
+ const ta = rowEffectiveTime(a);
599
+ const tb = rowEffectiveTime(b);
600
+ if (ta !== tb) return ta < tb ? 1 : -1;
601
+ return a.callId === b.callId ? 0 : a.callId < b.callId ? 1 : -1;
602
+ }
603
+
604
+ const RECENT_SCOPE_SQL: Record<RecentRowScope, string> = {
605
+ "skill-named": "(confidence IS NULL OR confidence <> 'low') AND TRIM(COALESCE(skill_name, '')) <> ''",
606
+ "mcp-named": "TRIM(COALESCE(mcp_server, '')) <> '' AND TRIM(COALESCE(mcp_tool, '')) <> ''",
607
+ };
608
+
609
+ function toolCallWhere(
610
+ filter: QueryFilter,
611
+ scope?: RecentRowScope,
612
+ ): { where: string; params: Array<string | number | null> } {
491
613
  const clauses: string[] = [];
492
614
  const params: Array<string | number | null> = [];
493
615
  if (filter.agentId) {
@@ -525,8 +647,9 @@ function toolCallSelectSql(filter: QueryFilter): { sql: string; params: Array<st
525
647
  clauses.push("COALESCE(ts, ingested_at) <= ?");
526
648
  params.push(filter.to);
527
649
  }
650
+ if (scope) clauses.push(RECENT_SCOPE_SQL[scope]);
528
651
  const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
529
- return { sql: `SELECT * FROM tool_calls${where}`, params };
652
+ return { where, params };
530
653
  }
531
654
 
532
655
  function userMessageSelectSql(filter: UserMessageFilter): { sql: string; params: Array<string | number | null> } {
@@ -582,18 +705,29 @@ class SqliteUsageStore implements UsageStore {
582
705
  private readonly insert: ReturnType<InstanceType<SqliteModule["DatabaseSync"]>["prepare"]>;
583
706
  private readonly insertAgent: ReturnType<InstanceType<SqliteModule["DatabaseSync"]>["prepare"]>;
584
707
  private readonly insertMessage: ReturnType<InstanceType<SqliteModule["DatabaseSync"]>["prepare"]>;
708
+ private writes = 0;
585
709
 
586
710
  constructor(filePath: string, sqlite: SqliteModule) {
587
- this.db = new sqlite.DatabaseSync(filePath);
711
+ // Instances installed side by side with --id share this file: wait for locks instead of failing.
712
+ this.db = new sqlite.DatabaseSync(filePath, { timeout: 5_000 });
713
+ this.db.exec("PRAGMA journal_mode = WAL");
588
714
  this.db.exec(SCHEMA_SQL);
589
715
  ensureUserMessageModelColumn(this.db);
716
+ ensureAgentProjectColumns(this.db);
717
+ this.db.exec(CLAMP_TS_SQL);
590
718
  this.insert = this.db.prepare(UPSERT_SQL);
591
719
  this.insertAgent = this.db.prepare(UPSERT_AGENT_SQL);
592
720
  this.insertMessage = this.db.prepare(UPSERT_MESSAGE_SQL);
721
+ this.pruneReplayDuplicateMessages();
722
+ }
723
+
724
+ generation(): number {
725
+ return this.writes;
593
726
  }
594
727
 
595
728
  upsertMany(rows: readonly ToolCallRow[]): number {
596
729
  if (rows.length === 0) return 0;
730
+ this.writes += 1;
597
731
  this.db.exec("BEGIN");
598
732
  try {
599
733
  for (const row of rows) {
@@ -622,13 +756,64 @@ class SqliteUsageStore implements UsageStore {
622
756
  }
623
757
 
624
758
  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));
759
+ const { where, params } = toolCallWhere(filter);
760
+ const records = this.db.prepare(`SELECT * FROM tool_calls${where}`).all(...params) as Record<string, unknown>[];
761
+ return records.map(rowFromRecord);
762
+ }
763
+
764
+ selectRecent(filter: QueryFilter, options: RecentRowOptions): ToolCallRow[] {
765
+ const { where, params } = toolCallWhere(filter, options.scope);
766
+ const records = this.db
767
+ .prepare(
768
+ `SELECT * FROM tool_calls${where}
769
+ ORDER BY COALESCE(ts, ingested_at) DESC, call_id DESC LIMIT ? OFFSET ?`,
770
+ )
771
+ .all(...params, options.limit, options.offset ?? 0) as Record<string, unknown>[];
772
+ return records.map(rowFromRecord);
773
+ }
774
+
775
+ countRows(filter: QueryFilter = {}): number {
776
+ const { where, params } = toolCallWhere(filter);
777
+ const record = this.db
778
+ .prepare(`SELECT COUNT(*) AS count FROM tool_calls${where}`)
779
+ .get(...params) as Record<string, unknown> | undefined;
780
+ return record ? Number(record.count) : 0;
781
+ }
782
+
783
+ agentActivitySpans(): AgentActivitySpan[] {
784
+ // Bare provider / workspace_id come from the MIN() row only while MIN is the
785
+ // sole aggregate (SQLite rule), so MAX lives in a correlated subquery.
786
+ const records = this.db
787
+ .prepare(
788
+ `SELECT agent_id, provider, workspace_id,
789
+ MIN(COALESCE(ts, ingested_at)) AS first_at,
790
+ (SELECT MAX(COALESCE(t.ts, t.ingested_at)) FROM tool_calls t
791
+ WHERE t.agent_id = tool_calls.agent_id) AS last_at
792
+ FROM tool_calls GROUP BY agent_id`,
793
+ )
794
+ .all() as Record<string, unknown>[];
795
+ return records.map((record) => ({
796
+ agentId: String(record.agent_id),
797
+ provider: String(record.provider),
798
+ workspaceId: record.workspace_id == null ? null : String(record.workspace_id),
799
+ firstAt: String(record.first_at),
800
+ lastAt: String(record.last_at),
801
+ }));
802
+ }
803
+
804
+ terminalCallIds(agentId: string): Set<string> {
805
+ const records = this.db
806
+ .prepare(
807
+ `SELECT call_id FROM tool_calls
808
+ WHERE agent_id = ? AND status IN ('completed', 'failed', 'canceled')`,
809
+ )
810
+ .all(agentId) as Record<string, unknown>[];
811
+ return new Set(records.map((record) => String(record.call_id)));
628
812
  }
629
813
 
630
814
  upsertAgents(rows: readonly AgentRow[]): number {
631
815
  if (rows.length === 0) return 0;
816
+ this.writes += 1;
632
817
  this.db.exec("BEGIN");
633
818
  try {
634
819
  for (const row of rows) {
@@ -644,6 +829,7 @@ class SqliteUsageStore implements UsageStore {
644
829
 
645
830
  upsertUserMessages(rows: readonly UserMessageRow[]): number {
646
831
  if (!rows.length) return 0;
832
+ this.writes += 1;
647
833
  this.db.exec("BEGIN");
648
834
  try {
649
835
  for (const row of rows) {
@@ -670,7 +856,7 @@ class SqliteUsageStore implements UsageStore {
670
856
  selectUserMessages(filter: UserMessageFilter = {}): UserMessageRow[] {
671
857
  const { sql, params } = userMessageSelectSql(filter);
672
858
  const rows = this.db.prepare(sql).all(...params) as Array<Record<string, unknown>>;
673
- return rows
859
+ const mapped = rows
674
860
  .map((row) => ({
675
861
  agentId: String(row.agentId),
676
862
  messageId: String(row.messageId),
@@ -681,8 +867,9 @@ class SqliteUsageStore implements UsageStore {
681
867
  seq: row.seq == null ? null : Number(row.seq),
682
868
  ts: row.ts == null ? null : String(row.ts),
683
869
  ingestedAt: String(row.ingestedAt),
684
- }))
685
- .filter((row) => messageMatchesFilter(row, filter));
870
+ }));
871
+ // Provider is compared normalized, so it cannot be pushed into SQL.
872
+ return filter.provider ? mapped.filter((row) => messageMatchesFilter(row, filter)) : mapped;
686
873
  }
687
874
 
688
875
  getAgent(agentId: string): AgentRow | null {
@@ -695,7 +882,8 @@ class SqliteUsageStore implements UsageStore {
695
882
  selectAgents(filter: AgentQueryFilter = {}): AgentRow[] {
696
883
  const { sql, params } = agentSelectSql(filter);
697
884
  const records = this.db.prepare(sql).all(...params) as Record<string, unknown>[];
698
- return records.map(agentFromRecord).filter((row) => agentMatchesFilter(row, filter));
885
+ const rows = records.map(agentFromRecord);
886
+ return filter.provider ? rows.filter((row) => agentMatchesFilter(row, filter)) : rows;
699
887
  }
700
888
 
701
889
  getSyncState(agentId: string): SyncState | null {
@@ -712,6 +900,7 @@ class SqliteUsageStore implements UsageStore {
712
900
  }
713
901
 
714
902
  setSyncState(agentId: string, epoch: string, lastSeq: number): void {
903
+ this.writes += 1;
715
904
  this.db
716
905
  .prepare(
717
906
  `INSERT INTO sync_state (agent_id, epoch, last_seq, updated_at)
@@ -725,12 +914,34 @@ class SqliteUsageStore implements UsageStore {
725
914
  }
726
915
 
727
916
  deleteCanonicalUserMessages(agentId: string): number {
917
+ this.writes += 1;
728
918
  const result = this.db
729
919
  .prepare(`DELETE FROM user_messages WHERE agent_id = ? AND message_id LIKE 'canonical:%'`)
730
920
  .run(agentId) as { changes?: number };
731
921
  return Number(result.changes ?? 0);
732
922
  }
733
923
 
924
+ pruneReplayDuplicateMessages(agentId?: string): number {
925
+ const duplicates = replayDuplicatesByAgent(this.selectUserMessages(agentId ? { agentId } : {}));
926
+ if (duplicates.length === 0) return 0;
927
+ this.writes += 1;
928
+ const remove = this.db.prepare("DELETE FROM user_messages WHERE agent_id = ? AND message_id = ?");
929
+ let removed = 0;
930
+ this.db.exec("BEGIN");
931
+ try {
932
+ for (const [id, messageIds] of duplicates) {
933
+ for (const messageId of messageIds) {
934
+ removed += Number((remove.run(id, messageId) as { changes?: number }).changes ?? 0);
935
+ }
936
+ }
937
+ this.db.exec("COMMIT");
938
+ } catch (error) {
939
+ this.db.exec("ROLLBACK");
940
+ throw error;
941
+ }
942
+ return removed;
943
+ }
944
+
734
945
  close(): void {
735
946
  this.db.close();
736
947
  }
@@ -755,7 +966,14 @@ class JsonlUsageStore implements UsageStore {
755
966
  try {
756
967
  const parsed = JSON.parse(line) as UserMessageRow | {
757
968
  __delete_canonical_messages?: { agentId: string };
969
+ } | {
970
+ __delete_messages?: { agentId: string; messageIds: string[] };
758
971
  };
972
+ if (parsed && "__delete_messages" in parsed && parsed.__delete_messages) {
973
+ const { agentId, messageIds } = parsed.__delete_messages;
974
+ for (const messageId of messageIds) this.messages.delete(rowKey(agentId, messageId));
975
+ continue;
976
+ }
759
977
  if (parsed && "__delete_canonical_messages" in parsed && parsed.__delete_canonical_messages) {
760
978
  const agentId = parsed.__delete_canonical_messages.agentId;
761
979
  for (const [key, row] of this.messages) {
@@ -770,6 +988,7 @@ class JsonlUsageStore implements UsageStore {
770
988
  this.messages.set(rowKey(row.agentId, row.messageId), {
771
989
  ...row,
772
990
  model: normalizeStoredModel(row.model),
991
+ ts: clampTs(row.ts, row.ingestedAt),
773
992
  });
774
993
  }
775
994
  } catch { /* Ignore incomplete lines, as with the other JSONL stores. */ }
@@ -787,7 +1006,7 @@ class JsonlUsageStore implements UsageStore {
787
1006
  }
788
1007
  const row = parsed as ToolCallRow;
789
1008
  if (!row.agentId || !row.callId) continue;
790
- this.rows.set(rowKey(row.agentId, row.callId), row);
1009
+ this.rows.set(rowKey(row.agentId, row.callId), { ...row, ts: clampTs(row.ts, row.ingestedAt) });
791
1010
  } catch {
792
1011
  continue;
793
1012
  }
@@ -806,10 +1025,18 @@ class JsonlUsageStore implements UsageStore {
806
1025
  }
807
1026
  }
808
1027
  }
1028
+ this.pruneReplayDuplicateMessages();
1029
+ }
1030
+
1031
+ private writes = 0;
1032
+
1033
+ generation(): number {
1034
+ return this.writes;
809
1035
  }
810
1036
 
811
1037
  upsertMany(rows: readonly ToolCallRow[]): number {
812
1038
  if (rows.length === 0) return 0;
1039
+ this.writes += 1;
813
1040
  const lines: string[] = [];
814
1041
  for (const row of rows) {
815
1042
  const key = rowKey(row.agentId, row.callId);
@@ -834,8 +1061,56 @@ class JsonlUsageStore implements UsageStore {
834
1061
  return [...this.rows.values()].filter((row) => rowMatchesFilter(row, filter));
835
1062
  }
836
1063
 
1064
+ selectRecent(filter: QueryFilter, options: RecentRowOptions): ToolCallRow[] {
1065
+ const offset = options.offset ?? 0;
1066
+ return this.select(filter)
1067
+ .filter((row) => rowMatchesRecentScope(row, options.scope))
1068
+ .sort(compareRecent)
1069
+ .slice(offset, offset + options.limit);
1070
+ }
1071
+
1072
+ countRows(filter: QueryFilter = {}): number {
1073
+ return this.select(filter).length;
1074
+ }
1075
+
1076
+ agentActivitySpans(): AgentActivitySpan[] {
1077
+ const spans = new Map<string, AgentActivitySpan>();
1078
+ for (const row of this.rows.values()) {
1079
+ const t = rowEffectiveTime(row);
1080
+ const span = spans.get(row.agentId);
1081
+ if (!span) {
1082
+ spans.set(row.agentId, {
1083
+ agentId: row.agentId,
1084
+ provider: row.provider,
1085
+ workspaceId: row.workspaceId,
1086
+ firstAt: t,
1087
+ lastAt: t,
1088
+ });
1089
+ continue;
1090
+ }
1091
+ if (t < span.firstAt) {
1092
+ span.firstAt = t;
1093
+ span.provider = row.provider;
1094
+ span.workspaceId = row.workspaceId;
1095
+ }
1096
+ if (t > span.lastAt) span.lastAt = t;
1097
+ }
1098
+ return [...spans.values()];
1099
+ }
1100
+
1101
+ terminalCallIds(agentId: string): Set<string> {
1102
+ const ids = new Set<string>();
1103
+ for (const row of this.rows.values()) {
1104
+ if (row.agentId === agentId && row.status && TERMINAL_STATUSES.has(row.status)) {
1105
+ ids.add(row.callId);
1106
+ }
1107
+ }
1108
+ return ids;
1109
+ }
1110
+
837
1111
  upsertAgents(rows: readonly AgentRow[]): number {
838
1112
  if (rows.length === 0) return 0;
1113
+ this.writes += 1;
839
1114
  const lines: string[] = [];
840
1115
  for (const row of rows) {
841
1116
  const previous = this.agents.get(row.agentId);
@@ -849,6 +1124,7 @@ class JsonlUsageStore implements UsageStore {
849
1124
 
850
1125
  upsertUserMessages(rows: readonly UserMessageRow[]): number {
851
1126
  if (!rows.length) return 0;
1127
+ this.writes += 1;
852
1128
  const lines: string[] = [];
853
1129
  for (const row of rows) {
854
1130
  const key = rowKey(row.agentId, row.messageId);
@@ -884,6 +1160,7 @@ class JsonlUsageStore implements UsageStore {
884
1160
  lastSeq,
885
1161
  updatedAt: new Date().toISOString(),
886
1162
  };
1163
+ this.writes += 1;
887
1164
  this.sync.set(agentId, state);
888
1165
  appendFileSync(this.filePath, `${JSON.stringify({ __sync: state })}\n`);
889
1166
  }
@@ -897,6 +1174,7 @@ class JsonlUsageStore implements UsageStore {
897
1174
  }
898
1175
  }
899
1176
  if (removed > 0) {
1177
+ this.writes += 1;
900
1178
  appendFileSync(
901
1179
  this.messagesPath,
902
1180
  `${JSON.stringify({ __delete_canonical_messages: { agentId, removed } })}\n`,
@@ -905,5 +1183,21 @@ class JsonlUsageStore implements UsageStore {
905
1183
  return removed;
906
1184
  }
907
1185
 
1186
+ pruneReplayDuplicateMessages(agentId?: string): number {
1187
+ const duplicates = replayDuplicatesByAgent(this.selectUserMessages(agentId ? { agentId } : {}));
1188
+ if (duplicates.length === 0) return 0;
1189
+ this.writes += 1;
1190
+ let removed = 0;
1191
+ const lines: string[] = [];
1192
+ for (const [id, messageIds] of duplicates) {
1193
+ for (const messageId of messageIds) {
1194
+ if (this.messages.delete(rowKey(id, messageId))) removed += 1;
1195
+ }
1196
+ lines.push(JSON.stringify({ __delete_messages: { agentId: id, messageIds } }));
1197
+ }
1198
+ appendFileSync(this.messagesPath, `${lines.join("\n")}\n`);
1199
+ return removed;
1200
+ }
1201
+
908
1202
  close(): void {}
909
1203
  }
@@ -23,6 +23,9 @@ export function createKeyedTtlCache<T>(ttlMs: number) {
23
23
  const now = Date.now();
24
24
  const hit = map.get(key);
25
25
  if (hit && hit.expiresAt > now) return hit.value;
26
+ for (const [staleKey, entry] of map) {
27
+ if (entry.expiresAt <= now) map.delete(staleKey);
28
+ }
26
29
  const value = compute();
27
30
  map.set(key, { value, expiresAt: now + ttlMs });
28
31
  return value;