@mmstack/mesh 22.10.2 → 22.12.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.
@@ -1,49 +1,162 @@
1
- import { ClientMsg, ServerMsg, Relay, PrincipalCtx, IceServer, ClientSignalMsg, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
2
- import { OpSync, MergePolicyEntry, OpEnvelope, AsyncStore, ForkStoreOptions, SyncedFork, WritableSignalStore, StoreOp, toStoreOptions } from '@mmstack/primitives/core';
3
- import { Signal, Injector, WritableSignal } from '@angular/core';
4
-
1
+ import { ClientMsg, ClientSignalMsg, IceServer, OpPolicy, PolicyViolation, PresenceState, PrincipalCtx, Relay, ServerMsg } from "@mmstack/mesh-protocol";
2
+ import { AsyncStore, DiffOpsOptions, ForkStoreOptions, MergePolicyEntry, OpEnvelope, OpSync, StoreOp, SyncedFork, WritableSignalStore, toStoreOptions } from "@mmstack/primitives/core";
3
+ import { Injector, Signal, WritableSignal } from "@angular/core";
5
4
  /**
6
5
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
7
6
  * represents a single connection and never reconnects itself.
8
7
  */
9
8
  type MeshTransport = {
10
- send(msg: ClientMsg): void;
11
- onMessage(cb: (msg: ServerMsg) => void): () => void;
12
- onClose(cb: () => void): () => void;
13
- close(): void;
9
+ send(msg: ClientMsg): void;
10
+ onMessage(cb: (msg: ServerMsg) => void): () => void;
11
+ onClose(cb: () => void): () => void;
12
+ close(): void;
14
13
  };
15
14
  type MeshTransportFactory = () => MeshTransport;
16
15
  /**
17
16
  * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and
18
17
  * flushed on open; malformed inbound frames are dropped.
19
18
  */
20
- declare function webSocketTransport(url: string, protocols?: string | string[]): MeshTransportFactory;
19
+ export declare function webSocketTransport(url: string, protocols?: string | string[]): MeshTransportFactory;
21
20
  /**
22
21
  * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop
23
22
  * tests, and handy for single-process demos or an SSR-side room.
24
23
  */
25
- declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
26
-
27
- type MeshStatus = 'connecting'
24
+ export declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
25
+ type MeshStatus = 'connecting' |
28
26
  /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */
29
- | 'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
30
-
27
+ 'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
28
+ /** One sequenced remote envelope's ops, attributed to the writer that made them. */
29
+ type RemoteBatch = {
30
+ /** The relay's total-order stamp for this batch. */
31
+ readonly seq: number;
32
+ readonly writer: string;
33
+ readonly ops: readonly StoreOp[];
34
+ };
35
+ /**
36
+ * Environment callbacks a session shell provides. All are optional except `onStatus`; the
37
+ * session never touches signals, timers beyond `schedule`, storage, or the DOM itself.
38
+ */
39
+ type MeshSessionHooks = {
40
+ onStatus(status: MeshStatus, reason?: string): void;
41
+ /** The current op engine's origin, published immediately before each hello. */
42
+ onOrigin?(origin: string): void;
43
+ /** Relay membership, independent of presence; undefined while disconnected or before welcome. */
44
+ onMembers?(members: readonly string[] | undefined): void;
45
+ /** A room message after the session has processed it, for consumers sharing its connection. */
46
+ onMessage?(msg: ServerMsg): void;
47
+ /** A welcome or envelope arrived — the shell's "last synced" moment. */
48
+ onSynced?(): void;
49
+ /** The presence roster changed (welcome replace, join/leave, teardown clear). */
50
+ onPeers?(peers: ReadonlyMap<string, PresenceState>): void;
51
+ /** A remote (non-own) envelope was ingested, in seq order. */
52
+ onRemote?(batch: RemoteBatch): void;
53
+ /**
54
+ * Seq continuity broke: a snapshot welcome (or a relay instance change) established state
55
+ * without delivering the individual envelopes in between. Any consumer deriving from the
56
+ * `onRemote` stream must rebuild from current state at this seq; appending across a resync
57
+ * would silently skip history.
58
+ */
59
+ onResync?(seq: number): void;
60
+ /** The unacknowledged local tail changed (emit or ack) — the durable-outbox trigger. */
61
+ onOutboxChange?(): void;
62
+ /**
63
+ * A local write violated the room policy. The session ejects itself immediately after —
64
+ * the outcome the relay's own independent check would have produced one hop later. The
65
+ * emit-side check spares the room the round trip; it is never the enforcement.
66
+ */
67
+ onLocalReject?(violation: PolicyViolation): void;
68
+ /**
69
+ * Teardown is starting; fired before the unacked tail is dropped, so a shell can persist
70
+ * it (and release any single-writer locks) while it is still intact.
71
+ */
72
+ onTerminal?(state: 'ejected' | 'closed', reason?: string): void;
73
+ /**
74
+ * The relay refused one of this session's writes: it is not in the room and never will be.
75
+ * `'generation'` — written in a room generation that has since been cut (the whole tail is
76
+ * refused at the welcome that names the new one, or one envelope by the relay's reply);
77
+ * `'schema'` — a data shape older than the room's; `'order'` — a version below this origin's
78
+ * admitted maximum that was never admitted (a second tab on one origin). The session drops
79
+ * the write locally and hydrates from a fresh snapshot; the envelope carries the values, so
80
+ * the application can offer to write them again. Any `whenAcked` waiter rejects.
81
+ */
82
+ onRefused?(env: OpEnvelope, reason: 'generation' | 'schema' | 'order'): void;
83
+ };
84
+ type MeshSessionOptions<T extends object> = {
85
+ readonly room: string;
86
+ readonly writer: string;
87
+ readonly transport: MeshTransportFactory;
88
+ /** The op engine this session feeds. The shell creates (and destroys) it. */
89
+ readonly sync: OpSync<T>;
90
+ readonly policies?: readonly MergePolicyEntry[];
91
+ readonly policy?: OpPolicy;
92
+ readonly ctx?: Omit<PrincipalCtx, 'writer'>;
93
+ readonly policyVersion: number;
94
+ readonly schemaVersion?: number;
95
+ /** The room generation a restored outbox was written in; the first welcome decides whether it still holds. */
96
+ readonly instance?: string;
97
+ readonly reconnect?: {
98
+ readonly maxDelayMs?: number;
99
+ };
100
+ /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */
101
+ readonly schedule?: {
102
+ set(fn: () => void, ms: number): unknown;
103
+ clear(handle: unknown): void;
104
+ };
105
+ readonly hooks: MeshSessionHooks;
106
+ };
107
+ /**
108
+ * The relay-room session protocol, shell-agnostic: hello/welcome handshakes (snapshot
109
+ * hydrate, delta replay, fresh-room seed), own-echo acknowledgement, unacked resend,
110
+ * the relay's per-envelope answers (`drop`), reconnect backoff, presence, eject/reject, the
111
+ * generation fence and settled-vector garbage collection. `meshSync` wraps it for
112
+ * Angular; `agentSeat` wraps it for injector-free environments. One implementation of the
113
+ * wire contract — shells differ only in environment concerns.
114
+ */
115
+ type MeshSession = {
116
+ /** Open the first connection. Call once, after any outbox restore has replayed. */
117
+ connect(): void;
118
+ status(): MeshStatus;
119
+ /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */
120
+ lastSeq(): number;
121
+ hasUnacked(): boolean;
122
+ /**
123
+ * Resolves once the unacknowledged local tail is empty — the acknowledgement barrier a
124
+ * caller awaits before treating its writes as the room's. Resolves immediately when
125
+ * nothing is outstanding. Rejects with the terminal reason if the session ends (eject or
126
+ * close) while entries remain: those writes never reached the room, and every later call
127
+ * rejects the same way.
128
+ *
129
+ * With a relay whose adapter confirms durability before echoing, acknowledged means
130
+ * stored; against a relay that echoes eagerly it means only "the relay has it".
131
+ */
132
+ whenAcked(): Promise<void>;
133
+ /** The unacknowledged local tail (the durable-outbox payload). */
134
+ unackedEnvs(): readonly OpEnvelope[];
135
+ /** The room generation this session is in, once a welcome (or a restored outbox) named one. */
136
+ instance(): string | undefined;
137
+ peers(): ReadonlyMap<string, PresenceState>;
138
+ setPresence(data: unknown): void;
139
+ /** Send peer signaling over the current connection without a second hello. */
140
+ sendSignal(msg: ClientSignalMsg): void;
141
+ close(): void;
142
+ };
143
+ declare function meshSession<T extends object>(opt: MeshSessionOptions<T>): MeshSession;
31
144
  /** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */
32
145
  type DataChannelLike = {
33
- send(frame: string): void;
34
- onMessage(cb: (frame: string) => void): () => void;
35
- onOpen(cb: () => void): () => void;
36
- onClose(cb: () => void): () => void;
37
- close(): void;
146
+ send(frame: string): void;
147
+ onMessage(cb: (frame: string) => void): () => void;
148
+ onOpen(cb: () => void): () => void;
149
+ onClose(cb: () => void): () => void;
150
+ close(): void;
38
151
  };
39
152
  /** One data channel on a peer link. `ordered: false` + `maxRetransmits: 0` makes it lossy. */
40
153
  type PeerChannelSpec = {
41
- readonly label: string;
42
- readonly ordered?: boolean;
43
- readonly maxRetransmits?: number;
154
+ readonly label: string;
155
+ readonly ordered?: boolean;
156
+ readonly maxRetransmits?: number;
44
157
  };
45
158
  /** The single reliable channel every link carries when no channels are asked for. */
46
- declare const defaultPeerChannels: readonly PeerChannelSpec[];
159
+ export declare const defaultPeerChannels: readonly PeerChannelSpec[];
47
160
  /**
48
161
  * Creates one peer link. `polite` assigns the perfect-negotiation role (derived
49
162
  * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads
@@ -60,19 +173,19 @@ declare const defaultPeerChannels: readonly PeerChannelSpec[];
60
173
  * said so; the links then rebuild it.
61
174
  */
62
175
  type PeerConnector = (opt: {
63
- readonly remote: string;
64
- readonly polite: boolean;
65
- readonly sendSignal: (data: unknown) => void;
66
- readonly channels: readonly PeerChannelSpec[];
67
- /** ICE servers the relay issued in the last welcome, if any. */
68
- readonly iceServers?: readonly IceServer[];
176
+ readonly remote: string;
177
+ readonly polite: boolean;
178
+ readonly sendSignal: (data: unknown) => void;
179
+ readonly channels: readonly PeerChannelSpec[];
180
+ /** ICE servers the relay issued in the last welcome, if any. */
181
+ readonly iceServers?: readonly IceServer[];
69
182
  }) => {
70
- readonly channel: DataChannelLike;
71
- readonly channels?: Readonly<Record<string, DataChannelLike>>;
72
- signal(data: unknown): void;
73
- /** Fires once when the link as a whole is gone, whether or not its channels reported it. */
74
- onClose?(cb: () => void): () => void;
75
- close(): void;
183
+ readonly channel: DataChannelLike;
184
+ readonly channels?: Readonly<Record<string, DataChannelLike>>;
185
+ signal(data: unknown): void;
186
+ /** Fires once when the link as a whole is gone, whether or not its channels reported it. */
187
+ onClose?(cb: () => void): () => void;
188
+ close(): void;
76
189
  };
77
190
  /**
78
191
  * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.
@@ -84,95 +197,95 @@ type PeerConnector = (opt: {
84
197
  * the link connects again, a closed connection, or a negotiation step the browser rejects
85
198
  * reports the link gone through `onClose`.
86
199
  */
87
- declare function rtcPeerConnector(config?: RTCConfiguration, opt?: {
88
- readonly disconnectGraceMs?: number;
200
+ export declare function rtcPeerConnector(config?: RTCConfiguration, opt?: {
201
+ readonly disconnectGraceMs?: number;
89
202
  }): PeerConnector;
90
203
  /**
91
204
  * A relay connection someone else owns (a live session, say). Peer links ride on it without
92
205
  * saying hello, so the links share that connection's origin and room membership.
93
206
  */
94
207
  type SignalingPort = {
95
- /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */
96
- members(): readonly string[] | undefined;
97
- /** ICE servers from the owner's last welcome, if it keeps them. Read after subscribing. */
98
- iceServers?(): readonly IceServer[] | undefined;
99
- send(msg: ClientSignalMsg): void;
100
- onMessage(cb: (msg: ServerMsg) => void): () => void;
208
+ /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */
209
+ members(): readonly string[] | undefined;
210
+ /** ICE servers from the owner's last welcome, if it keeps them. Read after subscribing. */
211
+ iceServers?(): readonly IceServer[] | undefined;
212
+ send(msg: ClientSignalMsg): void;
213
+ onMessage(cb: (msg: ServerMsg) => void): () => void;
101
214
  };
102
215
  type PeerLinksOptions = {
103
- readonly room: string;
104
- /** This side's origin; also decides the perfect-negotiation role against each remote. */
105
- readonly origin: string;
106
- /**
107
- * A transport factory means the links own their relay connection (hello, reconnect); a
108
- * {@link SignalingPort} means they ride on one that is already joined.
109
- */
110
- readonly signaling: MeshTransportFactory | SignalingPort;
111
- /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
112
- readonly connector?: PeerConnector;
113
- /**
114
- * The channels every link carries, first one the default for `send` and `broadcast`.
115
- * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.
116
- */
117
- readonly channels?: readonly PeerChannelSpec[];
118
- /** Sent in the hello when the links own their connection. */
119
- readonly policyVersion?: number;
120
- /**
121
- * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe
122
- * before the first link opens. Defaults to `true`.
123
- */
124
- readonly autoConnect?: boolean;
125
- /** How long a link may take to open every channel before it counts as lost. Default 15000. */
126
- readonly openTimeoutMs?: number;
127
- /** Backoff bounds for rebuilding a lost link. Defaults 1000 and 30000. */
128
- readonly retry?: {
129
- readonly minMs?: number;
130
- readonly maxMs?: number;
131
- };
132
- /** Random source for the backoff jitter; tests pass a seeded one. Default Math.random. */
133
- readonly random?: () => number;
134
- readonly injector?: Injector;
216
+ readonly room: string;
217
+ /** This side's origin; also decides the perfect-negotiation role against each remote. */
218
+ readonly origin: string;
219
+ /**
220
+ * A transport factory means the links own their relay connection (hello, reconnect); a
221
+ * {@link SignalingPort} means they ride on one that is already joined.
222
+ */
223
+ readonly signaling: MeshTransportFactory | SignalingPort;
224
+ /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
225
+ readonly connector?: PeerConnector;
226
+ /**
227
+ * The channels every link carries, first one the default for `send` and `broadcast`.
228
+ * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.
229
+ */
230
+ readonly channels?: readonly PeerChannelSpec[];
231
+ /** Sent in the hello when the links own their connection. */
232
+ readonly policyVersion?: number;
233
+ /**
234
+ * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe
235
+ * before the first link opens. Defaults to `true`.
236
+ */
237
+ readonly autoConnect?: boolean;
238
+ /** How long a link may take to open every channel before it counts as lost. Default 15000. */
239
+ readonly openTimeoutMs?: number;
240
+ /** Backoff bounds for rebuilding a lost link. Defaults 1000 and 30000. */
241
+ readonly retry?: {
242
+ readonly minMs?: number;
243
+ readonly maxMs?: number;
244
+ };
245
+ /** Random source for the backoff jitter; tests pass a seeded one. Default Math.random. */
246
+ readonly random?: () => number;
247
+ readonly injector?: Injector;
135
248
  };
136
249
  type PeerLinks = {
137
- /**
138
- * `live` once the relay has welcomed this side (or, over a port, once it has seen a
139
- * welcome); back to `connecting` while an owned relay connection is being re-established.
140
- * Peer links outlive that: they are retired only by their own close or a relay `gone`. Over
141
- * a port the same holds across the session's socket drops; when the session itself ends, the
142
- * port reports `gone` for every member and the links are retired with it.
143
- */
144
- readonly status: Signal<'connecting' | 'live'>;
145
- /** Origins whose link has every channel open. */
146
- readonly peers: Signal<readonly string[]>;
147
- /** Members whose link was lost at least once since it last opened: waiting to rebuild, or rebuilding. */
148
- readonly stalled: Signal<readonly string[]>;
149
- /**
150
- * Other origins in the room as the relay reports them (welcome, then join and leave). The
151
- * relay is the authority on who is present; a link can outlive a dead socket for a while.
152
- */
153
- readonly members: Signal<readonly string[]>;
154
- /** Replays current membership synchronously, then reports every change without coalescing. */
155
- onMembers(cb: (members: readonly string[]) => void): () => void;
156
- /** The labels every link carries, in the order they were asked for. */
157
- readonly channels: readonly string[];
158
- /** Fires when one channel of a link opens; replays channels that are already open. */
159
- onOpen(cb: (origin: string, channel: string) => void): () => void;
160
- onMessage(cb: (origin: string, frame: string, channel: string) => void): () => void;
161
- /**
162
- * Fires when a link goes away: a channel closed, the connector reported it gone, it did not
163
- * open in time, or the relay reported the origin gone. A lost link is rebuilt while the relay
164
- * lists its origin.
165
- */
166
- onClose(cb: (origin: string) => void): () => void;
167
- /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */
168
- onEnd(cb: () => void): () => void;
169
- /** Sends on one open channel; a frame for a channel that is not open is dropped. */
170
- send(origin: string, frame: string, channel?: string): void;
171
- /** Sends on the channel of every link where it is open. */
172
- broadcast(frame: string, channel?: string): void;
173
- /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */
174
- connect(): void;
175
- close(): void;
250
+ /**
251
+ * `live` once the relay has welcomed this side (or, over a port, once it has seen a
252
+ * welcome); back to `connecting` while an owned relay connection is being re-established.
253
+ * Peer links outlive that: they are retired only by their own close or a relay `gone`. Over
254
+ * a port the same holds across the session's socket drops; when the session itself ends, the
255
+ * port reports `gone` for every member and the links are retired with it.
256
+ */
257
+ readonly status: Signal<'connecting' | 'live'>;
258
+ /** Origins whose link has every channel open. */
259
+ readonly peers: Signal<readonly string[]>;
260
+ /** Members whose link was lost at least once since it last opened: waiting to rebuild, or rebuilding. */
261
+ readonly stalled: Signal<readonly string[]>;
262
+ /**
263
+ * Other origins in the room as the relay reports them (welcome, then join and leave). The
264
+ * relay is the authority on who is present; a link can outlive a dead socket for a while.
265
+ */
266
+ readonly members: Signal<readonly string[]>;
267
+ /** Replays current membership synchronously, then reports every change without coalescing. */
268
+ onMembers(cb: (members: readonly string[]) => void): () => void;
269
+ /** The labels every link carries, in the order they were asked for. */
270
+ readonly channels: readonly string[];
271
+ /** Fires when one channel of a link opens; replays channels that are already open. */
272
+ onOpen(cb: (origin: string, channel: string) => void): () => void;
273
+ onMessage(cb: (origin: string, frame: string, channel: string) => void): () => void;
274
+ /**
275
+ * Fires when a link goes away: a channel closed, the connector reported it gone, it did not
276
+ * open in time, or the relay reported the origin gone. A lost link is rebuilt while the relay
277
+ * lists its origin.
278
+ */
279
+ onClose(cb: (origin: string) => void): () => void;
280
+ /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */
281
+ onEnd(cb: () => void): () => void;
282
+ /** Sends on one open channel; a frame for a channel that is not open is dropped. */
283
+ send(origin: string, frame: string, channel?: string): void;
284
+ /** Sends on the channel of every link where it is open. */
285
+ broadcast(frame: string, channel?: string): void;
286
+ /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */
287
+ connect(): void;
288
+ close(): void;
176
289
  };
177
290
  /**
178
291
  * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
@@ -200,8 +313,7 @@ type PeerLinks = {
200
313
  * superseded by the welcome's roster and signals are held and replayed after it, so every link
201
314
  * is built with that welcome's ICE servers and never an earlier connection's.
202
315
  */
203
- declare function peerLinks(opt: PeerLinksOptions): PeerLinks;
204
-
316
+ export declare function peerLinks(opt: PeerLinksOptions): PeerLinks;
205
317
  type MeshPeer = PresenceState;
206
318
  /**
207
319
  * A composed, user-facing health status for a synced store the surface that
@@ -209,103 +321,109 @@ type MeshPeer = PresenceState;
209
321
  */
210
322
  type SyncHealthStatus = 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded';
211
323
  type SyncHealth = {
212
- readonly status: SyncHealthStatus;
213
- /** Why, when the status is `outdated`/`ejected`/`degraded`. */
214
- readonly reason?: 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});
215
- /** `Date.now()` of the last successful sync (welcome or applied env). */
216
- readonly lastSyncedAt?: number;
217
- /**
218
- * Offline writes persisted by an older build that could not be restored on boot. Envelopes
219
- * from a previous wire-protocol version lack the citation metadata current merging needs,
220
- * so they are dropped (loudly) instead of being upgraded with fabricated citations.
221
- */
222
- readonly droppedOfflineWrites?: number;
223
- /**
224
- * Writes the relay refused on this session: they are not in the room. Each was handed to
225
- * `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.
226
- */
227
- readonly refusedWrites?: number;
228
- /**
229
- * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id
230
- * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a
231
- * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line
232
- * against a malformed neighbor; through a relay these are also rejected at the relay.
233
- */
234
- readonly droppedInvalidEnvelopes?: number;
324
+ readonly status: SyncHealthStatus;
325
+ /** Why, when the status is `outdated`/`ejected`/`degraded`. */
326
+ readonly reason?: 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});
327
+ /** `Date.now()` of the last successful sync (welcome or applied env). */
328
+ readonly lastSyncedAt?: number;
329
+ /**
330
+ * Offline writes persisted by an older build that could not be restored on boot. Envelopes
331
+ * from a previous wire-protocol version lack the citation metadata current merging needs,
332
+ * so they are dropped (loudly) instead of being upgraded with fabricated citations.
333
+ */
334
+ readonly droppedOfflineWrites?: number;
335
+ /**
336
+ * Writes the relay refused on this session: they are not in the room. Each was handed to
337
+ * `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.
338
+ */
339
+ readonly refusedWrites?: number;
340
+ /**
341
+ * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id
342
+ * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a
343
+ * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line
344
+ * against a malformed neighbor; through a relay these are also rejected at the relay.
345
+ */
346
+ readonly droppedInvalidEnvelopes?: number;
235
347
  };
