@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,383 @@
1
+ import {
2
+ type PluginButtonContentProps,
3
+ useRpc,
4
+ } from "@getpaseo/plugin/client";
5
+ import { Icon } from "@getpaseo/plugin/client/react-native";
6
+ import { useQuery } from "@tanstack/react-query";
7
+ import { useEffect, useMemo, useState, type ReactNode } from "react";
8
+ import {
9
+ ActivityIndicator,
10
+ Platform,
11
+ Pressable,
12
+ Text,
13
+ View,
14
+ type TextStyle,
15
+ type ViewStyle,
16
+ } from "react-native";
17
+ import {
18
+ usageReadSkillRpc,
19
+ } from "../shared/usage.ts";
20
+ import { formatDayTime, formatDisplayName } from "../shared/format.ts";
21
+ import { useUsagePillData } from "./usage-query.tsx";
22
+
23
+ const MONO = Platform.select({ ios: "Menlo", default: "monospace" });
24
+
25
+ export type SkillDetail = { skillName: string; path: string };
26
+
27
+ export type UsagePopoverProps = PluginButtonContentProps & {
28
+ /** Open this SKILL.md in the agent Usage workspace panel (Skills-plugin pattern). */
29
+ openSkillInPanel?: (skill: SkillDetail) => void;
30
+ };
31
+
32
+ function CountBadge({
33
+ value,
34
+ styles,
35
+ }: {
36
+ value: number | string;
37
+ styles: { countBadge: ViewStyle; countText: TextStyle };
38
+ }): ReactNode {
39
+ return (
40
+ <View style={styles.countBadge}>
41
+ <Text style={styles.countText}>{value}</Text>
42
+ </View>
43
+ );
44
+ }
45
+
46
+ /**
47
+ * Composer-pill popover body. Host owns anchoring / sheet chrome / outer scroll;
48
+ * render content only.
49
+ */
50
+ export function UsagePopover(props: UsagePopoverProps) {
51
+ if (props.context !== "agent") {
52
+ return (
53
+ <Text style={{ color: props.theme.colors.foregroundMuted }}>
54
+ Activity is only available for an agent
55
+ </Text>
56
+ );
57
+ }
58
+ return <UsagePopoverAgent {...props} context="agent" />;
59
+ }
60
+
61
+ function UsagePopoverAgent(
62
+ props: UsagePopoverProps & { context: "agent" },
63
+ ) {
64
+ const { theme, layout, agentId, openSkillInPanel, close } = props;
65
+ const [tab, setTab] = useState<"skills" | "mcp" | null>(null);
66
+ const [skillDetail, setSkillDetail] = useState<SkillDetail | null>(null);
67
+ const compact = layout.compact;
68
+
69
+ const usage = useUsagePillData(agentId);
70
+ const readSkillRpc = useRpc(usageReadSkillRpc);
71
+
72
+ const skillFile = useQuery({
73
+ queryKey: ["activity", "read-skill", skillDetail?.path ?? ""],
74
+ queryFn: () => readSkillRpc({ path: skillDetail!.path }),
75
+ enabled: Boolean(skillDetail?.path),
76
+ retry: false,
77
+ });
78
+
79
+ const skillItems = useMemo(() => {
80
+ return (usage.data?.skills ?? [])
81
+ .filter((item) => item.total > 0)
82
+ .slice()
83
+ .sort((a, b) => {
84
+ const ta = a.lastUsedAt ?? "";
85
+ const tb = b.lastUsedAt ?? "";
86
+ return tb.localeCompare(ta) || a.skillName.localeCompare(b.skillName);
87
+ });
88
+ }, [usage.data?.skills]);
89
+ const mcpItems = useMemo(() => {
90
+ return (usage.data?.mcpTools ?? []).slice().sort((a, b) => {
91
+ const ta = a.lastUsedAt ?? "";
92
+ const tb = b.lastUsedAt ?? "";
93
+ return (
94
+ tb.localeCompare(ta) ||
95
+ a.server.localeCompare(b.server) ||
96
+ a.tool.localeCompare(b.tool)
97
+ );
98
+ });
99
+ }, [usage.data?.mcpTools]);
100
+
101
+ useEffect(() => {
102
+ if (skillItems.length > 0) setTab((t) => t ?? "skills");
103
+ else if (mcpItems.length > 0) setTab("mcp");
104
+ else setTab(null);
105
+ }, [skillItems.length, mcpItems.length]);
106
+
107
+ const styles = useMemo(
108
+ () => ({
109
+ root: {
110
+ gap: 16,
111
+ minWidth: compact ? undefined : 300,
112
+ maxWidth: compact ? undefined : 380,
113
+ },
114
+ rangeBar: {
115
+ flexDirection: "row" as const,
116
+ alignItems: "center" as const,
117
+ alignSelf: "flex-start" as const,
118
+ gap: 20,
119
+ },
120
+ rangeSegment: {
121
+ paddingVertical: 8,
122
+ },
123
+ rangeSegmentActive: {
124
+ borderBottomWidth: 1,
125
+ borderBottomColor: theme.colors.foreground,
126
+ },
127
+ chipText: {
128
+ color: theme.colors.foregroundMuted,
129
+ fontSize: 12,
130
+ fontWeight: "500" as const,
131
+ },
132
+ chipTextActive: {
133
+ color: theme.colors.foreground,
134
+ fontSize: 12,
135
+ fontWeight: "600" as const,
136
+ },
137
+ list: {
138
+ gap: 0,
139
+ },
140
+ row: {
141
+ flexDirection: "row" as const,
142
+ alignItems: "center" as const,
143
+ gap: 10,
144
+ paddingVertical: 10,
145
+ borderTopWidth: 0,
146
+ borderTopColor: theme.colors.border,
147
+ },
148
+ rowFirst: {
149
+ borderTopWidth: 0,
150
+ paddingTop: 2,
151
+ },
152
+ rowMain: {
153
+ flex: 1,
154
+ minWidth: 0,
155
+ gap: 2,
156
+ },
157
+ rowTitle: {
158
+ color: theme.colors.foreground,
159
+ fontSize: 13,
160
+ fontWeight: "500" as const,
161
+ },
162
+ rowLink: {
163
+ color: theme.colors.foreground,
164
+ fontSize: 13,
165
+ fontWeight: "500" as const,
166
+ },
167
+ rowMeta: {
168
+ color: theme.colors.foregroundMuted,
169
+ fontSize: 11,
170
+ },
171
+ countBadge: {
172
+ minWidth: 22,
173
+ alignItems: "flex-end" as const,
174
+ },
175
+ countText: {
176
+ color: theme.colors.foregroundMuted,
177
+ fontSize: 12,
178
+ fontVariant: ["tabular-nums" as const],
179
+ },
180
+ empty: {
181
+ color: theme.colors.foregroundMuted,
182
+ fontSize: 13,
183
+ paddingVertical: 4,
184
+ },
185
+ detailHeader: {
186
+ flexDirection: "row" as const,
187
+ alignItems: "center" as const,
188
+ justifyContent: "space-between" as const,
189
+ gap: 8,
190
+ },
191
+ backRow: {
192
+ flexDirection: "row" as const,
193
+ alignItems: "center" as const,
194
+ gap: 4,
195
+ },
196
+ back: {
197
+ color: theme.colors.foregroundMuted,
198
+ fontSize: 12,
199
+ fontWeight: "500" as const,
200
+ },
201
+ panelButton: {
202
+ paddingHorizontal: 10,
203
+ paddingVertical: 8,
204
+ borderRadius: 8,
205
+ backgroundColor: theme.colors.surface2,
206
+ flexDirection: "row" as const,
207
+ alignItems: "center" as const,
208
+ gap: 6,
209
+ },
210
+ title: {
211
+ color: theme.colors.foreground,
212
+ fontSize: compact ? 15 : 16,
213
+ fontWeight: "600" as const,
214
+ flexShrink: 1,
215
+ },
216
+ body: {
217
+ color: theme.colors.foreground,
218
+ fontSize: 13,
219
+ fontFamily: MONO,
220
+ lineHeight: 22,
221
+ backgroundColor: theme.colors.surface1,
222
+ padding: 16,
223
+ borderRadius: 12,
224
+ },
225
+ }),
226
+ [theme, compact],
227
+ );
228
+
229
+ // Cached pill data (QueryClient or module cache) must paint immediately; only
230
+ // spin when we have nothing to show yet.
231
+ const loading = !usage.data && usage.isLoading;
232
+ const error = usage.error;
233
+ const showTabs = skillItems.length > 0 && mcpItems.length > 0;
234
+
235
+ if (skillDetail) {
236
+ return (
237
+ <View style={styles.root}>
238
+ <View style={styles.detailHeader}>
239
+ <Pressable
240
+ accessibilityRole="button"
241
+ onPress={() => setSkillDetail(null)}
242
+ style={styles.backRow}
243
+ >
244
+ <Icon name="ChevronLeft" size={14} color={theme.colors.foregroundMuted} />
245
+ <Text style={styles.back}>Skills</Text>
246
+ </Pressable>
247
+ {openSkillInPanel ? (
248
+ <Pressable
249
+ accessibilityRole="button"
250
+ accessibilityLabel="Open SKILL.md in panel"
251
+ style={styles.panelButton}
252
+ onPress={() => {
253
+ openSkillInPanel(skillDetail);
254
+ close();
255
+ }}
256
+ >
257
+ <Icon name="ArrowUpRight" size={14} color={theme.colors.foregroundMuted} />
258
+ <Text style={styles.back}>Open in tab</Text>
259
+ </Pressable>
260
+ ) : null}
261
+ </View>
262
+ <Text style={styles.title}>{formatDisplayName(skillDetail.skillName)}</Text>
263
+ {skillFile.isLoading ? <ActivityIndicator color={theme.colors.accent} /> : null}
264
+ {skillFile.error ? (
265
+ <Text style={{ color: theme.colors.statusDanger }}>
266
+ {skillFile.error instanceof Error ? skillFile.error.message : String(skillFile.error)}
267
+ </Text>
268
+ ) : null}
269
+ {skillFile.data ? (
270
+ <Text style={styles.body} selectable>
271
+ {skillFile.data.body}
272
+ </Text>
273
+ ) : null}
274
+ </View>
275
+ );
276
+ }
277
+
278
+ return (
279
+ <View style={styles.root}>
280
+ {!compact ? (
281
+ <View style={{ gap: 4 }}>
282
+ <Text style={styles.title}>Activity</Text>
283
+ <Text style={styles.rowMeta}>Current conversation</Text>
284
+ </View>
285
+ ) : null}
286
+ {showTabs ? (
287
+ <View style={styles.rangeBar}>
288
+ {(
289
+ [
290
+ ["skills", "Skills"],
291
+ ["mcp", "MCP"],
292
+ ] as const
293
+ ).map(([id, label]) => {
294
+ const active = tab === id;
295
+ return (
296
+ <Pressable
297
+ key={id}
298
+ accessibilityRole="tab"
299
+ accessibilityState={{ selected: active }}
300
+ onPress={() => setTab(id)}
301
+ style={[styles.rangeSegment, active ? styles.rangeSegmentActive : null]}
302
+ >
303
+ <Text style={active ? styles.chipTextActive : styles.chipText}>{label}</Text>
304
+ </Pressable>
305
+ );
306
+ })}
307
+ </View>
308
+ ) : null}
309
+
310
+ {loading ? <ActivityIndicator color={theme.colors.accent} /> : null}
311
+ {error ? (
312
+ <Text style={{ color: theme.colors.statusDanger }}>
313
+ {error instanceof Error ? error.message : String(error)}
314
+ </Text>
315
+ ) : null}
316
+
317
+ {!loading && !error && skillItems.length === 0 && mcpItems.length === 0 ? (
318
+ <Text style={styles.empty}>No skill or MCP calls yet</Text>
319
+ ) : null}
320
+
321
+ {tab === "skills" && skillItems.length > 0 ? (
322
+ <View style={styles.list}>
323
+ {skillItems.map((item, index) => {
324
+ const name = formatDisplayName(item.skillName);
325
+ const title = item.skillPath ? (
326
+ <Pressable
327
+ accessibilityRole="link"
328
+ accessibilityLabel={`Open ${name} SKILL.md`}
329
+ onPress={() =>
330
+ setSkillDetail({ skillName: item.skillName, path: item.skillPath! })
331
+ }
332
+ >
333
+ <Text style={styles.rowLink} numberOfLines={1}>
334
+ {name}
335
+ </Text>
336
+ </Pressable>
337
+ ) : (
338
+ <Text style={styles.rowTitle} numberOfLines={1}>
339
+ {name}
340
+ </Text>
341
+ );
342
+ return (
343
+ <View key={item.skillName} style={[styles.row, index === 0 ? styles.rowFirst : null]}>
344
+ <Icon name="Sparkles" size={16} color={theme.colors.foregroundMuted} />
345
+ <View style={styles.rowMain}>
346
+ {title}
347
+ {item.lastUsedAt ? (
348
+ <Text style={styles.rowMeta}>{formatDayTime(item.lastUsedAt)}</Text>
349
+ ) : null}
350
+ </View>
351
+ <CountBadge value={item.total} styles={styles} />
352
+ </View>
353
+ );
354
+ })}
355
+ </View>
356
+ ) : null}
357
+
358
+ {tab === "mcp" && mcpItems.length > 0 ? (
359
+ <View style={styles.list}>
360
+ {mcpItems.map((item, index) => (
361
+ <View
362
+ key={`${item.server}.${item.tool}`}
363
+ style={[styles.row, index === 0 ? styles.rowFirst : null]}
364
+ >
365
+ <Icon name="Plug" size={16} color={theme.colors.foregroundMuted} />
366
+ <View style={styles.rowMain}>
367
+ <Text style={styles.rowTitle} numberOfLines={1}>
368
+ {formatDisplayName(`${item.server}.${item.tool}`)}
369
+ </Text>
370
+ {item.failures > 0 ? (
371
+ <Text style={styles.rowMeta}>{item.failures} failed</Text>
372
+ ) : item.lastUsedAt ? (
373
+ <Text style={styles.rowMeta}>{formatDayTime(item.lastUsedAt)}</Text>
374
+ ) : null}
375
+ </View>
376
+ <CountBadge value={item.count} styles={styles} />
377
+ </View>
378
+ ))}
379
+ </View>
380
+ ) : null}
381
+ </View>
382
+ );
383
+ }
@@ -0,0 +1,54 @@
1
+ import { useRpc } from "@getpaseo/plugin/client";
2
+ import { useQuery } from "@tanstack/react-query";
3
+ import {
4
+ usageMcpByToolRpc,
5
+ usageSkillsByNameRpc,
6
+ } from "../shared/usage.ts";
7
+ import {
8
+ pillDataIsEmpty,
9
+ seedPillDataForQuery,
10
+ writePillDataCache,
11
+ type UsagePillData,
12
+ } from "./pill-data-cache.ts";
13
+
14
+ export type { UsagePillData } from "./pill-data-cache.ts";
15
+ export { __setPillDataCacheForTests, clearPillDataCache } from "./pill-data-cache.ts";
16
+
17
+ /** Poll while empty so mid-turn mount can see post-turn_ended rows before hide. */
18
+ const EMPTY_REFETCH_MS = 1_500;
19
+
20
+ /** Current-agent skills/mcp breakdown for the composer pill (no summary — unused in UI). */
21
+ export function useUsagePillData(agentId: string) {
22
+ const skillsRpc = useRpc(usageSkillsByNameRpc);
23
+ const mcpRpc = useRpc(usageMcpByToolRpc);
24
+ return useQuery({
25
+ queryKey: ["activity", "pill", "agent", agentId],
26
+ queryFn: async () => {
27
+ const [skills, mcp] = await Promise.all([
28
+ skillsRpc({ agentId }),
29
+ mcpRpc({ agentId }),
30
+ ]);
31
+ const data: UsagePillData = {
32
+ skills: skills.items,
33
+ mcpTools: mcp.items,
34
+ };
35
+ writePillDataCache(agentId, data);
36
+ return data;
37
+ },
38
+ enabled: Boolean(agentId),
39
+ // Idle remount must not reuse a stale empty cache from mid-turn.
40
+ staleTime: 0,
41
+ refetchOnMount: "always",
42
+ // Host QueryClient defaults to retry:3; deterministic RPC errors just delay the badge.
43
+ retry: false,
44
+ // Seed non-empty module cache so popover paints immediately across QueryClients.
45
+ initialData: () => seedPillDataForQuery(agentId),
46
+ initialDataUpdatedAt: () =>
47
+ seedPillDataForQuery(agentId) ? Date.now() : undefined,
48
+ refetchInterval: (query) => {
49
+ const data = query.state.data;
50
+ if (!data) return EMPTY_REFETCH_MS;
51
+ return pillDataIsEmpty(data) ? EMPTY_REFETCH_MS : 15_000;
52
+ },
53
+ });
54
+ }
@@ -0,0 +1,18 @@
1
+ import { Text, View } from "react-native";
2
+
3
+ export function UsageStats({ items, colors, compact }: {
4
+ items: ReadonlyArray<{ label: string; value: string }>;
5
+ colors: { border: string; foreground: string; foregroundMuted: string };
6
+ compact: boolean;
7
+ }) {
8
+ return (
9
+ <View style={{ flexDirection: "row", flexWrap: "wrap", borderWidth: 1, borderColor: colors.border, borderRadius: 20, paddingVertical: compact ? 8 : 18, rowGap: 16 }}>
10
+ {items.map((item, index) => (
11
+ <View key={item.label} style={{ flexGrow: 1, flexBasis: compact ? 100 : 120, minWidth: 0, alignItems: "center", paddingHorizontal: 12, paddingVertical: 4, gap: 6, borderLeftWidth: index === 0 || compact ? 0 : 1, borderLeftColor: colors.border }}>
12
+ <Text style={{ color: colors.foreground, fontSize: compact ? 20 : 24, fontWeight: "500", fontVariant: ["tabular-nums"] }}>{item.value}</Text>
13
+ <Text style={{ color: colors.foregroundMuted, fontSize: compact ? 12 : 14 }}>{item.label}</Text>
14
+ </View>
15
+ ))}
16
+ </View>
17
+ );
18
+ }
@@ -0,0 +1,14 @@
1
+ import { useSyncExternalStore } from "react";
2
+ import { Platform } from "react-native";
3
+ import { readAppLanguage, subscribeAppLanguage } from "./web.ts";
4
+
5
+ const defaultLanguage = () => "en";
6
+ const noSubscription = () => () => {};
7
+
8
+ export function useAppLanguage(): string {
9
+ return useSyncExternalStore(
10
+ Platform.OS === "web" ? subscribeAppLanguage : noSubscription,
11
+ Platform.OS === "web" ? readAppLanguage : defaultLanguage,
12
+ defaultLanguage,
13
+ );
14
+ }
package/client/web.ts ADDED
@@ -0,0 +1,28 @@
1
+ // Browser-only bridge: the SDK currently does not expose the app locale.
2
+ // Keep DOM access here and call it only on the web platform.
3
+ type LanguageElement = { lang: string };
4
+ type LanguageObserver = {
5
+ observe(target: LanguageElement, options: { attributes: boolean; attributeFilter: string[] }): void;
6
+ disconnect(): void;
7
+ };
8
+ const browser = globalThis as unknown as {
9
+ document?: { documentElement: LanguageElement };
10
+ MutationObserver?: new (callback: () => void) => LanguageObserver;
11
+ };
12
+
13
+ export function readAppLanguage(): string {
14
+ const language = browser.document?.documentElement.lang.trim() || "en";
15
+ try {
16
+ return Intl.getCanonicalLocales(language)[0] ?? "en";
17
+ } catch {
18
+ return "en";
19
+ }
20
+ }
21
+
22
+ export function subscribeAppLanguage(onChange: () => void): () => void {
23
+ const root = browser.document?.documentElement;
24
+ if (!root || !browser.MutationObserver) return () => {};
25
+ const observer = new browser.MutationObserver(onChange);
26
+ observer.observe(root, { attributes: true, attributeFilter: ["lang"] });
27
+ return () => observer.disconnect();
28
+ }
@@ -0,0 +1,62 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { copyText } from "@getpaseo/plugin/client/react-native";
3
+ import { GlobalUsageSurface } from "./client/global-surface.tsx";
4
+ import { UsagePanel } from "./client/panel.tsx";
5
+ import { contributePills } from "./client/pill.tsx";
6
+ import { usageExportRpc } from "./shared/usage.ts";
7
+
8
+ const GLOBAL_SURFACE_ID = "activity";
9
+
10
+ export default function contribute(client: PluginClientContext) {
11
+ client.addSurface(GLOBAL_SURFACE_ID, GlobalUsageSurface);
12
+ client.addSidebarItem({
13
+ id: "activity",
14
+ title: "Activity",
15
+ icon: "Activity",
16
+ surface: GLOBAL_SURFACE_ID,
17
+ });
18
+
19
+ client.addWorkspacePanel({
20
+ id: "usage",
21
+ title: "Activity",
22
+ icon: "Activity",
23
+ context: "agent",
24
+ Component: UsagePanel,
25
+ });
26
+
27
+ client.addCommandCenterItem({
28
+ id: "open-usage-global",
29
+ title: "Open Activity (all providers)",
30
+ icon: "Activity",
31
+ keywords: ["activity", "tool", "usage", "provider", "all", "global", "sidebar"],
32
+ context: "global",
33
+ onSelect({ openSurface }) {
34
+ openSurface(GLOBAL_SURFACE_ID);
35
+ },
36
+ });
37
+
38
+ client.addCommandCenterItem({
39
+ id: "open-usage",
40
+ title: "Activity",
41
+ icon: "Activity",
42
+ keywords: ["activity", "tool", "usage", "shell", "skill", "mcp", "stats"],
43
+ context: "agent",
44
+ onSelect: ({ openPanel }) => {
45
+ openPanel("usage");
46
+ },
47
+ });
48
+
49
+ client.addCommandCenterItem({
50
+ id: "export-usage",
51
+ title: "Export activity report",
52
+ icon: "FileDown",
53
+ keywords: ["export", "report", "markdown", "activity", "tool usage"],
54
+ context: "agent",
55
+ async onSelect({ agent, rpc }) {
56
+ const result = await rpc(usageExportRpc, { agentId: agent?.id });
57
+ await copyText(result.markdown);
58
+ },
59
+ });
60
+
61
+ return contributePills(client);
62
+ }
@@ -0,0 +1,128 @@
1
+ import { createBackgroundSync } from "./server/background-sync.ts";
2
+ import { homedir } from "node:os";
3
+ import type { PluginServerContext } from "@getpaseo/plugin/server";
4
+ import {
5
+ createActivityByDayHandler,
6
+ createByProviderHandler,
7
+ createExportHandler,
8
+ createListHandler,
9
+ createMcpByToolHandler,
10
+ createReadSkillHandler,
11
+ createSkillsByNameHandler,
12
+ createSummaryHandler,
13
+ } from "./server/handlers.ts";
14
+ import { agentRowFromHook } from "./server/agents.ts";
15
+ import { ingestTimeline, ingestUserMessages } from "./server/ingest.ts";
16
+ import { resolveAgentModel } from "./server/resolve-model.ts";
17
+ import { createUsageStore } from "./server/store.ts";
18
+ import {
19
+ usageActivityByDayRpc,
20
+ usageByProviderRpc,
21
+ usageExportRpc,
22
+ usageListRpc,
23
+ usageMcpByToolRpc,
24
+ usageReadSkillRpc,
25
+ usageSkillsByNameRpc,
26
+ usageSummaryRpc,
27
+ } from "./shared/usage.ts";
28
+
29
+ export default function contribute(server: PluginServerContext) {
30
+ const store = createUsageStore();
31
+ const background = createBackgroundSync(store);
32
+ console.log(`[activity] store ready (driver=${store.driver})`);
33
+
34
+ server.handle(usageSummaryRpc, (input, context) => {
35
+ void background.request(context.paseo);
36
+ return createSummaryHandler(store)(input);
37
+ });
38
+ server.handle(usageListRpc, (input, context) => {
39
+ void background.request(context.paseo);
40
+ return createListHandler(store)(input);
41
+ });
42
+ server.handle(usageSkillsByNameRpc, (input, context) => {
43
+ void background.request(context.paseo);
44
+ return createSkillsByNameHandler(store)(input, context);
45
+ });
46
+ server.handle(usageMcpByToolRpc, (input, context) => {
47
+ void background.request(context.paseo);
48
+ return createMcpByToolHandler(store)(input);
49
+ });
50
+ server.handle(usageByProviderRpc, (input, context) => {
51
+ void background.request(context.paseo);
52
+ return createByProviderHandler(store)(input);
53
+ });
54
+ server.handle(usageActivityByDayRpc, (input, context) => {
55
+ void background.request(context.paseo);
56
+ return createActivityByDayHandler(store)(input);
57
+ });
58
+ server.handle(usageExportRpc, createExportHandler(store));
59
+ server.handle(usageReadSkillRpc, createReadSkillHandler());
60
+
61
+ const removeCreated = server.on("agent.created", (event, context) => {
62
+ void background.request(context.paseo);
63
+ try {
64
+ store.upsertAgents([agentRowFromHook(event.agent)]);
65
+ console.log(`[activity] agent.created id=${event.agent.id}`);
66
+ } catch (error) {
67
+ console.error("[activity] failed to ingest agent.created", error);
68
+ }
69
+ });
70
+
71
+ const removeArchived = server.on("agent.archived", (event, context) => {
72
+ void background.request(context.paseo);
73
+ try {
74
+ store.upsertAgents([
75
+ agentRowFromHook(event.agent, {
76
+ archivedAt: event.archivedAt,
77
+ createdAt: store.getAgent(event.agent.id)?.createdAt,
78
+ }),
79
+ ]);
80
+ console.log(`[activity] agent.archived id=${event.agent.id}`);
81
+ } catch (error) {
82
+ console.error("[activity] failed to ingest agent.archived", error);
83
+ }
84
+ });
85
+
86
+ const removeTurnEnded = server.on("agent.turn_ended", (event, context) => {
87
+ void background.request(context.paseo);
88
+ void (async () => {
89
+ try {
90
+ const existing = store.getAgent(event.agent.id);
91
+ store.upsertAgents([
92
+ agentRowFromHook(event.agent, {
93
+ createdAt: existing?.createdAt,
94
+ archivedAt: existing?.archivedAt,
95
+ }),
96
+ ]);
97
+ const model = await resolveAgentModel(context.paseo, event.agent.id);
98
+ store.upsertUserMessages(
99
+ ingestUserMessages(event.timeline, event.agent, { model }),
100
+ );
101
+ // mcpServers resolved inside ingestTimeline (OpenCode config + paseo inject + agent persistence)
102
+ const rows = ingestTimeline(event.timeline, event.agent, null, {
103
+ homeDir: homedir(),
104
+ });
105
+ if (rows.length > 0) {
106
+ store.upsertMany(rows);
107
+ console.log(
108
+ `[activity] turn_ended agent=${event.agent.id} rows=${rows.length} total=${store.count()}`,
109
+ );
110
+ }
111
+ } catch (error) {
112
+ console.error("[activity] failed to ingest agent.turn_ended", error);
113
+ }
114
+ })();
115
+ });
116
+
117
+ return () => {
118
+ background.stop();
119
+ removeCreated();
120
+ removeArchived();
121
+ removeTurnEnded();
122
+ try {
123
+ store.close();
124
+ } catch (error) {
125
+ console.error("[activity] failed to close store", error);
126
+ }
127
+ };
128
+ }