@zvada/agent-server 0.3.17 → 0.3.18

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 (44) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +30 -2
  3. package/docs/consuming.md +9 -2
  4. package/docs/harnesses.md +11 -3
  5. package/docs/sync-experiment.md +190 -0
  6. package/docs/sync-history.md +181 -0
  7. package/docs/sync-integration.md +133 -0
  8. package/package.json +14 -2
  9. package/src/client/client.ts +138 -33
  10. package/src/client/history.ts +88 -0
  11. package/src/client/index.ts +1 -1
  12. package/src/client/request.ts +19 -0
  13. package/src/core/index.ts +2 -0
  14. package/src/core/provision/pins.ts +2 -1
  15. package/src/core/runtime/agent-runtime.ts +53 -23
  16. package/src/core/runtime/event-processor.ts +10 -5
  17. package/src/core/runtime/event-sink.ts +45 -2
  18. package/src/core/runtime/model-lists.ts +24 -9
  19. package/src/protocol/history.ts +267 -0
  20. package/src/protocol/ids.ts +4 -5
  21. package/src/protocol/index.ts +1 -0
  22. package/src/protocol/wire.ts +82 -1
  23. package/src/server/agent-server.ts +167 -94
  24. package/src/server/bin.ts +22 -1
  25. package/src/server/history.ts +166 -0
  26. package/src/server/index.ts +1 -0
  27. package/src/server/session-store.ts +225 -0
  28. package/src/server/wire-error.ts +52 -0
  29. package/src/sync/event-log.ts +132 -0
  30. package/src/sync/fit.ts +124 -0
  31. package/src/sync/history-reader.ts +52 -0
  32. package/src/sync/history-sqlite.ts +344 -0
  33. package/src/sync/history.ts +226 -0
  34. package/src/sync/index.ts +6 -0
  35. package/src/sync/journal-sqlite.ts +353 -0
  36. package/src/sync/journal.ts +73 -0
  37. package/src/sync/node-sqlite.ts +20 -0
  38. package/src/sync/recovery.ts +112 -0
  39. package/src/sync/retry.ts +49 -0
  40. package/src/sync/schema.ts +56 -0
  41. package/src/sync/sql.ts +106 -0
  42. package/src/sync/sqlite-file.ts +38 -0
  43. package/src/sync/sqlite.ts +21 -0
  44. package/src/sync/worker.ts +259 -0
@@ -5,6 +5,7 @@ import {
5
5
  type DecodedLifecycleEvent,
6
6
  LifecycleEventSchema,
7
7
  PermissionOutcomeSchema,
8
+ TurnEndedEventSchema,
8
9
  type UnknownEvent,
9
10
  decodeLifecycleEvent,
10
11
  } from "./lifecycle.ts";
@@ -54,6 +55,25 @@ export const WIRE_ERROR_CODES = {
54
55
  sessionClosing: -32005,
55
56
  /** A turn with this turnId already ran (or is running) with DIFFERENT input. */
56
57
  turnConflict: -32006,
58
+ /** A durable session was closed; its id is not reused. */
59
+ sessionClosed: -32007,
60
+ /**
61
+ * The session's last turn was cut off by a server restart and its native
62
+ * execution may still be running. Confirm it stopped (`session/confirmStopped`
63
+ * with `data.headSeq`) before starting another turn.
64
+ */
65
+ recoveryRequired: -32008,
66
+ /**
67
+ * This server process has not run the durable session yet: pass its
68
+ * `data.nativeSessionId` as `config.resumeSessionId`, or use a new session.
69
+ */
70
+ resumeRequired: -32009,
71
+ /** The host refused this caller the history operation. */
72
+ notAuthorized: -32010,
73
+ /** No such history, or it does not hold the requested version. */
74
+ unknownHistory: -32011,
75
+ /** The request contradicts committed history (payload, hash, expected head or commit id). */
76
+ historyConflict: -32012,
57
77
  } as const;
58
78
 
59
79
  // ---- methods -----------------------------------------------------------------
@@ -66,6 +86,10 @@ export const WIRE_METHODS = {
66
86
  permissionRespond: "permission/respond",
67
87
  eventsReplay: "events/replay",
68
88
  modelsList: "models/list",
89
+ /** Durable servers only (`historyId` in `initialize`); others answer methodNotFound. */
90
+ turnGet: "turn/get",
91
+ sessionGet: "session/get",
92
+ sessionConfirmStopped: "session/confirmStopped",
69
93
  shutdown: "shutdown",
70
94
  /** Server -> client notification carrying one sequenced lifecycle event. */
71
95
  event: "event",
@@ -95,6 +119,12 @@ export const InitializeResultSchema = z.object({
95
119
  * fact four downstream heuristics used to guess.
96
120
  */
97
121
  instanceId: z.string(),
122
+ /**
123
+ * Durable servers only: the journal's identity, the `sourceId` of every
124
+ * session history it serves. It outlives the process, and so do the session
125
+ * logs: a client keeps its seq cursors while this is unchanged.
126
+ */
127
+ historyId: z.string().optional(),
98
128
  /** Capabilities per registered harness — only available harnesses appear. */
99
129
  harnesses: z.record(z.string(), AgentCapabilitiesSchema),
100
130
  });
@@ -124,6 +154,8 @@ export const TurnStartResultSchema = z.object({
124
154
  * execution happened; catch up on its events via `events/replay`.
125
155
  */
126
156
  deduplicated: z.boolean().optional(),
157
+ /** A deduplicated turn that already ended, on a durable server: its `turn.ended`. */
158
+ terminal: TurnEndedEventSchema.optional(),
127
159
  });
128
160
  export type TurnStartResult = z.infer<typeof TurnStartResultSchema>;
129
161
 
@@ -220,6 +252,7 @@ export interface DecodedEventsReplayResult {
220
252
  events: DecodedWireEventEnvelope[];
221
253
  firstAvailableSeq: number | null;
222
254
  latestSeq: number | null;
255
+ hasMore?: boolean;
223
256
  }
224
257
 
225
258
  /**
@@ -234,6 +267,7 @@ export function decodeEventsReplayResult(value: unknown): DecodedEventsReplayRes
234
267
  events: z.array(z.unknown()),
235
268
  firstAvailableSeq: z.number().int().positive().nullable(),
236
269
  latestSeq: z.number().int().positive().nullable(),
270
+ hasMore: z.boolean().optional(),
237
271
  })
238
272
  .parse(value);
239
273
  return { ...parsed, events: parsed.events.map((event) => decodeWireEventEnvelope(event)) };
@@ -249,12 +283,14 @@ export type EventsReplayParams = z.infer<typeof EventsReplayParamsSchema>;
249
283
  /**
250
284
  * Replay is served from a bounded per-session ring buffer. When
251
285
  * `firstAvailableSeq > fromSeq`, the requested prefix was evicted and the gap
252
- * is unfillable — the consumer must treat its local view as stale.
286
+ * is unfillable — the consumer must treat its local view as stale. A durable
287
+ * server keeps every event and answers in pages: `hasMore` asks for the next.
253
288
  */
254
289
  export const EventsReplayResultSchema = z.object({
255
290
  events: z.array(WireEventEnvelopeSchema),
256
291
  firstAvailableSeq: z.number().int().positive().nullable(),
257
292
  latestSeq: z.number().int().positive().nullable(),
293
+ hasMore: z.boolean().optional(),
258
294
  });
259
295
  export type EventsReplayResult = z.infer<typeof EventsReplayResultSchema>;
260
296
 
@@ -279,6 +315,51 @@ export type ModelsListParams = z.infer<typeof ModelsListParamsSchema>;
279
315
  /** Never an error for an available harness: without a live list it is the catalog, with `error`. */
280
316
  export const ModelsListResultSchema = ModelListSchema;
281
317
 
318
+ /**
319
+ * `turn/get`: a durable turn's receipt. Admission records it, with the input,
320
+ * before the `turn/start` ack, so a turn whose process died before its first
321
+ * event is still known; `interrupted` means a restart cut it off.
322
+ */
323
+ export const TurnGetParamsSchema = z.object({ sessionId: z.string(), turnId: z.string() });
324
+ export type TurnGetParams = z.infer<typeof TurnGetParamsSchema>;
325
+ export const TurnReceiptSchema = TurnGetParamsSchema.extend({
326
+ state: z.enum(["admitted", "completed", "interrupted"]),
327
+ input: AgentInputSchema.optional(),
328
+ terminal: TurnEndedEventSchema.optional(),
329
+ });
330
+ export type TurnReceipt = z.infer<typeof TurnReceiptSchema>;
331
+
332
+ /** `session/get`: what a durable server knows about a session. */
333
+ export const SessionGetParamsSchema = z.object({ sessionId: z.string() });
334
+ export type SessionGetParams = z.infer<typeof SessionGetParamsSchema>;
335
+ export const DurableSessionSchema = z.object({
336
+ sessionId: z.string(),
337
+ harness: AgentHarnessSchema,
338
+ /** The seq of its latest event; 0 before the first. */
339
+ headSeq: z.number().int().nonnegative(),
340
+ nativeSessionId: z.string().nullable(),
341
+ closed: z.boolean(),
342
+ /** A restart cut off a turn: see `recoveryRequired` and `session/confirmStopped`. */
343
+ recoveryRequired: z.boolean(),
344
+ });
345
+ export type DurableSession = z.infer<typeof DurableSessionSchema>;
346
+
347
+ /**
348
+ * `session/confirmStopped`: the caller checked that the native execution a
349
+ * restart cut off is no longer running (history alone cannot prove that a
350
+ * detached agent or tool process died). `expectedHeadSeq` fences a stale
351
+ * confirmation against a newer interruption.
352
+ */
353
+ export const SessionConfirmStoppedParamsSchema = z.object({
354
+ sessionId: z.string(),
355
+ expectedHeadSeq: z.number().int().nonnegative(),
356
+ confirmedStopped: z.literal(true),
357
+ });
358
+ export type SessionConfirmStoppedParams = z.infer<typeof SessionConfirmStoppedParamsSchema>;
359
+ /** `recovered: false` when nothing awaited confirmation. */
360
+ export const SessionConfirmStoppedResultSchema = z.object({ recovered: z.boolean() });
361
+ export type SessionConfirmStoppedResult = z.infer<typeof SessionConfirmStoppedResultSchema>;
362
+
282
363
  export const ShutdownParamsSchema = z.object({}).optional();
283
364
  export const ShutdownResultSchema = z.object({});
284
365
 
@@ -1,4 +1,9 @@
1
- import { type AgentRuntime, TurnConflictError, callbackSink } from "../core/index.ts";
1
+ import {
2
+ type AgentRuntime,
3
+ EventSinkError,
4
+ TurnConflictError,
5
+ callbackSink,
6
+ } from "../core/index.ts";
2
7
  import {
3
8
  type AgentCapabilities,
4
9
  type AgentHarness,
@@ -10,8 +15,11 @@ import {
10
15
  PermissionRespondParamsSchema,
11
16
  type RunRequest,
12
17
  SessionCloseParamsSchema,
18
+ SessionConfirmStoppedParamsSchema,
19
+ SessionGetParamsSchema,
13
20
  TurnCancelParamsSchema,
14
21
  type TurnCancelResult,
22
+ TurnGetParamsSchema,
15
23
  TurnStartParamsSchema,
16
24
  WIRE_ERROR_CODES,
17
25
  WIRE_METHODS,
@@ -26,15 +34,34 @@ import {
26
34
  encodeResponse,
27
35
  generateUUIDv7,
28
36
  } from "../protocol/index.ts";
29
- import { DEFAULT_BUFFER_SIZE, SessionLog } from "./session-log.ts";
30
-
31
- /** Structural slice of a ZodError — keeps zod out of this package's deps. */
32
- interface ValidationError {
33
- issues: ReadonlyArray<{ path: ReadonlyArray<PropertyKey>; message: string }>;
34
- }
37
+ import type { SessionJournal } from "../sync/journal.ts";
38
+ import { type HistoryHost, handleHistoryRequest } from "./history.ts";
39
+ import { JournalSessionStore, MemorySessionStore, type SessionStore } from "./session-store.ts";
40
+ import {
41
+ type ValidationError,
42
+ WireError,
43
+ invalidParams,
44
+ parseParams,
45
+ wireErrorOf,
46
+ } from "./wire-error.ts";
35
47
 
36
48
  export interface AgentServerOptions {
37
- /** Replay ring-buffer size per session (envelopes). */
49
+ /**
50
+ * Durable sessions: every admission and event is committed to this journal
51
+ * before it is acknowledged or delivered, and sessions survive a restart.
52
+ * The server takes execution ownership (one owner per journal); the host
53
+ * opens the journal and closes it after shutdown.
54
+ */
55
+ journal?: SessionJournal;
56
+ /**
57
+ * The journal failed to write. The server then stops (as `shutdown`), and
58
+ * restart recovery decides what the turns it cut off did. Called once,
59
+ * before `onShutdown`.
60
+ */
61
+ onJournalError?: (error: unknown) => void;
62
+ /** Opt-in `history/*` methods. The host supplies the store and its access control. */
63
+ history?: HistoryHost;
64
+ /** Replay ring-buffer size per session (envelopes). Volatile sessions only. */
38
65
  bufferSize?: number;
39
66
  /** Reported in the `initialize` result. */
40
67
  info?: WireImplementationInfo;
@@ -52,29 +79,30 @@ export interface AgentServerOptions {
52
79
  */
53
80
  export class AgentServer {
54
81
  private readonly transports = new Set<WireTransport>();
55
- private readonly sessions = new Map<string, SessionLog>();
82
+ /** The ONE persistence decision: everything else asks the store. */
83
+ private readonly store: SessionStore;
56
84
  private readonly activeTurns = new Map<string, { turnId: string; harness: AgentHarness }>();
57
85
  private readonly closingSessions = new Set<string>();
58
- /** Last assigned seq of closed sessions, so a reused id continues
59
- * monotonically. Memory: one number per closed-and-never-reused session id —
60
- * unbounded only across a server lifetime with unbounded distinct ids, the
61
- * same order of growth already accepted for `sessions`. */
62
- private readonly retiredSeqs = new Map<string, number>();
63
86
  private readonly observers = new Set<(envelope: WireEventEnvelope) => void>();
64
87
  /**
65
88
  * One id per server PROCESS, handed out in `initialize`. Within a process,
66
- * session logs never restart (`retiredSeqs` keeps seq monotonic across
89
+ * session logs never restart (the store keeps seq monotonic across
67
90
  * close/reopen of an id), so a client that sees this id change across a
68
91
  * reconnect knows — as a stated fact, not an inference — that every log it
69
- * tracked belongs to a dead process.
92
+ * tracked belongs to a dead process. Unless `historyId` says they outlive it.
70
93
  */
71
94
  private readonly instanceId = generateUUIDv7();
72
95
  private shuttingDown = false;
96
+ private shutdownPromise: Promise<void> | undefined;
73
97
 
74
98
  constructor(
75
99
  private readonly runtime: AgentRuntime,
76
100
  private readonly options: AgentServerOptions = {},
77
- ) {}
101
+ ) {
102
+ this.store = options.journal
103
+ ? new JournalSessionStore(options.journal, (error) => this.failStop(error))
104
+ : new MemorySessionStore(options.bufferSize);
105
+ }
78
106
 
79
107
  /** Serve the wire on a transport; returns a detach function. */
80
108
  attach(transport: WireTransport): () => void {
@@ -107,9 +135,14 @@ export class AgentServer {
107
135
  return () => this.observers.delete(observer);
108
136
  }
109
137
 
110
- /** Cancel all turns, terminate harnesses, and close every transport. */
111
- async shutdown(): Promise<void> {
112
- if (this.shuttingDown) return;
138
+ /** Cancel all turns, terminate harnesses, and close every transport. Every
139
+ * caller waits for the same drain. */
140
+ shutdown(): Promise<void> {
141
+ this.shutdownPromise ??= this.drain();
142
+ return this.shutdownPromise;
143
+ }
144
+
145
+ private async drain(): Promise<void> {
113
146
  this.shuttingDown = true;
114
147
  // Drain first so cancelled turns still broadcast their turn.ended.
115
148
  // The drain (and each transport's close) is a library extension point
@@ -127,10 +160,21 @@ export class AgentServer {
127
160
  // host's shutdown hook — same isolation broadcast uses for send.
128
161
  }
129
162
  }
163
+ this.store.release();
130
164
  this.options.onShutdown?.();
131
165
  }
132
166
  }
133
167
 
168
+ /** The journal failed to write: stop, delivering nothing it did not commit. */
169
+ private failStop(error: unknown): void {
170
+ try {
171
+ this.options.onJournalError?.(error);
172
+ } catch {
173
+ // The host's hook must not keep the server running.
174
+ }
175
+ void this.shutdown().catch(() => {});
176
+ }
177
+
134
178
  private async handleLine(transport: WireTransport, line: string): Promise<void> {
135
179
  if (!line.trim()) return;
136
180
  const msg = decodeWireMessage(line);
@@ -145,8 +189,12 @@ export class AgentServer {
145
189
  try {
146
190
  await this.handleRequest(transport, msg.id, msg.method, msg.params);
147
191
  } catch (err) {
148
- const message = err instanceof Error ? err.message : String(err);
149
- transport.send(encodeErrorResponse(msg.id, WIRE_ERROR_CODES.internalError, message));
192
+ const { code, message, data } = wireErrorOf(err);
193
+ try {
194
+ transport.send(encodeErrorResponse(msg.id, code, message, data));
195
+ } catch {
196
+ // The requester is gone; nothing else is owed this response.
197
+ }
150
198
  }
151
199
  }
152
200
 
@@ -156,6 +204,11 @@ export class AgentServer {
156
204
  method: string,
157
205
  params: unknown,
158
206
  ): Promise<void> {
207
+ if (
208
+ this.options.history &&
209
+ (await handleHistoryRequest(this.options.history, transport, id, method, params))
210
+ )
211
+ return;
159
212
  switch (method) {
160
213
  case WIRE_METHODS.initialize: {
161
214
  const parsed = InitializeParamsSchema.safeParse(params ?? {});
@@ -178,6 +231,7 @@ export class AgentServer {
178
231
  protocolVersion: WIRE_PROTOCOL_VERSION,
179
232
  server: this.options.info ?? { name: "agent-server" },
180
233
  instanceId: this.instanceId,
234
+ ...(this.store.historyId && { historyId: this.store.historyId }),
181
235
  harnesses,
182
236
  };
183
237
  return transport.send(encodeResponse(id, result));
@@ -213,24 +267,20 @@ export class AgentServer {
213
267
  ),
214
268
  );
215
269
  }
216
- const existing = this.sessions.get(sessionId);
217
- if (existing && existing.harness !== config.harness) {
218
- return transport.send(
219
- encodeErrorResponse(
220
- id,
221
- WIRE_ERROR_CODES.invalidParams,
222
- `session ${sessionId} is bound to harness ${existing.harness}`,
223
- ),
224
- );
225
- }
226
- // Idempotent admission, delegated to the runtime: a retried start
227
- // (same turnId, identical input) converges — ack again, never run
228
- // twice; `events/replay` serves anything the retryer missed. The
270
+ // Idempotent admission: a retried start (same turnId, identical
271
+ // input) converges — ack again, never run twice; `events/replay`
272
+ // serves anything the retryer missed. A durable store remembers
273
+ // every turn it admitted, the runtime only its recent ones. The
229
274
  // same turnId with different input is a caller bug → turnConflict.
230
275
  const request = { sessionId, turnId, input, config };
231
276
  try {
232
- if (this.runtime.admission(request).status !== "new") {
233
- return transport.send(encodeResponse(id, { sessionId, turnId, deduplicated: true }));
277
+ const duplicate =
278
+ this.store.duplicateOf(request) ??
279
+ (this.runtime.admission(request).status === "new" ? undefined : {});
280
+ if (duplicate) {
281
+ return transport.send(
282
+ encodeResponse(id, { sessionId, turnId, deduplicated: true, ...duplicate }),
283
+ );
234
284
  }
235
285
  } catch (err) {
236
286
  if (err instanceof TurnConflictError) {
@@ -240,6 +290,16 @@ export class AgentServer {
240
290
  }
241
291
  throw err;
242
292
  }
293
+ const bound = this.store.harnessOf(sessionId);
294
+ if (bound && bound !== config.harness) {
295
+ return transport.send(
296
+ encodeErrorResponse(
297
+ id,
298
+ WIRE_ERROR_CODES.invalidParams,
299
+ `session ${sessionId} is bound to harness ${bound}`,
300
+ ),
301
+ );
302
+ }
243
303
  if (this.activeTurns.has(sessionId)) {
244
304
  return transport.send(
245
305
  encodeErrorResponse(
@@ -250,20 +310,15 @@ export class AgentServer {
250
310
  ),
251
311
  );
252
312
  }
253
- const log =
254
- existing ??
255
- new SessionLog(
256
- sessionId,
257
- config.harness,
258
- this.options.bufferSize ?? DEFAULT_BUFFER_SIZE,
259
- (this.retiredSeqs.get(sessionId) ?? 0) + 1,
260
- );
261
- this.retiredSeqs.delete(sessionId);
262
- this.sessions.set(sessionId, log);
313
+ this.store.open(request);
263
314
  this.activeTurns.set(sessionId, { turnId, harness: config.harness });
264
- // Quick-ack before the first event can possibly be emitted.
265
- transport.send(encodeResponse(id, { sessionId, turnId }));
266
- void this.executeTurn({ sessionId, turnId, input, config }, log);
315
+ // Quick-ack before the first event can possibly be emitted. The turn
316
+ // runs (and releases its session) even if the requester is gone.
317
+ try {
318
+ transport.send(encodeResponse(id, { sessionId, turnId }));
319
+ } finally {
320
+ void this.executeTurn(request);
321
+ }
267
322
  return;
268
323
  }
269
324
 
@@ -328,28 +383,23 @@ export class AgentServer {
328
383
  ),
329
384
  );
330
385
  }
331
- const log = this.sessions.get(sessionId);
332
- if (!log) return transport.send(encodeResponse(id, { closed: false }));
386
+ const harness = this.store.closing(sessionId);
387
+ if (!harness) return transport.send(encodeResponse(id, { closed: false }));
333
388
  this.closingSessions.add(sessionId);
334
389
  try {
335
- await this.runtime.closeSession(log.harness, sessionId);
390
+ await this.runtime.closeSession(harness, sessionId);
336
391
  // The terminal fact for CONNECTED subscribers (spec §6.1): they
337
392
  // learn the session is over from the stream, not from the RPC
338
- // result (which only the closer sees). It is deliberately NOT
339
- // replayable — the log is retired on the next line, so a
340
- // subscriber that was detached gets `unknownSession` from
341
- // `events/replay`, and that answer IS its terminal signal (the
342
- // session is gone; nothing more will ever be appended).
393
+ // result (which only the closer sees). Appending it retires the
394
+ // session (see SessionStore.append).
343
395
  this.broadcast(
344
- log.append({
396
+ this.store.append(sessionId, {
345
397
  type: "session.ended",
346
398
  sessionId,
347
399
  reason: "released",
348
400
  timestamp: Date.now(),
349
401
  }),
350
402
  );
351
- if (log.latestSeq !== null) this.retiredSeqs.set(sessionId, log.latestSeq);
352
- if (this.sessions.get(sessionId) === log) this.sessions.delete(sessionId);
353
403
  return transport.send(encodeResponse(id, { closed: true }));
354
404
  } finally {
355
405
  this.closingSessions.delete(sessionId);
@@ -370,8 +420,8 @@ export class AgentServer {
370
420
  case WIRE_METHODS.eventsReplay: {
371
421
  const parsed = EventsReplayParamsSchema.safeParse(params);
372
422
  if (!parsed.success) return this.invalidParams(transport, id, parsed.error);
373
- const log = this.sessions.get(parsed.data.sessionId);
374
- if (!log) {
423
+ const replayed = this.store.replay(parsed.data.sessionId, parsed.data.fromSeq);
424
+ if (!replayed) {
375
425
  return transport.send(
376
426
  encodeErrorResponse(
377
427
  id,
@@ -380,13 +430,35 @@ export class AgentServer {
380
430
  ),
381
431
  );
382
432
  }
383
- return transport.send(
384
- encodeResponse(id, {
385
- events: log.replay(parsed.data.fromSeq),
386
- firstAvailableSeq: log.firstAvailableSeq,
387
- latestSeq: log.latestSeq,
388
- }),
433
+ return transport.send(encodeResponse(id, replayed));
434
+ }
435
+
436
+ case WIRE_METHODS.turnGet: {
437
+ if (!this.store.receipt) break;
438
+ const { sessionId, turnId } = parseParams(TurnGetParamsSchema, params);
439
+ const receipt = this.store.receipt(sessionId, turnId);
440
+ if (!receipt)
441
+ throw new WireError(WIRE_ERROR_CODES.unknownSession, `unknown turn: ${turnId}`);
442
+ return transport.send(encodeResponse(id, receipt));
443
+ }
444
+
445
+ case WIRE_METHODS.sessionGet: {
446
+ if (!this.store.session) break;
447
+ const { sessionId } = parseParams(SessionGetParamsSchema, params);
448
+ const session = this.store.session(sessionId);
449
+ if (!session)
450
+ throw new WireError(WIRE_ERROR_CODES.unknownSession, `unknown session: ${sessionId}`);
451
+ return transport.send(encodeResponse(id, session));
452
+ }
453
+
454
+ case WIRE_METHODS.sessionConfirmStopped: {
455
+ if (!this.store.confirmStopped) break;
456
+ const { sessionId, expectedHeadSeq } = parseParams(
457
+ SessionConfirmStoppedParamsSchema,
458
+ params,
389
459
  );
460
+ const recovered = this.store.confirmStopped(sessionId, expectedHeadSeq);
461
+ return transport.send(encodeResponse(id, { recovered }));
390
462
  }
391
463
 
392
464
  case WIRE_METHODS.modelsList: {
@@ -413,15 +485,14 @@ export class AgentServer {
413
485
  await this.shutdown().catch(() => {});
414
486
  return;
415
487
  }
416
-
417
- default:
418
- return transport.send(
419
- encodeErrorResponse(id, WIRE_ERROR_CODES.methodNotFound, `unknown method: ${method}`),
420
- );
421
488
  }
489
+ // Unknown here, or durable-only on a volatile server.
490
+ transport.send(
491
+ encodeErrorResponse(id, WIRE_ERROR_CODES.methodNotFound, `unknown method: ${method}`),
492
+ );
422
493
  }
423
494
 
424
- private async executeTurn(request: RunRequest, log: SessionLog): Promise<void> {
495
+ private async executeTurn(request: RunRequest): Promise<void> {
425
496
  // Only release the busy mark if it still belongs to THIS turn — a newer
426
497
  // turn may have been accepted between our turn.ended broadcast and run()
427
498
  // settling, and its lock must survive our cleanup.
@@ -431,28 +502,36 @@ export class AgentServer {
431
502
  }
432
503
  };
433
504
  const sink = callbackSink((event) => {
505
+ const envelope = this.store.append(request.sessionId, event);
434
506
  // Once turn.ended is on the wire the session is idle — clear the busy
435
507
  // mark here (not when run() settles) so clients acting on the event
436
508
  // never race the bookkeeping.
437
509
  if (event.type === "turn.ended") releaseTurn();
438
- this.broadcast(log.append(event));
510
+ this.broadcast(envelope);
439
511
  });
440
512
  try {
441
513
  await this.runtime.run(request, sink);
442
514
  } catch (err) {
515
+ // The store could not commit: deliver nothing it did not record, not
516
+ // even a turn.ended. Its fault already stops the server.
517
+ if (err instanceof EventSinkError) return;
443
518
  // runtime.run reports errors via events; a throw means it died before
444
519
  // emitting turn.ended — synthesize one so clients are never left hanging.
445
520
  const message = err instanceof Error ? err.message : String(err);
446
- this.broadcast(
447
- log.append({
448
- type: "turn.ended",
449
- sessionId: request.sessionId,
450
- turnId: request.turnId,
451
- stopReason: "error",
452
- error: { category: classifyError(err), message },
453
- timestamp: Date.now(),
454
- }),
455
- );
521
+ try {
522
+ this.broadcast(
523
+ this.store.append(request.sessionId, {
524
+ type: "turn.ended",
525
+ sessionId: request.sessionId,
526
+ turnId: request.turnId,
527
+ stopReason: "error",
528
+ error: { category: classifyError(err), message },
529
+ timestamp: Date.now(),
530
+ }),
531
+ );
532
+ } catch {
533
+ // A store that cannot commit it has failed, and stops the server.
534
+ }
456
535
  } finally {
457
536
  releaseTurn();
458
537
  }
@@ -483,13 +562,7 @@ export class AgentServer {
483
562
  }
484
563
 
485
564
  private invalidParams(transport: WireTransport, id: JsonRpcId, error: ValidationError): void {
486
- transport.send(
487
- encodeErrorResponse(
488
- id,
489
- WIRE_ERROR_CODES.invalidParams,
490
- "invalid params",
491
- error.issues.map((i) => ({ path: i.path.join("."), message: i.message })),
492
- ),
493
- );
565
+ const { code, message, data } = invalidParams(error);
566
+ transport.send(encodeErrorResponse(id, code, message, data));
494
567
  }
495
568
  }
package/src/server/bin.ts CHANGED
@@ -36,6 +36,7 @@ interface Args {
36
36
  harnesses?: string[];
37
37
  acpAgent?: string;
38
38
  bufferSize?: number;
39
+ journalPath?: string;
39
40
  provisionMode?: ProvisionMode;
40
41
  feedback?: { message?: string; category?: string; subject?: string; resume?: string };
41
42
  }
@@ -60,6 +61,7 @@ function usage(exitCode: number): never {
60
61
  " --acp-agent <spec> ACP agent: known name (pi|gemini) or launch command",
61
62
  " --provision <mode> CLI provisioning: auto | pinned | system (default auto)",
62
63
  " --buffer <n> replay buffer size per session (default 4096)",
64
+ " --journal <path> durable session history (wire modes only; Bun SQLite)",
63
65
  " --version, --help",
64
66
  "",
65
67
  "env: CLAUDE_CLI_PATH / CODEX_CLI_PATH (explicit binaries),",
@@ -109,6 +111,8 @@ function parseArgs(argv: string[]): Args {
109
111
  const mode = next();
110
112
  if (mode !== "auto" && mode !== "pinned" && mode !== "system") usage(1);
111
113
  args.provisionMode = mode;
114
+ } else if (arg === "--journal") {
115
+ args.journalPath = next();
112
116
  } else if (arg === "--buffer") {
113
117
  args.bufferSize = Number(next());
114
118
  if (!Number.isInteger(args.bufferSize) || args.bufferSize <= 0) usage(1);
@@ -122,6 +126,10 @@ function parseArgs(argv: string[]): Args {
122
126
  }
123
127
 
124
128
  const args = parseArgs(process.argv.slice(2));
129
+ if (args.journalPath && (args.mode === "acp" || args.command !== "serve")) {
130
+ console.error("--journal is supported only for the stdio/listen/dial wire server");
131
+ process.exit(1);
132
+ }
125
133
 
126
134
  if (args.command === "feedback") {
127
135
  const message = args.feedback?.message;
@@ -196,10 +204,23 @@ if (args.mode === "acp") {
196
204
  // Client hung up — shut down cleanly (mirrors the stdio wire transport).
197
205
  void connection.closed.then(() => shutdown());
198
206
  } else {
207
+ const journal = args.journalPath
208
+ ? new (await import("../sync/sqlite.ts")).SqliteSessionJournal(args.journalPath)
209
+ : undefined;
199
210
  const server = new AgentServer(runtime, {
211
+ journal,
212
+ // This CLI wire is a trusted local execution surface, not a public relay.
213
+ history: journal ? { store: journal.history, authorize: () => true } : undefined,
214
+ onJournalError: (error) => {
215
+ console.error("Journal failed; restart and inspect interrupted execution:", error);
216
+ process.exitCode = 1;
217
+ },
200
218
  bufferSize: args.bufferSize,
201
219
  info: { name: "agent-server", version: VERSION },
202
- onShutdown: () => process.exit(0),
220
+ onShutdown: () => {
221
+ journal?.close();
222
+ process.exit(process.exitCode ?? 0);
223
+ },
203
224
  });
204
225
  shutdown = () => void server.shutdown();
205
226