236
348
  type MeshSyncOptions = {
237
- readonly room: string;
238
- /** Opaque principal pseudonym — provided, never minted. */
239
- readonly writer: string;
240
- readonly transport: MeshTransportFactory;
241
- /** Per-path merge policies for rebase/convergence (`lww` default). */
242
- readonly policies?: readonly MergePolicyEntry[];
243
- /** Emit-side validation, symmetric with the relay's (tripwire honesty). */
244
- readonly policy?: OpPolicy;
245
- /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */
246
- readonly ctx?: Omit<PrincipalCtx, 'writer'>;
247
- /**
248
- * The room's shared configuration pin, checked at hello against the relay's. Bump it
249
- * together whenever anything peers must agree on changes: the write policy, and just as
250
- * importantly the merge/fold configuration (`policies`). Peers folding the same register
251
- * state with different rules read different values, so one room means one fold config; a
252
- * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.
253
- */
254
- readonly policyVersion?: number;
255
- /** The data shape this client speaks. Older-than-room → `outdated`, and a
256
- * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */
257
- readonly schemaVersion?: number;
258
- /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */
259
- readonly reconnect?: {
260
- readonly maxDelayMs?: number;
261
- };
262
- readonly injector?: Injector;
263
- /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */
264
- readonly register?: 'track' | 'suspend';
265
- readonly onEject?: (reason: string) => void;
266
- /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
267
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
349
+ readonly room: string;
350
+ /** Opaque principal pseudonym — provided, never minted. */
351
+ readonly writer: string;
352
+ readonly transport: MeshTransportFactory;
353
+ /** Per-path merge policies for rebase/convergence (`lww` default). */
354
+ readonly policies?: readonly MergePolicyEntry[];
355
+ /**
356
+ * How local writes are diffed into ops (forwarded to `opSync`; see `DiffOpsOptions`). Absent:
357
+ * whole-value adds, as before. A per-path `added` predicate keeps chosen collections leafy (so
358
+ * concurrent first writers merge) while their entries stay one atomic `set`.
359
+ */
360
+ readonly emit?: DiffOpsOptions;
361
+ /** Emit-side validation, symmetric with the relay's (tripwire honesty). */
362
+ readonly policy?: OpPolicy;
363
+ /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */
364
+ readonly ctx?: Omit<PrincipalCtx, 'writer'>;
365
+ /**
366
+ * The room's shared configuration pin, checked at hello against the relay's. Bump it
367
+ * together whenever anything peers must agree on changes: the write policy, and just as
368
+ * importantly the merge/fold configuration (`policies`). Peers folding the same register
369
+ * state with different rules read different values, so one room means one fold config; a
370
+ * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.
371
+ */
372
+ readonly policyVersion?: number;
373
+ /** The data shape this client speaks. Older-than-room → `outdated`, and a
374
+ * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */
375
+ readonly schemaVersion?: number;
376
+ /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */
377
+ readonly reconnect?: {
378
+ readonly maxDelayMs?: number;
379
+ };
380
+ readonly injector?: Injector;
381
+ /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */
382
+ readonly register?: 'track' | 'suspend';
383
+ readonly onEject?: (reason: string) => void;
384
+ /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */
385
+ readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
386
+ /**
387
+ * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
388
+ * (and before it restores an `outbox`), so a store hydrated from another source first (a worker
389
+ * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.
390
+ * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base
391
+ * that fails to load never wedges the connection.
392
+ */
393
+ readonly whenReady?: () => PromiseLike<void> | void;
394
+ /**
395
+ * Persist the unacknowledged local outbox (and the writing boot's origin) so offline writes
396
+ * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room
397
+ * on the next welcome, instead of being lost with in-memory state. The payload is written to
398
+ * `store` under `key`, debounced.
399
+ *
400
+ * The persisted outbox under `key` is a single-writer slot: every persist overwrites it whole, so
401
+ * two tabs writing one key would each drop the other's tail from disk. A Web Lock on `key` elects
402
+ * the one tab that restores from the slot and writes to it; origins are fresh on every boot either
403
+ * way, so the lock guards the slot, not the origin. `crossTab` sets what a tab that did not get the
404
+ * lock does: `'queue'` (default) waits (`status` reads `'waiting'`) and takes over when the owner
405
+ * closes; `'ephemeral'` runs live at once and never touches the slot. `'off'` skips the lock and
406
+ * leaves ownership to you (e.g. a per-tab key, or leader election over `tabSync`). A debounced
407
+ * write means a hard crash within the debounce window can drop the very last mint — a small,
408
+ * best-effort gap; tune it with `debounceMs`.
409
+ */
410
+ readonly outbox?: {
411
+ readonly key: string;
412
+ readonly store: AsyncStore;
413
+ /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */
414
+ readonly debounceMs?: number;
268
415
  /**
269
- * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects
270
- * (and before it restores an `outbox`), so a store hydrated from another source first (a worker
271
- * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.
272
- * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base
273
- * that fails to load never wedges the connection.
416
+ * Cross-tab contention for the shared `key`. The persisted outbox is a single-writer slot: the
417
+ * Web Lock elects the one tab that restores from it and writes to it.
418
+ * `'queue'` (default): a tab that did not get the lock WAITS (`status` reads `'waiting'`) and
419
+ * takes over when the owner closes. `'ephemeral'`: it runs live at once on its own fresh origin
420
+ * and never touches the slot — its unacknowledged writes live in memory only and are lost if that
421
+ * tab terminates before the room acknowledges them — online or offline, and it stays ephemeral
422
+ * for life, also after the owner leaves. When the lock is free both behave the same (take it,
423
+ * restore, persist). `'off'` skips the lock (you coordinate ownership).
274
424
  */
275
- readonly whenReady?: () => PromiseLike<void> | void;
276
- /**
277
- * Persist the unacknowledged local outbox (and the writing boot's origin) so offline writes
278
- * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room
279
- * on the next welcome, instead of being lost with in-memory state. The payload is written to
280
- * `store` under `key`, debounced.
281
- *
282
- * The persisted outbox under `key` is a single-writer slot: every persist overwrites it whole, so
283
- * two tabs writing one key would each drop the other's tail from disk. A Web Lock on `key` elects
284
- * the one tab that restores from the slot and writes to it; origins are fresh on every boot either
285
- * way, so the lock guards the slot, not the origin. `crossTab` sets what a tab that did not get the
286
- * lock does: `'queue'` (default) waits (`status` reads `'waiting'`) and takes over when the owner
287
- * closes; `'ephemeral'` runs live at once and never touches the slot. `'off'` skips the lock and
288
- * leaves ownership to you (e.g. a per-tab key, or leader election over `tabSync`). A debounced
289
- * write means a hard crash within the debounce window can drop the very last mint — a small,
290
- * best-effort gap; tune it with `debounceMs`.
291
- */
292
- readonly outbox?: {
293
- readonly key: string;
294
- readonly store: AsyncStore;
295
- /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */
296
- readonly debounceMs?: number;
297
- /**
298
- * Cross-tab contention for the shared `key`. The persisted outbox is a single-writer slot: the
299
- * Web Lock elects the one tab that restores from it and writes to it.
300
- * `'queue'` (default): a tab that did not get the lock WAITS (`status` reads `'waiting'`) and
301
- * takes over when the owner closes. `'ephemeral'`: it runs live at once on its own fresh origin
302
- * and never touches the slot — its unacknowledged writes live in memory only and are lost if that
303
- * tab terminates before the room acknowledges them — online or offline, and it stays ephemeral
304
- * for life, also after the owner leaves. When the lock is free both behave the same (take it,
305
- * restore, persist). `'off'` skips the lock (you coordinate ownership).
306
- */
307
- readonly crossTab?: 'queue' | 'off' | 'ephemeral';
308
- };
425
+ readonly crossTab?: 'queue' | 'off' | 'ephemeral';
426
+ };
309
427
  };
