@koinzhang/paseo-plugin-activity 0.5.0 → 0.7.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 (74) hide show
  1. package/CHANGELOG.md +78 -1
  2. package/README.md +15 -8
  3. package/client/activity-heatmap.tsx +126 -93
  4. package/client/agent-creations.tsx +216 -0
  5. package/client/attention-pill.tsx +16 -5
  6. package/client/attention-popover.tsx +19 -23
  7. package/client/color-mix.test.ts +27 -0
  8. package/client/color-mix.ts +38 -0
  9. package/client/design-tokens.test.ts +39 -0
  10. package/client/design-tokens.ts +168 -0
  11. package/client/fit-text.test.ts +41 -0
  12. package/client/fit-text.ts +33 -0
  13. package/client/formatted-time.tsx +4 -4
  14. package/client/global-surface.tsx +316 -275
  15. package/client/header-button.ts +136 -0
  16. package/client/hourly-activity-timeline.tsx +425 -0
  17. package/client/measured-width.ts +72 -0
  18. package/client/panel-visibility.test.ts +25 -0
  19. package/client/panel-visibility.ts +45 -0
  20. package/client/panel.tsx +83 -108
  21. package/client/provider-dropdown.tsx +131 -0
  22. package/client/provider-filter.test.ts +17 -13
  23. package/client/provider-filter.ts +5 -7
  24. package/client/range.test.ts +44 -0
  25. package/client/range.ts +14 -0
  26. package/client/rank-color.test.ts +108 -14
  27. package/client/rank-color.ts +261 -48
  28. package/client/ranking-bars.tsx +291 -0
  29. package/client/ui.tsx +339 -0
  30. package/client/usage-popover.tsx +62 -134
  31. package/client/usage-stats.tsx +137 -8
  32. package/client/use-agent-turn-end.ts +2 -1
  33. package/client/use-app-language.ts +17 -0
  34. package/client/web.ts +73 -18
  35. package/client/workspace/agent-row.tsx +18 -25
  36. package/client/workspace/agents-section.tsx +23 -20
  37. package/client/workspace/constants.ts +6 -6
  38. package/client/workspace/display-menu.tsx +5 -4
  39. package/client/workspace/filters.test.ts +1 -1
  40. package/client/workspace/filters.ts +4 -2
  41. package/client/workspace/panel.tsx +176 -104
  42. package/client/workspace/rank-section.tsx +157 -44
  43. package/client/workspace/terminals-section.tsx +13 -9
  44. package/index.client.tsx +40 -20
  45. package/index.server.ts +63 -31
  46. package/package.json +2 -2
  47. package/paseo-plugin.json +2 -1
  48. package/server/agents.ts +20 -2
  49. package/server/background-sync.test.ts +43 -0
  50. package/server/background-sync.ts +43 -4
  51. package/server/handlers-query.test.ts +252 -1
  52. package/server/handlers.ts +174 -13
  53. package/server/ingest.test.ts +8 -0
  54. package/server/messages.test.ts +96 -1
  55. package/server/prompt-dedupe.ts +52 -0
  56. package/server/rpc-cache.test.ts +74 -0
  57. package/server/rpc-cache.ts +48 -0
  58. package/server/store.test.ts +122 -0
  59. package/server/store.ts +313 -19
  60. package/server/ttl-cache.ts +3 -0
  61. package/shared/activity.test.ts +159 -6
  62. package/shared/activity.ts +140 -5
  63. package/shared/classify.test.ts +1 -0
  64. package/shared/classify.ts +4 -1
  65. package/shared/explorer-agent-display.test.ts +61 -0
  66. package/shared/explorer-agent-display.ts +21 -2
  67. package/shared/format.test.ts +28 -3
  68. package/shared/format.ts +25 -2
  69. package/shared/i18n.test.ts +34 -0
  70. package/shared/i18n.ts +363 -0
  71. package/shared/insights.test.ts +162 -80
  72. package/shared/insights.ts +136 -61
  73. package/shared/usage.test.ts +330 -0
  74. package/shared/usage.ts +471 -0
