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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-recap",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "Writes a short recap of each agent's goal, progress, and next step after every turn, like Claude Code's session recap.",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -19,9 +19,9 @@
19
19
  "test": "vitest run"
20
20
  },
21
21
  "devDependencies": {
22
- "@getpaseo/client": "^0.10.3",
23
- "@getpaseo/plugin": "0.10.3",
24
- "@getpaseo/protocol": "^0.10.3",
22
+ "@getpaseo/client": "0.17.5",
23
+ "@getpaseo/plugin": "0.17.5",
24
+ "@getpaseo/protocol": "0.17.5",
25
25
  "@tanstack/react-query": "^5.90.11",
26
26
  "@types/node": "^22.20.5",
27
27
  "@types/react": "~19.2.0",
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
  }
package/server/history.ts CHANGED
@@ -1,17 +1,5 @@
1
- import { SETTING_RANGES } from "../shared/recap";
2
1
  import type { AgentTimelineItem } from "./paseo-types";
3
2
 
4
- /** Most exchanges a recap can read; the `historyExchanges` setting picks how many, up to this. */
5
- export const HISTORY_EXCHANGES_LIMIT = SETTING_RANGES.historyExchanges.max;
6
- /** Timeline items a recap reads; everything else is dropped before holding a timeline in memory. */
7
- const RECAP_ITEM_TYPES: ReadonlySet<AgentTimelineItem["type"]> = new Set([
8
- "user_message",
9
- "assistant_message",
10
- "error",
11
- "compaction",
12
- "todo",
13
- ]);
14
-
15
3
  const OMITTED_HISTORY = "[Earlier exchanges omitted]\n\n";
16
4
  const EXCERPT_MARKER = "\n[... excerpted ...]\n";
17
5
  const ERROR_MAX_CHARS = 300;
@@ -31,27 +19,6 @@ export function buildRecapHistory(
31
19
  return formatHistory(collectExchanges(timeline).slice(-maxExchanges), maxHistoryBytes);
32
20
  }
33
21
 
34
- /**
35
- * Keeps only what a recap can read: the text items of the last `HISTORY_EXCHANGES_LIMIT` exchanges
36
- * plus the latest todo list. Turn-ended events carry the whole conversation, including tool output,
37
- * which is too much to hold for every agent.
38
- */
39
- export function trimForRecap(timeline: readonly AgentTimelineItem[]): AgentTimelineItem[] {
40
- let seen = 0;
41
- let start = 0;
42
- for (let index = timeline.length - 1; index >= 0; index--) {
43
- const item = timeline[index];
44
- if (item?.type === "user_message" && item.text.trim() !== "" && ++seen === HISTORY_EXCHANGES_LIMIT) {
45
- start = index;
46
- break;
47
- }
48
- }
49
- const kept = timeline.slice(start).filter((item) => RECAP_ITEM_TYPES.has(item.type));
50
- if (kept.some((item) => item.type === "todo")) return kept;
51
- const latestTodo = timeline.findLast((item) => item.type === "todo");
52
- return latestTodo ? [latestTodo, ...kept] : kept;
53
- }
54
-
55
22
  /** True while the provider is compacting context; a recap would describe a moving target. */
56
23
  export function isCompacting(timeline: readonly AgentTimelineItem[]): boolean {
57
24
  const last = timeline.findLast((item) => item.type === "compaction");
@@ -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
+ }
@@ -2,7 +2,7 @@ import type { PluginHookAgent, PluginTurnOutcome } from "@getpaseo/plugin/server
2
2
  import type { RecapSettings, RecapState, RecapView, StoredRecap } from "../shared/recap";
3
3
  import { errorMessage, NoGeneratorError, RecapSkippedError } from "./errors";
4
4
  import type { GeneratedRecap } from "./generators";
5
- import { buildRecapHistory, countUserTurns, isCompacting, latestActiveTask, trimForRecap } from "./history";
5
+ import { buildRecapHistory, countUserTurns, isCompacting, latestActiveTask } from "./history";
6
6
  import type { AgentTimelineItem } from "./paseo-types";
7
7
  import { historyBudget, renderPrompt } from "./prompt";
8
8
 