310
428
  /**
311
429
  * The authority surface of a peer's op-sync, for callers that compose over a seat rather than
@@ -318,42 +436,42 @@ type MeshSyncOptions = {
318
436
  */
319
437
  type SeatSync<T = unknown> = Pick<OpSync<T>, 'override' | 'captureFrontier' | 'commitScope' | 'liveUnder' | 'liveAt' | 'appliedFrontier'>;
320
438
  type MeshSyncRef<T extends object = Record<string, unknown>> = {
321
- readonly status: Signal<MeshStatus>;
322
- /** Origin used by the current session's hello; null until hello, including while waiting on an outbox. */
323
- readonly origin: Signal<string | null>;
324
- /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */
325
- readonly members: Signal<readonly string[]>;
326
- /** Peer signaling on this session's connection; buffers up to 256 early signals until the first listener. */
327
- readonly signaling: SignalingPort;
328
- /** Composed sync-health for a user-facing surface. */
329
- readonly health: Signal<SyncHealth>;
330
- /**
331
- * Every local write is acknowledged by the room. `false` while a write is still in the
332
- * unacknowledged tail, and it stays `false` once a session ends with writes outstanding —
333
- * those never landed, and no later echo can arrive to change that.
334
- */
335
- readonly acked: Signal<boolean>;
336
- /**
337
- * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
338
- * with the terminal reason if the session ends while writes are outstanding. The barrier
339
- * to await before publishing something that must contain every edit; `synced()` is a
340
- * connection indicator, not a save barrier.
341
- */
342
- whenAcked(): Promise<void>;
343
- readonly peers: Signal<readonly MeshPeer[]>;
344
- /** Publish this client's ephemeral presence payload (cursor, section, activity…). */
345
- setPresence(data: unknown): void;
346
- /**
347
- * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The
348
- * fork observes the room as it is now; committing emits its diff citing only those observed
349
- * writes, so an edit that lands on the room while the fork is open stays a concurrent value the
350
- * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe
351
- * the room and commit on top of the latest instead. `discard()` drops the staged edits.
352
- */
353
- fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
354
- /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */
355
- readonly sync: SeatSync<T>;
356
- close(): void;
439
+ readonly status: Signal<MeshStatus>;
440
+ /** Origin used by the current session's hello; null until hello, including while waiting on an outbox. */
441
+ readonly origin: Signal<string | null>;
442
+ /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */
443
+ readonly members: Signal<readonly string[]>;
444
+ /** Peer signaling on this session's connection; buffers up to 256 early signals until the first listener. */
445
+ readonly signaling: SignalingPort;
446
+ /** Composed sync-health for a user-facing surface. */
447
+ readonly health: Signal<SyncHealth>;
448
+ /**
449
+ * Every local write is acknowledged by the room. `false` while a write is still in the
450
+ * unacknowledged tail, and it stays `false` once a session ends with writes outstanding —
451
+ * those never landed, and no later echo can arrive to change that.
452
+ */
453
+ readonly acked: Signal<boolean>;
454
+ /**
455
+ * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
456
+ * with the terminal reason if the session ends while writes are outstanding. The barrier
457
+ * to await before publishing something that must contain every edit; `synced()` is a
458
+ * connection indicator, not a save barrier.
459
+ */
460
+ whenAcked(): Promise<void>;
461
+ readonly peers: Signal<readonly MeshPeer[]>;
462
+ /** Publish this client's ephemeral presence payload (cursor, section, activity…). */
463
+ setPresence(data: unknown): void;
464
+ /**
465
+ * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The
466
+ * fork observes the room as it is now; committing emits its diff citing only those observed
467
+ * writes, so an edit that lands on the room while the fork is open stays a concurrent value the
468
+ * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe
469
+ * the room and commit on top of the latest instead. `discard()` drops the staged edits.
470
+ */
471
+ fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
472
+ /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */
473
+ readonly sync: SeatSync<T>;
474
+ close(): void;
357
475
  };
