paseo-recap 0.2.5 → 0.3.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.
package/paseo-plugin.json CHANGED
@@ -2,6 +2,6 @@
2
2
  "id": "paseo-recap",
3
3
  "description": "Writes a short recap of each agent's goal, progress, and next step after every turn, like Claude Code's session recap.",
4
4
  "requirements": {
5
- "paseo": ">=0.10.3"
5
+ "paseo": ">=0.16.0"
6
6
  }
7
7
  }
@@ -1,8 +1,10 @@
1
- import type { PluginHookContext, PluginLifecycleEvents } from "@getpaseo/plugin/server";
1
+ import type { PluginHookContext } from "@getpaseo/plugin/server";
2
2
 
3
3
  // Paseo resolves only its plugin SDK when it builds a plugin, so `@getpaseo/client` and
4
4
  // `@getpaseo/protocol` cannot be imported, even for types. These come from the SDK instead.
5
5
 
6
6
  export type PaseoApi = PluginHookContext["paseo"];
7
- export type AgentTimelineItem = PluginLifecycleEvents["agent.turn_ended"]["timeline"][number];
7
+ type AgentHandle = ReturnType<PaseoApi["agents"]["ref"]>;
8
+ type Timeline = Awaited<ReturnType<AgentHandle["timeline"]["refetch"]>>;
9
+ export type AgentTimelineItem = Timeline["entries"][number]["item"];
8
10
  export type ProviderSnapshotEntry = Awaited<ReturnType<PaseoApi["providers"]["snapshot"]>>["entries"][number];
package/server/process.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawnProcess, terminateProcess } from "@getpaseo/plugin/server";
2
2
  import { abortError, GeneratorUnavailableError } from "./errors";
3
3
 
4
4
  const OUTPUT_LIMIT_BYTES = 1024 * 1024;
@@ -32,29 +32,46 @@ export function sanitizeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
32
32
  return clean;
33
33
  }
34
34
 
35
+ function collectOutput(stream: NodeJS.ReadableStream): () => string {
36
+ const chunks: Buffer[] = [];
37
+ let bytes = 0;
38
+ stream.on("data", (chunk: Buffer) => {
39
+ const remaining = OUTPUT_LIMIT_BYTES - bytes;
40
+ if (remaining === 0) return;
41
+ const kept = chunk.subarray(0, remaining);
42
+ chunks.push(kept);
43
+ bytes += kept.length;
44
+ });
45
+ return () => Buffer.concat(chunks, bytes).toString("utf8");
46
+ }
47
+
35
48
  export const runProcess: RunProcess = (command, args, options) =>
