@x1a0f3n9/dsh-session-persistence 0.1.2-alpha.6

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