358
476
  /**
359
477
  * Replicates a signal store across clients through a relay room: local writes emit stamped
@@ -362,15 +480,14 @@ type MeshSyncRef<T extends object = Record<string, unknown>> = {
362
480
  * A synced store reads exactly like a local one — connection state surfaces only through
363
481
  * `status` and the transition scope.
364
482
  */
365
- declare function meshSync<T extends object>(source: WritableSignal<T>, opt: MeshSyncOptions): MeshSyncRef<T>;
366
-
483
+ export declare function meshSync<T extends object>(source: WritableSignal<T>, opt: MeshSyncOptions): MeshSyncRef<T>;
367
484
  /** A sequenced batch of another writer's ops, delivered in relay order. */
368
485
  type SeatChange = {
369
- readonly kind: 'change';
370
- /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
371
- readonly seq: number;
372
- readonly writer: string;
373
- readonly ops: readonly StoreOp[];
486
+ readonly kind: 'change';
487
+ /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
488
+ readonly seq: number;
489
+ readonly writer: string;
490
+ readonly ops: readonly StoreOp[];
374
491
  };
375
492
  /**
376
493
  * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past
@@ -379,96 +496,102 @@ type SeatChange = {
379
496
  * prompt prefixes — no longer extends the stream and must be rebuilt from current state.
380
497
  */