@@ -40,17 +40,18 @@ 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 {
47
47
  store: RecapStoreLike;
48
48
  readSettings(): Promise<RecapSettings>;
49
49
  generate(prompt: string, signal: AbortSignal, options: GenerateOptions): Promise<GeneratedRecap>;
50
- /** Fresh timeline for manual recaps of agents this plugin has not observed yet. */
50
+ /** The conversation and live status, read right before each recap. */
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;
@@ -70,10 +72,6 @@ interface AgentEntry {
70
72
  lastTurnCompleted: boolean;
71
73
  /** Completed turns since the last stored recap; null until known (no recap observed yet). */
72
74
  turnsSinceRecap: number | null;
73
- /** User messages in the whole conversation (the kept timeline is trimmed). */
74
- userTurns: number;
75
- /** Trimmed to what a recap reads; see `trimForRecap`. */
76
- timeline: readonly AgentTimelineItem[] | null;
77
75
  pendingPermissions: Set<string>;
78
76
  runningChildren: Set<string>;
79
77
  timer: ReturnType<typeof setTimeout> | null;
@@ -107,26 +105,26 @@ export class RecapScheduler {
107
105
  entry.pendingPermissions.clear();
108
106
  entry.lastTurnCompleted = false;
109
107
  entry.failures = 0;
110
- entry.error = null;
111
- entry.state = "idle";
112
108
  this.#cancel(entry);
113
- void this.#deps.store.markStale(entry.id);
114
- 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
+ }
115
119
  }
116
120
 
117
- async turnEnded(
118
- agent: PluginHookAgent,
119
- outcome: PluginTurnOutcome,
120
- timeline: readonly AgentTimelineItem[],
121
- ): Promise<void> {
121
+ async turnEnded(agent: PluginHookAgent, outcome: PluginTurnOutcome): Promise<void> {
122
122
  const entry = this.#entry(agent);
123
123
  entry.running = false;
124
124
  entry.runningSince = null;
125
- entry.timeline = trimForRecap(timeline);
126
- entry.userTurns = countUserTurns(timeline);
127
125
  entry.lastTurnCompleted = outcome.kind === "completed";
128
126
  if (entry.lastTurnCompleted && entry.turnsSinceRecap !== null) entry.turnsSinceRecap++;
129
- if (entry.parentAgentId) {
127
+ if (!entry.background && entry.parentAgentId) {
130
128
  const parent = this.#entryById(entry.parentAgentId);
131
129
  parent.runningChildren.delete(entry.id);
132
130
  // The parent may have been waiting only for this child.
@@ -139,7 +137,7 @@ export class RecapScheduler {
139
137
  const entry = this.#entry(agent);
140
138
  entry.pendingPermissions.add(requestId);
141
139
  this.#clearTimer(entry);
142
- if (entry.state === "waiting") entry.state = "idle";
140
+ if (entry.state === "waiting") this.#setState(entry, "idle");
143
141
  }
144
142
 
145
143
  async permissionResolved(agent: PluginHookAgent, requestId: string): Promise<void> {
@@ -156,7 +154,8 @@ export class RecapScheduler {
156
154
  this.#entries.delete(agent.id);
157
155
  }
158
156
  if (agent.parentAgentId) this.#entries.get(agent.parentAgentId)?.runningChildren.delete(agent.id);
159
- await this.#deps.store.delete(agent.id);
157
+ await this.#deps.store.delete(agent.id, agent.metadata);
158
+ this.#notify(agent.id);
160
159
  }
161
160
 
162
161
  /** Manual recap: bypasses delay, frequency, and opt-out, but never runs during a turn. */
@@ -176,32 +175,7 @@ export class RecapScheduler {
176
175
  return this.view(agentId);
177
176
  }
178
177
  this.#clearTimer(entry);
179
- entry.error = null;
180
- entry.state = "generating";
181
- let context: AgentContext;
182
- try {
183
- context = await this.#deps.fetchAgentContext(agentId);
184
- } catch (error) {
185
- entry.state = "error";
186
- entry.error = "Could not read the conversation.";
187
- this.#deps.log(`could not fetch timeline for agent ${agentId}`, errorMessage(error));
188
- return this.view(agentId);
189
- }
190
- entry.timeline = trimForRecap(context.timeline);
191
- entry.userTurns = countUserTurns(context.timeline);
192
- entry.title = context.title ?? entry.title;
193
- entry.workspaceId = context.workspaceId ?? entry.workspaceId;
194
- entry.provider = context.provider ?? entry.provider;
195
- // Trust the daemon's live status over hook bookkeeping, which can miss a turn's end.
196
- if (context.running) {
197
- entry.state = "idle";
198
- entry.error = "The agent is running. Try again when it is idle.";
199
- return this.view(agentId);
200
- }
201
- if (entry.running) {
202
- entry.running = false;
203
- entry.runningSince = null;
204
- }
178
+ this.#setState(entry, "generating", null);
205
179
  await this.#run(entry, "manual");
206
180
  return this.view(agentId);
207
181
  }
@@ -227,6 +201,17 @@ export class RecapScheduler {
227
201
  return [...ids].map((id) => this.view(id));
228
202
  }
229
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
+
230
215
  dispose(): void {
231
216
  this.#disposed = true;
232
217
  for (const entry of this.#entries.values()) this.#cancel(entry);
@@ -241,7 +226,7 @@ export class RecapScheduler {
241
226
  }
242
227
  this.#clearTimer(entry);
243
228
  const revision = entry.revision;
244
- entry.state = "waiting";
229
+ this.#setState(entry, "waiting");
245
230
  entry.timer = setTimeout(() => {
246
231
  entry.timer = null;
247
232
  void this.#fire(entry, revision);
@@ -253,7 +238,7 @@ export class RecapScheduler {
253
238
  // Re-check: settings, permissions, or children may have changed during the delay.
254
239
  const settings = await this.#deps.readSettings();
255
240
  if (!this.#eligible(entry, settings)) {
256
- if (entry.state === "waiting") entry.state = entry.error ? "error" : "idle";
241
+ if (entry.state === "waiting") this.#setState(entry, entry.error ? "error" : "idle");
257
242
  this.#recheckAfterChildBlock(entry, settings);
258
243
  return;
259
244
  }
@@ -265,7 +250,8 @@ export class RecapScheduler {
265
250
  * event marks that deadline, so check again when it passes.
266
251
  */
267
252
  #recheckAfterChildBlock(entry: AgentEntry, settings: RecapSettings): void {
268
- 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;
269
255
  const now = Date.now();
270
256
  let blockEndsAt = now;
271
257
  for (const childId of entry.runningChildren) {
@@ -279,14 +265,12 @@ export class RecapScheduler {
279
265
  }
280
266
 
281
267
  #eligible(entry: AgentEntry, settings: RecapSettings): boolean {
282
- if (this.#disposed || !settings.autoRecap) return false;
268
+ if (this.#disposed || this.#entries.get(entry.id) !== entry || entry.background || !settings.autoRecap) return false;
283
269
  if (entry.parentAgentId && !settings.includeSubagents) return false;
284
270
  if (entry.running || !entry.lastTurnCompleted || entry.inFlight) return false;
285
271
  if (entry.pendingPermissions.size > 0) return false;
286
272
  if (settings.waitForSubagents && this.#hasBlockingChild(entry)) return false;
287
- if (entry.failures >= MAX_CONSECUTIVE_FAILURES || !entry.timeline) return false;
288
- if (isCompacting(entry.timeline)) return false;
289
- if (entry.userTurns < settings.minTurns) return false;
273
+ if (entry.failures >= MAX_CONSECUTIVE_FAILURES) return false;
290
274
  // Without an observed recap (fresh agent or daemon restart), recap the next completed turn.
291
275
  return entry.turnsSinceRecap === null || entry.turnsSinceRecap >= settings.turnsBetweenRecaps;
292
276
  }
@@ -302,20 +286,30 @@ export class RecapScheduler {
302
286
 
303
287
  async #generate(entry: AgentEntry, trigger: Trigger, abort: AbortController): Promise<void> {
304
288
  const revision = entry.revision;
305
- const { historyExchanges } = await this.#deps.readSettings();
306
- // A turn may have started while settings loaded; it has already reset this entry.
307
- if (abort.signal.aborted || entry.revision !== revision || this.#disposed) return;
308
- const timeline = entry.timeline ?? [];
309
- const context = { goal: entry.title, activeTask: latestActiveTask(timeline) };
310
- const history = buildRecapHistory(timeline, historyBudget(context), historyExchanges);
311
- if (history === "") {
312
- entry.state = "idle";
313
- entry.error = trigger === "manual" ? "There is no conversation to recap yet." : null;
314
- return;
315
- }
316
- entry.state = "generating";
317
- entry.error = null;
289
+ const manual = trigger === "manual";
290
+ const skip = (error: string | null) => {
291
+ this.#setState(entry, "idle", manual ? error : null);
292
+ };
318
293
  try {
294
+ const [settings, agent] = await Promise.all([
295
+ this.#deps.readSettings(),
296
+ this.#deps.fetchAgentContext(entry.id),
297
+ ]);
298
+ // A turn may have started meanwhile; it has already reset this entry.
299
+ if (abort.signal.aborted || entry.revision !== revision || this.#disposed) return;
300
+ entry.title = agent.title ?? entry.title;
301
+ entry.workspaceId = agent.workspaceId ?? entry.workspaceId;
302
+ entry.provider = agent.provider ?? entry.provider;
303
+ // Trust the daemon's live status over hook bookkeeping, which can miss a turn's end.
304
+ if (agent.running) return skip("The agent is running. Try again when it is idle.");
305
+ entry.running = false;
306
+ entry.runningSince = null;
307
+ const userTurns = countUserTurns(agent.timeline);
308
+ if (!manual && (isCompacting(agent.timeline) || userTurns < settings.minTurns)) return skip(null);
309
+ const context = { goal: entry.title, activeTask: latestActiveTask(agent.timeline) };
310
+ const history = buildRecapHistory(agent.timeline, historyBudget(context), settings.historyExchanges);
311
+ if (history === "") return skip("There is no conversation to recap yet.");
312
+ this.#setState(entry, "generating", null);
319
313
  const generated = await this.#deps.generate(renderPrompt(history, context), abort.signal, {
320
314
  agentProvider: entry.provider,
321
315
  trigger,
@@ -328,16 +322,17 @@ export class RecapScheduler {
328
322
  nextAction: generated.nextAction,
329
323
  generatedAt: new Date().toISOString(),
330
324
  revision,
331
- turnCount: entry.userTurns,
325
+ turnCount: userTurns,
332
326
  stale: false,
333
327
  trigger,
334
328
  generator: { provider: generated.provider, model: generated.model },
335
329
  agent: { title: entry.title, workspaceId: entry.workspaceId, provider: entry.provider },
336
330
  };
337
331
  await this.#deps.store.set(recap);
332
+ if (abort.signal.aborted || entry.revision !== revision || this.#disposed) return;
338
333
  entry.failures = 0;
339
334
  entry.turnsSinceRecap = 0;
340
- entry.state = "idle";
335
+ this.#setState(entry, "idle");
341
336
  await this.#deps.publish(recap).catch((error: unknown) => {
342
337
  this.#deps.log(`could not show recap for agent ${entry.id}`, errorMessage(error));
343
338
  });
@@ -345,20 +340,18 @@ export class RecapScheduler {
345
340
  if (abort.signal.aborted || entry.revision !== revision) return;
346
341
  if (error instanceof RecapSkippedError) {
347
342
  // Deliberate skip (usage limits): not a failure, nothing to retry or show.
348
- entry.state = "idle";
343
+ this.#setState(entry, "idle");
349
344
  this.#deps.log(`recap skipped for agent ${entry.id}`, error.message);
350
345
  return;
351
346
  }
352
347
  if (error instanceof NoGeneratorError) {
353
348
  // Retrying cannot help until the user fixes their setup; stop for this turn.
354
349
  entry.failures = MAX_CONSECUTIVE_FAILURES;
355
- entry.state = "error";
356
- entry.error = NO_GENERATOR;
350
+ this.#setState(entry, "error", NO_GENERATOR);
357
351
  return;
358
352
  }
359
353
  entry.failures++;
360
- entry.state = "error";
361
- entry.error = GENERIC_FAILURE;
354
+ this.#setState(entry, "error", GENERIC_FAILURE);
362
355
  this.#deps.log(`recap failed for agent ${entry.id}`, errorMessage(error));
363
356
  // Release the in-flight slot first; eligibility rejects agents with work in flight.
364
357
  if (entry.inFlight?.abort === abort) entry.inFlight = null;
@@ -396,6 +389,7 @@ export class RecapScheduler {
396
389
  entry.workspaceId = agent.workspaceId ?? entry.workspaceId;
397
390
  entry.provider = agent.provider;
398
391
  entry.title = agent.title ?? entry.title;
392
+ entry.background = agent.background;
399
393
  return entry;
400
394
  }
401
395
 
@@ -408,13 +402,12 @@ export class RecapScheduler {
408
402
  workspaceId: null,
409
403
  provider: null,
410
404
  title: null,
405
+ background: false,
411
406
  revision: 0,
412
407
  running: false,
413
408
  runningSince: null,
414
409
  lastTurnCompleted: false,
415
410
  turnsSinceRecap: null,
416
- userTurns: 0,
417
- timeline: null,
418
411
  pendingPermissions: new Set(),
419
412
  runningChildren: new Set(),
420
413
  timer: null,