@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,212 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { homedir as osHomedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createKeyedTtlCache } from "./ttl-cache.ts";
5
+
6
+ /** Paseo-injected agent MCP server name (`runtime-mcp-config.js`). */
7
+ export const PASEO_MCP_SERVER_NAME = "paseo";
8
+
9
+ export type ResolveMcpServersOptions = {
10
+ homeDir?: string;
11
+ cwd?: string | null;
12
+ /** Agent id — used to read persisted `mcpServers` from ~/.paseo/agents. */
13
+ agentId?: string | null;
14
+ /** Extra names (tests / callers). */
15
+ extra?: readonly string[];
16
+ };
17
+
18
+ const mcpServersCache = createKeyedTtlCache<string[]>(60_000);
19
+
20
+ /**
21
+ * Resolve MCP server names for OpenCode `<server>_<tool>` (and ACP title) matching.
22
+ *
23
+ * Sources (union, longest-prefix wins at classify time):
24
+ * 1. Always `paseo` when daemon injects MCP into agents (default on)
25
+ * 2. OpenCode user/project config `mcp` keys
26
+ * 3. Agent persistence `mcpServers` keys under ~/.paseo/agents
27
+ * 4. Caller `extra`
28
+ */
29
+ export function resolveMcpServers(options: ResolveMcpServersOptions = {}): string[] {
30
+ const homeDir = options.homeDir ?? osHomedir();
31
+ const cwd = options.cwd ?? null;
32
+ const agentId = options.agentId ?? null;
33
+ const extraKey = (options.extra ?? []).join("\0");
34
+ const key = `${homeDir}\0${cwd ?? ""}\0${agentId ?? ""}\0${extraKey}`;
35
+ return mcpServersCache.get(key, () => resolveMcpServersUncached(options));
36
+ }
37
+
38
+ function resolveMcpServersUncached(options: ResolveMcpServersOptions): string[] {
39
+ const homeDir = options.homeDir ?? osHomedir();
40
+ const names = new Set<string>();
41
+
42
+ if (isPaseoMcpInjectEnabled(homeDir)) {
43
+ names.add(PASEO_MCP_SERVER_NAME);
44
+ }
45
+
46
+ for (const name of readOpenCodeMcpServerNames(homeDir, options.cwd ?? null)) {
47
+ names.add(name);
48
+ }
49
+
50
+ if (options.agentId) {
51
+ for (const name of readAgentPersistedMcpServerNames(homeDir, options.agentId)) {
52
+ names.add(name);
53
+ }
54
+ }
55
+
56
+ for (const name of options.extra ?? []) {
57
+ if (name.trim()) names.add(name.trim());
58
+ }
59
+
60
+ return [...names];
61
+ }
62
+
63
+ export function isPaseoMcpInjectEnabled(homeDir: string): boolean {
64
+ const configPath = join(homeDir, ".paseo", "config.json");
65
+ try {
66
+ const raw = readFileSync(configPath, "utf8");
67
+ const parsed = JSON.parse(raw) as {
68
+ daemon?: { mcp?: { injectIntoAgents?: boolean } };
69
+ };
70
+ return parsed.daemon?.mcp?.injectIntoAgents !== false;
71
+ } catch {
72
+ // Missing / unreadable config — Paseo default is inject on.
73
+ return true;
74
+ }
75
+ }
76
+
77
+ export function readOpenCodeMcpServerNames(
78
+ homeDir: string,
79
+ cwd: string | null,
80
+ ): string[] {
81
+ const candidates = [
82
+ join(homeDir, ".config", "opencode", "opencode.jsonc"),
83
+ join(homeDir, ".config", "opencode", "opencode.json"),
84
+ ];
85
+ if (cwd) {
86
+ candidates.push(
87
+ join(cwd, "opencode.jsonc"),
88
+ join(cwd, "opencode.json"),
89
+ join(cwd, ".opencode", "opencode.jsonc"),
90
+ join(cwd, ".opencode", "opencode.json"),
91
+ );
92
+ }
93
+
94
+ const names = new Set<string>();
95
+ for (const path of candidates) {
96
+ for (const name of readMcpKeysFromConfigFile(path)) {
97
+ names.add(name);
98
+ }
99
+ }
100
+ return [...names];
101
+ }
102
+
103
+ function readMcpKeysFromConfigFile(path: string): string[] {
104
+ if (!existsSync(path)) return [];
105
+ try {
106
+ const text = readFileSync(path, "utf8");
107
+ const parsed = parseJsonc(text);
108
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];
109
+ const mcp = (parsed as { mcp?: unknown; mcpServers?: unknown }).mcp
110
+ ?? (parsed as { mcpServers?: unknown }).mcpServers;
111
+ if (!mcp || typeof mcp !== "object" || Array.isArray(mcp)) return [];
112
+ return Object.keys(mcp as Record<string, unknown>).filter((k) => k.trim().length > 0);
113
+ } catch {
114
+ return [];
115
+ }
116
+ }
117
+
118
+ export function readAgentPersistedMcpServerNames(
119
+ homeDir: string,
120
+ agentId: string,
121
+ ): string[] {
122
+ const agentsRoot = join(homeDir, ".paseo", "agents");
123
+ const file = findAgentFile(agentsRoot, agentId);
124
+ if (!file) return [];
125
+ try {
126
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as {
127
+ persistence?: { metadata?: { mcpServers?: Record<string, unknown> } };
128
+ config?: { mcpServers?: Record<string, unknown> };
129
+ };
130
+ const fromPersistence = parsed.persistence?.metadata?.mcpServers;
131
+ const fromConfig = parsed.config?.mcpServers;
132
+ const names = new Set<string>();
133
+ if (fromPersistence && typeof fromPersistence === "object") {
134
+ for (const k of Object.keys(fromPersistence)) names.add(k);
135
+ }
136
+ if (fromConfig && typeof fromConfig === "object") {
137
+ for (const k of Object.keys(fromConfig)) names.add(k);
138
+ }
139
+ return [...names];
140
+ } catch {
141
+ return [];
142
+ }
143
+ }
144
+
145
+ function findAgentFile(agentsRoot: string, agentId: string): string | null {
146
+ const direct = join(agentsRoot, `${agentId}.json`);
147
+ if (existsSync(direct)) return direct;
148
+ try {
149
+ for (const entry of readdirSync(agentsRoot, { withFileTypes: true })) {
150
+ if (!entry.isDirectory()) continue;
151
+ const nested = join(agentsRoot, entry.name, `${agentId}.json`);
152
+ if (existsSync(nested)) return nested;
153
+ }
154
+ } catch {
155
+ /* no agents dir */
156
+ }
157
+ return null;
158
+ }
159
+
160
+ /** Minimal JSONC: strip // and /* *\/ comments, then JSON.parse. */
161
+ export function parseJsonc(text: string): unknown {
162
+ let out = "";
163
+ let i = 0;
164
+ let inString = false;
165
+ let quote: '"' | "'" | null = null;
166
+ while (i < text.length) {
167
+ const ch = text[i]!;
168
+ const next = text[i + 1];
169
+
170
+ if (inString) {
171
+ out += ch;
172
+ if (ch === "\\" && i + 1 < text.length) {
173
+ out += text[i + 1]!;
174
+ i += 2;
175
+ continue;
176
+ }
177
+ if (ch === quote) {
178
+ inString = false;
179
+ quote = null;
180
+ }
181
+ i += 1;
182
+ continue;
183
+ }
184
+
185
+ if (ch === '"' || ch === "'") {
186
+ inString = true;
187
+ quote = ch;
188
+ out += ch;
189
+ i += 1;
190
+ continue;
191
+ }
192
+
193
+ if (ch === "/" && next === "/") {
194
+ i += 2;
195
+ while (i < text.length && text[i] !== "\n") i += 1;
196
+ continue;
197
+ }
198
+ if (ch === "/" && next === "*") {
199
+ i += 2;
200
+ while (i + 1 < text.length && !(text[i] === "*" && text[i + 1] === "/")) i += 1;
201
+ i += 2;
202
+ continue;
203
+ }
204
+
205
+ out += ch;
206
+ i += 1;
207
+ }
208
+
209
+ // Trailing commas before } or ]
210
+ const cleaned = out.replace(/,\s*([}\]])/g, "$1");
211
+ return JSON.parse(cleaned);
212
+ }
@@ -0,0 +1,150 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { mkdtempSync, rmSync, readFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
7
+ import { ingestUserMessages, ingestTurnTimeline } from "./ingest.ts";
8
+ import { createUsageStore } from "./store.ts";
9
+ import { createActivityByDayHandler, createByProviderHandler, resyncAgents } from "./handlers.ts";
10
+ import { aggregateActivityByDay, aggregateByProvider } from "../shared/usage.ts";
11
+ import { computeStreaks } from "../shared/activity.ts";
12
+
13
+ type PaseoApi = PluginHandlerContext["paseo"];
14
+
15
+ const agent = { id: "a1", workspaceId: "w1", parentAgentId: null, provider: "codex", cwd: "/tmp", title: null };
16
+ const now = "2026-09-19T12:00:00.000Z";
17
+ const earlier = "2026-09-18T12:00:00.000Z";
18
+ const message = { type: "user_message" as const, messageId: "m1", text: "private body" };
19
+
20
+ test("message identity precedence, empty messages, assistant exclusion and anonymous fallback", () => {
21
+ const rows = ingestUserMessages([
22
+ { ...message, clientMessageId: "client" },
23
+ { type: "user_message", text: "", clientMessageId: "client" },
24
+ { type: "assistant_message", text: "reply" },
25
+ { type: "user_message", text: "anonymous" },
26
+ ], agent, { ingestedAt: now, model: "gpt-5.4" });
27
+ assert.deepEqual(rows.map(row => row.messageId), ["m1", "client"]);
28
+ assert.ok(rows.every(row => row.ts === null && row.turnId === null && row.model === "gpt-5.4" && !("text" in row)));
29
+ const anonymous = [{ type: "user_message" as const, text: "" }];
30
+ assert.deepEqual(ingestUserMessages(anonymous, agent, { seq: 5, ingestedAt: now }),
31
+ ingestUserMessages(anonymous, agent, { seq: 5, ingestedAt: now }));
32
+ assert.notEqual(ingestUserMessages(anonymous, agent, { seq: 5 })[0]?.messageId,
33
+ ingestUserMessages(anonymous, agent, { seq: 6 })[0]?.messageId);
34
+ });
35
+
36
+ test("message model coalesce keeps first non-null on upsert", () => {
37
+ const dir = mkdtempSync(join(tmpdir(), "activity-model-"));
38
+ const store = createUsageStore({ dir, driver: "sqlite" });
39
+ try {
40
+ const first = ingestUserMessages([message], agent, { ingestedAt: now, model: "gpt-5.4" });
41
+ store.upsertUserMessages(first);
42
+ store.upsertUserMessages(ingestUserMessages([message], agent, { ingestedAt: now, model: null }));
43
+ assert.equal(store.selectUserMessages()[0]?.model, "gpt-5.4");
44
+ store.upsertUserMessages(ingestUserMessages([message], agent, { ingestedAt: now, model: "other" }));
45
+ assert.equal(store.selectUserMessages()[0]?.model, "gpt-5.4");
46
+ } finally {
47
+ store.close();
48
+ rmSync(dir, { recursive: true, force: true });
49
+ }
50
+ });
51
+
52
+ for (const driver of ["sqlite", "jsonl"] as const) {
53
+ test(`${driver}: live replay, canonical correction, filters, persistence and privacy`, () => {
54
+ const dir = mkdtempSync(join(tmpdir(), "activity-messages-"));
55
+ let store = createUsageStore({ dir, driver });
56
+ try {
57
+ assert.equal(store.driver, driver);
58
+ for (let i = 0; i < 2; i++) ingestTurnTimeline(agent, [message], { store, homeDir: "", now: () => now });
59
+ assert.equal(store.selectUserMessages().length, 1);
60
+ const canonical = ingestUserMessages([message], agent, { seq: 2, ts: earlier, turnId: "old", ingestedAt: now });
61
+ store.upsertUserMessages(canonical);
62
+ store.upsertUserMessages(ingestUserMessages([message], agent, { ingestedAt: "2026-09-20T00:00:00.000Z" }));
63
+ store.upsertUserMessages(ingestUserMessages([message], { ...agent, id: "a2", provider: "claude", workspaceId: "w2" }));
64
+ assert.equal(store.selectUserMessages({ from: now, agentId: "a1" }).length, 0);
65
+ assert.equal(store.selectUserMessages({ provider: "claude" }).length, 1);
66
+ assert.equal(store.selectUserMessages({ workspaceId: "w2" }).length, 1);
67
+ assert.equal(store.selectUserMessages({ to: earlier }).length, 1);
68
+ store.close();
69
+ store = createUsageStore({ dir, driver });
70
+ assert.equal(store.selectUserMessages().length, 2);
71
+ assert.deepEqual(store.selectUserMessages({ agentId: "a1" }), canonical);
72
+ const disk = readFileSync(join(dir, driver === "sqlite" ? "usage.db" : "user_messages.jsonl"));
73
+ assert.equal(disk.includes(Buffer.from("private body")), false);
74
+ } finally { store.close(); rmSync(dir, { recursive: true, force: true }); }
75
+ });
76
+ }
77
+
78
+ test("message-only days/providers are visible without altering tool totals; streaks count messages", () => {
79
+ const messages = ingestUserMessages([message], agent, { ts: earlier });
80
+ const days = aggregateActivityByDay([], { messages, provider: "codex" });
81
+ assert.equal(days.length, 1);
82
+ assert.equal(days[0]?.messages, 1);
83
+ assert.equal(days[0]?.total, 1);
84
+ assert.equal(days[0]?.agents, 0);
85
+ const [y, m, d] = days[0]!.date.split("-").map(Number);
86
+ assert.deepEqual(computeStreaks(days, new Date(y!, m! - 1, d!)), { current: 1, longest: 1 });
87
+ assert.deepEqual(aggregateActivityByDay([], { messages, provider: "claude" }), []);
88
+ const result = aggregateByProvider([], [], messages);
89
+ assert.equal(result.providers[0]?.messageCount, 1);
90
+ assert.equal(result.providers[0]?.agentCount, 0);
91
+ assert.equal(result.providers[0]?.callCount, 0);
92
+ });
93
+
94
+ test("resync paginates messages idempotently; query handlers use stored messages", async () => {
95
+ const dir = mkdtempSync(join(tmpdir(), "activity-resync-"));
96
+ const store = createUsageStore({ dir, driver: "sqlite" });
97
+ let calls = 0;
98
+ const paseo = { agents: {
99
+ list: async () => ({ entries: [{ agent: { ...agent, createdAt: earlier } }] }),
100
+ ref: () => ({ timeline: { refetch: async (input: { direction: string }) => {
101
+ calls++;
102
+ const tail = input.direction === "tail";
103
+ return {
104
+ entries: [{ item: tail ? message : { type: "user_message", text: "" },
105
+ timestamp: earlier, turnId: "t1", seqStart: tail ? 10 : 1 }],
106
+ hasOlder: tail, startCursor: { epoch: "e", seq: tail ? 10 : 1 }, endCursor: { epoch: "e", seq: 10 },
107
+ };
108
+ } } }),
109
+ } } as unknown as PaseoApi;
110
+ try {
111
+ for (let i = 0; i < 2; i++) {
112
+ const result = await resyncAgents(store, paseo);
113
+ assert.deepEqual(result.errors, []);
114
+ assert.equal(result.syncedAgents, 1);
115
+ }
116
+ assert.equal(calls, 4);
117
+ assert.equal(store.selectUserMessages().length, 2);
118
+ const activity = await createActivityByDayHandler(store)({ provider: "codex", to: earlier });
119
+ assert.equal(activity.days[0]?.messages, 2);
120
+ const providers = await createByProviderHandler(store)({ workspaceId: "w1", to: earlier });
121
+ assert.equal(providers.providers[0]?.messageCount, 2);
122
+ assert.equal(calls, 4, "queries must not refetch history");
123
+ } finally { store.close(); rmSync(dir, { recursive: true, force: true }); }
124
+ });
125
+
126
+ test("canceling an in-flight canonical scan prevents writes after the store closes", async () => {
127
+ const dir = mkdtempSync(join(tmpdir(), "history-cancel-"));
128
+ const store = createUsageStore({ dir, driver: "sqlite" });
129
+ const controller = new AbortController();
130
+ let release!: () => void;
131
+ let entered!: () => void;
132
+ const started = new Promise<void>(resolve => { entered = resolve; });
133
+ const gate = new Promise<void>(resolve => { release = resolve; });
134
+ const paseo = { agents: {
135
+ list: async () => ({ entries: [{ agent: { ...agent, createdAt: earlier } }] }),
136
+ ref: () => ({ timeline: { refetch: async () => {
137
+ entered(); await gate;
138
+ return { entries: [{ item: message, timestamp: earlier, seqStart: 1 }], hasOlder: false,
139
+ endCursor: { epoch: "e", seq: 1 } };
140
+ } } }),
141
+ } } as unknown as PaseoApi;
142
+ try {
143
+ const pending = resyncAgents(store, paseo, undefined, controller.signal);
144
+ await started;
145
+ controller.abort(); store.close(); release();
146
+ const result = await pending;
147
+ assert.equal(result.syncedAgents, 0);
148
+ assert.equal(result.errors[0]?.message, "History scan canceled");
149
+ } finally { rmSync(dir, { recursive: true, force: true }); }
150
+ });
@@ -0,0 +1,65 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { after, test } from "node:test";
6
+ import { resolveActivityDataDir } from "./migrate-data.ts";
7
+ import { LEGACY_PLUGIN_ID, PLUGIN_ID } from "../shared/plugin-id.ts";
8
+
9
+ const dirs: string[] = [];
10
+
11
+ function tempHome(): string {
12
+ const home = mkdtempSync(join(tmpdir(), "activity-migrate-"));
13
+ dirs.push(home);
14
+ return home;
15
+ }
16
+
17
+ after(() => {
18
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
19
+ });
20
+
21
+ test("migrate renames legacy tool-usage dir into activity", () => {
22
+ const home = tempHome();
23
+ const legacy = join(home, ".paseo", "plugin-data", LEGACY_PLUGIN_ID);
24
+ mkdirSync(legacy, { recursive: true });
25
+ writeFileSync(join(legacy, "usage.db"), "sqlite");
26
+ writeFileSync(join(legacy, "history-checkpoints.json"), "{}");
27
+
28
+ const logs: string[] = [];
29
+ const result = resolveActivityDataDir({
30
+ homeDir: home,
31
+ log: (message) => logs.push(message),
32
+ });
33
+
34
+ assert.equal(result.migrated, true);
35
+ assert.equal(result.dir, join(home, ".paseo", "plugin-data", PLUGIN_ID));
36
+ assert.deepEqual(readdirSync(result.dir).sort(), [
37
+ "history-checkpoints.json",
38
+ "usage.db",
39
+ ]);
40
+ assert.equal(readdirSync(join(home, ".paseo", "plugin-data")).includes(LEGACY_PLUGIN_ID), false);
41
+ assert.ok(logs.some((line) => line.includes("migrated")));
42
+ });
43
+
44
+ test("migrate is a no-op when activity already has data", () => {
45
+ const home = tempHome();
46
+ const legacy = join(home, ".paseo", "plugin-data", LEGACY_PLUGIN_ID);
47
+ const next = join(home, ".paseo", "plugin-data", PLUGIN_ID);
48
+ mkdirSync(legacy, { recursive: true });
49
+ mkdirSync(next, { recursive: true });
50
+ writeFileSync(join(legacy, "usage.db"), "old");
51
+ writeFileSync(join(next, "usage.db"), "new");
52
+
53
+ const result = resolveActivityDataDir({ homeDir: home, log: () => {} });
54
+ assert.equal(result.migrated, false);
55
+ assert.equal(readdirSync(legacy).includes("usage.db"), true);
56
+ assert.equal(readdirSync(next).includes("usage.db"), true);
57
+ });
58
+
59
+ test("fresh install creates empty activity dir", () => {
60
+ const home = tempHome();
61
+ const result = resolveActivityDataDir({ homeDir: home, log: () => {} });
62
+ assert.equal(result.migrated, false);
63
+ assert.equal(result.dir, join(home, ".paseo", "plugin-data", PLUGIN_ID));
64
+ assert.deepEqual(readdirSync(result.dir), []);
65
+ });
@@ -0,0 +1,54 @@
1
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { LEGACY_PLUGIN_ID, LOG_PREFIX, PLUGIN_ID } from "../shared/plugin-id.ts";
5
+
6
+ export type MigratePluginDataResult = {
7
+ dir: string;
8
+ migrated: boolean;
9
+ from: string | null;
10
+ };
11
+
12
+ function pluginDataDir(pluginId: string, homeDir: string): string {
13
+ return join(homeDir, ".paseo", "plugin-data", pluginId);
14
+ }
15
+
16
+ function dirHasEntries(path: string): boolean {
17
+ if (!existsSync(path)) return false;
18
+ try {
19
+ return readdirSync(path).length > 0;
20
+ } catch {
21
+ return false;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Ensure `~/.paseo/plugin-data/activity` exists.
27
+ * If the legacy `tool-usage` dir has data and the new dir is empty/missing, rename it.
28
+ */
29
+ export function resolveActivityDataDir(options: {
30
+ homeDir?: string;
31
+ log?: (message: string) => void;
32
+ } = {}): MigratePluginDataResult {
33
+ const homeDir = options.homeDir ?? homedir();
34
+ const log = options.log ?? ((message) => console.log(message));
35
+ const to = pluginDataDir(PLUGIN_ID, homeDir);
36
+ const from = pluginDataDir(LEGACY_PLUGIN_ID, homeDir);
37
+
38
+ if (dirHasEntries(to)) {
39
+ return { dir: to, migrated: false, from: null };
40
+ }
41
+
42
+ if (dirHasEntries(from)) {
43
+ mkdirSync(dirname(to), { recursive: true });
44
+ if (existsSync(to)) {
45
+ rmSync(to, { recursive: true, force: true });
46
+ }
47
+ renameSync(from, to);
48
+ log(`${LOG_PREFIX} migrated plugin data ${LEGACY_PLUGIN_ID} → ${PLUGIN_ID}`);
49
+ return { dir: to, migrated: true, from };
50
+ }
51
+
52
+ mkdirSync(to, { recursive: true });
53
+ return { dir: to, migrated: false, from: null };
54
+ }
@@ -0,0 +1,11 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { normalizeModelId } from "./resolve-model.ts";
4
+
5
+ test("normalizeModelId trims and rejects blanks", () => {
6
+ assert.equal(normalizeModelId(" gpt-5.4 "), "gpt-5.4");
7
+ assert.equal(normalizeModelId(""), null);
8
+ assert.equal(normalizeModelId(" "), null);
9
+ assert.equal(normalizeModelId(null), null);
10
+ assert.equal(normalizeModelId(12), null);
11
+ });
@@ -0,0 +1,30 @@
1
+ import type { PaseoApi } from "./host-types.ts";
2
+
3
+ /** Read the agent's current model id from the daemon snapshot. */
4
+ export async function resolveAgentModel(
5
+ paseo: PaseoApi,
6
+ agentId: string,
7
+ ): Promise<string | null> {
8
+ try {
9
+ const handle = paseo.agents.ref(agentId);
10
+ let snap = handle.current();
11
+ if (!snap) {
12
+ await handle.refresh();
13
+ snap = handle.current();
14
+ }
15
+ const raw = snap?.model ?? snap?.runtimeInfo?.model ?? null;
16
+ if (typeof raw !== "string") return null;
17
+ const trimmed = raw.trim();
18
+ return trimmed ? trimmed : null;
19
+ } catch (error) {
20
+ console.error("[activity] resolveAgentModel failed", error);
21
+ return null;
22
+ }
23
+ }
24
+
25
+ /** Normalize a snapshot / list model field for storage. */
26
+ export function normalizeModelId(value: unknown): string | null {
27
+ if (typeof value !== "string") return null;
28
+ const trimmed = value.trim();
29
+ return trimmed ? trimmed : null;
30
+ }
@@ -0,0 +1,56 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { describe, it } from "node:test";
6
+ import {
7
+ collapseHomePath,
8
+ expandHomePath,
9
+ finalizeSkillPaths,
10
+ resolveSkillMdPath,
11
+ } from "./skill-path.ts";
12
+
13
+ describe("collapseHomePath / expandHomePath", () => {
14
+ it("round-trips ~/ paths", () => {
15
+ const home = "/Users/koin";
16
+ assert.equal(collapseHomePath("/Users/koin/.claude/skills/x/SKILL.md", home), "~/.claude/skills/x/SKILL.md");
17
+ assert.equal(expandHomePath("~/.claude/skills/x/SKILL.md", home), "/Users/koin/.claude/skills/x/SKILL.md");
18
+ assert.equal(collapseHomePath(home, home), "~");
19
+ assert.equal(expandHomePath("~", home), home);
20
+ });
21
+
22
+ it("collapses case-insensitive home prefixes on macOS-style paths", () => {
23
+ const home = "/Users/koin";
24
+ assert.equal(
25
+ collapseHomePath("/users/koin/WorkSpace/proj/.agents/skills/a/SKILL.md", home),
26
+ "~/WorkSpace/proj/.agents/skills/a/SKILL.md",
27
+ );
28
+ });
29
+
30
+ it("leaves non-home paths unchanged", () => {
31
+ assert.equal(collapseHomePath("/opt/skills/x/SKILL.md", "/Users/koin"), "/opt/skills/x/SKILL.md");
32
+ });
33
+ });
34
+
35
+ describe("resolveSkillMdPath / finalizeSkillPaths", () => {
36
+ it("finds nested category skills and collapses home", () => {
37
+ const root = mkdtempSync(join(tmpdir(), "tool-usage-skills-"));
38
+ try {
39
+ const skillDir = join(root, "info", "zhihu");
40
+ mkdirSync(skillDir, { recursive: true });
41
+ writeFileSync(join(skillDir, "SKILL.md"), "# zhihu\n");
42
+
43
+ const abs = resolveSkillMdPath("zhihu", [join(root)]);
44
+ assert.equal(abs, join(skillDir, "SKILL.md"));
45
+
46
+ const [item] = finalizeSkillPaths(
47
+ [{ skillName: "zhihu", skillPath: null }],
48
+ [join(root)],
49
+ root,
50
+ );
51
+ assert.equal(item?.skillPath, "~/info/zhihu/SKILL.md");
52
+ } finally {
53
+ rmSync(root, { recursive: true, force: true });
54
+ }
55
+ });
56
+ });
@@ -0,0 +1,85 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { createKeyedTtlCache } from "./ttl-cache.ts";
4
+
5
+ /** Expand a leading `~` / `~/…` to an absolute path under `homeDir`. */
6
+ export function expandHomePath(path: string, homeDir: string): string {
7
+ const trimmed = path.trim();
8
+ if (trimmed === "~") return homeDir;
9
+ if (trimmed.startsWith("~/")) return join(homeDir, trimmed.slice(2));
10
+ return trimmed;
11
+ }
12
+
13
+ /** Collapse `homeDir` prefix to `~` so RPC/UI never expose `/Users/…`. */
14
+ export function collapseHomePath(path: string, homeDir: string): string {
15
+ const trimmed = path.trim();
16
+ if (!trimmed || !homeDir) return trimmed;
17
+ if (trimmed === homeDir) return "~";
18
+ const prefix = homeDir.endsWith("/") ? homeDir : `${homeDir}/`;
19
+ if (trimmed.startsWith(prefix)) {
20
+ return `~/${trimmed.slice(prefix.length)}`;
21
+ }
22
+ // Case-insensitive match (macOS default FS); preserve the remainder as-is.
23
+ const lower = trimmed.toLowerCase();
24
+ const homeLower = homeDir.toLowerCase();
25
+ if (lower === homeLower) return "~";
26
+ const prefixLower = homeLower.endsWith("/") ? homeLower : `${homeLower}/`;
27
+ if (lower.startsWith(prefixLower)) {
28
+ return `~/${trimmed.slice(prefixLower.length)}`;
29
+ }
30
+ return trimmed;
31
+ }
32
+
33
+ const rootListingCache = createKeyedTtlCache<string[]>(30_000);
34
+
35
+ function listRootEntries(root: string): string[] {
36
+ return rootListingCache.get(root, () => {
37
+ try {
38
+ return readdirSync(root);
39
+ } catch {
40
+ return [];
41
+ }
42
+ });
43
+ }
44
+
45
+ /** Find `<name>/SKILL.md` under skill roots (direct or one category level). */
46
+ export function resolveSkillMdPath(
47
+ skillName: string,
48
+ roots: readonly string[],
49
+ ): string | null {
50
+ const name = skillName.trim();
51
+ if (!name) return null;
52
+ for (const root of roots) {
53
+ const direct = join(root, name, "SKILL.md");
54
+ if (existsSync(direct)) return direct;
55
+ for (const entry of listRootEntries(root)) {
56
+ const nested = join(root, entry, name, "SKILL.md");
57
+ if (existsSync(nested)) return nested;
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** Fill missing skillPath values by scanning local skill roots. */
64
+ export function fillMissingSkillPaths<T extends { skillName: string; skillPath: string | null }>(
65
+ items: T[],
66
+ roots: readonly string[],
67
+ ): T[] {
68
+ return items.map((item) => {
69
+ if (item.skillPath) return item;
70
+ const skillPath = resolveSkillMdPath(item.skillName, roots);
71
+ return skillPath ? { ...item, skillPath } : item;
72
+ });
73
+ }
74
+
75
+ /** Resolve missing paths, then collapse homeDir → `~` on every skillPath. */
76
+ export function finalizeSkillPaths<T extends { skillName: string; skillPath: string | null }>(
77
+ items: T[],
78
+ roots: readonly string[],
79
+ homeDir: string,
80
+ ): T[] {
81
+ return fillMissingSkillPaths(items, roots).map((item) => ({
82
+ ...item,
83
+ skillPath: item.skillPath ? collapseHomePath(item.skillPath, homeDir) : null,
84
+ }));
85
+ }