381
498
  type SeatResync = {
382
- readonly kind: 'resync';
383
- /** The seq the re-established state corresponds to. */
384
- readonly seq: number;
499
+ readonly kind: 'resync';
500
+ /** The seq the re-established state corresponds to. */
501
+ readonly seq: number;
385
502
  };
386
503
  type SeatEvent = SeatChange | SeatResync;
387
504
  /** A base state provably derivable from the room's history alone — safe to cache. */
388
505
  type StableSnapshot<T> = {
389
- /** The relay seq this state is the fold of. */
390
- readonly seq: number;
391
- readonly doc: T;
506
+ /** The relay seq this state is the fold of. */
507
+ readonly seq: number;
508
+ readonly doc: T;
392
509
  };
393
510
  type AgentSeatOptions = {
394
- readonly room: string;
395
- /** Opaque principal pseudonym — provided, never minted. One identity per seat. */
396
- readonly writer: string;
397
- readonly transport: MeshTransportFactory;
398
- /** Per-path merge policies for rebase/convergence (`lww` default). */
399
- readonly policies?: readonly MergePolicyEntry[];
400
- /**
401
- * Emit-side validation, symmetric with the relay's — an optimization, not the
402
- * enforcement (the relay validates every envelope regardless). A violating write is
403
- * never sent and ejects the seat exactly as the relay would have; the refused value
404
- * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.
405
- */
406
- readonly policy?: OpPolicy;
407
- /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */
408
- readonly ctx?: Omit<PrincipalCtx, 'writer'>;
409
- readonly policyVersion?: number;
410
- readonly schemaVersion?: number;
411
- /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */
412
- readonly reconnect?: {
413
- readonly maxDelayMs?: number;
414
- };
415
- /**
416
- * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;
417
- * pass your own to share proxy caches across several seats in one process.
418
- */
419
- readonly context?: toStoreOptions;
420
- readonly onEject?: (reason: string) => void;
421
- /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
422
- readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
511
+ readonly room: string;
512
+ /** Opaque principal pseudonym — provided, never minted. One identity per seat. */
513
+ readonly writer: string;
514
+ readonly transport: MeshTransportFactory;
515
+ /** Per-path merge policies for rebase/convergence (`lww` default). */
516
+ readonly policies?: readonly MergePolicyEntry[];
517
+ /**
518
+ * How the seat's writes are diffed into ops (forwarded to its `opSync`; see `DiffOpsOptions`).
519
+ * Absent: whole-value adds, as before. A per-path `added` predicate keeps chosen collections
520
+ * leafy while each entry stays one atomic `set` (the whole-entry law the relay holds agents to).
521
+ */
522
+ readonly emit?: DiffOpsOptions;
523
+ /**
524
+ * Emit-side validation, symmetric with the relay's — an optimization, not the
525
+ * enforcement (the relay validates every envelope regardless). A violating write is
526
+ * never sent and ejects the seat exactly as the relay would have; the refused value
527
+ * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.
528
+ */
529
+ readonly policy?: OpPolicy;
530
+ /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */
531
+ readonly ctx?: Omit<PrincipalCtx, 'writer'>;
532
+ readonly policyVersion?: number;
533
+ readonly schemaVersion?: number;
534
+ /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */
535
+ readonly reconnect?: {
536
+ readonly maxDelayMs?: number;
537
+ };
538
+ /**
539
+ * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;
540
+ * pass your own to share proxy caches across several seats in one process.
541
+ */
542
+ readonly context?: toStoreOptions;
543
+ readonly onEject?: (reason: string) => void;
544
+ /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */
545
+ readonly onRefused?: (env: OpEnvelope, reason: 'generation' | 'schema' | 'order') => void;
423
546
  };