package/shared/usage.ts CHANGED
@@ -105,6 +105,47 @@ export const usageSkillsByNameRpc = defineRpc({
105
105
  }),
106
106
  });
107
107
 
108
+ export const RecentSkillCallItemSchema = z.object({
109
+ agentId: z.string(),
110
+ agentTitle: z.string().nullable(),
111
+ callId: z.string(),
112
+ skillName: z.string(),
113
+ calledAt: z.string(),
114
+ });
115
+ export type RecentSkillCallItem = z.infer<typeof RecentSkillCallItemSchema>;
116
+
117
+ export const usageRecentSkillCallsRpc = defineRpc({
118
+ name: "usage.recent-skill-calls",
119
+ input: z.object({
120
+ workspaceId: z.string().min(1),
121
+ limit: z.number().int().positive().max(100).optional(),
122
+ }),
123
+ output: z.object({
124
+ items: z.array(RecentSkillCallItemSchema),
125
+ }),
126
+ });
127
+
128
+ export const RecentMcpCallItemSchema = z.object({
129
+ agentId: z.string(),
130
+ agentTitle: z.string().nullable(),
131
+ callId: z.string(),
132
+ server: z.string(),
133
+ tool: z.string(),
134
+ calledAt: z.string(),
135
+ });
136
+ export type RecentMcpCallItem = z.infer<typeof RecentMcpCallItemSchema>;
137
+
138
+ export const usageRecentMcpCallsRpc = defineRpc({
139
+ name: "usage.recent-mcp-calls",
140
+ input: z.object({
141
+ workspaceId: z.string().min(1),
142
+ limit: z.number().int().positive().max(100).optional(),
143
+ }),
144
+ output: z.object({
145
+ items: z.array(RecentMcpCallItemSchema),
146
+ }),
147
+ });
148
+
108
149
  export const usageMcpByToolRpc = defineRpc({
109
150
  name: "usage.mcp-by-tool",
110
151
  input: z.object({
@@ -246,6 +287,212 @@ export const usageAgentsRpc = defineRpc({
246
287
  }),
247
288
  });
248
289
 
290
+ /** Archived or still-active agent with a created→(archived | now) span (049 / 051). */
291
+ export const AgentLifetimeItemSchema = z.object({
292
+ agentId: z.string(),
293
+ provider: z.string(),
294
+ workspaceId: z.string().nullable(),
295
+ title: z.string().nullable(),
296
+ createdAt: z.string(),
297
+ /** Null while the agent is active — the span then ends at request time. */
298
+ archivedAt: z.string().nullable(),
299
+ durationMs: z.number().int().nonnegative(),
300
+ });
301
+ export type AgentLifetimeItem = z.infer<typeof AgentLifetimeItemSchema>;
302
+
303
+ /** Longest created→archived / created→now agent over the whole registry (049 / 051). */
304
+ export const usageAgentLifetimeRpc = defineRpc({
305
+ name: "usage.agent-lifetime",
306
+ input: z.object({
307
+ /** Normalized provider id; omit / empty = all providers. */
308
+ provider: z.string().optional(),
309
+ }),
310
+ output: z.object({
311
+ longest: AgentLifetimeItemSchema.nullable(),
312
+ /** Rows compared after the provider filter (registry sample). */
313
+ sampleSize: z.number().int().nonnegative(),
314
+ /** Mean engaged time per session (072); null when no session has events. */
315
+ averageEngagedMs: z.number().int().nonnegative().nullable(),
316
+ /** Sessions with ≥1 prompt (072); denominator of the multi-turn share. */
317
+ promptedSessions: z.number().int().nonnegative(),
318
+ /** Sessions with ≥2 prompts (072). */
319
+ multiTurnSessions: z.number().int().nonnegative(),
320
+ }),
321
+ });
322
+
323
+ /** Sessions with ≥1 / ≥2 prompts among `agents` (072); prompts of unknown agents are ignored. */
324
+ export function countMultiTurnSessions(
325
+ agents: ReadonlyArray<{ agentId: string }>,
326
+ messages: ReadonlyArray<{ agentId: string }>,
327
+ ): { promptedSessions: number; multiTurnSessions: number } {
328
+ const prompts = new Map<string, number>(agents.map((agent) => [agent.agentId, 0]));
329
+ for (const message of messages) {
330
+ const count = prompts.get(message.agentId);
331
+ if (count !== undefined) prompts.set(message.agentId, count + 1);
332
+ }
333
+ let promptedSessions = 0;
334
+ let multiTurnSessions = 0;
335
+ for (const count of prompts.values()) {
336
+ if (count >= 1) promptedSessions += 1;
337
+ if (count >= 2) multiTurnSessions += 1;
338
+ }
339
+ return { promptedSessions, multiTurnSessions };
340
+ }
341
+
342
+ /** Gaps longer than this between a session's events count as idle, not engaged (072). */
343
+ export const SESSION_IDLE_GAP_MS = 30 * 60_000;
344
+
345
+ /**
346
+ * Mean engaged time per session (072): sum of gaps between consecutive events
347
+ * (creation, prompts, tool calls), skipping idle gaps over `idleGapMs`, so a
348
+ * session resumed days later is not counted as days long. Sessions without any
349
+ * prompt / tool call are excluded.
350
+ */
351
+ export function averageEngagedSessionMs(
352
+ agents: ReadonlyArray<{ agentId: string; createdAt?: string | null }>,
353
+ events: ReadonlyArray<{ agentId: string; ts: string | null; ingestedAt: string }>,
354
+ idleGapMs = SESSION_IDLE_GAP_MS,
355
+ ): number | null {
356
+ const times = new Map<string, number[]>();
357
+ for (const agent of agents) {
358
+ const created = agent.createdAt ? Date.parse(agent.createdAt) : Number.NaN;
359
+ times.set(agent.agentId, Number.isFinite(created) ? [created] : []);
360
+ }
361
+ const withEvents = new Set<string>();
362
+ for (const event of events) {
363
+ const list = times.get(event.agentId);
364
+ if (!list) continue;
365
+ const t = Date.parse(event.ts ?? event.ingestedAt);
366
+ if (!Number.isFinite(t)) continue;
367
+ list.push(t);
368
+ withEvents.add(event.agentId);
369
+ }
370
+ let total = 0;
371
+ for (const agentId of withEvents) {
372
+ const list = times.get(agentId)!.sort((a, b) => a - b);
373
+ for (let i = 1; i < list.length; i++) {
374
+ const gap = list[i]! - list[i - 1]!;
375
+ if (gap <= idleGapMs) total += gap;
376
+ }
377
+ }
378
+ return withEvents.size > 0 ? Math.round(total / withEvents.size) : null;
379
+ }
380
+
381
+ /**
382
+ * Longest-lived agent. Archived agents use their archive time; active agents
383
+ * count `createdAt → now` (051). Rows need a parseable `createdAt` and a
384
+ * non-negative span; ties keep the earlier `createdAt`.
385
+ */
386
+ export function pickLongestAgentLifetime(
387
+ agents: ReadonlyArray<{
388
+ agentId: string;
389
+ provider: string;
390
+ workspaceId?: string | null;
391
+ title?: string | null;
392
+ createdAt?: string | null;
393
+ archivedAt?: string | null;
394
+ }>,
395
+ options: { provider?: string; now?: number } = {},
396
+ ): { longest: AgentLifetimeItem | null; sampleSize: number } {
397
+ const provider = options.provider?.trim() ? normalizeProvider(options.provider) : undefined;
398
+ const now = options.now ?? Date.now();
399
+ let longest: AgentLifetimeItem | null = null;
400
+ let sampleSize = 0;
401
+ for (const agent of agents) {
402
+ if (!agent.createdAt) continue;
403
+ if (provider && normalizeProvider(agent.provider) !== provider) continue;
404
+ const createdAt = Date.parse(agent.createdAt);
405
+ if (!Number.isFinite(createdAt)) continue;
406
+ const end = agent.archivedAt ? Date.parse(agent.archivedAt) : now;
407
+ if (!Number.isFinite(end)) continue;
408
+ const durationMs = end - createdAt;
409
+ if (durationMs < 0) continue;
410
+ sampleSize += 1;
411
+ const candidate: AgentLifetimeItem = {
412
+ agentId: agent.agentId,
413
+ provider: agent.provider,
414
+ workspaceId: agent.workspaceId ?? null,
415
+ title: agent.title ?? null,
416
+ createdAt: agent.createdAt,
417
+ archivedAt: agent.archivedAt ?? null,
418
+ durationMs,
419
+ };
420
+ if (
421
+ !longest ||
422
+ candidate.durationMs > longest.durationMs ||
423
+ (candidate.durationMs === longest.durationMs && candidate.createdAt < longest.createdAt)
424
+ ) {
425
+ longest = candidate;
426
+ }
427
+ }
428
+ return { longest, sampleSize };
429
+ }
430
+
431
+ export const AgentCreationProviderSchema = z.object({
432
+ provider: z.string(),
433
+ label: z.string(),
434
+ count: z.number().int().nonnegative(),
435
+ });
436
+ export type AgentCreationProvider = z.infer<typeof AgentCreationProviderSchema>;
437
+
438
+ export const AgentCreationDaySchema = z.object({
439
+ /** Local calendar day `YYYY-MM-DD`. */
440
+ date: z.string(),
441
+ total: z.number().int().nonnegative(),
442
+ /** Providers that created agents that day, highest count first. */
443
+ providers: z.array(AgentCreationProviderSchema),
444
+ });
445
+ export type AgentCreationDay = z.infer<typeof AgentCreationDaySchema>;
446
+
447
+ /** Daily agent creations with a per-provider breakdown (051). */
448
+ export const usageAgentCreationsRpc = defineRpc({
449
+ name: "usage.agent-creations",
450
+ input: z.object({
451
+ from: z.string().optional(),
452
+ to: z.string().optional(),
453
+ /** Normalized provider id; omit / empty = all providers. */
454
+ provider: z.string().optional(),
455
+ }),
456
+ output: z.object({
457
+ days: z.array(AgentCreationDaySchema),
458
+ }),
459
+ });
460
+
461
+ /**
462
+ * Bucket agent creations by local day and normalized provider (051).
463
+ * Days without creations are omitted; callers zero-fill the window.
464
+ */
465
+ export function aggregateAgentCreations(
466
+ agents: ReadonlyArray<{ provider: string; createdAt: string }>,
467
+ options: { from?: string; to?: string; provider?: string } = {},
468
+ ): AgentCreationDay[] {
469
+ const provider = options.provider?.trim() ? normalizeProvider(options.provider) : undefined;
470
+ const byDay = new Map<string, Map<string, number>>();
471
+ for (const agent of agents) {
472
+ if (provider && normalizeProvider(agent.provider) !== provider) continue;
473
+ if (options.from && agent.createdAt < options.from) continue;
474
+ if (options.to && agent.createdAt > options.to) continue;
475
+ const day = localDayKey(agent.createdAt);
476
+ if (!day) continue;
477
+ const id = normalizeProvider(agent.provider);
478
+ const counts = byDay.get(day) ?? new Map<string, number>();
479
+ counts.set(id, (counts.get(id) ?? 0) + 1);
480
+ byDay.set(day, counts);
481
+ }
482
+ return [...byDay.entries()]
483
+ .map(([date, counts]) => {
484
+ const providers = [...counts.entries()]
485
+ .map(([id, count]) => ({ provider: id, label: providerLabel(id), count }))
486
+ .sort((a, b) => b.count - a.count || a.provider.localeCompare(b.provider));
487
+ return {
488
+ date,
489
+ total: providers.reduce((sum, item) => sum + item.count, 0),
490
+ providers,
491
+ };
492
+ })
493
+ .sort((a, b) => a.date.localeCompare(b.date));
494
+ }
495
+
249
496
  /** Unarchive via host `refreshAgent` (CLI: `paseo agent reload`). */
250
497
  export const usageAgentUnarchiveRpc = defineRpc({
251
498
  name: "usage.agent.unarchive",
@@ -272,6 +519,7 @@ const PROVIDER_LABELS: Record<string, string> = {
272
519
  opencode: "OpenCode",
273
520
  codex: "Codex",
274
521
  pi: "Pi",
522
+ omp: "Oh My Pi",
275
523
  cursor: "Cursor",
276
524
  codebuddy: "CodeBuddy",
277
525
  };
@@ -964,6 +1212,19 @@ export const ActivityDaySchema = z.object({
964
1212
  });
965
1213
  export type ActivityDay = z.infer<typeof ActivityDaySchema>;
966
1214
 
1215
+ export const ActivityHourSchema = z.object({
1216
+ /** Epoch milliseconds for the absolute hour start; unique across DST fallback. */
1217
+ key: z.string(),
1218
+ /** ISO timestamp for formatting in the client locale. */
1219
+ start: z.string(),
1220
+ skills: z.number().int().nonnegative(),
1221
+ mcp: z.number().int().nonnegative(),
1222
+ agents: z.number().int().nonnegative(),
1223
+ messages: z.number().int().nonnegative(),
1224
+ total: z.number().int().nonnegative(),
1225
+ });
1226
+ export type ActivityHour = z.infer<typeof ActivityHourSchema>;
1227
+
967
1228
  export const usageActivityByDayRpc = defineRpc({
968
1229
  name: "usage.activity-by-day",
969
1230
  input: z.object({
@@ -978,6 +1239,18 @@ export const usageActivityByDayRpc = defineRpc({
978
1239
  }),
979
1240
  });
980
1241
 
1242
+ export const usageActivityByHourRpc = defineRpc({
1243
+ name: "usage.activity-by-hour",
1244
+ input: z.object({
1245
+ hours: z.number().int().positive().max(168),
1246
+ /** Normalized provider id; omit / empty = all providers. */
1247
+ provider: z.string().optional(),
1248
+ }),
1249
+ output: z.object({
1250
+ hours: z.array(ActivityHourSchema),
1251
+ }),
1252
+ });
1253
+
981
1254
  function pad2(value: number): string {
982
1255
  return String(value).padStart(2, "0");
983
1256
  }
@@ -1056,3 +1329,201 @@ export function aggregateActivityByDay(
1056
1329
  .sort((a, b) => a.date.localeCompare(b.date));
1057
1330
  }
1058
1331
 
1332
+ const HOUR_MS = 60 * 60 * 1000;
1333
+
1334
+ /**
1335
+ * Zero-filled consecutive absolute-hour buckets. Epoch keys preserve both
1336
+ * repeated local-clock hours during DST fallback.
1337
+ */
1338
+ export function aggregateActivityByHour(
1339
+ rows: ReadonlyArray<{
1340
+ provider: string;
1341
+ category: string;
1342
+ confidence: string | null;
1343
+ ts: string | null;
1344
+ ingestedAt: string;
1345
+ }>,
1346
+ opts: {
1347
+ start: Date;
1348
+ hours: number;
1349
+ provider?: string;
1350
+ agents?: ReadonlyArray<{ provider: string; createdAt: string }>;
1351
+ messages?: ReadonlyArray<{ provider: string; ts: string | null; ingestedAt: string }>;
1352
+ },
1353
+ ): ActivityHour[] {
1354
+ const hours = Math.max(0, Math.trunc(opts.hours));
1355
+ const startMs = Math.floor(opts.start.getTime() / HOUR_MS) * HOUR_MS;
1356
+ if (!Number.isFinite(startMs) || hours === 0) return [];
1357
+ const providerFilter = opts.provider?.trim() ? normalizeProvider(opts.provider) : undefined;
1358
+ const buckets: ActivityHour[] = Array.from({ length: hours }, (_, index) => {
1359
+ const at = startMs + index * HOUR_MS;
1360
+ return {
1361
+ key: String(at),
1362
+ start: new Date(at).toISOString(),
1363
+ skills: 0,
1364
+ mcp: 0,
1365
+ agents: 0,
1366
+ messages: 0,
1367
+ total: 0,
1368
+ };
1369
+ });
1370
+
1371
+ const bucketAt = (iso: string): ActivityHour | undefined => {
1372
+ const at = Date.parse(iso);
1373
+ if (!Number.isFinite(at)) return undefined;
1374
+ const index = Math.floor((at - startMs) / HOUR_MS);
1375
+ return index >= 0 && index < buckets.length ? buckets[index] : undefined;
1376
+ };
1377
+ const accepts = (provider: string) =>
1378
+ !providerFilter || normalizeProvider(provider) === providerFilter;
1379
+
1380
+ for (const row of rows) {
1381
+ if (!accepts(row.provider)) continue;
1382
+ if (row.category !== "skill" && row.category !== "mcp") continue;
1383
+ if (row.category === "skill" && row.confidence === "low") continue;
1384
+ const bucket = bucketAt(row.ts ?? row.ingestedAt);
1385
+ if (!bucket) continue;
1386
+ if (row.category === "skill") bucket.skills += 1;
1387
+ else bucket.mcp += 1;
1388
+ }
1389
+ for (const agent of opts.agents ?? []) {
1390
+ if (!accepts(agent.provider)) continue;
1391
+ const bucket = bucketAt(agent.createdAt);
1392
+ if (bucket) bucket.agents += 1;
1393
+ }
1394
+ for (const message of opts.messages ?? []) {
1395
+ if (!accepts(message.provider)) continue;
1396
+ const bucket = bucketAt(message.ts ?? message.ingestedAt);
1397
+ if (bucket) bucket.messages += 1;
1398
+ }
1399
+ for (const bucket of buckets) {
1400
+ bucket.total = bucket.skills + bucket.mcp + bucket.agents + bucket.messages;
1401
+ }
1402
+ return buckets;
1403
+ }
1404
+
1405
+
1406
+ export const ProjectUsageItemSchema = z.object({
1407
+ /** Project root path; `OTHER_PROJECT_KEY` groups agents without a resolvable project. */
1408
+ key: z.string(),
1409
+ /** Paseo project display name, else the root's basename; empty for Other (client localizes). */
1410
+ label: z.string(),
1411
+ agentCount: z.number().int().nonnegative(),
1412
+ messageCount: z.number().int().nonnegative(),
1413
+ /** Exact + inferred skill calls (low excluded, same as provider KPI). */
1414
+ skillCalls: z.number().int().nonnegative(),
1415
+ mcpCalls: z.number().int().nonnegative(),
1416
+ });
1417
+ export type ProjectUsageItem = z.infer<typeof ProjectUsageItemSchema>;
1418
+
1419
+ /** Sessions / prompts / skill / MCP per project (070). */
1420
+ export const usageByProjectRpc = defineRpc({
1421
+ name: "usage.by-project",
1422
+ input: z.object({
1423
+ /** Normalized provider id; omit / empty = all providers. */
1424
+ provider: z.string().optional(),
1425
+ }),
1426
+ output: z.object({ projects: z.array(ProjectUsageItemSchema) }),
1427
+ });
1428
+
1429
+ export const OTHER_PROJECT_KEY = "__other__";
1430
+
1431
+ export type ProjectRef = { root: string; name: string };
1432
+
1433
+ function trimSlash(path: string): string {
1434
+ return path.length > 1 ? path.replace(/\/+$/, "") : path;
1435
+ }
1436
+
1437
+ function basename(path: string): string {
1438
+ const parts = trimSlash(path).split("/");
1439
+ return parts[parts.length - 1] || path;
1440
+ }
1441
+
1442
+ /** `<paseo-home>/worktrees/<hash>/<slug>[/…]` → `<hash>` (070). */
1443
+ function worktreeHash(cwd: string): string | null {
1444
+ return /\/worktrees\/([^/]+)\/[^/]+(?:\/|$)/.exec(cwd)?.[1] ?? null;
1445
+ }
1446
+
1447
+ /**
1448
+ * Agent → project root (070). Order: the workspace project root recorded while
1449
+ * the workspace was listed; the longest known project root containing `cwd`;
1450
+ * a sibling in the same Paseo worktree bucket that resolved; the `cwd` itself
1451
+ * (non-worktree only). Unresolved agents map to `OTHER_PROJECT_KEY`.
1452
+ */
1453
+ export function resolveAgentProjects(
1454
+ agents: ReadonlyArray<{ agentId: string; cwd?: string | null; projectRoot?: string | null }>,
1455
+ projects: readonly ProjectRef[],
1456
+ ): Map<string, string> {
1457
+ const roots = [...new Set(projects.map((project) => trimSlash(project.root)))].sort(
1458
+ (a, b) => b.length - a.length,
1459
+ );
1460
+ const containing = (cwd: string) =>
1461
+ roots.find((root) => cwd === root || cwd.startsWith(`${root}/`)) ?? null;
1462
+ const resolved = new Map<string, string>();
1463
+ const byHash = new Map<string, string>();
1464
+ const pending: Array<{ agentId: string; cwd: string | null; hash: string | null }> = [];
1465
+ for (const agent of agents) {
1466
+ const cwd = agent.cwd?.trim() ? trimSlash(agent.cwd.trim()) : null;
1467
+ const hash = cwd ? worktreeHash(cwd) : null;
1468
+ const root = agent.projectRoot?.trim()
1469
+ ? trimSlash(agent.projectRoot.trim())
1470
+ : cwd
1471
+ ? containing(cwd)
1472
+ : null;
1473
+ if (root) {
1474
+ resolved.set(agent.agentId, root);
1475
+ if (hash && !byHash.has(hash)) byHash.set(hash, root);
1476
+ } else {
1477
+ pending.push({ agentId: agent.agentId, cwd, hash });
1478
+ }
1479
+ }
1480
+ for (const agent of pending) {
1481
+ const root = agent.hash ? byHash.get(agent.hash) : agent.cwd;
1482
+ resolved.set(agent.agentId, root ?? OTHER_PROJECT_KEY);
1483
+ }
1484
+ return resolved;
1485
+ }
1486
+
1487
+ export function aggregateByProject(
1488
+ agents: ReadonlyArray<{ agentId: string; provider: string; cwd?: string | null; projectRoot?: string | null }>,
1489
+ rows: ReadonlyArray<{ agentId: string; provider: string; category: string; confidence: string | null }>,
1490
+ messages: ReadonlyArray<{ agentId: string; provider: string }>,
1491
+ projects: readonly ProjectRef[],
1492
+ options: { provider?: string } = {},
1493
+ ): ProjectUsageItem[] {
1494
+ const provider = options.provider?.trim() ? normalizeProvider(options.provider) : undefined;
1495
+ const matches = (value: string) => !provider || normalizeProvider(value) === provider;
1496
+ const projectOf = resolveAgentProjects(agents, projects);
1497
+ const names = new Map(projects.map((project) => [trimSlash(project.root), project.name]));
1498
+ const map = new Map<string, ProjectUsageItem>();
1499
+ const ensure = (agentId: string) => {
1500
+ const key = projectOf.get(agentId) ?? OTHER_PROJECT_KEY;
1501
+ let item = map.get(key);
1502
+ if (!item) {
1503
+ item = {
1504
+ key,
1505
+ label: key === OTHER_PROJECT_KEY ? "" : (names.get(key) ?? basename(key)),
1506
+ agentCount: 0,
1507
+ messageCount: 0,
1508
+ skillCalls: 0,
1509
+ mcpCalls: 0,
1510
+ };
1511
+ map.set(key, item);
1512
+ }
1513
+ return item;
1514
+ };
1515
+ for (const agent of agents) {
1516
+ if (matches(agent.provider)) ensure(agent.agentId).agentCount += 1;
1517
+ }
1518
+ for (const message of messages) {
1519
+ if (matches(message.provider)) ensure(message.agentId).messageCount += 1;
1520
+ }
1521
+ for (const row of rows) {
1522
+ if (!matches(row.provider)) continue;
1523
+ if (row.category === "skill" && row.confidence !== "low") ensure(row.agentId).skillCalls += 1;
1524
+ else if (row.category === "mcp") ensure(row.agentId).mcpCalls += 1;
1525
+ }
1526
+ return [...map.values()].sort(
1527
+ (a, b) => b.agentCount - a.agentCount || b.messageCount - a.messageCount || a.key.localeCompare(b.key),
1528
+ );
1529
+ }