36
49
  new Promise((resolve, reject) => {
37
50
  if (options.signal.aborted) {
38
51
  reject(abortError());
39
52
  return;
40
53
  }
41
- const child = spawn(command, args, {
54
+ const child = spawnProcess(command, [...args], {
42
55
  cwd: options.cwd,
43
56
  env: options.env,
44
- stdio: ["pipe", "pipe", "pipe"],
57
+ stdio: "pipe",
45
58
  detached: process.platform !== "win32",
46
59
  });
47
- let stdout = "";
48
- let stderr = "";
60
+ const stdout = collectOutput(child.stdout);
61
+ const stderr = collectOutput(child.stderr);
49
62
  let settled = false;
50
- const kill = () => {
51
- if (child.pid === undefined || child.exitCode !== null) return;
52
- try {
53
- // Negative pid targets the process group so CLI helpers die too.
54
- process.kill(process.platform === "win32" ? child.pid : -child.pid, "SIGTERM");
55
- } catch {
56
- child.kill("SIGTERM");
63
+ const kill = async () => {
64
+ if (child.pid === undefined) return;
65
+ if (process.platform !== "win32") {
66
+ try {
67
+ // On POSIX the SDK signals only the child, so signal its detached group first.
68
+ process.kill(-child.pid, "SIGTERM");
69
+ return;
70
+ } catch {
71
+ // The group can exit before the signal is sent.
72
+ }
57
73
  }
74
+ await terminateProcess(child, "SIGTERM");
58
75
  };
59
76
  const finish = (outcome: () => void) => {
60
77
  if (settled) return;
@@ -63,23 +80,18 @@ export const runProcess: RunProcess = (command, args, options) =>
63
80
  options.signal.removeEventListener("abort", onAbort);
64
81
  outcome();
65
82
  };
66
- const onAbort = () => {
67
- kill();
68
- finish(() => reject(abortError()));
83
+ const stop = (reason: Error) => {
84
+ finish(() => {
85
+ void kill().catch((error: unknown) => {
86
+ console.error("[paseo-recap] failed to terminate CLI", error);
87
+ }).finally(() => reject(reason));
88
+ });
69
89
  };
90
+ const onAbort = () => stop(abortError());
70
91
  const timer = setTimeout(() => {
71
- kill();
72
- finish(() => reject(new Error(`${command} timed out after ${options.timeoutMs} ms`)));
92
+ stop(new Error(`${command} timed out after ${options.timeoutMs} ms`));
73
93
  }, options.timeoutMs);
74
94
  options.signal.addEventListener("abort", onAbort, { once: true });
75
- child.stdout.setEncoding("utf8");
76
- child.stderr.setEncoding("utf8");
77
- child.stdout.on("data", (chunk: string) => {
78
- if (stdout.length < OUTPUT_LIMIT_BYTES) stdout += chunk;
79
- });
80
- child.stderr.on("data", (chunk: string) => {
81
- if (stderr.length < OUTPUT_LIMIT_BYTES) stderr += chunk;
82
- });
83
95
  child.on("error", (error: NodeJS.ErrnoException) => {
84
96
  finish(() =>
85
97
  reject(
@@ -89,7 +101,7 @@ export const runProcess: RunProcess = (command, args, options) =>
89
101
  ),
90
102
  );
91
103
  });
92
- child.on("close", (code) => finish(() => resolve({ code, stdout, stderr })));
104
+ child.on("close", (code) => finish(() => resolve({ code, stdout: stdout(), stderr: stderr() })));
93
105
  child.stdin.on("error", () => undefined);
94
106
  child.stdin.end(options.stdin);
95
107
  });
@@ -0,0 +1,39 @@
1
+ import type { RecapEvent, RecapView } from "../shared/recap";
2
+
3
+ export function createRecapStream() {
4
+ const subscribers = new Set<(event: RecapEvent) => void>();
5
+
6
+ function subscribe(
7
+ snapshot: () => RecapView[],
8
+ push: (event: RecapEvent) => Promise<void>,
9
+ signal: AbortSignal,
10
+ ): Promise<void> {
11
+ if (signal.aborted) return Promise.resolve();
12
+ return new Promise((resolve, reject) => {
13
+ const close = () => {
14
+ subscribers.delete(send);
15
+ signal.removeEventListener("abort", onAbort);
16
+ };
17
+ const onAbort = () => {
18
+ close();
19
+ resolve();
20
+ };
21
+ const send = (event: RecapEvent) => {
22
+ void push(event).catch((error: unknown) => {
23
+ close();
24
+ reject(error);
25
+ });
26
+ };
27
+ const initial = snapshot();
28
+ signal.addEventListener("abort", onAbort, { once: true });
29
+ subscribers.add(send);
30
+ send({ type: "snapshot", recaps: initial });
31
+ });
32
+ }
33
+
34
+ function update(view: RecapView): void {
35
+ for (const send of subscribers) send({ type: "update", view });
36
+ }
37
+
38
+ return { subscribe, update };
39
+ }
@@ -40,7 +40,7 @@ export interface RecapStoreLike {
40
40
  all(): StoredRecap[];
41
41
  set(recap: StoredRecap): Promise<void>;
42
42
  markStale(agentId: string): Promise<void>;
43
- delete(agentId: string): Promise<void>;
43
+ delete(agentId: string, metadata: PluginHookAgent["metadata"]): Promise<void>;
44
44
  }
45
45
 
46
46
  export interface SchedulerDeps {
@@ -51,6 +51,7 @@ export interface SchedulerDeps {
51
51
  fetchAgentContext(agentId: string): Promise<AgentContext>;
52
52
  /** Shows a newly stored recap in the agent's conversation. */
53
53
  publish(recap: StoredRecap): Promise<void>;
54
+ onChange(view: RecapView): void;
54
55
  log(message: string, detail?: unknown): void;
55
56
  }
56
57
 
@@ -62,6 +63,7 @@ interface AgentEntry {
62
63
  workspaceId: string | null;
63
64
  provider: string | null;
64
65
  title: string | null;
66
+ background: boolean;
65
67
  /** Incremented on every turn start; a recap is only kept for the revision it started on. */
66
68
  revision: number;
67
69
  running: boolean;
@@ -103,11 +105,17 @@ export class RecapScheduler {
103
105
  entry.pendingPermissions.clear();
104
106
  entry.lastTurnCompleted = false;
105
107
  entry.failures = 0;
106
- entry.error = null;
107
- entry.state = "idle";
108
108
  this.#cancel(entry);
109
- void this.#deps.store.markStale(entry.id);
110
- if (entry.parentAgentId) this.#entryById(entry.parentAgentId).runningChildren.add(entry.id);
109
+ this.#setState(entry, "idle", null);
110
+ const previous = this.#deps.store.get(entry.id);
111
+ void this.#deps.store.markStale(entry.id).then(() => {
112
+ if (previous !== this.#deps.store.get(entry.id)) this.#notify(entry.id);
113
+ }).catch((error: unknown) => {
114
+ this.#deps.log(`could not mark recap stale for agent ${entry.id}`, errorMessage(error));
115
+ });
116
+ if (!entry.background && entry.parentAgentId) {
117
+ this.#entryById(entry.parentAgentId).runningChildren.add(entry.id);
118
+ }
111
119
  }
112
120
 
113
121
  async turnEnded(agent: PluginHookAgent, outcome: PluginTurnOutcome): Promise<void> {
@@ -116,7 +124,7 @@ export class RecapScheduler {
116
124
  entry.runningSince = null;
117
125
  entry.lastTurnCompleted = outcome.kind === "completed";
118
126
  if (entry.lastTurnCompleted && entry.turnsSinceRecap !== null) entry.turnsSinceRecap++;
119
- if (entry.parentAgentId) {
127
+ if (!entry.background && entry.parentAgentId) {
120
128
  const parent = this.#entryById(entry.parentAgentId);
121
129
  parent.runningChildren.delete(entry.id);
122
130
  // The parent may have been waiting only for this child.
@@ -129,7 +137,7 @@ export class RecapScheduler {
129
137
  const entry = this.#entry(agent);
130
138
  entry.pendingPermissions.add(requestId);
131
139
  this.#clearTimer(entry);
132
- if (entry.state === "waiting") entry.state = "idle";
140
+ if (entry.state === "waiting") this.#setState(entry, "idle");
133
141
  }
134
142
 
135
143
  async permissionResolved(agent: PluginHookAgent, requestId: string): Promise<void> {
@@ -146,7 +154,8 @@ export class RecapScheduler {
146
154
  this.#entries.delete(agent.id);
147
155
  }
148
156
  if (agent.parentAgentId) this.#entries.get(agent.parentAgentId)?.runningChildren.delete(agent.id);
149
- await this.#deps.store.delete(agent.id);
157
+ await this.#deps.store.delete(agent.id, agent.metadata);
158
+ this.#notify(agent.id);
150
159
  }
151
160
 
152
161
  /** Manual recap: bypasses delay, frequency, and opt-out, but never runs during a turn. */
@@ -166,8 +175,7 @@ export class RecapScheduler {
166
175
  return this.view(agentId);
167
176
  }
168
177
  this.#clearTimer(entry);
169
- entry.error = null;
170
- entry.state = "generating";
178
+ this.#setState(entry, "generating", null);
171
179
  await this.#run(entry, "manual");
172
180
  return this.view(agentId);
173
181
  }
@@ -193,6 +201,17 @@ export class RecapScheduler {
193
201
  return [...ids].map((id) => this.view(id));
194
202
  }
195
203
 
204
+ #notify(agentId: string): void {
205
+ if (!this.#disposed) this.#deps.onChange(this.view(agentId));
206
+ }
207
+
208
+ #setState(entry: AgentEntry, state: RecapState, error = entry.error): void {
209
+ if (entry.state === state && entry.error === error) return;
210
+ entry.state = state;
211
+ entry.error = error;
212
+ this.#notify(entry.id);
213
+ }
214
+
196
215
  dispose(): void {
197
216
  this.#disposed = true;
198
217
  for (const entry of this.#entries.values()) this.#cancel(entry);
@@ -207,7 +226,7 @@ export class RecapScheduler {
207
226
  }
208
227
  this.#clearTimer(entry);
209
228
  const revision = entry.revision;
210
- entry.state = "waiting";
229
+ this.#setState(entry, "waiting");
211
230
  entry.timer = setTimeout(() => {
212
231
  entry.timer = null;
213
232
  void this.#fire(entry, revision);
@@ -219,7 +238,7 @@ export class RecapScheduler {
219
238
  // Re-check: settings, permissions, or children may have changed during the delay.
220
239
  const settings = await this.#deps.readSettings();
221
240
  if (!this.#eligible(entry, settings)) {
222
- if (entry.state === "waiting") entry.state = entry.error ? "error" : "idle";
241
+ if (entry.state === "waiting") this.#setState(entry, entry.error ? "error" : "idle");
223
242
  this.#recheckAfterChildBlock(entry, settings);
224
243
  return;
225
244
  }
@@ -231,7 +250,8 @@ export class RecapScheduler {
231
250
  * event marks that deadline, so check again when it passes.
232
251
  */
233
252
  #recheckAfterChildBlock(entry: AgentEntry, settings: RecapSettings): void {
234
- if (!settings.waitForSubagents || entry.timer || !this.#hasBlockingChild(entry)) return;
253
+ if (this.#disposed || this.#entries.get(entry.id) !== entry) return;
254
+ if (!settings.waitForSubagents || entry.background || entry.timer || !this.#hasBlockingChild(entry)) return;
235
255
  const now = Date.now();
236
256
  let blockEndsAt = now;
237
257
  for (const childId of entry.runningChildren) {
@@ -245,7 +265,7 @@ export class RecapScheduler {
245
265
  }
246
266
 
247
267
  #eligible(entry: AgentEntry, settings: RecapSettings): boolean {
248
- if (this.#disposed || !settings.autoRecap) return false;
268
+ if (this.#disposed || this.#entries.get(entry.id) !== entry || entry.background || !settings.autoRecap) return false;
249
269
  if (entry.parentAgentId && !settings.includeSubagents) return false;
250
270
  if (entry.running || !entry.lastTurnCompleted || entry.inFlight) return false;
251
271
  if (entry.pendingPermissions.size > 0) return false;
@@ -268,8 +288,7 @@ export class RecapScheduler {
268
288
  const revision = entry.revision;
269
289
  const manual = trigger === "manual";
270
290
  const skip = (error: string | null) => {
271
- entry.state = "idle";
272
- entry.error = manual ? error : null;
291
+ this.#setState(entry, "idle", manual ? error : null);
273
292
  };
274
293
  try {
275
294
  const [settings, agent] = await Promise.all([
@@ -290,8 +309,7 @@ export class RecapScheduler {
290
309
  const context = { goal: entry.title, activeTask: latestActiveTask(agent.timeline) };
291
310
  const history = buildRecapHistory(agent.timeline, historyBudget(context), settings.historyExchanges);
292
311
  if (history === "") return skip("There is no conversation to recap yet.");
293
- entry.state = "generating";
294
- entry.error = null;
312
+ this.#setState(entry, "generating", null);
295
313
  const generated = await this.#deps.generate(renderPrompt(history, context), abort.signal, {
296
314
  agentProvider: entry.provider,
297
315
  trigger,
@@ -311,9 +329,10 @@ export class RecapScheduler {
311
329
  agent: { title: entry.title, workspaceId: entry.workspaceId, provider: entry.provider },
312
330
  };
313
331
  await this.#deps.store.set(recap);
332
+ if (abort.signal.aborted || entry.revision !== revision || this.#disposed) return;
314
333
  entry.failures = 0;
315
334
  entry.turnsSinceRecap = 0;
316
- entry.state = "idle";
335
+ this.#setState(entry, "idle");
317
336
  await this.#deps.publish(recap).catch((error: unknown) => {
318
337
  this.#deps.log(`could not show recap for agent ${entry.id}`, errorMessage(error));
319
338
  });
@@ -321,20 +340,18 @@ export class RecapScheduler {
321
340
  if (abort.signal.aborted || entry.revision !== revision) return;
322
341
  if (error instanceof RecapSkippedError) {
323
342
  // Deliberate skip (usage limits): not a failure, nothing to retry or show.
324
- entry.state = "idle";
343
+ this.#setState(entry, "idle");
325
344
  this.#deps.log(`recap skipped for agent ${entry.id}`, error.message);
326
345
  return;
327
346
  }
328
347
  if (error instanceof NoGeneratorError) {
329
348
  // Retrying cannot help until the user fixes their setup; stop for this turn.
330
349
  entry.failures = MAX_CONSECUTIVE_FAILURES;
331
- entry.state = "error";
332
- entry.error = NO_GENERATOR;
350
+ this.#setState(entry, "error", NO_GENERATOR);
333
351
  return;
334
352
  }
335
353
  entry.failures++;
336
- entry.state = "error";
337
- entry.error = GENERIC_FAILURE;
354
+ this.#setState(entry, "error", GENERIC_FAILURE);
338
355
  this.#deps.log(`recap failed for agent ${entry.id}`, errorMessage(error));
339
356
  // Release the in-flight slot first; eligibility rejects agents with work in flight.
340
357
  if (entry.inFlight?.abort === abort) entry.inFlight = null;
@@ -372,6 +389,7 @@ export class RecapScheduler {
372
389
  entry.workspaceId = agent.workspaceId ?? entry.workspaceId;
373
390
  entry.provider = agent.provider;
374
391
  entry.title = agent.title ?? entry.title;
392
+ entry.background = agent.background;
375
393
  return entry;
376
394
  }
377
395
 
@@ -384,6 +402,7 @@ export class RecapScheduler {
384
402
  workspaceId: null,
385
403
  provider: null,
386
404
  title: null,
405
+ background: false,
387
406
  revision: 0,
388
407
  running: false,
389
408
  runningSince: null,
package/server/store.ts CHANGED
@@ -1,111 +1,183 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { dirname } from "node:path";
1
+ import { readFile, rename } from "node:fs/promises";
3
2
  import { z } from "zod";
4
3
  import { StoredRecapSchema, type StoredRecap } from "../shared/recap";
5
4
  import { errorMessage } from "./errors";
6
5
  import { parseJson } from "./json";
6
+ import type { PaseoApi } from "./paseo-types";
7
7
 
8
- /** Earlier recaps kept per agent besides the latest (OMP journals every recap; we keep a few). */
8
+ const METADATA_KEY = "paseo-recap";
9
+ /** Earlier recaps kept per agent besides the latest. */
9
10
  export const PREVIOUS_RECAPS_KEPT = 4;
10
- /** Recaps of agents not seen for this long are dropped on load (e.g. deleted without archiving). */
11
+ /** Recaps older than this are dropped when the plugin starts. */
11
12
  export const RECAP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
12
13
 
13
14
  const AgentRecapsSchema = z.object({
14
15
  latest: StoredRecapSchema,
15
16
  previous: z.array(StoredRecapSchema).default([]),
16
17
  });
17
- type AgentRecaps = z.output<typeof AgentRecapsSchema>;
18
+ const RecapMetadataSchema = AgentRecapsSchema.extend({ version: z.literal(1) });
19
+ type RecapMetadata = z.output<typeof RecapMetadataSchema>;
18
20
 
19
21
  const StoreFileSchema = z.object({
20
22
  version: z.literal(1),
21
23
  agents: z.record(z.string(), AgentRecapsSchema),
22
24
  });
23
25
 
24
- /** Latest recaps per agent, persisted as one JSON file under the user's Paseo home. */
26
+ type AgentActions = PaseoApi["agents"];
27
+ type AgentHandle = ReturnType<AgentActions["ref"]>;
28
+ type AgentList = Awaited<ReturnType<AgentActions["list"]>>;
29
+ type StoreAgent = Pick<AgentList["entries"][number]["agent"], "id" | "metadata">;
30
+ type RecapAgents = {
31
+ list(options: Parameters<AgentActions["list"]>[0]): Promise<{
32
+ entries: readonly { agent: StoreAgent }[];
33
+ pageInfo: Pick<AgentList["pageInfo"], "nextCursor">;
34
+ }>;
35
+ ref(agentId: string): Pick<AgentHandle, "setMetadata"> & {
36
+ refresh(): Promise<{ agent: StoreAgent } | null>;
37
+ };
38
+ };
39
+
40
+ /** Recaps remain available in memory when the daemon cannot save their metadata. */
25
41
  export class RecapStore {
26
- readonly #path: string;
42
+ readonly #agents: () => RecapAgents;
43
+ readonly #legacyPath: string;
27
44
  readonly #log: (message: string, detail?: unknown) => void;
28
- #agents = new Map<string, AgentRecaps>();
29
- #writeChain: Promise<void> = Promise.resolve();
45
+ readonly #recaps = new Map<string, RecapMetadata>();
46
+ readonly #writes = new Map<string, Promise<void>>();
47
+ // A recovery scan must account for turns and archives that happened before it finished.
48
+ #activityBeforeLoad: Map<string, "stale" | "archived"> | null = new Map();
30
49
 
31
- constructor(path: string, log: (message: string, detail?: unknown) => void) {
32
- this.#path = path;
50
+ constructor(agents: () => RecapAgents, legacyPath: string, log: (message: string, detail?: unknown) => void) {
51
+ this.#agents = agents;
52
+ this.#legacyPath = legacyPath;
33
53
  this.#log = log;
34
54
  }
35
55
 
36
- async load(now = Date.now()): Promise<void> {
37
- let text: string;
38
- try {
39
- text = await readFile(this.#path, "utf8");
40
- } catch (error) {
41
- if (isErrno(error, "ENOENT")) return;
42
- throw error;
43
- }
44
- const parsed = StoreFileSchema.safeParse(parseJson(text));
45
- if (!parsed.success) {
46
- this.#log("recap store is unreadable; starting empty", this.#path);
47
- return;
48
- }
49
- this.#agents = new Map(Object.entries(parsed.data.agents));
50
- let pruned = false;
51
- for (const [agentId, recaps] of this.#agents) {
52
- if (now - Date.parse(recaps.latest.generatedAt) > RECAP_RETENTION_MS) {
53
- this.#agents.delete(agentId);
54
- pruned = true;
56
+ async load(now = Date.now()): Promise<string[]> {
57
+ const agents = this.#agents();
58
+ await this.#migrate(agents);
59
+ const recaps = new Map<string, RecapMetadata>();
60
+ let cursor: string | undefined;
61
+ do {
62
+ // A metadata write changes updatedAt, so paginate using a stable sort.
63
+ const { entries, pageInfo } = await agents.list({
64
+ scope: "active",
65
+ sort: [{ key: "created_at", direction: "asc" }],
66
+ page: { limit: 200, cursor },
67
+ });
68
+ for (const { agent } of entries) {
69
+ const parsed = RecapMetadataSchema.safeParse(agent.metadata?.[METADATA_KEY]);
70
+ if (!parsed.success || parsed.data.latest.agentId !== agent.id) continue;
71
+ if (now - Date.parse(parsed.data.latest.generatedAt) > RECAP_RETENTION_MS) {
72
+ if (!this.#recaps.has(agent.id) && this.#activityBeforeLoad?.get(agent.id) !== "archived") {
73
+ await this.#persist(agent.id, null);
74
+ }
75
+ continue;
76
+ }
77
+ recaps.set(agent.id, parsed.data);
55
78
  }
79
+ cursor = pageInfo.nextCursor ?? undefined;
80
+ } while (cursor);
81
+ const restored: string[] = [];
82
+ for (const [agentId, recap] of recaps) {
83
+ const activity = this.#activityBeforeLoad?.get(agentId);
84
+ if (this.#recaps.has(agentId) || activity === "archived") continue;
85
+ this.#recaps.set(agentId, recap);
86
+ if (activity === "stale") void this.markStale(agentId);
87
+ restored.push(agentId);
56
88
  }
57
- if (pruned) await this.#persist();
89
+ this.#activityBeforeLoad = null;
90
+ return restored;
58
91
  }
59
92
 
60
93
  get(agentId: string): StoredRecap | null {
61
- return this.#agents.get(agentId)?.latest ?? null;
94
+ return this.#recaps.get(agentId)?.latest ?? null;
62
95
  }
63
96
 
64
97
  previous(agentId: string): StoredRecap[] {
65
- return this.#agents.get(agentId)?.previous ?? [];
98
+ return this.#recaps.get(agentId)?.previous ?? [];
66
99
  }
67
100
 
68
101
  all(): StoredRecap[] {
69
- return [...this.#agents.values()].map((recaps) => recaps.latest);
102
+ return [...this.#recaps.values()].map((recaps) => recaps.latest);
70
103
  }
71
104
 
72
105
  set(recap: StoredRecap): Promise<void> {
73
- const existing = this.#agents.get(recap.agentId);
74
- const previous = existing
75
- ? [{ ...existing.latest, stale: true }, ...existing.previous].slice(0, PREVIOUS_RECAPS_KEPT)
76
- : [];
77
- this.#agents.set(recap.agentId, { latest: recap, previous });
78
- return this.#persist();
106
+ return this.#update(recap.agentId, (existing) => ({
107
+ version: 1,
108
+ latest: recap,
109
+ previous: existing
110
+ ? [{ ...existing.latest, stale: true }, ...existing.previous].slice(0, PREVIOUS_RECAPS_KEPT)
111
+ : [],
112
+ }));
79
113
  }
80
114
 
81
115
  markStale(agentId: string): Promise<void> {
82
- const recaps = this.#agents.get(agentId);
83
- if (!recaps || recaps.latest.stale) return Promise.resolve();
84
- this.#agents.set(agentId, { ...recaps, latest: { ...recaps.latest, stale: true } });
85
- return this.#persist();
116
+ if (this.#activityBeforeLoad && !this.#activityBeforeLoad.has(agentId)) {
117
+ this.#activityBeforeLoad.set(agentId, "stale");
118
+ }
119
+ return this.#update(agentId, (recaps) =>
120
+ recaps && !recaps.latest.stale ? { ...recaps, latest: { ...recaps.latest, stale: true } } : recaps,
121
+ );
86
122
  }
87
123
 
88
- delete(agentId: string): Promise<void> {
89
- if (!this.#agents.delete(agentId)) return Promise.resolve();
90
- return this.#persist();
124
+ delete(agentId: string, metadata?: StoreAgent["metadata"]): Promise<void> {
125
+ this.#activityBeforeLoad?.set(agentId, "archived");
126
+ return this.#update(agentId, () => undefined, metadata?.[METADATA_KEY] !== undefined);
127
+ }
128
+
129
+ #update(
130
+ agentId: string,
131
+ change: (current?: RecapMetadata) => RecapMetadata | undefined,
132
+ force = false,
133
+ ): Promise<void> {
134
+ const current = this.#recaps.get(agentId);
135
+ const next = change(current);
136
+ if (!force && next === current) return Promise.resolve();
137
+ if (next) this.#recaps.set(agentId, next);
138
+ else this.#recaps.delete(agentId);
139
+ return this.#persist(agentId, next ?? null).catch((error: unknown) => {
140
+ this.#log(`could not save recap metadata for agent ${agentId}`, errorMessage(error));
141
+ });
91
142
  }
92
143
 
93
- /** Serializes writes; each write replaces the file atomically via rename. */
94
- #persist(): Promise<void> {
95
- const snapshot = JSON.stringify({ version: 1, agents: Object.fromEntries(this.#agents) });
144
+ #persist(agentId: string, recap: RecapMetadata | null): Promise<void> {
96
145
  const write = async () => {
97
- await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
98
- const temp = `${this.#path}.${process.pid}.tmp`;
99
- await writeFile(temp, snapshot, { mode: 0o600 });
100
- await rename(temp, this.#path);
146
+ await this.#agents().ref(agentId).setMetadata({ [METADATA_KEY]: recap });
101
147
  };
102
- this.#writeChain = this.#writeChain.then(write, write);
103
- return this.#writeChain.catch((error: unknown) => {
104
- this.#log("failed to persist recaps", errorMessage(error));
105
- });
148
+ const previous = this.#writes.get(agentId);
149
+ const result = previous ? previous.then(write, write) : write();
150
+ this.#writes.set(agentId, result);
151
+ const clear = () => {
152
+ if (this.#writes.get(agentId) === result) this.#writes.delete(agentId);
153
+ };
154
+ void result.then(clear, clear);
155
+ return result;
106
156
  }
107
- }
108
157
 
109
- function isErrno(error: unknown, code: string): boolean {
110
- return typeof error === "object" && error !== null && "code" in error && error.code === code;
158
+ async #migrate(agents: RecapAgents): Promise<void> {
159
+ let text: string;
160
+ try {
161
+ text = await readFile(this.#legacyPath, "utf8");
162
+ } catch (error) {
163
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
164
+ throw error;
165
+ }
166
+ const parsed = StoreFileSchema.safeParse(parseJson(text));
167
+ if (!parsed.success) {
168
+ this.#log("legacy recap file is unreadable", this.#legacyPath);
169
+ return;
170
+ }
171
+ for (const [agentId, recaps] of Object.entries(parsed.data.agents)) {
172
+ const handle = agents.ref(agentId);
173
+ const result = await handle.refresh();
174
+ if (result?.agent.id !== agentId || result.agent.metadata?.[METADATA_KEY] !== undefined ||
175
+ this.#activityBeforeLoad?.get(agentId) === "archived") continue;
176
+ await this.#persist(agentId, this.#recaps.get(agentId) ?? {
177
+ version: 1, latest: recaps.latest, previous: recaps.previous.slice(0, PREVIOUS_RECAPS_KEPT),
178
+ });
179
+ }
180
+ // Preserve the source if any read or write failed. Already migrated entries are skipped on retry.
181
+ await rename(this.#legacyPath, `${this.#legacyPath}.migrated`);
182
+ }
111
183
  }
package/shared/recap.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { defineRpc, defineSettings } from "@getpaseo/plugin";
1
+ import { defineRpc, defineSettings, defineSubscription } from "@getpaseo/plugin";
2
2
  import { z } from "zod";
3
3
 
4
4
  // Providers ------------------------------------------------------------------------------------
@@ -143,6 +143,16 @@ export const recapListRpc = defineRpc({
143
143
  output: z.object({ recaps: z.array(RecapViewSchema) }),
144
144
  });
145
145
 
146
+ export const recapSubscription = defineSubscription({
147
+ name: "recap.watch",
148
+ input: z.object({}),
149
+ event: z.discriminatedUnion("type", [
150
+ z.object({ type: z.literal("snapshot"), recaps: z.array(RecapViewSchema) }),
151
+ z.object({ type: z.literal("update"), view: RecapViewSchema }),
152
+ ]),
153
+ });
154
+ export type RecapEvent = z.output<typeof recapSubscription.event>;
155
+
146
156
  export const recapRegenerateRpc = defineRpc({
147
157
  name: "recap.regenerate",
148
158
  input: z.object({ agentId: z.string().min(1) }),