424
547
  type AgentSeat<T extends object> = {
425
- /** The live converging replica. Reads exactly like a local signal store. */
426
- readonly doc: WritableSignalStore<T & Record<string, any>>;
427
- status(): MeshStatus;
428
- peers(): readonly PresenceState[];
429
- /** The current document value — plain JSON-serializable data, for context assembly. */
430
- snapshot(): T;
431
- /**
432
- * The current document, stamped with the relay seq it is provably the pure fold of
433
- * or null when stability cannot be guaranteed
434
- */
435
- stableSnapshot(): StableSnapshot<T> | null;
436
- /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
437
- write(fn: () => void): void;
438
- /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */
439
- setAtPath(path: string | readonly (string | number)[], value: unknown): void;
440
- /**
441
- * The room's sequenced history as it arrives: `change` events carry another writer's ops
442
- * in strictly increasing seq order, so a listener may append them (narration, prompt
443
- * suffixes) without any diffing. A `resync` event voids that guarantee — everything
444
- * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).
445
- * Own writes never echo here.
446
- */
447
- changes(cb: (event: SeatEvent) => void): () => void;
448
- /**
449
- * An isolated branch for a reviewable proposal. The fork observes the room as it is now;
450
- * `commit()` emits its diff citing only those observed writes, so a room edit that lands
451
- * while the fork is open survives as a concurrent value for the merge policy to resolve
452
- * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the
453
- * staged edits.
454
- */
455
- fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
456
- /**
457
- * Every local write is acknowledged by the room. `false` while a write is still in the
458
- * unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.
459
- */
460
- acked(): boolean;
461
- /**
462
- * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
463
- * with the terminal reason if the seat ends while writes are outstanding. The barrier to
464
- * await before handing a result to something that must contain every edit.
465
- */
466
- whenAcked(): Promise<void>;
467
- /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */
468
- setPresence(data: unknown): void;
469
- /** Authority surface over this seat's op-sync; see {@link SeatSync}. */
470
- readonly sync: SeatSync<T>;
471
- close(): void;
548
+ /** The live converging replica. Reads exactly like a local signal store. */
549
+ readonly doc: WritableSignalStore<T & Record<string, any>>;
550
+ status(): MeshStatus;
551
+ peers(): readonly PresenceState[];
552
+ /** The current document value — plain JSON-serializable data, for context assembly. */
553
+ snapshot(): T;
554
+ /**
555
+ * The current document, stamped with the relay seq it is provably the pure fold of
556
+ * or null when stability cannot be guaranteed
557
+ */
558
+ stableSnapshot(): StableSnapshot<T> | null;
559
+ /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
560
+ write(fn: () => void): void;
561
+ /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */
562
+ setAtPath(path: string | readonly (string | number)[], value: unknown): void;
563
+ /**
564
+ * The room's sequenced history as it arrives: `change` events carry another writer's ops
565
+ * in strictly increasing seq order, so a listener may append them (narration, prompt
566
+ * suffixes) without any diffing. A `resync` event voids that guarantee — everything
567
+ * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).
568
+ * Own writes never echo here.
569
+ */
570
+ changes(cb: (event: SeatEvent) => void): () => void;
571
+ /**
572
+ * An isolated branch for a reviewable proposal. The fork observes the room as it is now;
573
+ * `commit()` emits its diff citing only those observed writes, so a room edit that lands
574
+ * while the fork is open survives as a concurrent value for the merge policy to resolve
575
+ * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the
576
+ * staged edits.
577
+ */
578
+ fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
579
+ /**
580
+ * Every local write is acknowledged by the room. `false` while a write is still in the
581
+ * unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.
582
+ */
583
+ acked(): boolean;
584
+ /**
585
+ * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects
586
+ * with the terminal reason if the seat ends while writes are outstanding. The barrier to
587
+ * await before handing a result to something that must contain every edit.
588
+ */
589
+ whenAcked(): Promise<void>;
590
+ /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */
591
+ setPresence(data: unknown): void;
592
+ /** Authority surface over this seat's op-sync; see {@link SeatSync}. */
593
+ readonly sync: SeatSync<T>;
594
+ close(): void;
472
595
  };
