@av-pi-studio/server 0.0.107 → 0.0.109

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.
@@ -1,3 +1,4 @@
1
+ import type { AgentStreamEvent } from "@av-pi-studio/protocol";
1
2
  import type { Logger } from "../logging/logger.js";
2
3
  import type { Session } from "../ws/session.js";
3
4
  import type { HandlerRegistry } from "../ws/router.js";
@@ -37,6 +38,20 @@ export declare function seedTimeline(agentId: string, rows: import("./timeline-s
37
38
  * need to special-case a never-spawned session.
38
39
  */
39
40
  export declare function resetTimeline(agentId: string, rows: import("./timeline-store.js").TimelineRow[]): void;
41
+ /**
42
+ * Record `event` on `agentId`'s timeline and broadcast it as an `agent_stream` frame carrying the
43
+ * daemon-owned seq/timestamp. The one append-and-broadcast path for stream events: `runTurn`'s
44
+ * subscription and any operation that subscribes outside a turn (today: compaction) both use it.
45
+ */
46
+ export declare function appendStreamEvent(agentId: string, event: AgentStreamEvent, broadcast: (sessions: Iterable<Session>, message: unknown) => void, sessions: Iterable<Session>): void;
47
+ /**
48
+ * Seed `agentId`'s in-memory timeline from its provider's durable history when it has none yet (a
49
+ * restarted daemon never has one). No-op when a store exists, or when the record has no persisted
50
+ * handle / the provider has nothing to replay. Anything that is about to append to a timeline
51
+ * outside `runTurn` must call this first: the first append would otherwise create an empty store,
52
+ * and `seedTimeline` never overwrites an existing one, so history would never hydrate.
53
+ */
54
+ export declare function ensureTimelineSeeded(agentId: string, manager: AgentManager, resolveClient: (provider: string) => AgentClient): void;
40
55
  /**
41
56
  * Ensure `agentId` has a live provider session: resume from a persisted handle, or — for a
42
57
  * deferred draft that was never spawned (`record.persistence` absent; see `AgentService.handleCreate`
@@ -39,6 +39,42 @@ export function seedTimeline(agentId, rows) {
39
39
  export function resetTimeline(agentId, rows) {
40
40
  getOrCreateTimeline(agentId).replaceRows(rows);
41
41
  }
42
+ /**
43
+ * Record `event` on `agentId`'s timeline and broadcast it as an `agent_stream` frame carrying the
44
+ * daemon-owned seq/timestamp. The one append-and-broadcast path for stream events: `runTurn`'s
45
+ * subscription and any operation that subscribes outside a turn (today: compaction) both use it.
46
+ */
47
+ export function appendStreamEvent(agentId, event, broadcast, sessions) {
48
+ const row = getOrCreateTimeline(agentId).append(event);
49
+ broadcast(sessions, {
50
+ type: "session",
51
+ message: {
52
+ type: "agent_stream",
53
+ agentId,
54
+ seq: row.seq,
55
+ timestamp: row.timestamp,
56
+ event,
57
+ },
58
+ });
59
+ }
60
+ /**
61
+ * Seed `agentId`'s in-memory timeline from its provider's durable history when it has none yet (a
62
+ * restarted daemon never has one). No-op when a store exists, or when the record has no persisted
63
+ * handle / the provider has nothing to replay. Anything that is about to append to a timeline
64
+ * outside `runTurn` must call this first: the first append would otherwise create an empty store,
65
+ * and `seedTimeline` never overwrites an existing one, so history would never hydrate.
66
+ */
67
+ export function ensureTimelineSeeded(agentId, manager, resolveClient) {
68
+ if (timelinesByAgentId.has(agentId))
69
+ return;
70
+ const record = manager.get(agentId)?.record;
71
+ const handle = record?.persistence;
72
+ if (!record || !handle)
73
+ return;
74
+ const rows = resolveClient(record.provider).hydrateTimeline?.(handle) ?? [];
75
+ if (rows.length > 0)
76
+ seedTimeline(agentId, rows);
77
+ }
42
78
  /**
43
79
  * Ensure `agentId` has a live provider session: resume from a persisted handle, or — for a
44
80
  * deferred draft that was never spawned (`record.persistence` absent; see `AgentService.handleCreate`
@@ -249,17 +285,7 @@ export class AgentService {
249
285
  }
250
286
  }
251
287
  // All other events: append + broadcast.
252
- const row = timeline.append(event);
253
- this.broadcastAll(getSessions(), {
254
- type: "session",
255
- message: {
256
- type: "agent_stream",
257
- agentId,
258
- seq: row.seq,
259
- timestamp: row.timestamp,
260
- event,
261
- },
262
- });
288
+ appendStreamEvent(agentId, event, this.deps.broadcast, getSessions());
263
289
  });
264
290
  // If provider never emits a user_message, emit one ourselves.
265
291
  if (!userMessageEmitted) {
@@ -95,6 +95,8 @@ export interface AgentCompactResult {
95
95
  summary?: string;
96
96
  firstKeptEntryId?: string;
97
97
  tokensBefore?: number;
98
+ /** Pi's estimate of the context size after compaction (not persisted). */
99
+ estimatedTokensAfter?: number;
98
100
  details?: unknown;
99
101
  }
100
102
  export interface AgentForkMessage {
@@ -1,5 +1,5 @@
1
1
  import type { AgentCapabilityFlags, AgentSessionConfig, AgentStreamEvent } from "@av-pi-studio/protocol";
2
- import type { AgentClient, AgentCommandDefinition, AgentModeDefinition, AgentModelDefinition, AgentSession, CreateSessionOptions, LaunchContext, PendingPermission, PersistenceHandle, ProviderRuntimeInfo, ProviderUiRequest, ProviderUiResponse, Unsubscribe } from "../../provider-contract.js";
2
+ import type { AgentClient, AgentCommandDefinition, AgentCompactResult, AgentModeDefinition, AgentModelDefinition, AgentSession, CreateSessionOptions, LaunchContext, PendingPermission, PersistenceHandle, ProviderRuntimeInfo, ProviderUiRequest, ProviderUiResponse, Unsubscribe } from "../../provider-contract.js";
3
3
  /**
4
4
  * In-process `mock` provider (features/agent-providers.md § Provider entry — dev/test only). It
5
5
  * implements the `AgentClient`/`AgentSession` contracts in memory and emits a scripted turn. Never
@@ -9,6 +9,8 @@ export declare const MOCK_CAPABILITIES: AgentCapabilityFlags;
9
9
  export interface MockSessionOptions {
10
10
  /** Delay before a started turn completes (ms). Small but non-zero so `interrupt` can win. */
11
11
  turnDelayMs?: number;
12
+ /** How long a mock `compact()` stays in its `started` phase (ms). */
13
+ compactDelayMs?: number;
12
14
  }
13
15
  /** Exported so tests (this file's, and downstream sprint-066 task-003/004 daemon-level tests) can
14
16
  * cast a created session to reach `emitUiRequest`/`uiResponses`, which are deliberately not part
@@ -33,6 +35,7 @@ export declare class MockAgentSession implements AgentSession {
33
35
  private readonly subscribers;
34
36
  private readonly history;
35
37
  private readonly turnDelayMs;
38
+ private readonly compactDelayMs;
36
39
  private activeTurn;
37
40
  private completionTimer;
38
41
  private mode;
@@ -96,11 +99,7 @@ export declare class MockAgentSession implements AgentSession {
96
99
  total: number;
97
100
  };
98
101
  }>;
99
- compact(): Promise<{
100
- summary: string;
101
- firstKeptEntryId: string;
102
- tokensBefore: number;
103
- }>;
102
+ compact(): Promise<AgentCompactResult>;
104
103
  newSession(): Promise<{
105
104
  cancelled: boolean;
106
105
  }>;
@@ -22,6 +22,10 @@ const MOCK_MODES = [
22
22
  /** Static thinking-level list for the mock provider (sprint-070/task-001) — small enough to
23
23
  * exercise clamping in the dev daemon without mirroring Pi's full 7-level ladder. */
24
24
  const MOCK_THINKING_LEVELS = ["off", "low", "medium", "high"];
25
+ /** Long enough to see the in-progress state in `npm run dev:daemon`. */
26
+ const MOCK_COMPACT_DELAY_MS = 1500;
27
+ const MOCK_COMPACT_TOKENS_BEFORE = 168_000;
28
+ const MOCK_COMPACT_TOKENS_AFTER = 14_000;
25
29
  /** Exported so tests (this file's, and downstream sprint-066 task-003/004 daemon-level tests) can
26
30
  * cast a created session to reach `emitUiRequest`/`uiResponses`, which are deliberately not part
27
31
  * of the provider-neutral `AgentSession` contract. */
@@ -33,6 +37,7 @@ export class MockAgentSession {
33
37
  subscribers = new Set();
34
38
  history = [];
35
39
  turnDelayMs;
40
+ compactDelayMs;
36
41
  activeTurn = null;
37
42
  completionTimer = null;
38
43
  mode = "default";
@@ -51,6 +56,7 @@ export class MockAgentSession {
51
56
  constructor(config, options = {}) {
52
57
  this.config = config;
53
58
  this.turnDelayMs = options.turnDelayMs ?? 5;
59
+ this.compactDelayMs = options.compactDelayMs ?? MOCK_COMPACT_DELAY_MS;
54
60
  }
55
61
  emit(event) {
56
62
  this.history.push(event);
@@ -282,12 +288,28 @@ export class MockAgentSession {
282
288
  tokens: { total: 0 },
283
289
  });
284
290
  }
285
- compact() {
286
- return Promise.resolve({
291
+ async compact() {
292
+ const compactionId = randomUUID();
293
+ this.emit({ kind: "compaction", compactionId, phase: "started", reason: "manual" });
294
+ const delay = Promise.withResolvers();
295
+ setTimeout(delay.resolve, this.compactDelayMs);
296
+ await delay.promise;
297
+ const result = {
287
298
  summary: "mock compaction summary",
288
299
  firstKeptEntryId: "mock-entry-0",
289
- tokensBefore: 0,
300
+ tokensBefore: MOCK_COMPACT_TOKENS_BEFORE,
301
+ estimatedTokensAfter: MOCK_COMPACT_TOKENS_AFTER,
302
+ };
303
+ this.emit({
304
+ kind: "compaction",
305
+ compactionId,
306
+ phase: "completed",
307
+ reason: "manual",
308
+ tokensBefore: result.tokensBefore,
309
+ estimatedTokensAfter: result.estimatedTokensAfter,
310
+ summary: result.summary,
290
311
  });
312
+ return result;
291
313
  }
292
314
  newSession() {
293
315
  return Promise.resolve({ cancelled: false });
@@ -218,13 +218,13 @@ class PiAgentSession {
218
218
  });
219
219
  }
220
220
  /**
221
- * Send a `/command` prompt *correlated* (`request`, not `notify`) so Pi's own ack is observable:
222
- * Pi acks on preflight (dist/modes/rpc/rpc-mode.js `case "prompt"`), then `get_state.isStreaming`
223
- * — set synchronously as `_runAgentPrompt`'s first statement, hence already `true` for a real
224
- * turn by the time the ack reaches us — says whether a turn is actually running. Not streaming ⇒
225
- * the command was handled inline (extension command) and this turn is already over. A rejected
226
- * ack (no model, no auth, "Agent is already processing") now surfaces as a failed turn instead of
227
- * being silently dropped the way an unmatched `notify` response is (rpc-transport.ts `handleLine`).
221
+ * Send a `/command` prompt *correlated* (`request`, not `notify`) so Pi's own ack is observable.
222
+ * Pi acks on preflight with `data.disposition` (dist/modes/rpc/rpc-mode.js `case "prompt"`,
223
+ * Pi ≥ 0.99.0): `"handled"` ⇒ an extension command ran inline, no run started and no
224
+ * `agent_settled` will follow, so this turn is already over; `"started"`/`"queued"` ⇒ a run is
225
+ * (or will be) in flight, so await its terminal event. A rejected ack (no model, no auth, "Agent
226
+ * is already processing") surfaces as a failed turn instead of being silently dropped the way an
227
+ * unmatched `notify` response is (rpc-transport.ts `handleLine`).
228
228
  */
229
229
  async runSlashPrompt(prompt, opts) {
230
230
  let terminated = false;
@@ -242,14 +242,11 @@ class PiAgentSession {
242
242
  });
243
243
  try {
244
244
  const images = this.toPiImages(opts?.images);
245
- await this.transport.request("prompt", {
245
+ const ack = (await this.transport.request("prompt", {
246
246
  message: prompt,
247
247
  ...(images ? { images } : {}),
248
- });
249
- if (terminated)
250
- return;
251
- const state = (await this.transport.request("get_state"));
252
- if (state.isStreaming === false)
248
+ }));
249
+ if (terminated || ack?.disposition === "handled")
253
250
  return;
254
251
  await terminal;
255
252
  }
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  /**
2
3
  * Maps raw Pi RPC events → provider-neutral `AgentStreamEvent`s, and Pi tool calls →
3
4
  * `ToolCallDetail` kinds (features/agent-sessions.md § Stream events). The exact Pi event schema is
@@ -9,6 +10,7 @@ function asRecord(value) {
9
10
  function str(value) {
10
11
  return typeof value === "string" ? value : undefined;
11
12
  }
13
+ const COMPACTION_REASONS = ["manual", "threshold", "overflow"];
12
14
  /** Join `result.content` text blocks (Pi RPC `tool_execution_end` shape) into one string. */
13
15
  function outputOf(tool) {
14
16
  const content = asRecord(tool.result).content;
@@ -98,6 +100,8 @@ export function createPiEventMapper() {
98
100
  disposition = next;
99
101
  error = nextError;
100
102
  };
103
+ /** Id of the compaction between `compaction_start` and its `compaction_end`, if any. */
104
+ let openCompactionId;
101
105
  return {
102
106
  map(raw) {
103
107
  const event = asRecord(raw);
@@ -135,12 +139,15 @@ export function createPiEventMapper() {
135
139
  return null;
136
140
  }
137
141
  case "agent_settled": {
138
- // The true terminal (docs/rpc.md § agent_settled: Pi will not continue automatically
139
- // through retry, compaction retry, or queued follow-up messages past this point).
140
- const result = disposition === "failed"
141
- ? { kind: "turn_failed", error: error ?? "error" }
142
- : disposition === "canceled"
143
- ? { kind: "turn_canceled" }
142
+ // The true terminal (docs/json.md § Agent and turn events: Pi will not continue
143
+ // automatically through retry, compaction retry, or queued follow-up messages past this).
144
+ // `aborted` (Pi ≥ 1.1.0) is authoritative for a user abort and wins over the latch: an
145
+ // abort landing between runs — during an auto-retry backoff or a compaction — produces
146
+ // no `stopReason: "aborted"` message to latch, so the latch alone would misreport it.
147
+ const result = event.aborted === true || disposition === "canceled"
148
+ ? { kind: "turn_canceled" }
149
+ : disposition === "failed"
150
+ ? { kind: "turn_failed", error: error ?? "error" }
144
151
  : { kind: "turn_completed" };
145
152
  latch("completed");
146
153
  return result;
@@ -213,6 +220,54 @@ export function createPiEventMapper() {
213
220
  return { kind: "error", message: str(event.error) };
214
221
  case "error":
215
222
  return { kind: "error", message: str(event.message ?? event.error) };
223
+ // ── Context compaction (manual + automatic) ──
224
+ // Pi emits `compaction_start {reason}` and `compaction_end {reason, result?, aborted,
225
+ // willRetry, errorMessage?}`; the mapper mints one id per compaction so the two halves
226
+ // upsert a single timeline row. Every failure path inside Pi's `compact()` emits an end
227
+ // (no `result`, `errorMessage`) before throwing, so an end always closes the row.
228
+ case "compaction_start": {
229
+ openCompactionId = randomUUID();
230
+ const reason = COMPACTION_REASONS.find((r) => r === event.reason);
231
+ return {
232
+ kind: "compaction",
233
+ compactionId: openCompactionId,
234
+ phase: "started",
235
+ ...(reason ? { reason } : {}),
236
+ };
237
+ }
238
+ case "compaction_end": {
239
+ const compactionId = openCompactionId ?? randomUUID();
240
+ openCompactionId = undefined;
241
+ const reason = COMPACTION_REASONS.find((r) => r === event.reason);
242
+ const base = { kind: "compaction", compactionId, ...(reason ? { reason } : {}) };
243
+ if (event.aborted === true)
244
+ return { ...base, phase: "canceled" };
245
+ if (event.result && typeof event.result === "object") {
246
+ const result = asRecord(event.result);
247
+ return {
248
+ ...base,
249
+ phase: "completed",
250
+ tokensBefore: typeof result.tokensBefore === "number" ? result.tokensBefore : undefined,
251
+ estimatedTokensAfter: typeof result.estimatedTokensAfter === "number"
252
+ ? result.estimatedTokensAfter
253
+ : undefined,
254
+ summary: str(result.summary),
255
+ ...(event.willRetry === true ? { willRetry: true } : {}),
256
+ };
257
+ }
258
+ // Pi formats its own failure text as `Compaction failed: <cause>` (manual) or
259
+ // `Auto-compaction failed: <cause>` (automatic), and the web client's row label already
260
+ // says "Compaction failed" - so carry only the cause. Other texts, e.g. `Context overflow
261
+ // recovery failed: ...`, say something the label does not and pass through untouched.
262
+ const cause = str(event.errorMessage)
263
+ ?.replace(/^(?:auto-)?compaction failed:?\s*/i, "")
264
+ .trim();
265
+ return {
266
+ ...base,
267
+ phase: "failed",
268
+ ...(cause ? { error: cause } : {}),
269
+ };
270
+ }
216
271
  // ── Ignored (handled elsewhere / not surfaced as timeline events) ──
217
272
  // `auto_retry_end` left Pi's *declared* session-event union in 0.85.0 but the shipped
218
273
  // bundle still emits it, so the case stays. This switch is on a loose `string`, not Pi's
@@ -223,8 +278,6 @@ export function createPiEventMapper() {
223
278
  case "message_start":
224
279
  case "message_end":
225
280
  case "tool_execution_update":
226
- case "compaction_start":
227
- case "compaction_end":
228
281
  case "auto_retry_start":
229
282
  case "auto_retry_end":
230
283
  return null;
@@ -112,6 +112,19 @@ function mapMessage(message) {
112
112
  function mapEntry(entry) {
113
113
  if (entry.type === "message")
114
114
  return mapMessage(entry.message);
115
+ // Pi persists neither `reason` nor `estimatedTokensAfter`, and writes nothing for a failed or
116
+ // cancelled compaction — so a replayed one is always a lone `completed` row.
117
+ if (entry.type === "compaction") {
118
+ return [
119
+ {
120
+ kind: "compaction",
121
+ phase: "completed",
122
+ compactionId: entry.id,
123
+ tokensBefore: entry.tokensBefore,
124
+ summary: entry.summary,
125
+ },
126
+ ];
127
+ }
115
128
  return [];
116
129
  }
117
130
  /**
@@ -34,7 +34,18 @@ export declare class SlashCommandOperationsService {
34
34
  * stats poll a self-correcting source for the status bar's model segment, covering `/model`
35
35
  * cycle and cross-client changes that `agent_update` alone doesn't fully convey). */
36
36
  handleSessionStats(msg: Record<string, unknown>): Promise<unknown>;
37
- /** `/compact` — context changed, broadcast. */
37
+ /**
38
+ * `/compact` — context changed, broadcast.
39
+ *
40
+ * Pi's `compact()` starts with `abort()`, so compacting mid-turn would kill the run and a second
41
+ * concurrent compact would cancel the first: both are refused with `busy` BEFORE anything is
42
+ * resumed or subscribed. A record with no live process (every record after a daemon restart) is
43
+ * resumed first — compacting an old, oversized session before continuing it is a primary use.
44
+ *
45
+ * Compaction runs outside any turn, so `runTurn`'s subscription is not there to record its
46
+ * `compaction` events: this handler holds its own subscription window for the duration of the
47
+ * call and forwards only `compaction` events through the shared `appendStreamEvent` path.
48
+ */
38
49
  handleCompact(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
39
50
  /**
40
51
  * `/new` — starts a fresh session in place; broadcast.
@@ -1,4 +1,4 @@
1
- import { resetTimeline, spawnOrResumeSession } from "./agent-service.js";
1
+ import { appendStreamEvent, ensureTimelineSeeded, resetTimeline, spawnOrResumeSession, } from "./agent-service.js";
2
2
  /** Resolve the live session for `agentId`, or throw an error the router turns into `rpc_error`. */
3
3
  function requireSession(manager, agentId) {
4
4
  const managed = manager.get(agentId);
@@ -12,6 +12,9 @@ function requireSession(manager, agentId) {
12
12
  function unsupported(agentId, op) {
13
13
  return new Error(`agent ${agentId}'s provider does not support '${op}'`);
14
14
  }
15
+ /** Agent ids with a `compact` call in flight (a daemon restart kills the Pi child and any
16
+ * compaction with it, so in-memory is enough). */
17
+ const compactionsInFlight = new Set();
15
18
  export class SlashCommandOperationsService {
16
19
  deps;
17
20
  constructor(deps) {
@@ -50,16 +53,75 @@ export class SlashCommandOperationsService {
50
53
  const payload = stats.model !== undefined ? stats : { ...stats, model: session.getRuntimeInfo().model };
51
54
  return { type: "agent_session_stats_response", payload };
52
55
  }
53
- /** `/compact` — context changed, broadcast. */
56
+ /**
57
+ * `/compact` — context changed, broadcast.
58
+ *
59
+ * Pi's `compact()` starts with `abort()`, so compacting mid-turn would kill the run and a second
60
+ * concurrent compact would cancel the first: both are refused with `busy` BEFORE anything is
61
+ * resumed or subscribed. A record with no live process (every record after a daemon restart) is
62
+ * resumed first — compacting an old, oversized session before continuing it is a primary use.
63
+ *
64
+ * Compaction runs outside any turn, so `runTurn`'s subscription is not there to record its
65
+ * `compaction` events: this handler holds its own subscription window for the duration of the
66
+ * call and forwards only `compaction` events through the shared `appendStreamEvent` path.
67
+ */
54
68
  async handleCompact(msg, getSessions) {
55
69
  const agentId = msg.agentId;
56
- const session = requireSession(this.deps.manager, agentId);
57
- if (!session.compact)
58
- throw unsupported(agentId, "compact");
59
- const customInstructions = typeof msg.customInstructions === "string" ? msg.customInstructions : undefined;
60
- const payload = await session.compact(customInstructions);
61
- this.broadcastAgentUpdate(getSessions, agentId, { compacted: true });
62
- return { type: "agent_compact_response", payload };
70
+ const managed = this.deps.manager.get(agentId);
71
+ if (!managed)
72
+ throw new Error(`unknown agent: ${agentId}`);
73
+ if (managed.record.lastStatus === "running") {
74
+ throw new Error(`busy: agent ${agentId} is running; wait for the turn to finish before compacting`);
75
+ }
76
+ if (compactionsInFlight.has(agentId)) {
77
+ throw new Error(`busy: agent ${agentId} is already compacting`);
78
+ }
79
+ compactionsInFlight.add(agentId);
80
+ try {
81
+ const session = managed.session ?? (await spawnOrResumeSession(this.deps, agentId));
82
+ if (!session.compact)
83
+ throw unsupported(agentId, "compact");
84
+ const customInstructions = typeof msg.customInstructions === "string" ? msg.customInstructions : undefined;
85
+ // Before the first append: otherwise the compaction row would create an empty store that
86
+ // `seedTimeline` (never overwrites) could no longer hydrate history into.
87
+ ensureTimelineSeeded(agentId, this.deps.manager, this.deps.resolveClient);
88
+ let openId;
89
+ let terminalSeen = false;
90
+ const unsubscribe = session.subscribe((event) => {
91
+ if (event.kind !== "compaction")
92
+ return;
93
+ if (event.phase === "started")
94
+ openId = event.compactionId;
95
+ else
96
+ terminalSeen = true;
97
+ appendStreamEvent(agentId, event, this.deps.broadcast, getSessions());
98
+ });
99
+ let payload;
100
+ try {
101
+ payload = await session.compact(customInstructions);
102
+ }
103
+ catch (err) {
104
+ // A started row must never be left without its terminal row (process crash, transport
105
+ // failure). Pi's own failures emit `failed` before throwing, so `terminalSeen` is set then.
106
+ if (openId !== undefined && !terminalSeen) {
107
+ appendStreamEvent(agentId, {
108
+ kind: "compaction",
109
+ compactionId: openId,
110
+ phase: "failed",
111
+ error: err instanceof Error ? err.message : String(err),
112
+ }, this.deps.broadcast, getSessions());
113
+ }
114
+ throw err;
115
+ }
116
+ finally {
117
+ unsubscribe();
118
+ }
119
+ this.broadcastAgentUpdate(getSessions, agentId, { compacted: true });
120
+ return { type: "agent_compact_response", payload };
121
+ }
122
+ finally {
123
+ compactionsInFlight.delete(agentId);
124
+ }
63
125
  }
64
126
  /**
65
127
  * `/new` — starts a fresh session in place; broadcast.
@@ -1,4 +1,4 @@
1
- import { getTimeline, seedTimeline } from "./agent-service.js";
1
+ import { ensureTimelineSeeded, getTimeline } from "./agent-service.js";
2
2
  import { DEFAULT_PAGE_SIZE } from "./timeline-store.js";
3
3
  /**
4
4
  * `fetch_agent_timeline_request` handler (features/timeline-streaming.md § Fetch request/response,
@@ -19,18 +19,8 @@ export function registerTimelineHandler(registry, deps) {
19
19
  const direction = msg.direction ?? "after";
20
20
  const cursor = msg.cursor;
21
21
  const limit = typeof msg.limit === "number" && msg.limit > 0 ? msg.limit : DEFAULT_PAGE_SIZE;
22
- let timeline = getTimeline(agentId);
23
- if (!timeline) {
24
- const record = deps.manager.get(agentId)?.record;
25
- const handle = record?.persistence;
26
- if (record && handle) {
27
- const client = deps.resolveClient(record.provider);
28
- const rows = client.hydrateTimeline?.(handle) ?? [];
29
- if (rows.length > 0)
30
- seedTimeline(agentId, rows);
31
- }
32
- timeline = getTimeline(agentId);
33
- }
22
+ ensureTimelineSeeded(agentId, deps.manager, deps.resolveClient);
23
+ const timeline = getTimeline(agentId);
34
24
  if (!timeline) {
35
25
  // No in-memory timeline and no rehydratable native history — genuinely empty.
36
26
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@av-pi-studio/server",
3
- "version": "0.0.107",
3
+ "version": "0.0.109",
4
4
  "bin": {
5
5
  "pi-studio-daemon": "dist/daemon/main.js"
6
6
  },
@@ -24,9 +24,9 @@
24
24
  "clean": "rm -rf dist *.tsbuildinfo"
25
25
  },
26
26
  "dependencies": {
27
- "@av-pi-studio/protocol": "^0.0.107",
28
- "@av-pi-studio/relay": "^0.0.107",
29
- "@earendil-works/pi-coding-agent": ">=0.85.1 <1.0.0",
27
+ "@av-pi-studio/protocol": "^0.0.109",
28
+ "@av-pi-studio/relay": "^0.0.109",
29
+ "@earendil-works/pi-coding-agent": "^1.1.0",
30
30
  "@xterm/addon-serialize": "^0.14.0",
31
31
  "@xterm/headless": "^6.0.0",
32
32
  "bcryptjs": "^3.0.3",