paseo-recap 0.2.4 → 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/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) }),