473
596
  /**
474
597
  * A headless mesh peer: the same replica and wire contract `meshSync` implements in the
@@ -478,7 +601,7 @@ type AgentSeat<T extends object> = {
478
601
  * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as
479
602
  * to any human peer.
480
603
  */
481
- declare function agentSeat<T extends object>(initial: T, opt: AgentSeatOptions): AgentSeat<T>;
604
+ export declare function agentSeat<T extends object>(initial: T, opt: AgentSeatOptions): AgentSeat<T>;
482
605
  type PathSegment = string | number;
483
606
  /**
484
607
  * Applies `value` at a path on a signal-store node — the write shape a tool-calling model
@@ -488,44 +611,45 @@ type PathSegment = string | number;
488
611
  * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer
489
612
  * `seat.setAtPath`, which also emits immediately.
490
613
  */
491
- declare function setAtPath(node: unknown, path: string | readonly PathSegment[], value: unknown): void;
614
+ export declare function setAtPath(node: unknown, path: string | readonly PathSegment[], value: unknown): void;
492
615
  /**
493
616
  * One store op as a plain-English line ("mira set plan.endDate to \"2026-10-11\""), for
494
617
  * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
495
618
  * `changes` stream: narrating each batch's ops yields an append-only account of the room.
496
619
  */
