@mmstack/mesh 21.15.2 → 21.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@mmstack/mesh",
3
- "version": "21.15.2",
3
+ "version": "21.16.0",
4
+ "description": "Local-first sync for signal stores: multi-writer, offline-capable, reads like a local store.",
4
5
  "keywords": [
5
6
  "angular",
6
7
  "signals",
@@ -9,7 +10,10 @@
9
10
  "multiplayer",
10
11
  "collaboration",
11
12
  "local-first",
12
- "presence"
13
+ "presence",
14
+ "offline-first",
15
+ "crdt",
16
+ "realtime"
13
17
  ],
14
18
  "license": "MIT",
15
19
  "repository": {
@@ -20,8 +24,8 @@
20
24
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/mesh/client",
21
25
  "peerDependencies": {
22
26
  "@angular/core": ">=21 <22",
23
- "@mmstack/primitives": ">=21.25 <22",
24
- "@mmstack/mesh-protocol": ">=0.15.2 <1"
27
+ "@mmstack/primitives": ">=21.26 <22",
28
+ "@mmstack/mesh-protocol": ">=0.16.0 <1"
25
29
  },
26
30
  "sideEffects": false,
27
31
  "module": "fesm2022/mmstack-mesh.mjs",
@@ -1,6 +1,12 @@
1
1
  import { Signal, Injector, WritableSignal } from '@angular/core';
2
- import { StoreOp, GenerationReason, TailPolicy, Hlc, ClientMsg, ServerMsg, Relay, PrincipalCtx, IceServer, ClientSignalMsg, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
3
- import { OpEnvelope, OpSync, MergePolicyEntry, DiffOpsOptions, AsyncStore, ForkStoreOptions, SyncedFork, WritableSignalStore, StoreOp as StoreOp$1, toStoreOptions } from '@mmstack/primitives/core';
2
+ import { GenerationReason, TailPolicy, Hlc, ClientMsg, ServerMsg, Relay, PrincipalCtx, IceServer, ClientSignalMsg, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
3
+ import { StoreOp, OpEnvelope, OpSync, MergePolicyEntry, DiffOpsOptions, JournalStore, ForkStoreOptions, SyncedFork, WritableSignalStore, toStoreOptions } from '@mmstack/primitives/core';
4
+
5
+ /** The authored intent of an own envelope: its raw ops and one bump flag, what a re-author rebuilds from. */
6
+ type Intent = {
7
+ readonly raws: readonly StoreOp[];
8
+ readonly bump: boolean;
9
+ };
4
10
 
5
11
  /**
6
12
  * The client half of a room generation: the record fields a snapshot welcome carries, the admission
@@ -20,17 +26,6 @@ type InstalledGeneration = {
20
26
  /** The seq of the snapshot welcome that installed it (or a later one of the same generation). */
21
27
  readonly seq: number;
22
28
  };
23
- /**
24
- * The authored intent of an envelope: its raw op list and one bump flag, what a re-author rebuilds
25
- * from. The raws are the stamped ops without their expansion clears (a diffed write never emits a
26
- * `clear` of its own, so every `clear` is one) and without cites and epoch. The envelope bumped when
27
- * an op's epoch rises above the register baseline at its path as the client held it before the
28
- * envelope (the relay's own test for a bump).
29
- */
30
- type Intent = {
31
- readonly raws: readonly StoreOp[];
32
- readonly bump: boolean;
33
- };
34
29
 
35
30
  /**
36
31
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
@@ -84,17 +79,50 @@ type ConflictCause = 'uncovered' | 'citation' | 'epoch-bump';
84
79
  * A write that will never be admitted as it stands. Its local effect is retracted (a replay that
85
80
  * failed its pre-check is never applied; a refused write is dropped by the snapshot that follows).
86
81
  * The two verbs are the whole surface: `discard()` lets it go, `reauthor()` writes its raw ops again
87
- * as a new write citing the current state. Neither can submit the original envelope.
82
+ * as a new write citing the current state. Neither can submit the original envelope. A conflict is
83
+ * listed once its verdict is stored, and stays listed across reboots until it is answered.
88
84
  */
89
85
  type MeshConflict = {
90
86
  /** The envelope as it was authored (its values, cites and epoch). */
91
87
  readonly env: OpEnvelope;
92
88
  readonly intent: Intent;
93
89
  readonly cause: ConflictCause;
90
+ /** Let the write go. Nothing happens once the session has ended. */
94
91
  discard(): void;
95
- /** Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`). */
92
+ /**
93
+ * Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`).
94
+ * Also false when the conflict's ops cannot be written again as one write (a path twice, or an
95
+ * op under another op's path that is not an earlier set of a plain record); the conflict then
96
+ * stays, so it can still be discarded. Also false once the session has ended (closed or
97
+ * ejected): nothing is written and the conflict stays held. Also false inside
98
+ * {@link MeshSession.recordTogether}, with the same outcome.
99
+ * `true` means the write was emitted, not that it shows: one whose parent is gone by now, or
100
+ * that loses its fold, leaves the store as it was. The answer and the new write are stored
101
+ * together: after a crash either both are there or neither is. A write made before the call is
102
+ * not part of them: it is recorded on its own, first. False when the re-author emitted nothing.
103
+ */
96
104
  reauthor(): boolean;
97
105
  };
106
+ /**
107
+ * Why an own write was not stored: `'generation'` (written in a room generation a cut or a lost
108
+ * room creation closed), `'schema'` (a data shape older than the room's), `'order'` (a version below
109
+ * this origin's admitted maximum that was never admitted: a second writer on one origin),
110
+ * `'compacting'` (a host refused it while this client was declared ready for a cut) or
111
+ * `'incompatible'` (a restored write this client can no longer send).
112
+ */
113
+ type UnstoredReason = 'generation' | 'schema' | 'order' | 'compacting' | 'incompatible';
114
+ /**
115
+ * An own write that is not in the room and never will be, listed until the application dismisses it.
116
+ * It is listed once its verdict is stored, and again after a reboot until its dismissal is stored.
117
+ */
118
+ type UnstoredWrite = {
119
+ /** The envelope as it was authored: its values, so the application can offer to write them again. */
120
+ readonly env: OpEnvelope;
121
+ readonly intent: Intent;
122
+ readonly reason: UnstoredReason;
123
+ /** Remove the entry; it leaves the list at once. Nothing happens once the session has ended. */
124
+ dismiss(): void;
125
+ };
98
126
  /** The room's compaction state, as the relay last announced it. */
99
127
  type CompactionState = {
100
128
  /** Droppable tombstones counted against the budget. */
@@ -116,7 +144,11 @@ type MeshDirect = {
116
144
  readonly data: unknown;
117
145
  };
118
146
 
119
- /** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */
147
+ /**
148
+ * A data channel as the P2P engine needs it; it opens later. Peer links send only on an open
149
+ * channel, so the contract asks for no buffering, but the channels of {@link rtcPeerConnector}
150
+ * buffer sends made before open and flush them when the channel opens.
151
+ */
120
152
  type DataChannelLike = {
121
153
  send(frame: string): void;
122
154
  onMessage(cb: (frame: string) => void): () => void;
@@ -294,25 +326,37 @@ type MeshPeer = PresenceState;
294
326
  /**
295
327
  * A composed, user-facing health status for a synced store the surface that
296
328
  * turns a versioned reject from a dead socket into a speakable 'outdated' banner.
329
+ * `'storage'`: the outbox can no longer save this handle's writes, and the session has ended and
330
+ * sends nothing more. The reason says why: `'moved'` (another tab wrote the outbox in its place),
331
+ * `'exhausted'` (the outbox ran out of sequence numbers) or `'storage'` (a save failed, or the
332
+ * outcome of a write is not known: it is reported neither as saved nor as lost). A first read of
333
+ * the outbox that fails does not end the handle; see `outboxUnreadable`.
297
334
  */
298
- type SyncHealthStatus = 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded';
335
+ type SyncHealthStatus = 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded' | 'storage';
299
336
  type SyncHealth = {
300
337
  readonly status: SyncHealthStatus;
301
- /** Why, when the status is `outdated`/`ejected`/`degraded`. */
302
- readonly reason?: 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});
338
+ /** Why, when the status is `outdated`/`ejected`/`degraded`/`storage`. */
339
+ readonly reason?: 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | 'storage' | 'moved' | 'exhausted' | (string & {});
303
340
  /** `Date.now()` of the last successful sync (welcome or applied env). */
304
341
  readonly lastSyncedAt?: number;
305
342
  /**
306
- * Offline writes persisted by an older build that could not be restored on boot. Envelopes
307
- * from a previous wire-protocol version lack the citation metadata current merging needs,
308
- * so they are dropped (loudly) instead of being upgraded with fabricated citations.
343
+ * How many groups of this handle's writes are in storage's hands and not yet saved. Nothing times
344
+ * out: a store that never answers keeps it above zero until the handle closes.
345
+ */
346
+ readonly storing: number;
347
+ /**
348
+ * Saved offline writes this boot cannot send: written under another writer, protocol version or
349
+ * policy version, malformed, or rejected by the room policy. They are never sent; each is listed
350
+ * in `unstored` with the reason `'incompatible'`.
309
351
  */
310
352
  readonly droppedOfflineWrites?: number;
311
353
  /**
312
- * Writes the relay refused on this session: they are not in the room. Each was handed to
313
- * `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.
354
+ * The saved outbox could not be read: it is in a format this build cannot read, or the store
355
+ * failed the read. It is left as it is, and this boot's writes are kept in memory only, under an
356
+ * origin of their own, until the handle closes. The handle runs live over memory, and its
357
+ * health does not turn `'storage'` for this.
314
358
  */
315
- readonly refusedWrites?: number;
359
+ readonly outboxUnreadable?: true;
316
360
  /**
317
361
  * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id
318
362
  * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a
@@ -353,14 +397,36 @@ type MeshSyncOptions = {
353
397
  readonly reconnect?: {
354
398
  readonly maxDelayMs?: number;
355
399
  };
400
+ /**
401
+ * How long a hello may go unanswered before the connection is closed and opened again:
402
+ * `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up to
403
+ * `maxTimeoutMs` (default 120 000). An answered hello starts the count again. A hello that goes
404
+ * unanswered also counts as a failed attempt for the reconnect backoff. A relay that never
405
+ * answers a hello within `maxTimeoutMs` leaves the client resetting the connection at that pace
406
+ * for as long as it lasts: nothing is lost, and nothing gets through.
407
+ */
408
+ readonly handshake?: {
409
+ readonly timeoutMs?: number;
410
+ readonly maxTimeoutMs?: number;
411
+ };
356
412
  readonly injector?: Injector;
357
413
  /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */
358
414
  readonly register?: 'track' | 'suspend';
415
+ /**
416
+ * Called once when the handle ends by itself (`ejected`, with the reason) and when a
417
+ * `clearOutbox()` ends it (`'cleared'`); never for `close()`. A callback that throws is reported
418
+ * and changes nothing.
419
+ */
359
420
  readonly onEject?: (reason: string) => void;
360
- /** The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message too big, 1006 = dropped). */
421
+ /**
422
+ * The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message
423
+ * too big, 1006 = dropped). The client also closes a connection itself, with code 1000 and the
424
+ * reason `'timeout'` (a hello went unanswered), `'displaced'` (a later connection of this client
425
+ * took its place) or `'counter'` (the connection used up its request ids). A transport factory or
426
+ * a `send` that throws is reported and loses the connection, with code 1006 and the reason
427
+ * `'transport'` or `'send'`.
428
+ */
361
429
  readonly onDisconnect?: (code: number, reason: string) => void;
362
- /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
363
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order' | 'compacting') => void;
364
430
  /**
365
431
  * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
366
432
  * (and before it restores an `outbox`), so a store hydrated from another source first (a worker
@@ -370,35 +436,50 @@ type MeshSyncOptions = {
370
436
  */
371
437
  readonly whenReady?: () => PromiseLike<void> | void;
372
438
  /**
373
- * Persist the unacknowledged local outbox (and the writing boot's origin) so offline writes
374
- * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room
375
- * on the next welcome, instead of being lost with in-memory state. The payload is written to
376
- * `store` under `key`, debounced.
439
+ * Keep this client's own writes in `store` under `key`, so offline writes survive a reboot, not
440
+ * just a live reconnect. Every write is saved before it is sent, and every answer about it is
441
+ * saved before it shows, so a crash at any moment loses nothing that was sent. On boot the saved
442
+ * writes that are still pending are restored and sent again, unchanged, after the next welcome.
443
+ * The saved outbox also keeps this client's origin, so every boot that reads it continues as the
444
+ * same client. Without an outbox, writes are kept in memory only and each boot has an origin of
445
+ * its own.
377
446
  *
378
- * The persisted outbox under `key` is a single-writer slot: every persist overwrites it whole, so
379
- * two tabs writing one key would each drop the other's tail from disk. A Web Lock on `key` elects
380
- * the one tab that restores from the slot and writes to it; origins are fresh on every boot either
381
- * way, so the lock guards the slot, not the origin. `crossTab` sets what a tab that did not get the
382
- * lock does: `'queue'` (default) waits (`status` reads `'waiting'`) and takes over when the owner
383
- * closes; `'ephemeral'` runs live at once and never touches the slot. `'off'` skips the lock and
384
- * leaves ownership to you (e.g. a per-tab key, or leader election over `tabSync`). A debounced
385
- * write means a hard crash within the debounce window can drop the very last mint — a small,
386
- * best-effort gap; tune it with `debounceMs`.
447
+ * The store is a `JournalStore` (build one over idb-keyval's shape with `journalStore`). Two
448
+ * keys are written, `<key>:log` and `<key>:snap`. A value saved under `key` itself by an earlier
449
+ * version of this library is deleted unread at each boot, when the store can delete.
450
+ *
451
+ * Storage decides between tabs: when another tab has written the outbox in this handle's place,
452
+ * this handle ends `ejected` with the reason `'moved'`. A write it had not saved by then is not
453
+ * saved, and no other tab can send it: `acked` reads `false` and `whenAcked()` rejects, and the
454
+ * application decides what to do with it. A Web Lock on `key` keeps live tabs from taking each
455
+ * other's place; `crossTab` sets what a tab that did not get the lock does. Within one page, a handle
456
+ * made in the turn another handle over the same key was closed takes over from it (unless another
457
+ * tab asked for the lock first). A handle made while another handle of this page over the
458
+ * same key is still open is treated as a second tab would be: `'queue'` waits for it, `'ephemeral'`
459
+ * runs over memory for its life. So close the old handle first. Two copies of this library in one
460
+ * page behave as two tabs. Store writes made while the boot
461
+ * waits (for the lock or the read) are held in memory and sent, as their net change, when the tab
462
+ * boots. Nothing times out: a store call that never answers keeps the handle live and holding the
463
+ * lock, and `health().storing` above zero, until it closes.
387
464
  */
388
465
  readonly outbox?: {
389
466
  readonly key: string;
390
- readonly store: AsyncStore;
391
- /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */
392
- readonly debounceMs?: number;
467
+ readonly store: JournalStore;
393
468
  /**
394
- * Cross-tab contention for the shared `key`. The persisted outbox is a single-writer slot: the
395
- * Web Lock elects the one tab that restores from it and writes to it.
396
- * `'queue'` (default): a tab that did not get the lock WAITS (`status` reads `'waiting'`) and
397
- * takes over when the owner closes. `'ephemeral'`: it runs live at once on its own fresh origin
398
- * and never touches the slot — its unacknowledged writes live in memory only and are lost if that
399
- * tab terminates before the room acknowledges them — online or offline, and it stays ephemeral
400
- * for life, also after the owner leaves. When the lock is free both behave the same (take it,
401
- * restore, persist). `'off'` skips the lock (you coordinate ownership).
469
+ * What a tab does when another tab holds the lock for `key`.
470
+ * `'queue'` (default): it WAITS (`status` reads `'waiting'`) and takes over when the owner
471
+ * closes; store writes made while it waits are sent, as their net change, when it takes over.
472
+ * `'ephemeral'`: it runs live at once, as a client of its own, and never touches the saved
473
+ * outbox: its writes live in memory only and are lost if that tab ends before the room
474
+ * acknowledges them. It stays ephemeral for life, also after the owner leaves. When the lock is
475
+ * free both behave the same (take it, restore, save).
476
+ * A `'queue'` handle closed while it waits for another tab keeps its place in the browser's lock
477
+ * queue until its turn; then the lock is taken and given back at once. Until then a new handle
478
+ * of this page is treated as it would be while that other tab holds the lock.
479
+ * `'off'` skips the lock: every tab that opens the key continues the same saved client, and
480
+ * when two tabs write it, one of them ends `ejected` with the reason `'moved'`. Without the
481
+ * lock a tab that has only read the outbox does not keep another tab's `clearOutbox()` from
482
+ * wiping what it is about to send. In development mode it warns once.
402
483
  */
403
484
  readonly crossTab?: 'queue' | 'off' | 'ephemeral';
404
485
  };
@@ -415,7 +496,10 @@ type MeshSyncOptions = {
415
496
  type SeatSync<T = unknown> = Pick<OpSync<T>, 'override' | 'captureFrontier' | 'commitScope' | 'liveUnder' | 'liveAt' | 'appliedFrontier'>;
416
497
  type MeshSyncRef<T extends object = Record<string, unknown>> = {
417
498
  readonly status: Signal<MeshStatus>;
418
- /** Origin used by the current session's hello; null until hello, including while waiting on an outbox. */
499
+ /**
500
+ * This client's origin: the saved outbox's, the same on every boot that reads it, or one of its
501
+ * own for a boot without a saved outbox. Null until the outbox has loaded.
502
+ */
419
503
  readonly origin: Signal<string | null>;
420
504
  /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */
421
505
  readonly members: Signal<readonly string[]>;
@@ -424,16 +508,36 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
424
508
  /** Composed sync-health for a user-facing surface. */
425
509
  readonly health: Signal<SyncHealth>;
426
510
  /**
427
- * Every local write is acknowledged by the room. `false` while a write is still in the
428
- * unacknowledged tail, and it stays `false` once a session ends with writes outstanding —
429
- * those never landed, and no later echo can arrive to change that.
511
+ * Everything written through this handle is saved as the room's: nothing is pending or still
512
+ * being saved and no conflict is held. The signal follows the sync engine, which takes a store
513
+ * write up a moment later, at its next tick: read in the same turn as a write, it still gives
514
+ * the earlier answer. `whenAcked()` counts a write made in this turn, and from that call this
515
+ * signal counts it too. To ask whether everything is saved, including what was just written,
516
+ * call `whenAcked()`. `false` until the outbox has
517
+ * loaded (what is pending is not known before), while a write waits for the room or for storage,
518
+ * while a conflict is held (until it is discarded or written again), and for good once a write
519
+ * can no longer land: a write after an eject, or a write the emit-side policy
520
+ * rejected. After an eject it is `true` exactly when nothing was outstanding at the ejection
521
+ * and nothing was written since. A close freezes it: it keeps the value it had at the close,
522
+ * and a write after the close does not change it. After a storage failure or `clearOutbox()` it
523
+ * is `false`. Writes inside `whenReady` are the local base, not writes of their own. Writes made
524
+ * while the boot is held (waiting for the outbox lock or its read) are saved and sent, as their
525
+ * net change, when the boot ends; each `sync.override` made in the hold is its own authority
526
+ * write, in order. A write the relay refused is listed in `unstored`, not here.
430
527
  */
431
528
  readonly acked: Signal<boolean>;
432
529
  /**
433
- * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
434
- * with the terminal reason if the session ends while writes are outstanding. The barrier
435
- * to await before publishing something that must contain every edit; `synced()` is a
436
- * connection indicator, not a save barrier.
530
+ * Resolves once nothing written through this handle is outstanding and that is saved
531
+ * (immediately if it already is). Before the outbox has loaded it waits for the load. Rejects
532
+ * with the terminal reason if the session ends while writes are outstanding or a write can no
533
+ * longer land (`'closed'` for writes held in a boot that is closed before it connects), with
534
+ * `'storage'`, `'moved'` or `'exhausted'` once the outbox can no longer save, with `'cleared'`
535
+ * after `clearOutbox()`, and with `'schema'` when this client's data shape is older than the
536
+ * room's. While a conflict is held it rejects at once with `conflict: <cause>`; a terminal reason
537
+ * wins. A write the relay refused rejects the calls pending when its answer is saved with
538
+ * `refused: <reason>`; a later call does not wait for it. The barrier to await before publishing
539
+ * something that must contain every edit; `synced()` is a connection indicator, not a save
540
+ * barrier.
437
541
  */
438
542
  whenAcked(): Promise<void>;
439
543
  readonly peers: Signal<readonly MeshPeer[]>;
@@ -447,6 +551,7 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
447
551
  /**
448
552
  * Listen for `direct` frames addressed to this client; returns the unsubscribe. A frame that
449
553
  * arrives with no listener is lost. Peer links on {@link MeshSyncRef.signaling} never see them.
554
+ * A listener that throws is reported, and the others still hear the frame.
450
555
  */
451
556
  direct(cb: (msg: MeshDirect) => void): () => void;
452
557
  /**
@@ -454,23 +559,40 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
454
559
  * fork observes the room as it is now; committing emits its diff citing only those observed
455
560
  * writes, so an edit that lands on the room while the fork is open stays a concurrent value the
456
561
  * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe
457
- * the room and commit on top of the latest instead. `discard()` drops the staged edits.
562
+ * the room and commit on top of the latest instead. `discard()` drops the staged edits and also
563
+ * re-observes the room, so a later commit on the same fork cites the room as it is at the discard.
564
+ * Before the boot nothing has been observed, so a fork commit made then is a plain held write.
458
565
  */
459
566
  fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
460
- /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */
567
+ /**
568
+ * Authority surface over this handle's op-sync; see {@link SeatSync}. It is one object for the
569
+ * handle's life: taken before the boot, it works over the engine once the outbox has loaded.
570
+ * When the callback of `override` throws, the error reaches the caller and the writes it made are
571
+ * still sent with the override's authority, also while the boot is held. Before the boot nothing
572
+ * has been observed, so a `commitScope` run then is a plain held write.
573
+ */
461
574
  readonly sync: SeatSync<T>;
462
575
  /**
463
576
  * Writes that will never be admitted as they stand: a write a compaction cut could not replay
464
577
  * (it cites something the cut folded away) or one the relay refused. Each offers `discard()` or
465
- * `reauthor()` (write its values again, citing the current state). Persisted with the outbox.
578
+ * `reauthor()` (write its values again, citing the current state). Saved with the outbox: a
579
+ * conflict stays listed across reboots until it is answered.
466
580
  */
467
581
  readonly conflicts: Signal<readonly MeshConflict[]>;
582
+ /**
583
+ * Own writes that are not in the room and never will be, in the order they were made: refused by
584
+ * the relay, discarded with a room generation, or saved offline and no longer sendable by this
585
+ * boot (`'incompatible'`). Each entry holds the write, so it can be offered again, its reason, and
586
+ * `dismiss()`, which removes it. An entry is listed once its answer is saved and stays listed
587
+ * across reboots until its dismissal is saved. Empty before the outbox has loaded.
588
+ */
589
+ readonly unstored: Signal<readonly UnstoredWrite[]>;
468
590
  /** The room's compaction state as the relay last announced it; undefined before any notice. */
469
591
  readonly compaction: Signal<CompactionState | undefined>;
470
592
  /**
471
593
  * The room generation this client installed: set by every snapshot welcome of a new generation
472
594
  * (a cut's welcome flips it), untouched by one of the installed generation. Undefined until the
473
- * first snapshot welcome and after a room was recreated without its record.
595
+ * first snapshot welcome of this boot.
474
596
  */
475
597
  readonly generation: Signal<GenerationState | undefined>;
476
598
  /**
@@ -479,6 +601,55 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
479
601
  * reconnect or a new generation releases it.
480
602
  */
481
603
  declareReady(pressed: boolean): void;
604
+ /**
605
+ * Discard every write not yet in the room, every conflict and every `unstored` entry, and end the
606
+ * session. From the call nothing more is sent or saved, `acked` reads `false` and `whenAcked()`
607
+ * rejects with `'cleared'`; the handle keeps the outbox lock and its status until storage answers.
608
+ * The session ends `closed` with the reason `'cleared'` once storage holds the wipe, and the
609
+ * promise resolves then. It rejects with `'moved'` when another tab wrote the outbox first, with
610
+ * `'storage'` when the outcome is not known, and with the reason of any ending that comes first
611
+ * (`'closed'` for `close()`). A crash before it resolves leaves the outbox as it was, and the next
612
+ * boot continues it and sends what is pending. Called before the boot has finished, it clears
613
+ * once the boot is done, or rejects with the boot's reason.
614
+ *
615
+ * A handle runs over memory when it was given no `outbox`, when it is an `'ephemeral'` tab beside
616
+ * another tab that holds the outbox, or when the saved outbox could not be read. Called while
617
+ * such a handle is live, the clear discards this handle's own writes, resolves, and ends the
618
+ * handle `closed` with `'cleared'`, calling `onEject('cleared')`. A saved outbox the handle never
619
+ * held is left exactly as it is, and the next boot that can read it sends what it holds. An
620
+ * outbox that could not be read is not removed by `clearOutbox()`: the application removes it
621
+ * from its own store, under the key it gave, when it wants it gone.
622
+ *
623
+ * Called once the session has ended by itself (ejected, outdated, a storage ending), it takes the
624
+ * outbox lock if it is free (else it rejects with `'busy'`), reads the outbox again and wipes it
625
+ * only when no other tab has written it since this handle ended (else it rejects with `'moved'`);
626
+ * it rejects with `'unreadable'` when the outbox cannot be read again, and with `'storage'` when
627
+ * the store does not say whether the wipe was stored. It
628
+ * holds the lock until storage answers, and `close()` meanwhile rejects it with `'closed'`.
629
+ * After `close()`, and for a handle that never held the saved outbox, it rejects with
630
+ * `'closed'`. A second call while one runs joins it.
631
+ */
632
+ clearOutbox(): Promise<void>;
633
+ /**
634
+ * Leave the room, release the outbox lock and destroy the op engine. A write made in the same
635
+ * tick is handed to storage, before the lock is released, only when nothing of this handle is in
636
+ * storage's hands: no earlier write still being saved, and not the record the handle saves as it
637
+ * goes live, which storage holds for a moment as the status turns `'live'`. A write queued behind
638
+ * anything still out is not saved. Either way nobody is told it is stored: `acked` reads `false`
639
+ * and `whenAcked()` rejects with `'closed'`. To know that every write is saved, wait for
640
+ * `whenAcked()`, or for `acked` to read `true`, before closing.
641
+ * A save in storage's hands may still land after the lock is released, and storage decides
642
+ * between it and the next tab's writes.
643
+ * Closed while the boot is still held, the writes made in the hold are dropped: they were never
644
+ * saved, and with a net change `acked` reads `false` and `whenAcked()` rejects with `'closed'`.
645
+ * Without one, an outbox read in flight is let finish, writing nothing, and both answer from it:
646
+ * nothing pending and no conflict held reads `true` and resolves; anything else, or an outbox
647
+ * that cannot be read, reads `false` and rejects with `'closed'`. Until then `acked` is `false`
648
+ * and `whenAcked()` waits.
649
+ * The handle is frozen from then on: the store keeps working locally, but nothing is sent or
650
+ * saved, and `acked`, `conflicts`, `unstored` and `generation` keep the value they had at close.
651
+ * Destroying the injector closes it the same way.
652
+ */
482
653
  close(): void;
483
654
  };
484
655
  /**
@@ -496,7 +667,7 @@ type SeatChange = {
496
667
  /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
497
668
  readonly seq: number;
498
669
  readonly writer: string;
499
- readonly ops: readonly StoreOp$1[];
670
+ readonly ops: readonly StoreOp[];
500
671
  };
501
672
  /**
502
673
  * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past
@@ -544,14 +715,30 @@ type AgentSeatOptions = {
544
715
  readonly reconnect?: {
545
716
  readonly maxDelayMs?: number;
546
717
  };
718
+ /**
719
+ * How long a hello may go unanswered before the connection is closed and opened again:
720
+ * `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up to
721
+ * `maxTimeoutMs` (default 120 000). An answered hello starts the count again. A relay that never
722
+ * answers a hello within `maxTimeoutMs` leaves the seat resetting the connection at that pace for
723
+ * as long as it lasts: nothing is lost, and nothing gets through.
724
+ */
725
+ readonly handshake?: {
726
+ readonly timeoutMs?: number;
727
+ readonly maxTimeoutMs?: number;
728
+ };
547
729
  /**
548
730
  * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;
549
731
  * pass your own to share proxy caches across several seats in one process.
550
732
  */
551
733
  readonly context?: toStoreOptions;
734
+ /**
735
+ * Called once when the seat ends by itself (`ejected`, with the reason, an outdated data shape
736
+ * included) and when a `clearOutbox()` ends it (`'cleared'`); never for `close()`. It is called
737
+ * last: the seat has ended and every clear it owed has settled, so inside it `status()`,
738
+ * `peers()`, `acked()` and `whenAcked()` answer as they do after it (`'ejected'`, or `'closed'`
739
+ * after a clear). A callback that throws is reported and changes nothing.
740
+ */
552
741
  readonly onEject?: (reason: string) => void;
553
- /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
554
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order' | 'compacting') => void;
555
742
  };
556
743
  type AgentSeat<T extends object> = {
557
744
  /** The live converging replica. Reads exactly like a local signal store. */
@@ -561,8 +748,11 @@ type AgentSeat<T extends object> = {
561
748
  /** The current document value — plain JSON-serializable data, for context assembly. */
562
749
  snapshot(): T;
563
750
  /**
564
- * The current document, stamped with the relay seq it is provably the pure fold of
565
- * or null when stability cannot be guaranteed
751
+ * The current document, stamped with the relay seq it is provably the pure fold of, or null
752
+ * when that cannot be guaranteed: before the first welcome, while one of the seat's own writes
753
+ * is still unacknowledged, and from a refused write until the snapshot that replaces it lands.
754
+ * It stays null for good once the seat ended with writes outstanding, after an emit-side policy
755
+ * reject, and after `close()`.
566
756
  */
567
757
  stableSnapshot(): StableSnapshot<T> | null;
568
758
  /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
@@ -572,6 +762,12 @@ type AgentSeat<T extends object> = {
572
762
  * carry, or a relay refusal), each with `discard()` and `reauthor()`.
573
763
  */
574
764
  conflicts(): readonly MeshConflict[];
765
+ /**
766
+ * The seat's writes that are not in the room and never will be, in the order they were made:
767
+ * refused by the relay or discarded with a room generation. Each entry holds the write, its
768
+ * reason and `dismiss()`, which removes it.
769
+ */
770
+ readonly unstored: Signal<readonly UnstoredWrite[]>;
575
771
  /** The room's compaction state as the relay last announced it; undefined before any notice. */
576
772
  readonly compaction: Signal<CompactionState | undefined>;
577
773
  /**
@@ -595,20 +791,43 @@ type AgentSeat<T extends object> = {
595
791
  * `commit()` emits its diff citing only those observed writes, so a room edit that lands
596
792
  * while the fork is open survives as a concurrent value for the merge policy to resolve
597
793
  * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the
598
- * staged edits.
794
+ * staged edits and also re-observes the room, so a later commit on the same fork cites the
795
+ * room as it is at the discard.
599
796
  */
600
797
  fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
601
798
  /**
602
- * Every local write is acknowledged by the room. `false` while a write is still in the
603
- * unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.
799
+ * Everything written through this seat is the room's: nothing is pending and no conflict is
800
+ * held. It counts a write made in the same turn as the call. `false` until the seat has started
801
+ * (a moment after it is created),
802
+ * while a write waits for the room, while a conflict is held (until it is discarded or written
803
+ * again), and for good once a write can no longer land: a write after an eject,
804
+ * or a write the emit-side policy rejected. After an eject it is `true` exactly when nothing was
805
+ * outstanding at the ejection and nothing was written since. A close freezes it: it keeps the
806
+ * answer it had at the close, and a write after the close does not change it. After a storage
807
+ * failure or `clearOutbox()` it is `false`. A write the relay refused is listed in `unstored`,
808
+ * not here.
604
809
  */
605
810
  acked(): boolean;
606
811
  /**
607
- * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
608
- * with the terminal reason if the seat ends while writes are outstanding. The barrier to
609
- * await before handing a result to something that must contain every edit.
812
+ * Resolves once nothing written through this seat is outstanding (immediately if it already is;
813
+ * before the seat has started it waits for the start). Rejects with the terminal reason if the
814
+ * seat ends while writes are outstanding or a write can no longer land, and with `'cleared'`
815
+ * after `clearOutbox()`. While a conflict is held it rejects at once with `conflict: <cause>`; a
816
+ * terminal reason wins. A write the relay refused rejects the calls pending when it is answered
817
+ * with `refused: <reason>`. The barrier to await before handing a result to something that must
818
+ * contain every edit.
610
819
  */
611
820
  whenAcked(): Promise<void>;
821
+ /**
822
+ * Discard every write not yet in the room, every conflict and every `unstored` entry, and end the
823
+ * seat: nothing more is sent, the status reads `'closed'`, and `whenAcked()` rejects with
824
+ * `'cleared'`. Called before the seat has started, it clears once it has; when the start fails it
825
+ * rejects with that reason, then and on every later call. After `close()` it rejects with
826
+ * `'closed'`. After an eject or an outdated ending the seat's journal is already closed, as at
827
+ * every ending, and a seat keeps nothing on storage: the call marks the seat cleared (`acked()`
828
+ * reads `false`, `whenAcked()` rejects with `'cleared'`) and resolves at once.
829
+ */
830
+ clearOutbox(): Promise<void>;
612
831
  /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */
613
832
  setPresence(data: unknown): void;
614
833
  /**
@@ -623,6 +842,13 @@ type AgentSeat<T extends object> = {
623
842
  direct(cb: (msg: MeshDirect) => void): () => void;
624
843
  /** Authority surface over this seat's op-sync; see {@link SeatSync}. */
625
844
  readonly sync: SeatSync<T>;
845
+ /**
846
+ * Leave the room and destroy the seat's op engine. The handle is frozen from then on: `doc`
847
+ * still reads and writes locally, but nothing is sent, `acked()` and `whenAcked()` keep the
848
+ * answer they had at close, and `stableSnapshot()` is null. Closed before the seat has started,
849
+ * they answer once its journal has been read: with nothing written, `acked()` reads `true` and
850
+ * `whenAcked()` resolves; until then `acked()` is `false` and `whenAcked()` waits.
851
+ */
626
852
  close(): void;
627
853
  };
628
854
  /**
@@ -649,7 +875,7 @@ declare function setAtPath(node: unknown, path: string | readonly PathSegment[],
649
875
  * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
650
876
  * `changes` stream: narrating each batch's ops yields an append-only account of the room.
651
877
  */
652
- declare function describeOp(op: StoreOp$1, writer: string): string;
878
+ declare function describeOp(op: StoreOp, writer: string): string;
653
879
 
654
880
  type WebRtcMeshOptions = {
655
881
  readonly room: string;
@@ -688,8 +914,8 @@ type WebRtcMeshRef = {
688
914
  * Peer-to-peer mesh sync: the relay only signals
689
915
  * and tracks membership; envelopes flow over WebRTC data channels and converge via the
690
916
  * per-path register map. Catch-up is pairwise: on channel open both sides exchange
691
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
692
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
917
+ * watermarks; a side whose state is covered (the other holds every envelope it holds)
918
+ * hydrates from the other's FULL checkpoint (root + per-path register state + watermark), so supersession and precedence
693
919
  * carry over intact: a late joiner is indistinguishable from a peer that saw every
694
920
  * envelope. Two peers that each hold envelopes the other lacks keep their convergent
695
921
  * go-forward guarantees but do not exchange the missed envelopes retroactively.
@@ -765,4 +991,4 @@ type RtcPresenceRef<T> = {
765
991
  declare function rtcPresence<T>(links: PeerLinks, opt: RtcPresenceOptions): RtcPresenceRef<T>;
766
992
 
767
993
  export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
768
- export type { AgentSeat, AgentSeatOptions, DataChannelLike, DirectTransportOptions, MeshDirect, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };
994
+ export type { AgentSeat, AgentSeatOptions, DataChannelLike, DirectTransportOptions, MeshDirect, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, UnstoredReason, UnstoredWrite, WebRtcMeshOptions, WebRtcMeshRef };