@hasna-internal/kai-session-persistence 0.1.1-rc.2

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/lib/index.js ADDED
@@ -0,0 +1,1396 @@
1
+ import { Service } from "@deepseek-ai/cordis";
2
+ import { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, SessionPreparation, adoptSessionEvent, interruptedTurnClosers, snapshotJsonValue, snapshotSessionEvent } from "@hasna-internal/kai-session";
3
+ import { MAX_TIMER_DELAY_MS } from "@hasna-internal/kai-timeout";
4
+ //#region lib/types/revision.js
5
+ /** Opaque revision identity for lightweight persistence observations. */
6
+ /**
7
+ * Brand a backend revision for the provider-neutral persistence contract.
8
+ * @param value - backend-owned opaque revision representation.
9
+ * @returns the same runtime string with persistence-revision identity.
10
+ */
11
+ function SessionPersistenceRevision(value) {
12
+ return value;
13
+ }
14
+ //#endregion
15
+ //#region lib/types/preparations.js
16
+ /**
17
+ * Bounded sharing and exclusive reservation of unpublished Sessions.
18
+ * @module @hasna-internal/kai-session-persistence/preparations
19
+ */
20
+ /** Per-coordinator cold-read sharing, exclusive reservation, and ready-entry LRU. */
21
+ var SessionPreparations = class {
22
+ capacity;
23
+ entries = /* @__PURE__ */ new Map();
24
+ constructor(capacity) {
25
+ this.capacity = capacity;
26
+ }
27
+ /**
28
+ * Whether this pool currently knows about an unpublished identity.
29
+ * @param id - session identity.
30
+ * @returns whether an entry exists for the identity.
31
+ */
32
+ has(id) {
33
+ return this.entries.has(id);
34
+ }
35
+ /**
36
+ * Observe one prepared source, sharing an in-flight read for the same id.
37
+ * @param id - session identity.
38
+ * @param load - cold loader used when no entry exists.
39
+ * @param signal - optional cancellation signal while waiting.
40
+ * @returns the shared prepared source.
41
+ */
42
+ async inspect(id, load, signal) {
43
+ const entry = this.entryFor(id, load);
44
+ const loaded = signal === void 0 ? await entry.result : await observeQueuedAbort(entry.result, signal);
45
+ const source = entry.source ?? loaded;
46
+ if (this.entries.get(id) === entry && entry.phase === "ready") this.touch(entry);
47
+ return source;
48
+ }
49
+ /**
50
+ * Reserve one ready source after committing its pending durable repair.
51
+ * @param id - session identity.
52
+ * @param load - cold loader used when no entry exists.
53
+ * @param commit - durable repair and cursor-state commit.
54
+ * @param signal - optional cancellation signal while waiting.
55
+ * @returns the exclusive reservation, or undefined if its entry was invalidated.
56
+ */
57
+ async reserve(id, load, commit, signal) {
58
+ const entry = this.entryFor(id, load);
59
+ await (signal === void 0 ? entry.result : observeQueuedAbort(entry.result, signal));
60
+ while (this.entries.get(id) === entry && entry.phase !== "ready") {
61
+ const settled = entry.reservationSettled;
62
+ /* v8 ignore next -- committing/reserved transitions install this waiter synchronously. */
63
+ if (settled === void 0) throw new Error(`session "${id}" preparation lost its reservation waiter`);
64
+ if (signal === void 0) await settled;
65
+ else await observeQueuedAbort(settled, signal);
66
+ }
67
+ if (this.entries.get(id) !== entry) return void 0;
68
+ const source = entry.source;
69
+ const reservationSettled = Promise.withResolvers();
70
+ entry.phase = "committing";
71
+ entry.reservationSettled = reservationSettled.promise;
72
+ entry.settleReservation = reservationSettled.resolve;
73
+ let committed;
74
+ try {
75
+ committed = await commit(source);
76
+ } catch (error) {
77
+ this.remove(entry);
78
+ throw error;
79
+ }
80
+ if (committed === void 0) {
81
+ this.remove(entry);
82
+ return;
83
+ }
84
+ entry.source = committed.source;
85
+ try {
86
+ signal?.throwIfAborted();
87
+ } catch (error) {
88
+ this.makeReady(entry);
89
+ throw error;
90
+ }
91
+ if (this.entries.get(id) !== entry) return void 0;
92
+ const reservation = {
93
+ entry,
94
+ source: committed.source,
95
+ state: committed.state
96
+ };
97
+ entry.phase = "reserved";
98
+ entry.reservation = reservation;
99
+ return reservation;
100
+ }
101
+ /**
102
+ * Return the exact reservation for Session publication, rejecting aliases.
103
+ * @param session - exact Session candidate for publication.
104
+ * @returns its reservation, or undefined when no preparation exists.
105
+ */
106
+ reservationFor(session) {
107
+ const entry = this.entries.get(session.id);
108
+ if (entry === void 0) return void 0;
109
+ if (entry.phase === "reserved" && entry.source?.session === session && entry.reservation !== void 0) return entry.reservation;
110
+ throw new Error(`cannot publish session "${session.id}": persisted state already owns this identity`);
111
+ }
112
+ /**
113
+ * Consume a reservation after its exact Session has attached.
114
+ * @param reservation - reservation to consume.
115
+ */
116
+ attach(reservation) {
117
+ const { entry } = reservation;
118
+ if (this.entries.get(entry.id) !== entry || entry.reservation !== reservation) throw new Error(`session "${entry.id}" preparation is no longer reserved`);
119
+ this.remove(entry);
120
+ }
121
+ /**
122
+ * Consume a reservation whose caller only needs the committed inspection.
123
+ * @param reservation - reservation to consume.
124
+ */
125
+ discard(reservation) {
126
+ const { entry } = reservation;
127
+ if (this.entries.get(entry.id) !== entry || entry.reservation !== reservation) return;
128
+ this.remove(entry);
129
+ }
130
+ /**
131
+ * Return a reusable unpublished reservation to the ready LRU.
132
+ * @param reservation - reservation to release.
133
+ * @param reusable - whether the source remains valid for reuse.
134
+ */
135
+ release(reservation, reusable) {
136
+ const { entry } = reservation;
137
+ if (this.entries.get(entry.id) !== entry || entry.reservation !== reservation || entry.phase !== "reserved") return;
138
+ if (!reusable) {
139
+ this.remove(entry);
140
+ return;
141
+ }
142
+ delete entry.reservation;
143
+ this.makeReady(entry);
144
+ }
145
+ /**
146
+ * Discard a prepared view after the durable log changes.
147
+ * @param id - changed session identity.
148
+ */
149
+ invalidate(id) {
150
+ const entry = this.entries.get(id);
151
+ if (entry !== void 0) this.remove(entry);
152
+ }
153
+ /**
154
+ * Discard an exact stale ready source without disturbing an exclusive owner.
155
+ * @param id - changed session identity.
156
+ * @param expected - exact source observed before its revision check.
157
+ * @returns whether the source was discarded, retained by a reservation, or is absent.
158
+ */
159
+ discardReady(id, expected) {
160
+ const entry = this.entries.get(id);
161
+ if (entry === void 0 || entry.source !== expected) return "missing";
162
+ if (entry.phase !== "ready") return "retained";
163
+ this.remove(entry);
164
+ return "discarded";
165
+ }
166
+ /**
167
+ * Reject writes while an unpublished Session exclusively reserves the id.
168
+ * @param id - session identity to check.
169
+ */
170
+ assertWritable(id) {
171
+ const phase = this.entries.get(id)?.phase;
172
+ if (phase === "committing" || phase === "reserved") throw new Error(`cannot append session "${id}" while its persisted preparation is reserved`);
173
+ }
174
+ /**
175
+ * Remove a completed entry for an already-serialized append adoption.
176
+ * @param id - adopted session identity.
177
+ * @returns the prepared source, or undefined when no ready entry exists.
178
+ */
179
+ takeReady(id) {
180
+ const entry = this.entries.get(id);
181
+ if (entry === void 0 || entry.phase !== "ready" || entry.source === void 0) return void 0;
182
+ this.remove(entry);
183
+ return entry.source;
184
+ }
185
+ entryFor(id, load) {
186
+ const existing = this.entries.get(id);
187
+ if (existing !== void 0) return existing;
188
+ const deferred = Promise.withResolvers();
189
+ const entry = {
190
+ id,
191
+ result: deferred.promise,
192
+ phase: "loading"
193
+ };
194
+ this.entries.set(id, entry);
195
+ let loading;
196
+ try {
197
+ loading = load();
198
+ } catch (error) {
199
+ this.remove(entry);
200
+ deferred.reject(error);
201
+ return entry;
202
+ }
203
+ loading.then((source) => {
204
+ if (this.entries.get(id) === entry) {
205
+ entry.source = source;
206
+ this.makeReady(entry);
207
+ }
208
+ deferred.resolve(source);
209
+ }, (error) => {
210
+ this.remove(entry);
211
+ deferred.reject(error);
212
+ });
213
+ return entry;
214
+ }
215
+ makeReady(entry) {
216
+ if (this.entries.get(entry.id) !== entry) return;
217
+ entry.phase = "ready";
218
+ const settle = entry.settleReservation;
219
+ delete entry.reservationSettled;
220
+ delete entry.settleReservation;
221
+ settle?.();
222
+ this.touch(entry);
223
+ }
224
+ remove(entry) {
225
+ if (this.entries.get(entry.id) !== entry) return;
226
+ this.entries.delete(entry.id);
227
+ const settle = entry.settleReservation;
228
+ delete entry.reservationSettled;
229
+ delete entry.settleReservation;
230
+ settle?.();
231
+ }
232
+ touch(entry) {
233
+ this.entries.delete(entry.id);
234
+ this.entries.set(entry.id, entry);
235
+ let readyCount = 0;
236
+ for (const candidate of this.entries.values()) if (candidate.phase === "ready") readyCount += 1;
237
+ if (readyCount <= this.capacity) return;
238
+ for (const [id, candidate] of this.entries) {
239
+ if (candidate.phase !== "ready") continue;
240
+ this.entries.delete(id);
241
+ return;
242
+ }
243
+ }
244
+ };
245
+ /**
246
+ * Give a queued observer a prompt cancellation view without cancelling shared work.
247
+ * @param operation - shared operation whose settlement remains authoritative.
248
+ * @param signal - observer-local cancellation signal.
249
+ * @param started - whether the operation has crossed its cancellation cutoff.
250
+ * @returns the operation result or the observer's prompt cancellation.
251
+ */
252
+ function observeQueuedAbort(operation, signal, started = () => false) {
253
+ return new Promise((resolve, reject) => {
254
+ let settled = false;
255
+ const finish = (callback) => {
256
+ if (settled) return;
257
+ settled = true;
258
+ signal.removeEventListener("abort", onAbort);
259
+ callback();
260
+ };
261
+ const onAbort = () => {
262
+ if (started()) return;
263
+ finish(() => {
264
+ try {
265
+ signal.throwIfAborted();
266
+ } catch (reason) {
267
+ rejectObservation(reject, reason);
268
+ return;
269
+ }
270
+ /* v8 ignore next -- a native AbortSignal emits abort only after becoming aborted. */
271
+ reject(/* @__PURE__ */ new Error("queued observation abort event lacked an aborted signal"));
272
+ });
273
+ };
274
+ signal.addEventListener("abort", onAbort, { once: true });
275
+ operation.then((value) => {
276
+ finish(() => {
277
+ resolve(value);
278
+ });
279
+ }, (reason) => {
280
+ finish(() => {
281
+ rejectObservation(reject, reason);
282
+ });
283
+ });
284
+ if (signal.aborted) onAbort();
285
+ });
286
+ }
287
+ /** Preserve an exact loader or AbortSignal reason, including legacy non-Error values. */
288
+ function rejectObservation(reject, reason) {
289
+ reject(reason);
290
+ }
291
+ //#endregion
292
+ //#region lib/types/write-behind.js
293
+ /**
294
+ * Bounded per-session write batching for the shared persistence coordinator.
295
+ * @module @hasna-internal/kai-session-persistence/write-behind
296
+ */
297
+ /**
298
+ * Owns one live session's pending events, fixed batching deadline, active write,
299
+ * failure retention, and explicit quiescence barrier.
300
+ */
301
+ var SessionWriteBehind = class {
302
+ options;
303
+ pending = [];
304
+ timer;
305
+ active;
306
+ barrier;
307
+ deadlineExpired = false;
308
+ automaticPaused = false;
309
+ /**
310
+ * @param options - fixed scheduling policy and durable batch sink.
311
+ */
312
+ constructor(options) {
313
+ this.options = options;
314
+ }
315
+ /** Whether this controller owns queued events or an active durable write. */
316
+ get hasWork() {
317
+ return this.pending.length > 0 || this.active !== void 0;
318
+ }
319
+ /**
320
+ * Copy one event into the persistence-owned queue and start a fixed deadline
321
+ * when the automatic path is idle.
322
+ * @param event - frozen live event to retain independently of its producer.
323
+ */
324
+ enqueue(event) {
325
+ const wasEmpty = this.pending.length === 0;
326
+ this.pending.push(structuredClone(event));
327
+ if (this.barrier !== void 0) return;
328
+ if (this.automaticPaused) {
329
+ this.automaticPaused = false;
330
+ this.deadlineExpired = false;
331
+ this.armTimer();
332
+ } else if (wasEmpty) this.armTimer();
333
+ }
334
+ /**
335
+ * Cancel the batching wait and durably drain through a quiescent point.
336
+ * Concurrent callers join the same barrier.
337
+ * @returns a promise that rejects if the barrier's durable retry fails.
338
+ */
339
+ flush() {
340
+ if (this.barrier !== void 0) return this.barrier;
341
+ this.cancelTimer();
342
+ this.deadlineExpired = false;
343
+ this.automaticPaused = false;
344
+ const barrier = Promise.withResolvers();
345
+ this.barrier = barrier.promise;
346
+ this.drainBarrier(barrier.resolve, barrier.reject);
347
+ return barrier.promise;
348
+ }
349
+ /** Cancel the current automatic deadline without draining retained work. */
350
+ cancelAutomaticWait() {
351
+ this.cancelTimer();
352
+ this.deadlineExpired = false;
353
+ }
354
+ /** Start the one fixed window for the current pending prefix. */
355
+ armTimer() {
356
+ this.timer = setTimeout(() => {
357
+ this.onDeadline();
358
+ }, this.options.maxDelayMs);
359
+ }
360
+ /** Cancel any pending automatic deadline. */
361
+ cancelTimer() {
362
+ if (this.timer === void 0) return;
363
+ clearTimeout(this.timer);
364
+ this.timer = void 0;
365
+ }
366
+ /** Start a background write now, or remember that an active write used the budget. */
367
+ onDeadline() {
368
+ this.timer = void 0;
369
+ if (this.active !== void 0) {
370
+ this.deadlineExpired = true;
371
+ return;
372
+ }
373
+ this.startBackground();
374
+ }
375
+ /** Start one detached write whose failure is reported and retained. */
376
+ startBackground() {
377
+ this.startWrite(true).then(() => {
378
+ this.continueAutomatic();
379
+ }, () => {});
380
+ }
381
+ /** Continue immediately after an over-budget active write, otherwise keep its timer. */
382
+ continueAutomatic() {
383
+ if (this.barrier !== void 0 || this.pending.length === 0) return;
384
+ if (this.deadlineExpired) {
385
+ this.deadlineExpired = false;
386
+ this.startBackground();
387
+ }
388
+ }
389
+ /** Await overlapping work, drain to quiescence, and settle the shared barrier. */
390
+ async drainBarrier(resolve, reject) {
391
+ try {
392
+ const overlapping = this.active;
393
+ if (overlapping !== void 0) {
394
+ await Promise.allSettled([overlapping]);
395
+ this.automaticPaused = false;
396
+ }
397
+ while (this.pending.length > 0) await this.startWrite(false);
398
+ } catch (error) {
399
+ this.barrier = void 0;
400
+ reject(error);
401
+ return;
402
+ }
403
+ this.barrier = void 0;
404
+ resolve();
405
+ }
406
+ /** Start one stable pending prefix, retaining it in order if durability fails. */
407
+ startWrite(background) {
408
+ const batch = this.pending.splice(0);
409
+ this.cancelTimer();
410
+ this.deadlineExpired = false;
411
+ const active = Promise.resolve().then(() => this.options.write(batch)).catch((error) => {
412
+ this.pending = batch.concat(this.pending);
413
+ this.cancelTimer();
414
+ this.deadlineExpired = false;
415
+ this.automaticPaused = true;
416
+ if (background) this.options.reportBackgroundFailure(error);
417
+ throw error;
418
+ }).finally(() => {
419
+ this.active = void 0;
420
+ });
421
+ this.active = active;
422
+ return active;
423
+ }
424
+ };
425
+ //#endregion
426
+ //#region lib/types/coordinator.js
427
+ /**
428
+ * Shared buffering, serialization, adoption, repair, and disposal orchestration
429
+ * for first-party backends. Third-party backends may implement the public
430
+ * persistence seam directly.
431
+ * @module @hasna-internal/kai-session-persistence/coordinator
432
+ */
433
+ /** Default number of detached session preparations retained by a coordinator. */
434
+ const DEFAULT_PREPARED_SESSION_CACHE_SIZE = 5;
435
+ /** Default maximum intentional wait before a live session batch starts writing. */
436
+ const DEFAULT_WRITE_BATCH_MAX_DELAY_MS = 200;
437
+ /** Largest write batching delay accepted by Node's timer implementation. */
438
+ const MAX_WRITE_BATCH_DELAY_MS = MAX_TIMER_DELAY_MS;
439
+ /** Durable session contents failed validation after a successful backend read. */
440
+ var SessionPersistenceCorruptionError = class extends Error {
441
+ /**
442
+ * @param message - stable corruption context.
443
+ * @param options - original validation failure.
444
+ */
445
+ constructor(message, options) {
446
+ super(message, options);
447
+ this.name = "SessionPersistenceCorruptionError";
448
+ }
449
+ };
450
+ /**
451
+ * The stored log is intact but this runtime cannot faithfully interpret it:
452
+ * the header carries an unsupported format version, or an event's type is
453
+ * unknown to this build and the event is not marked ignorable. Distinct from
454
+ * {@link SessionPersistenceCorruptionError} — nothing is damaged; the raw log
455
+ * remains readable at {@link location} when the backend keeps one artifact
456
+ * per session.
457
+ */
458
+ var SessionFormatUnsupportedError = class extends Error {
459
+ location;
460
+ /**
461
+ * @param message - stable reason the log cannot be interpreted, already
462
+ * including the raw-log path when one exists.
463
+ * @param location - the backend's artifact location, when one exists.
464
+ */
465
+ constructor(message, location) {
466
+ super(message);
467
+ this.location = location;
468
+ this.name = "SessionFormatUnsupportedError";
469
+ }
470
+ };
471
+ /**
472
+ * Direction-aware refusal text for a stored session whose format version this
473
+ * build does not read. Shared by the coordinator's load-time check and by
474
+ * backends that must refuse BEFORE decoding version-dependent structure (a
475
+ * future format may not satisfy today's structural checks at all, and the
476
+ * user must see "upgrade the harness", never "corrupt").
477
+ * @param id - the stored session id, for message context.
478
+ * @param version - the stored format version.
479
+ * @returns the stable refusal text, without a raw-log path suffix.
480
+ */
481
+ function sessionFormatVersionRefusal(id, version) {
482
+ return version > SESSION_FORMAT_VERSION ? `session "${id}" uses log format v${version}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it` : `session "${id}" uses log format v${version}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it`;
483
+ }
484
+ /** Collect the rejection reasons from a set of promises (none-throwing). */
485
+ async function settledErrors(promises) {
486
+ const settled = await Promise.allSettled([...promises]);
487
+ const errors = [];
488
+ for (const result of settled) if (result.status === "rejected") errors.push(result.reason);
489
+ return errors;
490
+ }
491
+ /** Whether a live session seed reproduces a persisted prefix exactly. */
492
+ function seedCoversPrefix(seed, prefix) {
493
+ return prefix.length <= seed.length && prefix.every((event, index) => {
494
+ const seedEvent = seed[index];
495
+ return seedEvent !== void 0 && JSON.stringify(seedEvent) === JSON.stringify(event);
496
+ });
497
+ }
498
+ /** Reject events from an obsolete v0 vocabulary that this build cannot replay. */
499
+ function assertSupportedEvents(events, id) {
500
+ const legacyType = "request/header-delta";
501
+ const legacy = events.find((event) => event.type === legacyType);
502
+ if (legacy !== void 0) throw new Error(`session "${id}" contains unsupported legacy request/header-delta event at seq ${legacy.seq}`);
503
+ const legacyModeType = "mode/set";
504
+ const legacyMode = events.find((event) => event.type === legacyModeType);
505
+ if (legacyMode !== void 0) throw new Error(`session "${id}" contains unsupported legacy mode/set event at seq ${legacyMode.seq}`);
506
+ const fallback = events.find((event) => event.type === "request/header" && event.data.reason === "fallback");
507
+ if (fallback !== void 0) throw new Error(`session "${id}" contains unsupported legacy request/header reason "fallback" at seq ${fallback.seq}`);
508
+ }
509
+ /** Return an object record without widening arrays into message payloads. */
510
+ function asRecord(value) {
511
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
512
+ }
513
+ /** Whether a record contains every required key and no key outside the optional extension set. */
514
+ function hasOnlyKeys(record, required, optional = []) {
515
+ const allowed = [...required, ...optional];
516
+ return Object.keys(record).every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(record, key));
517
+ }
518
+ /** Mint the stable import identity for a message persisted before identities existed. */
519
+ function legacyMessageId(id, seq) {
520
+ return `legacy-message:${id}:${seq}`;
521
+ }
522
+ /** Read a replacement target while leaving malformed surface metadata to the session validator. */
523
+ function replacementStart(event) {
524
+ const op = asRecord(event.surfaceOp);
525
+ return op?.["op"] === "replace" && typeof op["start"] === "number" ? op["start"] : void 0;
526
+ }
527
+ /** Whether one suffix event needs facts available only from the preceding stored prefix. */
528
+ function needsLegacyPrefix(event) {
529
+ const data = asRecord(event.data);
530
+ if (event.type === "steering/message") return true;
531
+ if (data === void 0) return false;
532
+ switch (event.type) {
533
+ case "user/message": return !Object.hasOwn(data, "id") && Object.hasOwn(data, "content");
534
+ case "assistant/message": return !Object.hasOwn(data, "message") && Object.hasOwn(data, "content");
535
+ case "tool/result": return !Object.hasOwn(data, "message") && Object.hasOwn(data, "callId");
536
+ default: return false;
537
+ }
538
+ }
539
+ /** Upgrade the removed steering surface event into its current user-message equivalent. */
540
+ function migrateLegacySteeringEvent(event, id) {
541
+ if (event.type !== "steering/message") return event;
542
+ const data = asRecord(event.data);
543
+ if (data === void 0) throw new Error(`session "${id}" contains malformed pre-react-loop steering/message at seq ${event.seq}`);
544
+ const wrapped = asRecord(data["message"]);
545
+ if (wrapped !== void 0 && Number.isSafeInteger(data["turn"]) && hasOnlyKeys(data, ["turn", "message"])) return {
546
+ ...event,
547
+ type: "user/message",
548
+ data: wrapped
549
+ };
550
+ if (!Number.isSafeInteger(data["turn"]) || !hasOnlyKeys(data, [
551
+ "turn",
552
+ "content",
553
+ "source"
554
+ ])) throw new Error(`session "${id}" contains malformed pre-react-loop steering/message at seq ${event.seq}`);
555
+ const { turn: _turn, ...message } = data;
556
+ return {
557
+ ...event,
558
+ type: "user/message",
559
+ data: {
560
+ ...message,
561
+ id: legacyMessageId(id, event.seq),
562
+ role: "user"
563
+ }
564
+ };
565
+ }
566
+ /** Remove the obsolete trigger after verifying the complete old turn-start envelope. */
567
+ function migrateLegacyTurnStartEvent(event, id) {
568
+ if (event.type !== "turn/start") return event;
569
+ const data = asRecord(event.data);
570
+ if (data === void 0 || !Object.hasOwn(data, "trigger")) return event;
571
+ const trigger = asRecord(data["trigger"]);
572
+ if (!Number.isSafeInteger(data["turn"]) || data["turn"] < 1 || !hasOnlyKeys(data, ["turn", "trigger"]) || trigger === void 0 || typeof trigger["kind"] !== "string" || trigger["kind"].length === 0) throw new Error(`session "${id}" contains malformed pre-react-loop turn/start at seq ${event.seq}`);
573
+ return {
574
+ ...event,
575
+ data: { turn: data["turn"] }
576
+ };
577
+ }
578
+ /** Upgrade an obsolete turn ending while preserving the latest-master envelope. */
579
+ function migrateLegacyTurnEndEvent(event, id) {
580
+ if (event.type !== "turn/end") return event;
581
+ const data = asRecord(event.data);
582
+ /* v8 ignore next -- a non-record current envelope cannot match a legacy shape. */
583
+ if (data === void 0) return event;
584
+ const malformed = () => {
585
+ throw new Error(`session "${id}" contains malformed pre-react-loop turn/end at seq ${event.seq}`);
586
+ };
587
+ const reason = asRecord(data["reason"]);
588
+ if (!Number.isSafeInteger(data["turn"]) || data["turn"] < 1 || !hasOnlyKeys(data, ["turn", "reason"]) || reason === void 0 || typeof reason["kind"] !== "string") return malformed();
589
+ let currentReason;
590
+ switch (reason["kind"]) {
591
+ case "completed":
592
+ case "blocked":
593
+ case "max-tokens":
594
+ case "interrupted":
595
+ if (!hasOnlyKeys(reason, ["kind"])) return malformed();
596
+ return event;
597
+ case "aborted":
598
+ if (Object.hasOwn(reason, "reason")) return event;
599
+ if (!hasOnlyKeys(reason, ["kind"])) return malformed();
600
+ currentReason = {
601
+ kind: "aborted",
602
+ reason: { kind: "legacy" }
603
+ };
604
+ break;
605
+ case "disposed":
606
+ if (!hasOnlyKeys(reason, ["kind"])) return malformed();
607
+ currentReason = {
608
+ kind: "aborted",
609
+ reason: { kind: "disposed" }
610
+ };
611
+ break;
612
+ case "error": {
613
+ if (Object.hasOwn(reason, "error")) return event;
614
+ if (!Number.isSafeInteger(reason["step"]) || reason["step"] < 0) return malformed();
615
+ const failure = asRecord(reason["failure"]);
616
+ if (failure !== void 0 && hasOnlyKeys(reason, [
617
+ "kind",
618
+ "step",
619
+ "failure"
620
+ ]) && hasOnlyKeys(failure, ["message", "code"], [
621
+ "status",
622
+ "providerRetryAfterMs",
623
+ "requestId"
624
+ ]) && typeof failure["message"] === "string" && typeof failure["code"] === "string" && (failure["status"] === void 0 || typeof failure["status"] === "number") && (failure["providerRetryAfterMs"] === void 0 || typeof failure["providerRetryAfterMs"] === "number") && (failure["requestId"] === void 0 || typeof failure["requestId"] === "string")) {
625
+ currentReason = {
626
+ kind: "error",
627
+ error: failure
628
+ };
629
+ break;
630
+ }
631
+ if (!hasOnlyKeys(reason, reason["code"] === void 0 ? [
632
+ "kind",
633
+ "step",
634
+ "message"
635
+ ] : [
636
+ "kind",
637
+ "step",
638
+ "message",
639
+ "code"
640
+ ]) || typeof reason["message"] !== "string" || reason["code"] !== void 0 && typeof reason["code"] !== "string") return malformed();
641
+ currentReason = {
642
+ kind: "error",
643
+ error: {
644
+ message: reason["message"],
645
+ code: typeof reason["code"] === "string" ? reason["code"] : "UNKNOWN"
646
+ }
647
+ };
648
+ break;
649
+ }
650
+ default: return event;
651
+ }
652
+ return {
653
+ ...event,
654
+ data: {
655
+ ...data,
656
+ reason: currentReason
657
+ }
658
+ };
659
+ }
660
+ /**
661
+ * Upgrade one pre-identity message event into the current wrapper shape.
662
+ * Current-looking malformed events remain untouched so validation rejects them
663
+ * instead of disguising corruption as legacy data.
664
+ */
665
+ function migrateLegacyMessageEvent(event, id, messageIds) {
666
+ const data = asRecord(event.data);
667
+ if (data === void 0) return event;
668
+ switch (event.type) {
669
+ case "user/message":
670
+ if (Object.hasOwn(data, "id") || Object.hasOwn(data, "role") || Object.hasOwn(data, "message") || !Object.hasOwn(data, "content") || !Object.hasOwn(data, "source")) return event;
671
+ return {
672
+ ...event,
673
+ data: {
674
+ ...data,
675
+ id: legacyMessageId(id, event.seq),
676
+ role: "user"
677
+ }
678
+ };
679
+ case "assistant/message": {
680
+ if (Object.hasOwn(data, "message") || !Object.hasOwn(data, "content") || !Object.hasOwn(data, "provenance")) return event;
681
+ const { content, provenance, ...eventData } = data;
682
+ return {
683
+ ...event,
684
+ data: {
685
+ ...eventData,
686
+ message: {
687
+ id: legacyMessageId(id, event.seq),
688
+ role: "assistant",
689
+ content,
690
+ source: {
691
+ ...asRecord(provenance),
692
+ kind: "model"
693
+ }
694
+ }
695
+ }
696
+ };
697
+ }
698
+ case "tool/result": {
699
+ if (Object.hasOwn(data, "message") || !Object.hasOwn(data, "callId") || !Object.hasOwn(data, "content") || !Object.hasOwn(data, "isError")) return event;
700
+ const { callId, content, isError, ...eventData } = data;
701
+ const inheritedId = replacementStart(event);
702
+ return {
703
+ ...event,
704
+ data: {
705
+ ...eventData,
706
+ message: {
707
+ id: inheritedId === void 0 ? legacyMessageId(id, event.seq) : messageIds.get(inheritedId),
708
+ role: "user",
709
+ content: [{
710
+ type: "tool-result",
711
+ toolCallId: callId,
712
+ content,
713
+ isError
714
+ }],
715
+ source: {
716
+ kind: "tool",
717
+ callId
718
+ }
719
+ }
720
+ }
721
+ };
722
+ }
723
+ default: return event;
724
+ }
725
+ }
726
+ /** Read the identified message carried by one validated current event. */
727
+ function eventMessageId(event) {
728
+ const data = asRecord(event.data);
729
+ const message = event.type === "user/message" ? data : asRecord(data?.["message"]);
730
+ return typeof message?.["id"] === "string" ? message["id"] : void 0;
731
+ }
732
+ /** Materialize stored events as upgraded, validated snapshots with immutable messages. */
733
+ function snapshotStoredEvents(events, id) {
734
+ assertSupportedEvents(events, id);
735
+ const messageIds = /* @__PURE__ */ new Map();
736
+ return events.map((event) => {
737
+ const snapshot = snapshotSessionEvent(migrateLegacyMessageEvent(migrateLegacySteeringEvent(migrateLegacyTurnEndEvent(migrateLegacyTurnStartEvent(event, id), id), id), id, messageIds));
738
+ const messageId = eventMessageId(snapshot);
739
+ if (messageId !== void 0) messageIds.set(snapshot.seq, messageId);
740
+ return snapshot;
741
+ });
742
+ }
743
+ /** Upgrade and validate an exclusively owned backend result without copying it. */
744
+ function adoptStoredEvents(events, id) {
745
+ assertSupportedEvents(events, id);
746
+ const messageIds = /* @__PURE__ */ new Map();
747
+ for (const [index, event] of events.entries()) {
748
+ const adopted = adoptSessionEvent(migrateLegacyMessageEvent(migrateLegacySteeringEvent(migrateLegacyTurnEndEvent(migrateLegacyTurnStartEvent(event, id), id), id), id, messageIds));
749
+ events[index] = adopted;
750
+ const messageId = eventMessageId(adopted);
751
+ if (messageId !== void 0) messageIds.set(adopted.seq, messageId);
752
+ }
753
+ return events;
754
+ }
755
+ /**
756
+ * Owns the backend-agnostic session write-path orchestration. A backend
757
+ * constructs one (`new PersistenceCoordinator(ctx, this)`), implements
758
+ * {@link PersistenceBackend}, and delegates its write/read service methods to
759
+ * the matching coordinator methods.
760
+ *
761
+ * All per-id operations are serialized (a per-id promise chain) so concurrent
762
+ * flushes / a flush racing a load never interleave storage writes. The
763
+ * constructor installs the write-path listeners, per-session retirement, and
764
+ * the backend dispose effect.
765
+ *
766
+ * @typeParam TornMarker - the backend's opaque torn-tail repair token.
767
+ */
768
+ var PersistenceCoordinator = class {
769
+ ctx;
770
+ backend;
771
+ /** Backend bookkeeping keyed by session id (NOT the live Session object). */
772
+ states = /* @__PURE__ */ new Map();
773
+ /** Lifecycle and write-behind state keyed by the exact live Session. */
774
+ live = /* @__PURE__ */ new Map();
775
+ /** Exact disposed lifecycles whose buffered tail is still draining. */
776
+ retirements = /* @__PURE__ */ new Map();
777
+ /** Shared cold reads, unpublished reservations, and completed LRU entries. */
778
+ preparations;
779
+ /**
780
+ * Per-session serialization: every operation chains onto the prior one for the
781
+ * same id, so writes for one session never interleave. Keyed by session id.
782
+ */
783
+ chains = /* @__PURE__ */ new Map();
784
+ /** Resolved fixed write-batching window shared by per-session controllers. */
785
+ writeBatchMaxDelayMs;
786
+ constructor(ctx, backend, options = {
787
+ preparedSessionCacheSize: 5,
788
+ writeBatchMaxDelayMs: 200
789
+ }) {
790
+ this.ctx = ctx;
791
+ this.backend = backend;
792
+ if (!Number.isSafeInteger(options.preparedSessionCacheSize) || options.preparedSessionCacheSize < 1) throw new TypeError("preparedSessionCacheSize must be a positive safe integer");
793
+ if (!Number.isSafeInteger(options.writeBatchMaxDelayMs) || options.writeBatchMaxDelayMs < 1 || options.writeBatchMaxDelayMs > MAX_WRITE_BATCH_DELAY_MS) throw new TypeError(`writeBatchMaxDelayMs must be an integer between 1 and ${MAX_WRITE_BATCH_DELAY_MS}`);
794
+ this.writeBatchMaxDelayMs = options.writeBatchMaxDelayMs;
795
+ this.preparations = new SessionPreparations(options.preparedSessionCacheSize);
796
+ this.installWritePath();
797
+ }
798
+ /**
799
+ * Register detached session metadata for lazy creation on the first append.
800
+ * @param meta - header to snapshot; duplicate tracked or persisted ids reject.
801
+ */
802
+ create(meta) {
803
+ const snapshot = snapshotJsonValue(meta);
804
+ if (snapshot === void 0) return Promise.reject(/* @__PURE__ */ new TypeError("session metadata must be losslessly JSON-serializable"));
805
+ if (!Number.isSafeInteger(snapshot.createdAt) || snapshot.createdAt < 0) return Promise.reject(/* @__PURE__ */ new TypeError("session metadata createdAt must be a non-negative safe integer"));
806
+ return this.serialize(snapshot.id, () => this.createCore(snapshot));
807
+ }
808
+ async createCore(meta) {
809
+ if (this.states.has(meta.id) || this.preparations.has(meta.id)) throw new Error(`session "${meta.id}" already exists in this backend`);
810
+ if (await this.backend.loadStored(meta.id) !== void 0) throw new Error(`session "${meta.id}" already has a persisted log on disk; load/resume it instead of creating`);
811
+ this.states.set(meta.id, {
812
+ meta,
813
+ cursor: 0,
814
+ materialized: false
815
+ });
816
+ }
817
+ /**
818
+ * Durably persist a batch of events. Honors the append-only and contiguous-seq
819
+ * contracts; rejects non-JSON-serializable `event.data`.
820
+ * @param id - the session the batch belongs to.
821
+ * @param events - the contiguous batch to persist, in seq order; materialized
822
+ * as a detached lossless-JSON snapshot at call time.
823
+ */
824
+ async append(id, events) {
825
+ const batch = snapshotJsonValue(events);
826
+ if (batch === void 0) throw new TypeError("session event batch is not losslessly JSON-serializable because it contains non-JSON-serializable data");
827
+ return this.serialize(id, () => this.appendCore(id, batch));
828
+ }
829
+ async appendCore(id, events) {
830
+ assertSupportedEvents(events, id);
831
+ if (events.length === 0) return;
832
+ this.preparations.assertWritable(id);
833
+ let state = this.states.get(id);
834
+ if (state === void 0) state = await this.adopt(id);
835
+ for (const [i, event] of events.entries()) if (event.seq !== state.cursor + i) throw new Error(`append seq mismatch for "${id}": expected ${state.cursor + i} at index ${i}, got ${event.seq}`);
836
+ await this.backend.appendBatch(state.meta, events, state.materialized);
837
+ state.materialized = true;
838
+ state.cursor += events.length;
839
+ this.preparations.invalidate(id);
840
+ }
841
+ /**
842
+ * Prepare and reserve the exact unpublished Session used by resume.
843
+ * Revision retries converge once the durable log remains unchanged for one
844
+ * read/check round trip; continuous external writers may delay completion.
845
+ * @param id - persisted session to prepare.
846
+ * @param signal - optional cancellation for reading and repair.
847
+ * @returns an owned preparation released after publication or rollback.
848
+ */
849
+ async prepare(id, signal) {
850
+ for (;;) {
851
+ await this.waitForRetirement(id, signal);
852
+ if (this.ctx.sessions.get(id) !== void 0) throw new Error(`cannot prepare session "${id}" while it is live`);
853
+ const reservation = await this.preparations.reserve(id, () => this.serialize(id, () => this.prepareCore(id)), (source) => this.serialize(id, () => this.commitPrepared(source), signal), signal);
854
+ if (reservation === void 0) continue;
855
+ if (this.ctx.sessions.get(id) !== void 0) {
856
+ this.preparations.release(reservation, false);
857
+ throw new Error(`cannot prepare session "${id}" while it is live`);
858
+ }
859
+ return SessionPreparation.create(reservation.source.session, { release: () => {
860
+ this.preparations.release(reservation, reservation.state.owner === void 0 && reservation.source.session.events.length === reservation.source.sessionLength);
861
+ } });
862
+ }
863
+ }
864
+ /**
865
+ * Commit recovery and return its immutable logical view without publication.
866
+ * Revision retries converge once the durable log remains unchanged for one
867
+ * read/check round trip; continuous external writers may delay completion.
868
+ * @param id - persisted session to load.
869
+ * @returns prepared header and balanced events.
870
+ */
871
+ async load(id) {
872
+ for (;;) {
873
+ await this.waitForRetirement(id);
874
+ const live = this.ctx.sessions.get(id);
875
+ if (live !== void 0) return this.loadLiveSnapshot(live);
876
+ const reservation = await this.preparations.reserve(id, () => this.serialize(id, () => this.prepareCore(id)), (source) => this.serialize(id, () => this.commitPrepared(source)));
877
+ if (reservation === void 0) continue;
878
+ const attached = this.ctx.sessions.get(id);
879
+ if (attached !== void 0) {
880
+ this.preparations.discard(reservation);
881
+ return this.loadLiveSnapshot(attached);
882
+ }
883
+ this.preparations.discard(reservation);
884
+ return reservation.source.inspection;
885
+ }
886
+ }
887
+ /**
888
+ * Inspect a logical session without publishing it or committing recovery.
889
+ * A stale ready source is reloaded. A source already committing or reserved
890
+ * for resume remains exclusive, and inspection may borrow its immutable view.
891
+ * Revision retries converge once the log is stable for one read/check round
892
+ * trip; continuous external writers may delay completion.
893
+ * @param id - persisted session to inspect.
894
+ * @param signal - optional cancellation for preparation work.
895
+ * @returns immutable prepared metadata and events; a live view may have an open turn.
896
+ */
897
+ async inspect(id, signal) {
898
+ for (;;) {
899
+ signal?.throwIfAborted();
900
+ if (this.retirements.has(id)) await this.waitForRetirement(id, signal);
901
+ const live = this.ctx.sessions.get(id);
902
+ if (live !== void 0) return this.inspectLive(live);
903
+ try {
904
+ const source = await this.preparations.inspect(id, () => this.serialize(id, () => this.prepareCore(id)), signal);
905
+ const attached = this.ctx.sessions.get(id);
906
+ if (attached !== void 0) return this.inspectLive(attached);
907
+ const current = await this.serialize(id, () => this.isPreparedSourceCurrent(source, signal), signal);
908
+ const published = this.ctx.sessions.get(id);
909
+ if (published !== void 0) return this.inspectLive(published);
910
+ if (current) return source.inspection;
911
+ if (this.preparations.discardReady(id, source) === "retained") return source.inspection;
912
+ } catch (error) {
913
+ signal?.throwIfAborted();
914
+ const attached = this.ctx.sessions.get(id);
915
+ if (attached !== void 0) return this.inspectLive(attached);
916
+ throw error;
917
+ }
918
+ }
919
+ }
920
+ /**
921
+ * Read the stored events from `fromSeq` onward, detached and non-mutating
922
+ * (the read-from-seq primitive behind the service's `readFrom`). Runs on
923
+ * the same per-id chain as writes; a backend with the seek-capable
924
+ * {@link PersistenceBackend.loadStoredFrom} hook reads only the suffix,
925
+ * every other backend reads its stored prefix and skips forward here.
926
+ * @param id - persisted session to read.
927
+ * @param fromSeq - first event seq to include; a non-negative safe integer.
928
+ * @param signal - optional cancellation for queued and backend read work.
929
+ * @returns stored header and the valid stored events with `seq >= fromSeq`.
930
+ */
931
+ readFrom(id, fromSeq, signal) {
932
+ if (!Number.isSafeInteger(fromSeq) || fromSeq < 0) return Promise.reject(/* @__PURE__ */ new TypeError(`readFrom fromSeq must be a non-negative safe integer, got ${String(fromSeq)}`));
933
+ const retired = Promise.resolve(this.retirements.get(id));
934
+ return (signal === void 0 ? retired : observeQueuedAbort(retired, signal, () => false)).then(() => this.serialize(id, () => this.readFromCore(id, fromSeq, signal), signal));
935
+ }
936
+ async readFromCore(id, fromSeq, signal) {
937
+ signal?.throwIfAborted();
938
+ if (this.backend.loadStoredFrom !== void 0) {
939
+ let suffix;
940
+ try {
941
+ suffix = await this.backend.loadStoredFrom(id, fromSeq, signal);
942
+ } catch (error) {
943
+ if (signal?.aborted) signal.throwIfAborted();
944
+ throw error;
945
+ }
946
+ signal?.throwIfAborted();
947
+ if (suffix === void 0) throw new Error(`session "${id}" not found`);
948
+ this.assertStoredId(id, suffix.meta);
949
+ this.assertVersion(suffix.meta);
950
+ if (suffix.events.some(needsLegacyPrefix)) {
951
+ const whole = await this.readStoredPrefix(id, signal);
952
+ return {
953
+ meta: whole.meta,
954
+ events: whole.events.filter((event) => event.seq >= fromSeq)
955
+ };
956
+ }
957
+ const events = snapshotStoredEvents(suffix.events, id);
958
+ this.assertEventsSupported(suffix.meta, events);
959
+ return {
960
+ meta: structuredClone(suffix.meta),
961
+ events
962
+ };
963
+ }
964
+ const whole = await this.readStoredPrefix(id, signal);
965
+ return {
966
+ meta: whole.meta,
967
+ events: whole.events.slice(fromSeq)
968
+ };
969
+ }
970
+ /** Read one detached physical prefix without logical recovery or caching. */
971
+ async readStoredPrefix(id, signal) {
972
+ signal?.throwIfAborted();
973
+ const stored = await this.backend.loadStored(id, signal);
974
+ signal?.throwIfAborted();
975
+ if (stored === void 0) throw new Error(`session "${id}" not found`);
976
+ this.assertStoredId(id, stored.meta);
977
+ this.assertVersion(stored.meta);
978
+ const events = snapshotStoredEvents(stored.events, id);
979
+ this.assertEventsSupported(stored.meta, events);
980
+ return {
981
+ meta: structuredClone(stored.meta),
982
+ events
983
+ };
984
+ }
985
+ /** Read, repair in memory, validate, and freeze one cold source once. */
986
+ async prepareCore(id) {
987
+ const stored = await this.backend.loadStored(id);
988
+ if (stored === void 0) throw new Error(`session "${id}" not found`);
989
+ try {
990
+ const { meta, events, revision, tornMarker } = stored;
991
+ this.assertStoredId(id, meta);
992
+ this.assertVersion(meta);
993
+ const storedEvents = adoptStoredEvents(events, id);
994
+ this.assertEventsSupported(meta, storedEvents);
995
+ const closers = interruptedTurnClosers(storedEvents).map(adoptSessionEvent);
996
+ const balanced = [...storedEvents, ...closers];
997
+ const session = this.ctx.sessions.prepare(id, {
998
+ seed: balanced,
999
+ meta,
1000
+ seedSource: "persistence"
1001
+ });
1002
+ return {
1003
+ inspection: Object.freeze({
1004
+ meta: session.header,
1005
+ events: Object.freeze(balanced)
1006
+ }),
1007
+ session,
1008
+ revision,
1009
+ sessionLength: session.events.length,
1010
+ tornMarker,
1011
+ closers
1012
+ };
1013
+ } catch (error) {
1014
+ if (error instanceof SessionFormatUnsupportedError) throw error;
1015
+ throw new SessionPersistenceCorruptionError(`stored session "${id}" failed validation: ${String(error)}`, { cause: error });
1016
+ }
1017
+ }
1018
+ /** Commit one prepared repair and establish its ownerless durable cursor. */
1019
+ async commitPrepared(source) {
1020
+ const id = source.inspection.meta.id;
1021
+ const cursor = source.inspection.events.length;
1022
+ const existing = this.states.get(id);
1023
+ if (existing?.owner !== void 0) throw new Error(`session "${id}" already has a live persistence owner`);
1024
+ if (!await this.isPreparedSourceCurrent(source)) return void 0;
1025
+ if (source.tornMarker !== void 0 || source.closers.length > 0) {
1026
+ await this.backend.commitRepair(source.inspection.meta, source.tornMarker, source.closers);
1027
+ return;
1028
+ }
1029
+ const state = existing ?? {
1030
+ meta: source.inspection.meta,
1031
+ cursor,
1032
+ materialized: true
1033
+ };
1034
+ state.meta = source.inspection.meta;
1035
+ state.cursor = cursor;
1036
+ state.materialized = true;
1037
+ this.states.set(id, state);
1038
+ return {
1039
+ source,
1040
+ state
1041
+ };
1042
+ }
1043
+ /** Whether one cached source still names the current durable log revision. */
1044
+ async isPreparedSourceCurrent(source, signal) {
1045
+ return await this.backend.readStoredRevision(source.inspection.meta.id, signal) === source.revision;
1046
+ }
1047
+ /** Return one durable immutable view of an already-live Session. */
1048
+ async loadLiveSnapshot(session) {
1049
+ const events = session.events;
1050
+ await this.flush(session);
1051
+ const state = this.states.get(session.id);
1052
+ /* v8 ignore next -- successful flush always publishes this live session's durable state */
1053
+ if (state === void 0) throw new Error(`session "${session.id}" lost persistence state during load`);
1054
+ if (events.length === 0) throw new Error(`session "${session.id}" not found`);
1055
+ if (interruptedTurnClosers(events).length > 0) throw new Error(`cannot load session "${session.id}" while its live turn is open; use the live Session or wait for the turn to close`);
1056
+ return Object.freeze({
1057
+ meta: state.meta,
1058
+ events
1059
+ });
1060
+ }
1061
+ /** Borrow one immutable view from an already-live Session. */
1062
+ inspectLive(session) {
1063
+ return Object.freeze({
1064
+ meta: session.header,
1065
+ events: session.events
1066
+ });
1067
+ }
1068
+ /** Await one retiring lifecycle with caller cancellation. */
1069
+ waitForRetirement(id, signal) {
1070
+ const retired = Promise.resolve(this.retirements.get(id));
1071
+ return signal === void 0 ? retired : observeQueuedAbort(retired, signal, () => false);
1072
+ }
1073
+ /**
1074
+ * Run `op` after any in-flight operation for the same session id, so writes for
1075
+ * one session never interleave. Errors do not poison the chain. NOTE: serialized
1076
+ * public methods must NOT call each other (deadlock); they call the unserialized
1077
+ * `*Core` helpers instead.
1078
+ */
1079
+ serialize(id, op, signal) {
1080
+ const prior = this.chains.get(id) ?? Promise.resolve();
1081
+ let started = false;
1082
+ const run = () => {
1083
+ signal?.throwIfAborted();
1084
+ started = true;
1085
+ return op();
1086
+ };
1087
+ const next = prior.then(run, run);
1088
+ const tail = next.then(() => void 0, () => void 0);
1089
+ this.chains.set(id, tail);
1090
+ tail.then(() => {
1091
+ if (this.chains.get(id) === tail) this.chains.delete(id);
1092
+ });
1093
+ return signal === void 0 ? next : observeQueuedAbort(next, signal, () => started);
1094
+ }
1095
+ /** Build a state for a session discovered in storage but not yet in memory. */
1096
+ async adopt(id) {
1097
+ for (;;) {
1098
+ const source = this.preparations.takeReady(id) ?? await this.prepareCore(id);
1099
+ const committed = await this.commitPrepared(source);
1100
+ if (committed !== void 0) return committed.state;
1101
+ }
1102
+ }
1103
+ assertVersion(meta) {
1104
+ if (meta.version === SESSION_FORMAT_VERSION) return;
1105
+ throw this.unsupported(meta, sessionFormatVersionRefusal(meta.id, meta.version));
1106
+ }
1107
+ /**
1108
+ * Refuse a log containing an event type this build does not know, unless the
1109
+ * writer marked the event ignorable: an unrecognized required event may
1110
+ * change how the rest of the log must be interpreted, so silently skipping
1111
+ * it would reconstruct a wrong session (the envelope contract on
1112
+ * `SessionEvent.ignorable`). Runs on NORMALIZED events — after
1113
+ * `snapshotStoredEvents`/`adoptStoredEvents` has upgraded the legacy shapes
1114
+ * this build still reads and rejected the ones it does not, so those keep
1115
+ * their specific diagnostics.
1116
+ */
1117
+ assertEventsSupported(meta, events) {
1118
+ for (const event of events) {
1119
+ if (KNOWN_SESSION_EVENT_TYPES.has(event.type) || event.ignorable === true) continue;
1120
+ throw this.unsupported(meta, `session "${meta.id}" contains event type "${event.type}" (seq ${event.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`);
1121
+ }
1122
+ }
1123
+ /** Build a format refusal that points at the raw artifact when the backend has one. */
1124
+ unsupported(meta, reason) {
1125
+ const location = this.backend.locate?.(meta);
1126
+ return new SessionFormatUnsupportedError(location === void 0 ? reason : `${reason} (raw log: ${location.path})`, location);
1127
+ }
1128
+ /** Reject backend metadata that is not bound to the requested session id. */
1129
+ assertStoredId(id, meta) {
1130
+ if (meta.id !== id) throw new Error(`stored session identity mismatch: requested "${id}", header contains "${meta.id}"`);
1131
+ }
1132
+ installWritePath() {
1133
+ const ctx = this.ctx;
1134
+ ctx.effect(() => async () => {
1135
+ let disposeError;
1136
+ try {
1137
+ const errors = await settledErrors([...this.live.keys()].map((session) => this.flush(session)));
1138
+ while (this.chains.size > 0) await Promise.allSettled([...this.chains.values()]);
1139
+ if (errors.length > 0) throw new AggregateError(errors, `${this.backend.name} dispose failed`);
1140
+ } catch (error) {
1141
+ disposeError = error;
1142
+ throw error;
1143
+ } finally {
1144
+ try {
1145
+ await this.backend.close?.();
1146
+ } catch (closeError) {
1147
+ /* v8 ignore start -- close failure racing disposal is a defensive teardown edge */
1148
+ if (disposeError === void 0) throw closeError;
1149
+ }
1150
+ }
1151
+ }, `${this.backend.name} write path`);
1152
+ ctx.on("session/created", (session) => {
1153
+ this.initFor(session);
1154
+ });
1155
+ ctx.on("session/event", (session, event) => {
1156
+ this.initFor(session).writes.enqueue(event);
1157
+ });
1158
+ ctx.on("session/flush", (session) => this.flush(session));
1159
+ ctx.on("session/disposed", (session) => {
1160
+ this.retire(session);
1161
+ });
1162
+ for (const session of ctx.sessions.list()) this.initFor(session);
1163
+ }
1164
+ /** Start and observe one disposed session's final drain. */
1165
+ retire(session) {
1166
+ if (!this.live.has(session)) return;
1167
+ const retirement = this.retireCore(session);
1168
+ this.retirements.set(session.id, retirement);
1169
+ const forget = () => {
1170
+ if (this.retirements.get(session.id) === retirement) this.retirements.delete(session.id);
1171
+ };
1172
+ retirement.then(forget, forget);
1173
+ retirement.catch((error) => {
1174
+ this.ctx.logger.warn(`${this.backend.name}: session "${session.id}" retirement failed: ${String(error)}`);
1175
+ });
1176
+ }
1177
+ /** Drain and release state owned by one exact disposed Session lifecycle. */
1178
+ async retireCore(session) {
1179
+ await this.flush(session);
1180
+ const id = session.header.id;
1181
+ await this.serialize(id, () => {
1182
+ this.live.delete(session);
1183
+ if (this.states.get(id)?.owner === session) this.states.delete(id);
1184
+ });
1185
+ }
1186
+ /** Return the one lifecycle controller for a live session, creating it if needed. */
1187
+ initFor(session) {
1188
+ const existing = this.live.get(session);
1189
+ if (existing) return existing;
1190
+ const reservation = this.preparations.reservationFor(session);
1191
+ if (reservation !== void 0) {
1192
+ const restored = this.attachPrepared(session, reservation);
1193
+ this.live.set(session, restored);
1194
+ return restored;
1195
+ }
1196
+ const seed = session.events;
1197
+ const live = {
1198
+ init: Promise.resolve(),
1199
+ writes: this.createWriteBehind(session, () => live.init)
1200
+ };
1201
+ this.live.set(session, live);
1202
+ live.init = this.serialize(session.header.id, () => this.onCreated(session, seed));
1203
+ live.init.catch(() => {});
1204
+ return live;
1205
+ }
1206
+ /** Bind one exact prepared Session and persist only its unpublished suffix. */
1207
+ attachPrepared(session, reservation) {
1208
+ const { source, state } = reservation;
1209
+ if (source.session !== session || state.owner !== void 0 || state.cursor !== source.inspection.events.length || session.firstLiveSeq !== state.cursor) throw new Error(`session "${session.id}" preparation no longer matches its persistence state`);
1210
+ const suffix = session.events.slice(state.cursor).map((event) => structuredClone(event));
1211
+ this.preparations.attach(reservation);
1212
+ state.owner = session;
1213
+ const live = {
1214
+ init: Promise.resolve(),
1215
+ writes: this.createWriteBehind(session, () => live.init)
1216
+ };
1217
+ if (suffix.length > 0) {
1218
+ live.init = this.serialize(session.id, () => this.appendCore(session.id, suffix));
1219
+ live.init.catch(() => {});
1220
+ }
1221
+ return live;
1222
+ }
1223
+ /**
1224
+ * Whether a live session's `seed` reproduces the first `cursor` persisted
1225
+ * events. A `cursor` of 0 (nothing persisted yet) trivially matches. Used when
1226
+ * a live session claims ownerless state left by a prior `load()`/`create()`.
1227
+ */
1228
+ async seedMatchesPersisted(id, seed, cursor) {
1229
+ if (cursor === 0) return true;
1230
+ const stored = await this.backend.loadStored(id);
1231
+ /* v8 ignore next -- a cursor > 0 means the session was materialized, so it exists */
1232
+ if (stored === void 0) return false;
1233
+ this.assertStoredId(id, stored.meta);
1234
+ return seedCoversPrefix(seed, snapshotStoredEvents(stored.events, id).slice(0, cursor));
1235
+ }
1236
+ /**
1237
+ * On session/created: sync the backend's in-memory state to a live Session.
1238
+ *
1239
+ * Cases, by whether this backend tracks the id and whether an artifact exists:
1240
+ * 1. Already tracked → no-op (or claim ownerless state if the seed matches,
1241
+ * or reclaim a truly-abandoned id, else reject as a collision).
1242
+ * 2. Not tracked, an artifact EXISTS at the same cwd and is a seq-aligned
1243
+ * PREFIX of the live events → ADOPT it, persisting any live suffix.
1244
+ * 3. Not tracked, an artifact EXISTS at another cwd or is NOT a prefix →
1245
+ * REJECT (collision).
1246
+ * 4. Not tracked and NO artifact → a genuinely new session: register meta
1247
+ * (lazy) and persist its seed once.
1248
+ */
1249
+ async onCreated(session, seed) {
1250
+ const id = session.header.id;
1251
+ const tracked = this.states.get(id);
1252
+ if (tracked !== void 0) {
1253
+ /* v8 ignore next -- initFor dedupes per session object; same-object re-entry can't occur */
1254
+ if (tracked.owner === session) return;
1255
+ if (tracked.owner === void 0) {
1256
+ if (tracked.meta.cwd !== session.header.cwd) throw new Error(`session "${id}" is already persisted at a different cwd (persisted: ${String(tracked.meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`);
1257
+ if (!await this.seedMatchesPersisted(id, seed, tracked.cursor)) throw new Error(`session "${id}" is already persisted with ${tracked.cursor} event(s) that do not match this live session (id collision)`);
1258
+ tracked.owner = session;
1259
+ const suffix = seed.slice(tracked.cursor);
1260
+ if (suffix.length > 0) await this.appendCore(id, suffix);
1261
+ return;
1262
+ }
1263
+ const owner = this.live.get(tracked.owner);
1264
+ if (!tracked.materialized && !owner?.writes.hasWork) this.states.delete(id);
1265
+ else throw new Error(`session "${id}" is already bound to a different live session in this backend (id collision)`);
1266
+ }
1267
+ const live = await this.backend.loadStored(id);
1268
+ if (live !== void 0) {
1269
+ await this.adoptLivePrefix(session, seed, live);
1270
+ return;
1271
+ }
1272
+ const meta = { ...session.header };
1273
+ await this.createCore(meta);
1274
+ const created = this.states.get(id);
1275
+ /* v8 ignore next -- create() always sets the state for the id */
1276
+ if (created !== void 0) created.owner = session;
1277
+ if (seed.length > 0) await this.appendCore(id, seed);
1278
+ }
1279
+ /**
1280
+ * Adopt a stored prefix as a live session's history (HMR/reload): verify the
1281
+ * seed covers the stored prefix, truncate any torn tail (NOT the open turn —
1282
+ * the live Session is still the authority), bind ownership, and persist the
1283
+ * live suffix that was ahead of the stored prefix.
1284
+ */
1285
+ async adoptLivePrefix(session, seed, stored) {
1286
+ const { meta, events, tornMarker } = stored;
1287
+ this.assertStoredId(session.header.id, meta);
1288
+ if (meta.cwd !== session.header.cwd) throw new Error(`session "${session.header.id}" is already persisted at a different cwd (persisted: ${String(meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`);
1289
+ this.assertVersion(meta);
1290
+ const storedEvents = snapshotStoredEvents(events, session.header.id);
1291
+ this.assertEventsSupported(meta, storedEvents);
1292
+ if (!seedCoversPrefix(seed, storedEvents)) throw new Error(`session "${session.header.id}" already has a persisted log on disk that does not match this live session (id collision)`);
1293
+ if (tornMarker !== void 0) await this.backend.commitRepair(meta, tornMarker, []);
1294
+ this.states.set(session.header.id, {
1295
+ meta: { ...meta },
1296
+ cursor: storedEvents.length,
1297
+ materialized: true,
1298
+ owner: session
1299
+ });
1300
+ const suffix = seed.slice(storedEvents.length);
1301
+ if (suffix.length > 0) await this.appendCore(session.header.id, suffix);
1302
+ }
1303
+ async flush(session) {
1304
+ const live = this.initFor(session);
1305
+ live.writes.cancelAutomaticWait();
1306
+ try {
1307
+ await live.init;
1308
+ } catch (error) {
1309
+ live.writes.cancelAutomaticWait();
1310
+ throw error;
1311
+ }
1312
+ await live.writes.flush();
1313
+ }
1314
+ /** Build one package-private write controller around initialization and id serialization. */
1315
+ createWriteBehind(session, ready) {
1316
+ return new SessionWriteBehind({
1317
+ maxDelayMs: this.writeBatchMaxDelayMs,
1318
+ write: async (batch) => {
1319
+ await ready();
1320
+ await this.serialize(session.header.id, () => this.appendLiveBatch(session.header.id, batch));
1321
+ },
1322
+ reportBackgroundFailure: (error) => {
1323
+ this.ctx.logger.warn(`${this.backend.name}: background write for session "${session.id}" failed (buffered events retained): ${String(error)}`);
1324
+ }
1325
+ });
1326
+ }
1327
+ /** Append one controller-owned prefix after filtering events initialization already stored. */
1328
+ async appendLiveBatch(id, batch) {
1329
+ /* v8 ignore next -- state is always set by the awaited initialization */
1330
+ const cursor = this.states.get(id)?.cursor ?? 0;
1331
+ const fresh = batch.filter((e) => e.seq >= cursor);
1332
+ await this.appendCore(id, fresh);
1333
+ }
1334
+ };
1335
+ //#endregion
1336
+ //#region lib/types/index.js
1337
+ /**
1338
+ * Durable session-persistence Service Definition (`ctx.sessionPersistence`). Backends store
1339
+ * {@link SessionEvent}s as the event-sourced log and carry non-replayable
1340
+ * {@link SessionHeader} metadata separately.
1341
+ * @module @hasna-internal/kai-session-persistence
1342
+ */
1343
+ /**
1344
+ * Durable append-only session storage. Implementations preserve contiguous,
1345
+ * losslessly JSON-serializable events; {@link append} resolves only after
1346
+ * durability, and {@link load} balances a complete interrupted tail without
1347
+ * rewriting committed events.
1348
+ */
1349
+ var SessionPersistence = class extends Service {
1350
+ constructor(ctx) {
1351
+ super(ctx, "sessionPersistence");
1352
+ }
1353
+ /**
1354
+ * Read a session's backend-owned artifact text verbatim — the exact durable
1355
+ * bytes the backend wrote (decoded from its physical encoding, e.g. a
1356
+ * decompressed JSONL). The returned `content` is the raw text, not a
1357
+ * reconstruction from parsed events, so it preserves backend-specific
1358
+ * serialization (chunk packing, key order, line breaks). Callers first test
1359
+ * {@link supportsRawArtifacts}; `undefined` then means only that the requested
1360
+ * session has no materialized artifact.
1361
+ * @param _id - the persisted session to read (unused by the default: no
1362
+ * per-session artifact).
1363
+ * @param signal - optional cancellation for backend read work.
1364
+ * @returns the raw artifact plus its parsed header, or `undefined` when the
1365
+ * session is absent.
1366
+ * @throws when this backend does not expose per-session raw artifacts.
1367
+ */
1368
+ readRaw(_id, signal) {
1369
+ if (signal?.aborted === true) return Promise.reject(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
1370
+ return Promise.reject(/* @__PURE__ */ new Error("this session persistence backend does not expose raw artifacts"));
1371
+ }
1372
+ /**
1373
+ * Prepare the exact unpublished Session used by resume. Implementations may
1374
+ * reuse object graphs retained by an earlier {@link inspect} after confirming
1375
+ * their durable revision is still current; disposal releases an unpublished
1376
+ * reservation. Revision retries require the durable log to remain unchanged
1377
+ * for one read/check round trip; continuous external writers may delay completion.
1378
+ * @param id - persisted session to prepare.
1379
+ * @param signal - optional cancellation for preparation work.
1380
+ * @returns one owned unpublished Session preparation.
1381
+ */
1382
+ async prepare(id, signal) {
1383
+ signal?.throwIfAborted();
1384
+ const loaded = await this.load(id);
1385
+ signal?.throwIfAborted();
1386
+ const sessions = this.ctx.get("sessions");
1387
+ if (sessions === void 0) throw new Error("cannot prepare a session: SessionStore is not configured");
1388
+ return SessionPreparation.create(sessions.prepare(id, {
1389
+ seed: loaded.events.map((event) => structuredClone(event)),
1390
+ meta: structuredClone(loaded.meta),
1391
+ seedSource: "persistence"
1392
+ }));
1393
+ }
1394
+ };
1395
+ //#endregion
1396
+ export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionFormatUnsupportedError, SessionPersistence, SessionPersistence as default, SessionPersistenceCorruptionError, SessionPersistenceRevision, sessionFormatVersionRefusal };