497
- declare function describeOp(op: StoreOp, writer: string): string;
498
-
620
+ export declare function describeOp(op: StoreOp, writer: string): string;
499
621
  type WebRtcMeshOptions = {
500
- readonly room: string;
501
- readonly writer: string;
502
- /**
503
- * This replica's origin, its identity in the room; defaults to a random id per instance.
504
- * One origin is one seat, so never share one between two live instances.
505
- */
506
- readonly origin?: string;
507
- /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */
508
- readonly signaling: MeshTransportFactory;
509
- /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
510
- readonly connector?: PeerConnector;
511
- /**
512
- * Further channels every link carries beside the mesh's own reliable one, for consumers
513
- * that share the links (`rtcPresence`, say). Reach them through {@link WebRtcMeshRef.links}.
514
- */
515
- readonly channels?: readonly PeerChannelSpec[];
516
- readonly policies?: readonly MergePolicyEntry[];
517
- readonly policyVersion?: number;
518
- readonly injector?: Injector;
622
+ readonly room: string;
623
+ readonly writer: string;
624
+ /**
625
+ * This replica's origin, its identity in the room; defaults to a random id per instance.
626
+ * One origin is one seat, so never share one between two live instances.
627
+ */
628
+ readonly origin?: string;
629
+ /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */
630
+ readonly signaling: MeshTransportFactory;
631
+ /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
632
+ readonly connector?: PeerConnector;
633
+ /**
634
+ * Further channels every link carries beside the mesh's own reliable one, for consumers
635
+ * that share the links (`rtcPresence`, say). Reach them through {@link WebRtcMeshRef.links}.
636
+ */
637
+ readonly channels?: readonly PeerChannelSpec[];
638
+ readonly policies?: readonly MergePolicyEntry[];
639
+ readonly policyVersion?: number;
640
+ readonly injector?: Injector;
641
+ /** How local writes are diffed into ops (forwarded to `opSync`; see `DiffOpsOptions`). Absent: as before. */
642
+ readonly emit?: DiffOpsOptions;
519
643
  };
520
644
  type WebRtcMeshRef = {
521
- /** This replica's origin: what other peers see this side as, in `peers` and on the wire. */
522
- readonly origin: string;
523
- readonly status: Signal<'connecting' | 'live'>;
524
- /** Origins with an OPEN data channel. */
525
- readonly peers: Signal<readonly string[]>;
526
- /** The links the mesh runs on; other channels asked for in `channels` are sent on these. */
527
- readonly links: PeerLinks;
528
- close(): void;
645
+ /** This replica's origin: what other peers see this side as, in `peers` and on the wire. */
646
+ readonly origin: string;
647
+ readonly status: Signal<'connecting' | 'live'>;
648
+ /** Origins with an OPEN data channel. */
649
+ readonly peers: Signal<readonly string[]>;
650
+ /** The links the mesh runs on; other channels asked for in `channels` are sent on these. */
651
+ readonly links: PeerLinks;
652
+ close(): void;
529
653
  };
530
654
  /**
531
655
  * Peer-to-peer mesh sync: the relay only signals
@@ -541,45 +665,44 @@ type WebRtcMeshRef = {
541
665
  * relay-backed session over the same document a peer channel may hand on only envelopes the
542
666
  * relay has sequenced, never a peer's own unacknowledged writes.
543
667
  */
544
- declare function webRtcMesh<T extends object>(source: WritableSignal<T>, opt: WebRtcMeshOptions): WebRtcMeshRef;
545
-
668
+ export declare function webRtcMesh<T extends object>(source: WritableSignal<T>, opt: WebRtcMeshOptions): WebRtcMeshRef;
546
669
  /**
547
670
  * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
548
671
  * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
549
672
  * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
550
673
  */
551
- declare const presenceChannel: PeerChannelSpec;
674
+ export declare const presenceChannel: PeerChannelSpec;
552
675
  /**
553
676
  * What goes over the wire. `seq` counts frames sent on one channel of one links object, in
554
677
  * send order, and is shared by every sender created on those links; it never restarts while
555
678
  * the links live. It orders frames of one link only, and is never compared across links.
556
679
  */
557
680
  type PresenceFrame<T> = {
558
- readonly seq: number;
559
- readonly value: T;
681
+ readonly seq: number;
682
+ readonly value: T;
560
683
  };
561
684
  type RtcPresenceOptions = {
562
- /** The channel label on the links; defaults to {@link presenceChannel}'s. */
563
- readonly channel?: string;
564
- /** Minimum gap between two published frames. Defaults to 33 ms (about 30 per second). */
565
- readonly throttleMs?: number;
566
- /**
567
- * Who is in the room, from the relay. A value is held only for an origin in it: a peer link
568
- * can outlive the relay membership on a dead socket, so the link is not proof of presence.
569
- * Subscribe synchronously with the current roster, then report every transition, including
570
- * a leave followed immediately by a rejoin. Use `links.onMembers` for the links' relay roster.
571
- * A sampled signal or an effect cannot preserve these transitions.
572
- */
573
- readonly roster: (cb: (members: readonly string[]) => void) => () => void;
574
- readonly injector?: Injector;
685
+ /** The channel label on the links; defaults to {@link presenceChannel}'s. */
686
+ readonly channel?: string;
687
+ /** Minimum gap between two published frames. Defaults to 33 ms (about 30 per second). */
688
+ readonly throttleMs?: number;
689
+ /**
690
+ * Who is in the room, from the relay. A value is held only for an origin in it: a peer link
691
+ * can outlive the relay membership on a dead socket, so the link is not proof of presence.
692
+ * Subscribe synchronously with the current roster, then report every transition, including
693
+ * a leave followed immediately by a rejoin. Use `links.onMembers` for the links' relay roster.
694
+ * A sampled signal or an effect cannot preserve these transitions.
695
+ */
696
+ readonly roster: (cb: (members: readonly string[]) => void) => () => void;
697
+ readonly injector?: Injector;
575
698
  };
576
699
  type RtcPresenceRef<T> = {
577
- /** Publishes this side's value; throttled, and the last value of a burst always goes out. */
578
- set(value: T): void;
579
- /** The latest value per origin, only for origins in the roster. */
580
- readonly peers: Signal<ReadonlyMap<string, T>>;
581
- /** Stops publishing and forgets every held value. The links stay open. */
582
- close(): void;
700
+ /** Publishes this side's value; throttled, and the last value of a burst always goes out. */
701
+ set(value: T): void;
702
+ /** The latest value per origin, only for origins in the roster. */
703
+ readonly peers: Signal<ReadonlyMap<string, T>>;
704
+ /** Stops publishing and forgets every held value. The links stay open. */
705
+ close(): void;
583
706
  };
584
707
  /**
585
708
  * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
@@ -605,7 +728,5 @@ type RtcPresenceRef<T> = {
605
728
  *
606
729
  * Values travel as JSON.
607
730
  */
608
- declare function rtcPresence<T>(links: PeerLinks, opt: RtcPresenceOptions): RtcPresenceRef<T>;
609
-
610
- export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
611
- export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };
731
+ export declare function rtcPresence<T>(links: PeerLinks, opt: RtcPresenceOptions): RtcPresenceRef<T>;
732
+ export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };