@mmstack/mesh 21.3.0 → 21.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -211,7 +211,10 @@ here", or an agent's current activity.
211
211
 
212
212
  Pass a `policy` and (when your policy reads claims) a `ctx`, and the client validates each write
213
213
  before it hits the wire, matching the relay's own check. An honest client never emits an op the
214
- relay would reject, so the tripwire only ever fires on a broken or hostile peer.
214
+ relay would reject, so the tripwire only ever fires on a broken or hostile peer. When it does
215
+ fire, the client ejects itself with the same reason the relay would have used: the local check
216
+ saves the room a round trip, but it is an optimization, not the enforcement. The relay validates
217
+ every envelope on arrival no matter what the client claims to have checked.
215
218
 
216
219
  ```ts
217
220
  meshSync(store, {
@@ -226,25 +229,54 @@ meshSync(store, {
226
229
  ## Agents
227
230
 
228
231
  An agent acts under the same protocol as a person: the same envelopes, attribution, ACLs, and undo.
229
- There are two ways to give it write access, for two levels of trust.
232
+ `agentSeat` gives it a seat anywhere JavaScript runs, with no Angular and no browser APIs: a Node
233
+ service, a worker, an edge runtime. A seat is one identity holding its own live replica; for
234
+ several agents in one room (one drafting, one reviewing), open several seats and scope each with
235
+ the relay policy. Roles are a policy question, not an API one.
236
+
237
+ ### A seat at the table
238
+
239
+ ```ts
240
+ import { agentSeat, describeOp, webSocketTransport } from '@mmstack/mesh';
241
+
242
+ const seat = agentSeat(initialBoard(), {
243
+ room: 'board-42',
244
+ writer: agentId, // an opaque principal id, like any peer's
245
+ transport: webSocketTransport('wss://sync.example.com'),
246
+ ctx: { kind: 'agent' },
247
+ });
248
+
249
+ seat.snapshot(); // the current document, plain data
250
+ seat.changes((e) => {
251
+ if (e.kind === 'change') {
252
+ activity.push(...e.ops.map((op) => describeOp(op, e.writer)));
253
+ }
254
+ });
255
+ seat.setAtPath('tasks.t1.done', true); // a direct write, attributed like any peer's
256
+ seat.setPresence({ name: 'Scribe', kind: 'agent' });
257
+ ```
258
+
259
+ `seat.doc` is the same signal store `meshSync` replicates in the browser, so computeds and reactive
260
+ reads work as usual. `setAtPath` takes the dot paths a tool-calling model naturally produces.
261
+ Reconnection, delta resume, and offline rebase behave exactly as in `meshSync`; the two are shells
262
+ over one session implementation.
230
263
 
231
264
  ### Review a branch
232
265
 
233
- `mesh.fork()` gives the agent a fork of the synced store. Its writes stay on the fork, so nothing
234
- reaches the room until a person approves. `ops()` is the staged change as data, ready to render for
235
- review. `commit()` emits it to the room; `discard()` drops it.
266
+ An agent's write is a sample that can be wrong, so the safe default keeps it behind a person's
267
+ approval. `seat.fork()` (and `mesh.fork()` in the browser) gives the agent an isolated branch of
268
+ the synced store. Its writes stay on the fork, so nothing reaches the room until someone approves.
269
+ `ops()` is the staged change as data, ready to render for review. `commit()` emits it to the room;
270
+ `discard()` drops it.
236
271
 
237
272
  ```ts
238
- const board = store<Board>(initialBoard());
239
- const mesh = meshSync(board, { room: 'board-42', writer: userId, transport });
240
-
241
- const proposal = mesh.fork(); // the agent's isolated branch, off the room
242
- runAgent(proposal.store); // it writes here
273
+ const proposal = seat.fork(); // the agent's isolated branch, off the room
274
+ setAtPath(proposal.store, 'plan.endDate', '2026-10-11'); // it writes here
243
275
 
244
- const changes = proposal.ops(); // StoreOp[] for the reviewer to see
245
- proposal.commit(); // approve: emits as concurrent writes to the room
246
- // proposal.rebase(); // re-observe the room, then commit on top
247
- // proposal.discard(); // reject: drops the staged writes
276
+ const staged = proposal.ops(); // StoreOp[] for the reviewer to see
277
+ proposal.commit(); // approve: emits as concurrent writes to the room
278
+ // proposal.rebase(); // re-observe the room, then commit on top
279
+ // proposal.discard(); // reject: drops the staged writes
248
280
  ```
249
281
 
250
282
  The commit cites what the fork observed when it forked, so an edit that lands on the room while a
@@ -253,18 +285,79 @@ approval. Call `rebase()` to re-observe the room first when the proposal should
253
285
  latest. The reviewer reads and writes normal store values, and the agent never touches the room
254
286
  directly. This is the fit when a write should be seen before it lands.
255
287
 
288
+ ### Feed the model diffs, not the world
289
+
290
+ Room state and the model loop meet at two calls. `stableSnapshot()` returns the document stamped
291
+ with the relay sequence number it is provably the fold of, or `null` while one of the seat's own
292
+ writes is still in flight. A non-null result is byte-stable for its seq: rebuilding the room at
293
+ that seq yields exactly this document, which is what makes it safe to put in a provider prompt
294
+ cache. `changes` then delivers everything after that seq in order, so a prompt becomes a cached
295
+ prefix plus an append-only suffix, and each turn sends only what happened since.
296
+
297
+ ```ts
298
+ let base = seat.stableSnapshot(); // { seq, doc } | null
299
+ const sinceBase: string[] = [];
300
+
301
+ seat.changes((e) => {
302
+ if (e.kind === 'change') {
303
+ sinceBase.push(...e.ops.map((op) => describeOp(op, e.writer)));
304
+ } else {
305
+ // 'resync': the seat rejoined past the relay's retention, the suffix no longer
306
+ // extends the stream. Rebuild: take a fresh base, drop the accumulated lines.
307
+ base = null;
308
+ sinceBase.length = 0;
309
+ }
310
+ });
311
+
312
+ // per model turn: refresh the base on your own cadence (message velocity, context size)
313
+ if (!base || sinceBase.length > 200) {
314
+ const next = seat.stableSnapshot();
315
+ if (next) {
316
+ base = next; // new cached prefix
317
+ sinceBase.length = 0;
318
+ }
319
+ }
320
+ ```
321
+
322
+ The seat carries no model code and no provider dependency. Its reads and writes are plain
323
+ JSON-shaped functions, so they wrap directly into any tool-calling loop, for example the
324
+ [`ai`](https://www.npmjs.com/package/ai) SDK:
325
+
326
+ ```ts
327
+ import { setAtPath } from '@mmstack/mesh';
328
+ import { tool } from 'ai';
329
+ import { z } from 'zod';
330
+
331
+ const propose = tool({
332
+ description: 'Stage edits for human review.',
333
+ inputSchema: z.object({
334
+ rationale: z.string(),
335
+ changes: z.array(z.object({ path: z.string(), value: z.unknown() })),
336
+ }),
337
+ execute: async ({ rationale, changes }) => {
338
+ const fork = seat.fork();
339
+ for (const c of changes) setAtPath(fork.store, c.path, c.value);
340
+ openProposals.set(stageForReview(fork, rationale), fork);
341
+ return 'staged for review';
342
+ },
343
+ });
344
+ // approval, wherever it happens in your UI: fork.commit() or fork.discard()
345
+ ```
346
+
256
347
  ### Write as a peer
257
348
 
258
- An agent can also join the room directly, scoped by the relay ACL. Give it a narrower `ctx` and a
259
- `policy`, and the relay ejects any write outside its scope (see [Trust](#trust)).
349
+ A trusted, in-scope agent can also write to the room directly, scoped by the relay ACL. Give it a
350
+ narrower `ctx` and a `policy`, and the relay ejects any write outside its scope (see
351
+ [Trust](#trust)). The options are the same on `agentSeat` and `meshSync`.
260
352
 
261
353
  ```ts
262
- meshSync(board, {
354
+ agentSeat(initialBoard(), {
263
355
  room: 'board-42',
264
356
  writer: agentId,
265
357
  transport,
266
358
  ctx: { kind: 'agent', claims: { scope: 'pricing' } },
267
359
  policy: pricingScopeOnly,
360
+ onEject: (reason) => log.warn('agent ejected', reason),
268
361
  });
269
362
  ```
270
363
 
Binary file
@@ -1 +1 @@
1
- {"version":3,"file":"mmstack-mesh.mjs","sources":["../../../../../packages/mesh/client/src/lib/mesh-sync.ts","../../../../../packages/mesh/client/src/lib/transport.ts","../../../../../packages/mesh/client/src/lib/webrtc-mesh.ts","../../../../../packages/mesh/client/src/mmstack-mesh.ts"],"sourcesContent":["import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n runInInjectionContext,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport {\n checkEnvelope,\n MESH_PROTO_VERSION,\n type OpPolicy,\n type PresenceState,\n type PrincipalCtx,\n type SeqEnvelope,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createConvergingApply,\n forkStore,\n OP_PROTO_VERSION,\n opSync,\n registerResource,\n type AsyncStore,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type ResourceLike,\n type SyncedFork,\n type SyncOp,\n type WritableSignalStore,\n} from '@mmstack/primitives';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\nexport type MeshStatus =\n | 'connecting'\n | 'live'\n | 'reconnecting'\n | 'ejected'\n | 'closed';\n\nexport type MeshPeer = PresenceState;\n\n/**\n * A composed, user-facing health status for a synced store the surface that\n * turns a versioned reject from a dead socket into a speakable 'outdated' banner.\n */\nexport type SyncHealthStatus =\n | 'live'\n | 'offline'\n | 'outdated'\n | 'ejected'\n | 'degraded';\n\nexport type SyncHealth = {\n readonly status: SyncHealthStatus;\n /** Why, when the status is `outdated`/`ejected`/`degraded`. */\n readonly reason?:\n | 'proto'\n | 'policy-version'\n | 'schema'\n | 'quota'\n | 'worker'\n | (string & {});\n /** `Date.now()` of the last successful sync (welcome or applied env). */\n readonly lastSyncedAt?: number;\n /**\n * Offline writes persisted by an older build that could not be restored on boot. Envelopes\n * from a previous wire-protocol version lack the citation metadata current merging needs,\n * so they are dropped (loudly) instead of being upgraded with fabricated citations.\n */\n readonly droppedOfflineWrites?: number;\n /**\n * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id\n * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a\n * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line\n * against a malformed neighbor; through a relay these are also rejected at the relay.\n */\n readonly droppedInvalidEnvelopes?: number;\n};\n\n// a versioned reject means \"your build is behind\" → prompt an update, not a dead socket\nconst OUTDATED_REASONS: ReadonlySet<string> = new Set([\n 'proto',\n 'policy-version',\n 'schema',\n]);\n\nexport type MeshSyncOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /** Emit-side validation, symmetric with the relay's (tripwire honesty). */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n /**\n * The room's shared configuration pin, checked at hello against the relay's. Bump it\n * together whenever anything peers must agree on changes: the write policy, and just as\n * importantly the merge/fold configuration (`policies`). Peers folding the same register\n * state with different rules read different values, so one room means one fold config; a\n * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.\n */\n readonly policyVersion?: number;\n /** The data shape this client speaks. Older-than-room → `outdated`, and a\n * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n readonly injector?: Injector;\n /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */\n readonly register?: 'track' | 'suspend';\n readonly onEject?: (reason: string) => void;\n /**\n * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects\n * (and before it restores an `outbox`), so a store hydrated from another source first (a worker\n * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.\n * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base\n * that fails to load never wedges the connection.\n */\n readonly whenReady?: () => PromiseLike<void> | void;\n /**\n * Persist the unacknowledged local outbox (and this client's stable origin) so offline writes\n * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room\n * on the next welcome, instead of being lost with in-memory state. The payload is written to\n * `store` under `key`, debounced.\n *\n * By default (`crossTab: 'queue'`) a Web Lock on `key` makes this a single-writer-per-key resource:\n * a second tab sharing the key WAITS (stays `connecting`, surfaced via `status`/`health`) until the\n * first releases, rather than restoring the same origin and colliding on version mints. Set\n * `crossTab: 'off'` to skip the lock and coordinate ownership yourself (e.g. a per-tab key, or\n * leader election over `tabSync`). A debounced write means a hard crash within the debounce window\n * can drop the very last mint — a small, best-effort gap; tune it with `debounceMs`.\n */\n readonly outbox?: {\n readonly key: string;\n readonly store: AsyncStore;\n /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */\n readonly debounceMs?: number;\n /**\n * Cross-tab contention for the shared `key`. `'queue'` (default) holds a Web Lock so only one tab\n * owns the durable outbox at a time; others wait. `'off'` skips the lock (you coordinate).\n * (A future `'ephemeral'` — non-leaders run live with a throwaway origin — is planned.)\n */\n readonly crossTab?: 'queue' | 'off';\n };\n};\n\n/** The shape persisted under `outbox.key`: the stable origin, the emit high-water, and the tail. */\ntype PersistedOutbox = {\n readonly origin: string;\n readonly version: number;\n readonly envs: readonly OpEnvelope[];\n};\n\nexport type MeshSyncRef<T extends object = Record<string, unknown>> = {\n readonly status: Signal<MeshStatus>;\n /** Composed sync-health for a user-facing surface. */\n readonly health: Signal<SyncHealth>;\n readonly peers: Signal<readonly MeshPeer[]>;\n /** Publish this client's ephemeral presence payload (cursor, section, activity…). */\n setPresence(data: unknown): void;\n /**\n * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The\n * fork observes the room as it is now; committing emits its diff citing only those observed\n * writes, so an edit that lands on the room while the fork is open stays a concurrent value the\n * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe\n * the room and commit on top of the latest instead. `discard()` drops the staged edits.\n */\n fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;\n close(): void;\n};\n\nconst RECONNECT_BASE_MS = 500;\nconst OUTBOX_DEBOUNCE_MS = 300;\n\n/**\n * Replicates a signal store across clients through a relay room: local writes emit stamped\n * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot\n * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.\n * A synced store reads exactly like a local one — connection state surfaces only through\n * `status` and the transition scope.\n */\nexport function meshSync<T extends object>(\n source: WritableSignal<T>,\n opt: MeshSyncOptions,\n): MeshSyncRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const status = signal<MeshStatus>('connecting');\n const lastReason = signal<string | undefined>(undefined);\n const lastSyncedAt = signal<number | undefined>(undefined);\n const droppedOffline = signal(0);\n const droppedInvalid = signal(0);\n const peerMap = signal<ReadonlyMap<string, MeshPeer>>(new Map());\n const peers = computed(() => [...peerMap().values()]);\n const policyVersion = opt.policyVersion ?? 0;\n\n const health = computed<SyncHealth>(() => {\n const at = lastSyncedAt();\n const dropped = droppedOffline();\n const invalid = droppedInvalid();\n const extra = {\n ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),\n ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),\n };\n switch (status()) {\n case 'live':\n return { status: 'live', lastSyncedAt: at, ...extra };\n case 'ejected': {\n const reason = lastReason();\n return reason && OUTDATED_REASONS.has(reason)\n ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }\n : { status: 'ejected', reason, lastSyncedAt: at, ...extra };\n }\n default: // connecting / reconnecting / closed — not reachable\n return { status: 'offline', lastSyncedAt: at, ...extra };\n }\n });\n\n // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything\n let sync!: OpSync<T>;\n let started = false;\n let unsubLocal: () => void = () => undefined;\n\n // A fresh origin is minted every boot; a restored outbox tail resends under ITS recorded origin.\n // So this client is responsible for more than one origin, and unacked writes are keyed by\n // (origin, version) with an acked high-water per origin. `ownOrigins` is every origin we resend\n // for (the fresh mint plus any restored-tail origins), so an echo of any of them clears an ack.\n const ownOrigins = new Set<string>();\n const unacked = new Map<string, OpEnvelope>();\n const acked = new Map<string, number>();\n const unackedKey = (env: { origin: string; version: number }): string =>\n `${env.origin}\u0000${env.version}`;\n let lastSeq = 0;\n let instance: string | undefined;\n let presenceData: unknown;\n let hasPresence = false;\n let transport: MeshTransport | null = null;\n let attempts = 0;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let unsubs: (() => void)[] = [];\n let closed = false;\n let persistTimer: ReturnType<typeof setTimeout> | undefined;\n // single-writer Web Lock (crossTab:'queue'): `release` frees it for the next tab once acquired;\n // `cancel` aborts a still-queued request if we tear down before the lock is ever granted.\n let releaseLock: (() => void) | undefined;\n let cancelLock: (() => void) | undefined;\n\n const doPersist = (): void => {\n if (!opt.outbox || !started) return;\n const payload: PersistedOutbox = {\n origin: sync.origin,\n version: sync.watermark()[sync.origin] ?? 0,\n envs: [...unacked.values()],\n };\n void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));\n };\n // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)\n const persistOutbox = (immediate = false): void => {\n if (!opt.outbox) return;\n if (immediate) {\n if (persistTimer !== undefined) clearTimeout(persistTimer);\n persistTimer = undefined;\n doPersist();\n return;\n }\n if (persistTimer !== undefined) return;\n persistTimer = setTimeout(() => {\n persistTimer = undefined;\n doPersist();\n }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);\n };\n\n const terminal = (state: 'ejected' | 'closed', reason?: string): void => {\n closed = true;\n cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown\n releaseLock?.(); // free a held lock for the next waiting tab\n cancelLock = releaseLock = undefined;\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n for (const unsub of unsubs.splice(0)) unsub();\n unsubLocal();\n persistOutbox(true); // save the still-unacked tail for the next boot before dropping it\n unacked.clear();\n transport?.close();\n transport = null;\n peerMap.set(new Map());\n lastReason.set(reason);\n status.set(state);\n if (reason !== undefined) opt.onEject?.(reason);\n };\n\n const sendEnv = (env: OpEnvelope): void => {\n transport?.send({ t: 'env', room: opt.room, env });\n };\n\n const flushUnacked = (): void => {\n // per origin, versions must go out in order; across origins the order is irrelevant\n for (const env of [...unacked.values()].sort((a, b) =>\n a.origin === b.origin ? a.version - b.version : a.origin < b.origin ? -1 : 1,\n )) {\n sendEnv(env);\n }\n };\n\n const handle = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome': {\n if (instance !== undefined && msg.instance !== instance) lastSeq = 0;\n instance = msg.instance;\n peerMap.set(new Map(msg.peers.map((p) => [p.origin, p])));\n if (msg.mode === 'delta') {\n for (const env of msg.envs) applyRemote(env);\n } else if (msg.mode === 'snapshot') {\n // The room ships register state, not a value: fold it locally (this client's own\n // policies) to derive the root, then hydrate root + registers together. Each own\n // origin's watermark stays at its acked high-water so unacked local writes rebase on top.\n const conv = createConvergingApply({ policies: opt.policies });\n conv.load(msg.registers);\n const ownWm: Record<string, number> = {};\n for (const o of ownOrigins) ownWm[o] = acked.get(o) ?? 0;\n // rebase from the durable outbox, not opSync's bounded recent-local ring, so a long\n // offline burst larger than that ring is never dropped from the rebase on a snapshot join\n sync.hydrate(\n {\n root: conv.materialize() as T,\n registers: msg.registers,\n wm: { ...msg.wm, ...ownWm },\n },\n [...unacked.values()],\n );\n lastSeq = msg.seq;\n } else if (msg.seq === 0 && lastSeq === 0) {\n sync.seed();\n }\n lastSeq = Math.max(lastSeq, msg.seq);\n attempts = 0;\n lastSyncedAt.set(Date.now());\n status.set('live');\n flushUnacked();\n if (hasPresence)\n transport?.send({\n t: 'presence',\n room: opt.room,\n data: presenceData,\n });\n return;\n }\n case 'env':\n applyRemote(msg.env);\n return;\n case 'presence': {\n const next = new Map(peerMap());\n if (msg.gone) next.delete(msg.peer.origin);\n else next.set(msg.peer.origin, msg.peer);\n peerMap.set(next);\n return;\n }\n case 'eject':\n if (msg.writer === opt.writer) terminal('ejected', msg.reason);\n return;\n case 'reject':\n terminal('ejected', msg.reason);\n return;\n case 'frontier':\n // the relay compacted past this stamp: reclaim our own settled register state to match,\n // so a long-lived connection stays bounded by live data rather than history\n if (started) sync.prune(msg.frontier);\n return;\n }\n };\n\n const applyRemote = (env: SeqEnvelope): void => {\n lastSeq = Math.max(lastSeq, env.seq);\n lastSyncedAt.set(Date.now());\n // a migration to a shape newer than ours: stop applying + surface 'outdated' (never downgrade-interpret newer data)\n if (\n opt.schemaVersion !== undefined &&\n env.schemaVersion !== undefined &&\n env.schemaVersion > opt.schemaVersion\n ) {\n terminal('ejected', 'schema');\n return;\n }\n if (ownOrigins.has(env.origin)) {\n unacked.delete(unackedKey(env));\n acked.set(env.origin, Math.max(acked.get(env.origin) ?? 0, env.version));\n persistOutbox();\n return;\n }\n sync.receive(env);\n };\n\n const connect = (): void => {\n if (closed) return;\n for (const unsub of unsubs.splice(0)) unsub();\n const t = opt.transport();\n transport = t;\n unsubs = [\n t.onMessage(handle),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n status.set('reconnecting');\n const delay = Math.min(\n opt.reconnect?.maxDelayMs ?? 15_000,\n RECONNECT_BASE_MS * 2 ** attempts++,\n );\n reconnectTimer = setTimeout(\n () => {\n reconnectTimer = undefined;\n connect();\n },\n delay + Math.random() * 100,\n );\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion,\n seq: lastSeq > 0 ? lastSeq : undefined,\n schemaVersion: opt.schemaVersion,\n });\n };\n\n const wireLocal = (): void => {\n unsubLocal = sync.subscribe((env) => {\n const violation = checkEnvelope(opt.policy, env, {\n ...opt.ctx,\n writer: opt.writer,\n });\n if (violation) {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] local write violates the room policy — not sent',\n violation,\n );\n }\n return;\n }\n ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim\n unacked.set(unackedKey(env), env);\n persistOutbox();\n if (status() === 'live') sendEnv(env);\n });\n };\n\n // A persisted envelope from a previous wire-protocol version lacks cites/epoch; there is no\n // sound way to mint citations after the fact, so such writes are dropped loudly, never adapted.\n const restorable = (env: OpEnvelope): boolean =>\n env.proto === OP_PROTO_VERSION &&\n env.ops.every(\n (op) =>\n Array.isArray((op as SyncOp).cites) &&\n typeof (op as SyncOp).epoch === 'number',\n );\n\n const initCore = (restore?: PersistedOutbox): void => {\n if (closed) return;\n // Mint a FRESH origin every boot: a dot is (origin, hlc), so a never-before-used origin cannot\n // collide with anything a prior boot (or a byte clone of this outbox) emitted. The persisted\n // origin is NOT reused for minting; it survives only as metadata on the restored tail, which\n // resends verbatim under it. Per-boot origin growth is bounded (one per boot) and dead origins'\n // register watermarks compact away below the prune frontier.\n sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n injector,\n onReject: (_env, reason) => {\n droppedInvalid.update((n) => n + 1);\n if (isDevMode()) {\n console.warn(`[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`);\n }\n },\n });\n ownOrigins.add(sync.origin);\n started = true;\n wireLocal();\n if (restore && (restore.envs.length > 0 || restore.version > 0)) {\n const kept = restore.envs.filter(restorable);\n const dropped = restore.envs.length - kept.length;\n if (dropped > 0) {\n droppedOffline.set(dropped);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped ${dropped} persisted offline write(s) from an older protocol version: ops without cites/epoch cannot be merged soundly, and citations are never fabricated`,\n );\n }\n }\n // the tail resends verbatim under its recorded origin; new writes mint on the fresh origin,\n // so a version acked + dropped before the reboot can never be re-minted (the origin differs)\n sync.restore(kept, restore.version); // → subscribe repopulates `unacked` for resend\n }\n persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe\n connect();\n };\n\n if (opt.register) {\n const connection: ResourceLike = {\n status: computed(() => {\n const s = status();\n return s === 'connecting'\n ? 'loading'\n : s === 'reconnecting'\n ? 'reloading'\n : s === 'ejected'\n ? 'error'\n : 'resolved';\n }),\n isLoading: computed(\n () => status() === 'connecting' || status() === 'reconnecting',\n ),\n hasValue: () => true,\n };\n runInInjectionContext(injector, () =>\n registerResource(connection, { suspends: opt.register === 'suspend' }),\n );\n }\n\n injector.get(DestroyRef).onDestroy(() => {\n if (!closed) terminal('closed');\n unsubLocal();\n if (started) sync.destroy();\n });\n\n // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.\n const bootFromDisk = async (): Promise<void> => {\n if (closed || !opt.outbox) return;\n let saved: PersistedOutbox | undefined;\n try {\n const raw = await opt.outbox.store.get(opt.outbox.key);\n saved =\n raw && typeof raw === 'object' && 'origin' in raw\n ? (raw as PersistedOutbox)\n : undefined;\n } catch {\n saved = undefined; // an unreadable slot must not wedge the boot\n }\n initCore(saved);\n };\n\n const beginConnect = (): void => {\n if (closed) return;\n if (!opt.outbox) {\n initCore();\n } else if ((opt.outbox.crossTab ?? 'queue') === 'off') {\n void bootFromDisk(); // no single-writer lock — the app coordinates ownership\n } else {\n // crossTab:'queue' — hold an exclusive Web Lock on the key for this tab's lifetime, so a\n // second tab sharing the key WAITS (stays 'connecting') instead of restoring the same origin\n // and colliding on version mints. The lock auto-releases if the tab crashes.\n const locks = globalThis.navigator?.locks;\n if (!locks) {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] outbox crossTab:\"queue\" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock. Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:\"off\" to silence this.',\n );\n }\n void bootFromDisk();\n } else {\n const abort = new AbortController();\n cancelLock = () => abort.abort();\n void locks\n .request(\n `@mmstack/mesh:outbox:${opt.outbox.key}`,\n { mode: 'exclusive', signal: abort.signal },\n () => {\n cancelLock = undefined; // granted — no longer abortable, only releasable\n if (closed) return Promise.resolve();\n // hold the lock until teardown resolves this promise\n return new Promise<void>((release) => {\n releaseLock = release;\n void bootFromDisk();\n });\n },\n )\n .catch((e: unknown) => {\n // an aborted request is our own teardown; any other failure → degrade to no-lock\n if (!closed && (e as { name?: string })?.name !== 'AbortError') {\n void bootFromDisk();\n }\n });\n }\n }\n };\n\n // Assemble the local base first (worker hydration, disk snapshot), THEN connect, so the room\n // welcome rebases pending onto a populated store instead of racing it. A rejection is treated as\n // ready so a failed base load never wedges the connection.\n if (opt.whenReady) {\n void Promise.resolve()\n .then(() => opt.whenReady?.())\n .then(\n () => beginConnect(),\n () => beginConnect(),\n );\n } else {\n beginConnect();\n }\n\n return {\n status: status.asReadonly(),\n health,\n peers,\n setPresence: (data) => {\n presenceData = data;\n hasPresence = true;\n if (status() === 'live') {\n transport?.send({ t: 'presence', room: opt.room, data });\n }\n },\n fork: (forkOpt) => {\n const f = forkStore(\n source as unknown as WritableSignalStore<T & Record<string, any>>,\n forkOpt,\n );\n // a fork created before the sync connected observed nothing, so an empty frontier is correct\n // (its commit cites nothing and lands as concurrent); once connected, capture the live one\n let frontier: DotFrontier = started ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = started ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () =>\n started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n close: () => {\n if (!closed) terminal('closed');\n unsubLocal();\n if (started) sync.destroy();\n },\n };\n}\n","import { isDevMode } from '@angular/core';\nimport type {\n ClientMsg,\n PrincipalCtx,\n Relay,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\n\n/**\n * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport\n * represents a single connection and never reconnects itself.\n */\nexport type MeshTransport = {\n send(msg: ClientMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\nexport type MeshTransportFactory = () => MeshTransport;\n\n/**\n * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and\n * flushed on open; malformed inbound frames are dropped.\n */\nexport function webSocketTransport(\n url: string,\n protocols?: string | string[],\n): MeshTransportFactory {\n return () => {\n const ws = new WebSocket(url, protocols);\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n\n ws.onopen = () => {\n for (const frame of pending.splice(0)) ws.send(frame);\n };\n ws.onmessage = (event) => {\n let msg: ServerMsg;\n try {\n msg = JSON.parse(String(event.data)) as ServerMsg;\n } catch {\n if (isDevMode()) {\n console.warn('[@mmstack/mesh] dropped unparseable frame (expected JSON text)');\n }\n return;\n }\n for (const cb of [...messageCbs]) cb(msg);\n };\n ws.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n\n return {\n send: (msg) => {\n const frame = JSON.stringify(msg);\n if (ws.readyState === WebSocket.OPEN) ws.send(frame);\n else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => ws.close(),\n };\n };\n}\n\n/**\n * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop\n * tests, and handy for single-process demos or an SSR-side room.\n */\nexport function directTransport(\n relay: Relay,\n ctx: PrincipalCtx,\n): MeshTransportFactory {\n return () => {\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n let open = true;\n\n const connection = relay.connect(\n {\n send: (msg) => {\n if (!open) return;\n for (const cb of [...messageCbs]) cb(msg);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n },\n ctx,\n );\n\n return {\n send: (msg) => {\n if (open) connection.receive(msg);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n };\n };\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport { MESH_PROTO_VERSION, type ServerMsg } from '@mmstack/mesh-protocol';\nimport {\n opSync,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSyncCheckpoint,\n} from '@mmstack/primitives';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\n/** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */\nexport type DataChannelLike = {\n send(frame: string): void;\n onMessage(cb: (frame: string) => void): () => void;\n onOpen(cb: () => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\n/**\n * Creates one peer link. `polite` assigns the perfect-negotiation role (derived\n * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads\n * through the relay; `signal` delivers the remote side's payloads.\n */\nexport type PeerConnector = (opt: {\n readonly remote: string;\n readonly polite: boolean;\n readonly sendSignal: (data: unknown) => void;\n}) => {\n readonly channel: DataChannelLike;\n signal(data: unknown): void;\n close(): void;\n};\n\n/** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */\nexport function rtcPeerConnector(config?: RTCConfiguration): PeerConnector {\n return ({ polite, sendSignal }) => {\n const pc = new RTCPeerConnection(config);\n const messageCbs = new Set<(frame: string) => void>();\n const openCbs = new Set<() => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n let dc: RTCDataChannel | null = null;\n let makingOffer = false;\n let ignoreOffer = false;\n\n const attach = (channel: RTCDataChannel): void => {\n dc = channel;\n channel.onmessage = (e) => {\n for (const cb of [...messageCbs]) cb(String(e.data));\n };\n channel.onopen = () => {\n for (const frame of pending.splice(0)) channel.send(frame);\n for (const cb of [...openCbs]) cb();\n };\n channel.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n };\n\n if (!polite) attach(pc.createDataChannel('mmstack-mesh'));\n else pc.ondatachannel = (e) => attach(e.channel);\n\n pc.onicecandidate = (e) => {\n if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });\n };\n pc.onnegotiationneeded = async () => {\n try {\n makingOffer = true;\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n } finally {\n makingOffer = false;\n }\n };\n\n return {\n channel: {\n send: (frame) => {\n if (dc && dc.readyState === 'open') dc.send(frame);\n else pending.push(frame);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n close: () => dc?.close(),\n },\n signal: async (data) => {\n const { description, ice } = (data ?? {}) as {\n description?: RTCSessionDescriptionInit;\n ice?: RTCIceCandidateInit;\n };\n if (description) {\n const collision =\n description.type === 'offer' &&\n (makingOffer || pc.signalingState !== 'stable');\n ignoreOffer = !polite && collision;\n if (ignoreOffer) return;\n await pc.setRemoteDescription(description);\n if (description.type === 'offer') {\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n }\n } else if (ice) {\n try {\n await pc.addIceCandidate(ice);\n } catch (err) {\n if (!ignoreOffer) throw err;\n }\n }\n },\n close: () => {\n dc?.close();\n pc.close();\n },\n };\n };\n}\n\ntype P2PMsg =\n | { t: 'hello'; wm: Record<string, number> }\n // the full checkpoint (root + register state + watermark), NOT a bare value: the covered\n // side must inherit supersession state or already-superseded stragglers would resurrect\n | { t: 'state'; state: OpSyncCheckpoint<object> }\n | { t: 'uptodate' }\n | { t: 'env'; env: OpEnvelope };\n\nexport type WebRtcMeshOptions = {\n readonly room: string;\n readonly writer: string;\n /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */\n readonly signaling: MeshTransportFactory;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policyVersion?: number;\n readonly injector?: Injector;\n};\n\nexport type WebRtcMeshRef = {\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins with an OPEN data channel. */\n readonly peers: Signal<readonly string[]>;\n close(): void;\n};\n\ntype Peer = {\n link: ReturnType<PeerConnector>;\n open: boolean;\n unsubs: (() => void)[];\n};\n\n/**\n * Peer-to-peer mesh sync: the relay only signals\n * and tracks membership; envelopes flow over WebRTC data channels and converge via the\n * per-path register map. Catch-up is pairwise: on channel open both sides exchange\n * watermarks; a side whose state is strictly covered hydrates from the other's FULL\n * checkpoint (root + per-path register state + watermark), so supersession and precedence\n * carry over intact: a late joiner is indistinguishable from a peer that saw every\n * envelope. Two peers that each hold envelopes the other lacks keep their convergent\n * go-forward guarantees but do not exchange the missed envelopes retroactively.\n */\nexport function webRtcMesh<T extends object>(\n source: WritableSignal<T>,\n opt: WebRtcMeshOptions,\n): WebRtcMeshRef {\n const injector = opt.injector ?? inject(Injector);\n const connector = opt.connector ?? rtcPeerConnector();\n const status = signal<'connecting' | 'live'>('connecting');\n const openPeers = signal<ReadonlySet<string>>(new Set());\n const peers = new Map<string, Peer>();\n let signalingUnsubs: (() => void)[] = [];\n let transport: MeshTransport | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n\n const sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion: opt.policyVersion,\n injector,\n });\n\n const covered = (\n mine: Record<string, number>,\n theirs: Record<string, number>,\n ): boolean => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);\n\n const sendTo = (peer: Peer, msg: P2PMsg): void => {\n peer.link.channel.send(JSON.stringify(msg));\n };\n\n const broadcast = (msg: P2PMsg): void => {\n for (const peer of peers.values()) {\n if (peer.open) sendTo(peer, msg);\n }\n };\n\n const dropPeer = (origin: string): void => {\n const peer = peers.get(origin);\n if (!peer) return;\n peers.delete(origin);\n for (const unsub of peer.unsubs) unsub();\n peer.link.close();\n openPeers.update((set) => {\n const next = new Set(set);\n next.delete(origin);\n return next;\n });\n };\n\n const ensurePeer = (origin: string): Peer => {\n let peer = peers.get(origin);\n if (peer) return peer;\n const link = connector({\n remote: origin,\n polite: sync.origin > origin,\n sendSignal: (data) =>\n transport?.send({ t: 'signal', room: opt.room, to: origin, data }),\n });\n peer = { link, open: false, unsubs: [] };\n peers.set(origin, peer);\n peer.unsubs.push(\n link.channel.onOpen(() => {\n peer!.open = true;\n openPeers.update((set) => new Set(set).add(origin));\n sendTo(peer!, { t: 'hello', wm: sync.watermark() });\n }),\n link.channel.onMessage((frame) => {\n let msg: P2PMsg;\n try {\n msg = JSON.parse(frame) as P2PMsg;\n } catch {\n return;\n }\n handlePeerMsg(peer!, msg);\n }),\n link.channel.onClose(() => dropPeer(origin)),\n );\n return peer;\n };\n\n const handlePeerMsg = (peer: Peer, msg: P2PMsg): void => {\n switch (msg.t) {\n case 'hello': {\n const snap = sync.snapshot();\n if (covered(snap.wm, msg.wm)) sendTo(peer, { t: 'uptodate' });\n else sendTo(peer, { t: 'state', state: snap });\n return;\n }\n case 'state': {\n if (covered(sync.watermark(), msg.state.wm)) {\n sync.hydrate(msg.state as OpSyncCheckpoint<T>);\n }\n return;\n }\n case 'uptodate':\n return;\n case 'env':\n sync.receive(msg.env);\n return;\n }\n };\n\n const handleSignaling = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome':\n for (const origin of msg.members) ensurePeer(origin);\n status.set('live');\n return;\n case 'member':\n if (msg.gone) dropPeer(msg.origin);\n else ensurePeer(msg.origin);\n return;\n case 'signal':\n ensurePeer(msg.from).link.signal(msg.data);\n return;\n case 'reject':\n close();\n return;\n }\n };\n\n const connectSignaling = (): void => {\n if (closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n const t = opt.signaling();\n transport = t;\n signalingUnsubs = [\n t.onMessage(handleSignaling),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n reconnectTimer = setTimeout(connectSignaling, 1000);\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion ?? 0,\n });\n };\n\n const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n unsubLocal();\n for (const origin of [...peers.keys()]) dropPeer(origin);\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport?.close();\n transport = null;\n sync.destroy();\n status.set('connecting');\n };\n\n injector.get(DestroyRef).onDestroy(close);\n connectSignaling();\n\n return {\n status: status.asReadonly(),\n peers: computed(() => [...openPeers()]),\n close,\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;AAsFA;AACA,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC;IACpD,OAAO;IACP,gBAAgB;IAChB,QAAQ;AACT,CAAA,CAAC;AA0FF,MAAM,iBAAiB,GAAG,GAAG;AAC7B,MAAM,kBAAkB,GAAG,GAAG;AAE9B;;;;;;AAMG;AACG,SAAU,QAAQ,CACtB,MAAyB,EACzB,GAAoB,EAAA;IAEpB,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C,EAAE,OAAO;YACV,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,MAAM,EAAE,IAAI,CAAC,MAAM;AACnB,YAAA,KAAK,EAAE,kBAAkB;AACzB,YAAA,aAAa,EAAE,GAAG,CAAC,aAAa,IAAI,CAAC;AACtC,SAAA,CAAC;AACJ,IAAA,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,KAAK,SAAS,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IAExE,MAAM,KAAK,GAAG,MAAW;AACvB,QAAA,IAAI,MAAM;YAAE;QACZ,MAAM,GAAG,IAAI;QACb,IAAI,cAAc,KAAK,SAAS;YAAE,YAAY,CAAC,cAAc,CAAC;AAC9D,QAAA,UAAU,EAAE;QACZ,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;YAAE,QAAQ,CAAC,MAAM,CAAC;QACxD,KAAK,MAAM,KAAK,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;AAAE,YAAA,KAAK,EAAE;QACtD,SAAS,EAAE,KAAK,EAAE;QAClB,SAAS,GAAG,IAAI;QAChB,IAAI,CAAC,OAAO,EAAE;AACd,QAAA,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC;AAC1B,IAAA,CAAC;IAED,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC;AACzC,IAAA,gBAAgB,EAAE;IAElB,OAAO;AACL,QAAA,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE;QAC3B,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,SAAS,EAAE,CAAC,CAAC;QACvC,KAAK;KACN;AACH;;ACjVA;;AAEG;;;;"}
1
+ {"version":3,"file":"mmstack-mesh.mjs","sources":["../../../../../packages/mesh/client/src/lib/session.ts","../../../../../packages/mesh/client/src/lib/agent-seat.ts","../../../../../packages/mesh/client/src/lib/mesh-sync.ts","../../../../../packages/mesh/client/src/lib/transport.ts","../../../../../packages/mesh/client/src/lib/webrtc-mesh.ts","../../../../../packages/mesh/client/src/mmstack-mesh.ts"],"sourcesContent":["import {\n checkEnvelope,\n MESH_PROTO_VERSION,\n type OpPolicy,\n type PolicyViolation,\n type PresenceState,\n type PrincipalCtx,\n type SeqEnvelope,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createConvergingApply,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type StoreOp,\n} from '@mmstack/primitives';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\nexport type MeshStatus =\n 'connecting' | 'live' | 'reconnecting' | 'ejected' | 'closed';\n\n/** One sequenced remote envelope's ops, attributed to the writer that made them. */\nexport type RemoteBatch = {\n /** The relay's total-order stamp for this batch. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Environment callbacks a session shell provides. All are optional except `onStatus`; the\n * session never touches signals, timers beyond `schedule`, storage, or the DOM itself.\n */\nexport type MeshSessionHooks = {\n onStatus(status: MeshStatus, reason?: string): void;\n /** A welcome or envelope arrived — the shell's \"last synced\" moment. */\n onSynced?(): void;\n /** The presence roster changed (welcome replace, join/leave, teardown clear). */\n onPeers?(peers: ReadonlyMap<string, PresenceState>): void;\n /** A remote (non-own) envelope was ingested, in seq order. */\n onRemote?(batch: RemoteBatch): void;\n /**\n * Seq continuity broke: a snapshot welcome (or a relay instance change) established state\n * without delivering the individual envelopes in between. Any consumer deriving from the\n * `onRemote` stream must rebuild from current state at this seq; appending across a resync\n * would silently skip history.\n */\n onResync?(seq: number): void;\n /** The unacknowledged local tail changed (emit or ack) — the durable-outbox trigger. */\n onOutboxChange?(): void;\n /**\n * A local write violated the room policy. The session ejects itself immediately after —\n * the outcome the relay's own independent check would have produced one hop later. The\n * emit-side check spares the room the round trip; it is never the enforcement.\n */\n onLocalReject?(violation: PolicyViolation): void;\n /**\n * Teardown is starting; fired before the unacked tail is dropped, so a shell can persist\n * it (and release any single-writer locks) while it is still intact.\n */\n onTerminal?(state: 'ejected' | 'closed', reason?: string): void;\n};\n\nexport type MeshSessionOptions<T extends object> = {\n readonly room: string;\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** The op engine this session feeds. The shell creates (and destroys) it. */\n readonly sync: OpSync<T>;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policy?: OpPolicy;\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion: number;\n readonly schemaVersion?: number;\n readonly reconnect?: { readonly maxDelayMs?: number };\n /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */\n readonly schedule?: {\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n };\n readonly hooks: MeshSessionHooks;\n};\n\n/**\n * The relay-room session protocol, shell-agnostic: hello/welcome handshakes (snapshot\n * hydrate, delta replay, fresh-room seed), own-echo acknowledgement, unacked resend,\n * reconnect backoff, presence, eject/reject and frontier compaction. `meshSync` wraps it for\n * Angular; `agentSeat` wraps it for injector-free environments. One implementation of the\n * wire contract — shells differ only in environment concerns.\n */\nexport type MeshSession = {\n /** Open the first connection. Call once, after any outbox restore has replayed. */\n connect(): void;\n status(): MeshStatus;\n /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */\n lastSeq(): number;\n hasUnacked(): boolean;\n /** The unacknowledged local tail (the durable-outbox payload). */\n unackedEnvs(): readonly OpEnvelope[];\n peers(): ReadonlyMap<string, PresenceState>;\n setPresence(data: unknown): void;\n close(): void;\n};\n\nconst RECONNECT_BASE_MS = 500;\n\nexport function meshSession<T extends object>(\n opt: MeshSessionOptions<T>,\n): MeshSession {\n const { sync, hooks } = opt;\n const schedule = opt.schedule ?? {\n set: (fn: () => void, ms: number) => setTimeout(fn, ms),\n clear: (handle: unknown) =>\n clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n\n let status: MeshStatus = 'connecting';\n const ownOrigins = new Set<string>([sync.origin]);\n const unacked = new Map<string, OpEnvelope>();\n const acked = new Map<string, number>();\n const unackedKey = (env: { origin: string; version: number }): string =>\n `${env.origin} ${env.version}`;\n let lastSeq = 0;\n let instance: string | undefined;\n let peers: ReadonlyMap<string, PresenceState> = new Map();\n let presenceData: unknown;\n let hasPresence = false;\n let transport: MeshTransport | null = null;\n let attempts = 0;\n let reconnectTimer: unknown;\n let unsubs: (() => void)[] = [];\n let closed = false;\n\n const setStatus = (next: MeshStatus, reason?: string): void => {\n status = next;\n hooks.onStatus(next, reason);\n };\n\n const terminal = (state: 'ejected' | 'closed', reason?: string): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) {\n schedule.clear(reconnectTimer);\n reconnectTimer = undefined;\n }\n for (const unsub of unsubs.splice(0)) unsub();\n unsubLocal();\n hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window\n unacked.clear();\n transport?.close();\n transport = null;\n peers = new Map();\n hooks.onPeers?.(peers);\n setStatus(state, reason);\n };\n\n const sendEnv = (env: OpEnvelope): void => {\n transport?.send({ t: 'env', room: opt.room, env });\n };\n\n const flushUnacked = (): void => {\n for (const env of unacked.values()) sendEnv(env);\n };\n\n const applyRemote = (env: SeqEnvelope): void => {\n if (closed) return; // a delta welcome keeps iterating after an eject — nothing lands past it\n\n if (\n opt.schemaVersion !== undefined &&\n env.schemaVersion !== undefined &&\n env.schemaVersion > opt.schemaVersion\n ) {\n terminal('ejected', 'schema');\n return;\n }\n lastSeq = Math.max(lastSeq, env.seq);\n hooks.onSynced?.();\n if (ownOrigins.has(env.origin)) {\n unacked.delete(unackedKey(env));\n acked.set(env.origin, Math.max(acked.get(env.origin) ?? 0, env.version));\n hooks.onOutboxChange?.();\n return;\n }\n sync.receive(env);\n hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });\n };\n\n const handle = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome': {\n const instanceChanged =\n instance !== undefined && msg.instance !== instance;\n\n const prevSeq = lastSeq;\n if (instanceChanged) lastSeq = 0;\n instance = msg.instance;\n peers = new Map(msg.peers.map((p) => [p.origin, p]));\n hooks.onPeers?.(peers);\n const resync = msg.mode === 'snapshot' || instanceChanged;\n if (msg.mode === 'delta') {\n for (const env of msg.envs) applyRemote(env);\n } else if (msg.mode === 'snapshot') {\n const conv = createConvergingApply({ policies: opt.policies });\n conv.load(msg.registers);\n const ownWm: Record<string, number> = {};\n for (const o of ownOrigins) ownWm[o] = acked.get(o) ?? 0;\n sync.hydrate(\n {\n root: conv.materialize() as T,\n registers: msg.registers,\n wm: { ...msg.wm, ...ownWm },\n },\n [...unacked.values()],\n );\n lastSeq = msg.seq;\n } else if (msg.seq === 0 && lastSeq === 0) {\n sync.seed();\n }\n // every branch can end terminal (schema eject in a delta env, a seed or rebase\n // emission tripping the emit-side policy) — never revive to live\n if (closed) {\n if (instanceChanged && lastSeq === 0) lastSeq = prevSeq;\n return;\n }\n lastSeq = Math.max(lastSeq, msg.seq);\n attempts = 0;\n hooks.onSynced?.();\n if (resync) hooks.onResync?.(lastSeq);\n setStatus('live');\n flushUnacked();\n if (hasPresence)\n transport?.send({\n t: 'presence',\n room: opt.room,\n data: presenceData,\n });\n return;\n }\n case 'env':\n applyRemote(msg.env);\n return;\n case 'presence': {\n const next = new Map(peers);\n if (msg.gone) next.delete(msg.peer.origin);\n else next.set(msg.peer.origin, msg.peer);\n peers = next;\n hooks.onPeers?.(peers);\n return;\n }\n case 'eject':\n if (msg.writer === opt.writer) terminal('ejected', msg.reason);\n return;\n case 'reject':\n terminal('ejected', msg.reason);\n return;\n case 'frontier':\n sync.prune(msg.frontier);\n return;\n }\n };\n\n const connect = (): void => {\n if (closed) return;\n for (const unsub of unsubs.splice(0)) unsub();\n const t = opt.transport();\n transport = t;\n unsubs = [\n t.onMessage(handle),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n setStatus('reconnecting');\n const delay = Math.min(\n opt.reconnect?.maxDelayMs ?? 15_000,\n RECONNECT_BASE_MS * 2 ** attempts++,\n );\n reconnectTimer = schedule.set(\n () => {\n reconnectTimer = undefined;\n connect();\n },\n delay + Math.random() * 100,\n );\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion,\n seq: lastSeq > 0 ? lastSeq : undefined,\n schemaVersion: opt.schemaVersion,\n });\n };\n\n const unsubLocal = sync.subscribe((env) => {\n const violation = checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n );\n if (violation) {\n // same outcome the relay's own check would produce one hop later — the emit-side\n // check is an optimization, never the enforcement\n hooks.onLocalReject?.(violation);\n terminal('ejected', violation.reason);\n return;\n }\n ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim\n unacked.set(unackedKey(env), env);\n hooks.onOutboxChange?.();\n if (status === 'live') sendEnv(env);\n });\n\n return {\n connect,\n status: () => status,\n lastSeq: () => lastSeq,\n hasUnacked: () => unacked.size > 0,\n unackedEnvs: () => [...unacked.values()],\n peers: () => peers,\n setPresence: (data) => {\n presenceData = data;\n hasPresence = true;\n if (status === 'live') {\n transport?.send({ t: 'presence', room: opt.room, data });\n }\n },\n close: () => terminal('closed'),\n };\n}\n","import { createWatch } from '@angular/core/primitives/signals';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n createStoreContext,\n forkStore,\n opSync,\n store,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpLogDriver,\n type OpSync,\n type StoreOp,\n type SyncedFork,\n type toStoreOptions,\n type WritableSignalStore,\n} from '@mmstack/primitives';\nimport { meshSession, type MeshStatus } from './session';\nimport type { MeshTransportFactory } from './transport';\n\nconst microtaskDriver = (): OpLogDriver => (run) => {\n let scheduled = false;\n const watch = createWatch(\n () => run(),\n (w) => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n w.run();\n });\n },\n false,\n );\n watch.notify();\n return { destroy: () => watch.destroy() };\n};\n\n/** A sequenced batch of another writer's ops, delivered in relay order. */\nexport type SeatChange = {\n readonly kind: 'change';\n /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past\n * the relay's retention, or a relay restart) without seeing the individual changes in\n * between. Anything accumulated from prior `change` events — narration buffers, cached\n * prompt prefixes — no longer extends the stream and must be rebuilt from current state.\n */\nexport type SeatResync = {\n readonly kind: 'resync';\n /** The seq the re-established state corresponds to. */\n readonly seq: number;\n};\n\nexport type SeatEvent = SeatChange | SeatResync;\n\n/** A base state provably derivable from the room's history alone — safe to cache. */\nexport type StableSnapshot<T> = {\n /** The relay seq this state is the fold of. */\n readonly seq: number;\n readonly doc: T;\n};\n\nexport type AgentSeatOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. One identity per seat. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * Emit-side validation, symmetric with the relay's — an optimization, not the\n * enforcement (the relay validates every envelope regardless). A violating write is\n * never sent and ejects the seat exactly as the relay would have; the refused value\n * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.\n */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion?: number;\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;\n * pass your own to share proxy caches across several seats in one process.\n */\n readonly context?: toStoreOptions;\n readonly onEject?: (reason: string) => void;\n};\n\nexport type AgentSeat<T extends object> = {\n /** The live converging replica. Reads exactly like a local signal store. */\n readonly doc: WritableSignalStore<T & Record<string, any>>;\n status(): MeshStatus;\n peers(): readonly PresenceState[];\n /** The current document value — plain JSON-serializable data, for context assembly. */\n snapshot(): T;\n /**\n * The current document, stamped with the relay seq it is provably the pure fold of\n * or null when stability cannot be guaranteed\n */\n stableSnapshot(): StableSnapshot<T> | null;\n /** Run local writes and emit them to the room as one envelope, like any peer's edit. */\n write(fn: () => void): void;\n /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */\n setAtPath(path: string | readonly (string | number)[], value: unknown): void;\n /**\n * The room's sequenced history as it arrives: `change` events carry another writer's ops\n * in strictly increasing seq order, so a listener may append them (narration, prompt\n * suffixes) without any diffing. A `resync` event voids that guarantee — everything\n * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).\n * Own writes never echo here.\n */\n changes(cb: (event: SeatEvent) => void): () => void;\n /**\n * An isolated branch for a reviewable proposal. The fork observes the room as it is now;\n * `commit()` emits its diff citing only those observed writes, so a room edit that lands\n * while the fork is open survives as a concurrent value for the merge policy to resolve\n * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the\n * staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */\n setPresence(data: unknown): void;\n close(): void;\n};\n\n/**\n * A headless mesh peer: the same replica and wire contract `meshSync` implements in the\n * browser, without Angular's injector or any browser API — for agents, server-side bridges,\n * and device writers joining a room as first-class, attributed participants. Each call is\n * one identity with its own replica; run several seats in one process for several\n * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as\n * to any human peer.\n */\nexport function agentSeat<T extends object>(\n initial: T,\n opt: AgentSeatOptions,\n): AgentSeat<T> {\n const context = opt.context ?? createStoreContext();\n const root = store(initial as T & Record<string, any>, context);\n const doc = root as unknown as WritableSignalStore<T & Record<string, any>>;\n const read = root as unknown as () => T;\n const policyVersion = opt.policyVersion ?? 0;\n\n // onReject fires synchronously inside receive(); the flag keeps a malformed envelope's\n // ops (which did NOT apply) out of the change stream.\n let rejected = false;\n const sync = opSync(root as never, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n driver: microtaskDriver(),\n onReject: (_env, reason) => {\n rejected = true;\n console.warn(\n `[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`,\n );\n },\n }) as OpSync<T>;\n\n const listeners = new Set<(event: SeatEvent) => void>();\n const emit = (event: SeatEvent): void => {\n for (const cb of [...listeners]) cb(event);\n };\n let welcomed = false;\n let diverged = false;\n let terminated = false;\n\n const session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n hooks: {\n onStatus: (s, reason) => {\n if (s === 'live') welcomed = true;\n if (s === 'ejected' && reason !== undefined) opt.onEject?.(reason);\n },\n onRemote: (batch) => {\n if (rejected) {\n rejected = false;\n return;\n }\n emit({ kind: 'change', ...batch });\n },\n onResync: (seq) => emit({ kind: 'resync', seq }),\n onLocalReject: (violation) => {\n diverged = true; // the write stays in the replica but will never reach the room\n console.warn(\n '[@mmstack/mesh] agent seat write violates the room policy — not sent',\n violation,\n );\n },\n onTerminal: () => {\n if (session.hasUnacked()) diverged = true;\n terminated = true;\n },\n },\n });\n // a write after the terminal state is one the room will never sequence: the doc keeps it\n // (post-mortem), but the seat stops claiming provable folds — same latch as a refused write\n sync.subscribe(() => {\n if (terminated) diverged = true;\n });\n session.connect();\n\n return {\n doc,\n status: () => session.status(),\n peers: () => [...session.peers().values()],\n snapshot: () => read(),\n stableSnapshot: () => {\n sync.flush(); // a write made this tick must count as pending, not linger unstamped\n if (!welcomed || diverged || session.hasUnacked()) return null;\n return { seq: session.lastSeq(), doc: read() };\n },\n write: (fn) => {\n fn();\n sync.flush();\n },\n setAtPath: (path, value) => {\n setAtPath(doc, path, value);\n sync.flush();\n },\n changes: (cb) => {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(doc, forkOpt);\n let frontier: DotFrontier = sync.captureFrontier();\n const recapture = (): void => {\n frontier = sync.captureFrontier();\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () => {\n sync.commitScope(frontier, () => f.commit());\n sync.flush();\n },\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n setPresence: (data) => session.setPresence(data),\n close: () => {\n diverged = true; // sync is destroyed below: later writes are unwatched, so no more proofs\n session.close();\n sync.destroy();\n },\n };\n}\n\ntype PathSegment = string | number;\n\nconst parsePath = (\n path: string | readonly PathSegment[],\n): readonly PathSegment[] =>\n typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;\n\n// resolve a string segment against an array ('0' → 0) so dot-paths address list items\nconst resolveKey = (current: unknown, seg: PathSegment): PathSegment =>\n Array.isArray(current) && typeof seg === 'string' && /^\\d+$/.test(seg)\n ? Number(seg)\n : seg;\n\nfunction withPathSet(\n current: unknown,\n path: readonly PathSegment[],\n value: unknown,\n): unknown {\n if (path.length === 0) return value;\n const [head, ...rest] = path;\n if (Array.isArray(current)) {\n const idx = typeof head === 'number' ? head : Number(head);\n const copy = [...current];\n copy[idx] = withPathSet(current[idx], rest, value);\n return copy;\n }\n const base =\n current !== null && typeof current === 'object'\n ? (current as Record<PathSegment, unknown>)\n : {};\n return { ...base, [head]: withPathSet(base[head], rest, value) };\n}\n\n/**\n * Applies `value` at a path on a signal-store node — the write shape a tool-calling model\n * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as\n * the path exists in the current value and finishes with one immutable set on the deepest\n * real node, which also covers paths that do not exist yet (a fresh record key creates it).\n * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer\n * `seat.setAtPath`, which also emits immediately.\n */\nexport function setAtPath(\n node: unknown,\n path: string | readonly PathSegment[],\n value: unknown,\n): void {\n const segs = parsePath(path);\n let cursor = node as Record<PathSegment, unknown> & {\n (): unknown;\n set(v: unknown): void;\n };\n let walked = 0;\n for (const seg of segs) {\n const current = cursor();\n if (current === null || typeof current !== 'object') break;\n const key = resolveKey(current, seg);\n if (!Object.hasOwn(current, key)) break;\n const child = cursor[key];\n if (typeof child !== 'function') break;\n cursor = child as typeof cursor;\n walked++;\n }\n const rest = segs.slice(walked);\n if (rest.length === 0) {\n cursor.set(value);\n return;\n }\n cursor.set(withPathSet(cursor(), rest, value));\n}\n\nconst MAX_VALUE_CHARS = 120;\n\nconst printable = (value: unknown): string => {\n const json = JSON.stringify(value);\n if (json === undefined) return String(value);\n return json.length > MAX_VALUE_CHARS\n ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`\n : json;\n};\n\n/**\n * One store op as a plain-English line (\"mira set plan.endDate to \\\"2026-10-11\\\"\"), for\n * activity feeds and model context. Values render as truncated JSON. Pair with a seat's\n * `changes` stream: narrating each batch's ops yields an append-only account of the room.\n */\nexport function describeOp(op: StoreOp, writer: string): string {\n const at = op.path.length === 0 ? 'the document root' : op.path.join('.');\n switch (op.kind) {\n case 'set':\n return `${writer} set ${at} to ${printable(op.next)}`;\n case 'delete':\n return `${writer} removed ${at}`;\n case 'clear':\n return `${writer} cleared ${at}`;\n }\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n runInInjectionContext,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n forkStore,\n OP_PROTO_VERSION,\n opSync,\n registerResource,\n type AsyncStore,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type ResourceLike,\n type SyncedFork,\n type SyncOp,\n type WritableSignalStore,\n} from '@mmstack/primitives';\nimport { meshSession, type MeshSession, type MeshStatus } from './session';\nimport type { MeshTransportFactory } from './transport';\n\nexport type { MeshStatus } from './session';\n\nexport type MeshPeer = PresenceState;\n\n/**\n * A composed, user-facing health status for a synced store the surface that\n * turns a versioned reject from a dead socket into a speakable 'outdated' banner.\n */\nexport type SyncHealthStatus =\n | 'live'\n | 'offline'\n | 'outdated'\n | 'ejected'\n | 'degraded';\n\nexport type SyncHealth = {\n readonly status: SyncHealthStatus;\n /** Why, when the status is `outdated`/`ejected`/`degraded`. */\n readonly reason?:\n | 'proto'\n | 'policy-version'\n | 'schema'\n | 'quota'\n | 'worker'\n | (string & {});\n /** `Date.now()` of the last successful sync (welcome or applied env). */\n readonly lastSyncedAt?: number;\n /**\n * Offline writes persisted by an older build that could not be restored on boot. Envelopes\n * from a previous wire-protocol version lack the citation metadata current merging needs,\n * so they are dropped (loudly) instead of being upgraded with fabricated citations.\n */\n readonly droppedOfflineWrites?: number;\n /**\n * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id\n * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a\n * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line\n * against a malformed neighbor; through a relay these are also rejected at the relay.\n */\n readonly droppedInvalidEnvelopes?: number;\n};\n\n// a versioned reject means \"your build is behind\" → prompt an update, not a dead socket\nconst OUTDATED_REASONS: ReadonlySet<string> = new Set([\n 'proto',\n 'policy-version',\n 'schema',\n]);\n\nexport type MeshSyncOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /** Emit-side validation, symmetric with the relay's (tripwire honesty). */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n /**\n * The room's shared configuration pin, checked at hello against the relay's. Bump it\n * together whenever anything peers must agree on changes: the write policy, and just as\n * importantly the merge/fold configuration (`policies`). Peers folding the same register\n * state with different rules read different values, so one room means one fold config; a\n * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.\n */\n readonly policyVersion?: number;\n /** The data shape this client speaks. Older-than-room → `outdated`, and a\n * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n readonly injector?: Injector;\n /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */\n readonly register?: 'track' | 'suspend';\n readonly onEject?: (reason: string) => void;\n /**\n * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects\n * (and before it restores an `outbox`), so a store hydrated from another source first (a worker\n * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.\n * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base\n * that fails to load never wedges the connection.\n */\n readonly whenReady?: () => PromiseLike<void> | void;\n /**\n * Persist the unacknowledged local outbox (and this client's stable origin) so offline writes\n * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room\n * on the next welcome, instead of being lost with in-memory state. The payload is written to\n * `store` under `key`, debounced.\n *\n * By default (`crossTab: 'queue'`) a Web Lock on `key` makes this a single-writer-per-key resource:\n * a second tab sharing the key WAITS (stays `connecting`, surfaced via `status`/`health`) until the\n * first releases, rather than restoring the same origin and colliding on version mints. Set\n * `crossTab: 'off'` to skip the lock and coordinate ownership yourself (e.g. a per-tab key, or\n * leader election over `tabSync`). A debounced write means a hard crash within the debounce window\n * can drop the very last mint — a small, best-effort gap; tune it with `debounceMs`.\n */\n readonly outbox?: {\n readonly key: string;\n readonly store: AsyncStore;\n /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */\n readonly debounceMs?: number;\n /**\n * Cross-tab contention for the shared `key`. `'queue'` (default) holds a Web Lock so only one tab\n * owns the durable outbox at a time; others wait. `'off'` skips the lock (you coordinate).\n * (A future `'ephemeral'` — non-leaders run live with a throwaway origin — is planned.)\n */\n readonly crossTab?: 'queue' | 'off';\n };\n};\n\n/** The shape persisted under `outbox.key`: the stable origin, the emit high-water, and the tail. */\ntype PersistedOutbox = {\n readonly origin: string;\n readonly version: number;\n readonly envs: readonly OpEnvelope[];\n};\n\nexport type MeshSyncRef<T extends object = Record<string, unknown>> = {\n readonly status: Signal<MeshStatus>;\n /** Composed sync-health for a user-facing surface. */\n readonly health: Signal<SyncHealth>;\n readonly peers: Signal<readonly MeshPeer[]>;\n /** Publish this client's ephemeral presence payload (cursor, section, activity…). */\n setPresence(data: unknown): void;\n /**\n * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The\n * fork observes the room as it is now; committing emits its diff citing only those observed\n * writes, so an edit that lands on the room while the fork is open stays a concurrent value the\n * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe\n * the room and commit on top of the latest instead. `discard()` drops the staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n close(): void;\n};\n\nconst OUTBOX_DEBOUNCE_MS = 300;\n\n/**\n * Replicates a signal store across clients through a relay room: local writes emit stamped\n * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot\n * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.\n * A synced store reads exactly like a local one — connection state surfaces only through\n * `status` and the transition scope.\n */\nexport function meshSync<T extends object>(\n source: WritableSignal<T>,\n opt: MeshSyncOptions,\n): MeshSyncRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const status = signal<MeshStatus>('connecting');\n const lastReason = signal<string | undefined>(undefined);\n const lastSyncedAt = signal<number | undefined>(undefined);\n const droppedOffline = signal(0);\n const droppedInvalid = signal(0);\n const peerMap = signal<ReadonlyMap<string, MeshPeer>>(new Map());\n const peers = computed(() => [...peerMap().values()]);\n const policyVersion = opt.policyVersion ?? 0;\n\n const health = computed<SyncHealth>(() => {\n const at = lastSyncedAt();\n const dropped = droppedOffline();\n const invalid = droppedInvalid();\n const extra = {\n ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),\n ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),\n };\n switch (status()) {\n case 'live':\n return { status: 'live', lastSyncedAt: at, ...extra };\n case 'ejected': {\n const reason = lastReason();\n return reason && OUTDATED_REASONS.has(reason)\n ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }\n : { status: 'ejected', reason, lastSyncedAt: at, ...extra };\n }\n default: // connecting / reconnecting / closed — not reachable\n return { status: 'offline', lastSyncedAt: at, ...extra };\n }\n });\n\n // Created lazily: with a persisted outbox we must adopt the stored origin BEFORE minting anything\n let sync!: OpSync<T>;\n let session: MeshSession | undefined;\n let started = false;\n let closed = false;\n let pendingPresence: { data: unknown } | undefined;\n let persistTimer: ReturnType<typeof setTimeout> | undefined;\n let releaseLock: (() => void) | undefined;\n let cancelLock: (() => void) | undefined;\n\n const doPersist = (): void => {\n if (closed || !opt.outbox || !started || !session) return;\n const payload: PersistedOutbox = {\n origin: sync.origin,\n version: sync.watermark()[sync.origin] ?? 0,\n envs: session.unackedEnvs(),\n };\n void Promise.resolve(opt.outbox.store.set(opt.outbox.key, payload));\n };\n // coalesce outbox writes; `immediate` forces a synchronous-path write (first boot, teardown)\n const persistOutbox = (immediate = false): void => {\n if (!opt.outbox) return;\n if (immediate) {\n if (persistTimer !== undefined) clearTimeout(persistTimer);\n persistTimer = undefined;\n doPersist();\n return;\n }\n if (persistTimer !== undefined) return;\n persistTimer = setTimeout(() => {\n persistTimer = undefined;\n doPersist();\n }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);\n };\n\n const dropLocks = (): void => {\n cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown\n releaseLock?.(); // free a held lock for the next waiting tab\n cancelLock = releaseLock = undefined;\n };\n\n // Only a tail this boot could actually get admitted is worth resending: recorded under\n // this writer, on the current proto and policyVersion pins (the relay rejects a stale pin\n // per envelope, so restoring one would eject the boot, persist the tail intact, and brick\n // every boot after). Anything else drops loudly instead.\n const restorable = (env: OpEnvelope): boolean =>\n env.proto === OP_PROTO_VERSION &&\n env.writer === opt.writer &&\n env.policyVersion === policyVersion &&\n env.ops.every(\n (op) =>\n Array.isArray((op as SyncOp).cites) &&\n typeof (op as SyncOp).epoch === 'number',\n );\n\n const initCore = (restore?: PersistedOutbox): void => {\n if (closed) return;\n sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n injector,\n onReject: (_env, reason) => {\n droppedInvalid.update((n) => n + 1);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`,\n );\n }\n },\n });\n started = true;\n session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n hooks: {\n onStatus: (s, reason) => {\n if (s === 'ejected' || s === 'closed') {\n closed = true;\n lastReason.set(reason);\n }\n status.set(s);\n if ((s === 'ejected' || s === 'closed') && reason !== undefined) {\n opt.onEject?.(reason);\n }\n },\n onSynced: () => lastSyncedAt.set(Date.now()),\n onPeers: (map) => peerMap.set(map),\n onOutboxChange: () => persistOutbox(),\n onTerminal: () => {\n dropLocks();\n persistOutbox(true); // save the still-unacked tail for the next boot before dropping it\n },\n onLocalReject: (violation) => {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] local write violates the room policy — not sent',\n violation,\n );\n }\n },\n },\n });\n if (restore && (restore.envs.length > 0 || restore.version > 0)) {\n const kept = restore.envs.filter(restorable);\n const dropped = restore.envs.length - kept.length;\n if (dropped > 0) {\n droppedOffline.set(dropped);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`,\n );\n }\n }\n\n sync.restore(kept, restore.version); // → the session's subscribe repopulates its unacked tail for resend\n }\n persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe\n if (pendingPresence) {\n session.setPresence(pendingPresence.data);\n pendingPresence = undefined;\n }\n session.connect();\n };\n\n if (opt.register) {\n const connection: ResourceLike = {\n status: computed(() => {\n const s = status();\n return s === 'connecting'\n ? 'loading'\n : s === 'reconnecting'\n ? 'reloading'\n : s === 'ejected'\n ? 'error'\n : 'resolved';\n }),\n isLoading: computed(\n () => status() === 'connecting' || status() === 'reconnecting',\n ),\n hasValue: () => true,\n };\n runInInjectionContext(injector, () =>\n registerResource(connection, { suspends: opt.register === 'suspend' }),\n );\n }\n\n const teardown = (): void => {\n if (session) {\n session.close(); // no-op if already terminal; onTerminal handled locks + persist\n } else if (!closed) {\n // closed before the (async) boot ever created the session\n closed = true;\n dropLocks();\n status.set('closed');\n }\n if (started) sync.destroy();\n };\n\n injector.get(DestroyRef).onDestroy(teardown);\n\n // Load the persisted outbox, then boot with the adopted origin. A fresh/unreadable slot boots clean.\n const bootFromDisk = async (): Promise<void> => {\n if (closed || !opt.outbox) return;\n let saved: PersistedOutbox | undefined;\n try {\n const raw = await opt.outbox.store.get(opt.outbox.key);\n saved =\n raw && typeof raw === 'object' && 'origin' in raw\n ? (raw as PersistedOutbox)\n : undefined;\n } catch {\n saved = undefined; // an unreadable slot must not wedge the boot\n }\n initCore(saved);\n };\n\n const beginConnect = (): void => {\n if (closed) return;\n if (!opt.outbox) {\n initCore();\n } else if ((opt.outbox.crossTab ?? 'queue') === 'off') {\n void bootFromDisk(); // no single-writer lock — the app coordinates ownership\n } else {\n const locks = globalThis.navigator?.locks;\n if (!locks) {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] outbox crossTab:\"queue\" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock. Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:\"off\" to silence this.',\n );\n }\n void bootFromDisk();\n } else {\n const abort = new AbortController();\n cancelLock = () => abort.abort();\n void locks\n .request(\n `@mmstack/mesh:outbox:${opt.outbox.key}`,\n { mode: 'exclusive', signal: abort.signal },\n () => {\n cancelLock = undefined; // granted — no longer abortable, only releasable\n if (closed) return Promise.resolve();\n // hold the lock until teardown resolves this promise\n return new Promise<void>((release) => {\n releaseLock = release;\n void bootFromDisk();\n });\n },\n )\n .catch((e: unknown) => {\n // an aborted request is our own teardown; any other failure → degrade to no-lock\n if (!closed && (e as { name?: string })?.name !== 'AbortError') {\n void bootFromDisk();\n }\n });\n }\n }\n };\n\n if (opt.whenReady) {\n void Promise.resolve()\n .then(() => opt.whenReady?.())\n .then(\n () => beginConnect(),\n () => beginConnect(),\n );\n } else {\n beginConnect();\n }\n\n return {\n status: status.asReadonly(),\n health,\n peers,\n setPresence: (data) => {\n if (session) session.setPresence(data);\n else pendingPresence = { data };\n },\n fork: (forkOpt) => {\n const f = forkStore(\n source as unknown as WritableSignalStore<T & Record<string, any>>,\n forkOpt,\n );\n\n let frontier: DotFrontier = started ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = started ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () =>\n started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n close: teardown,\n };\n}\n","import { isDevMode } from '@angular/core';\nimport type {\n ClientMsg,\n PrincipalCtx,\n Relay,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\n\n/**\n * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport\n * represents a single connection and never reconnects itself.\n */\nexport type MeshTransport = {\n send(msg: ClientMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\nexport type MeshTransportFactory = () => MeshTransport;\n\n/**\n * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and\n * flushed on open; malformed inbound frames are dropped.\n */\nexport function webSocketTransport(\n url: string,\n protocols?: string | string[],\n): MeshTransportFactory {\n return () => {\n const ws = new WebSocket(url, protocols);\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n\n ws.onopen = () => {\n for (const frame of pending.splice(0)) ws.send(frame);\n };\n ws.onmessage = (event) => {\n let msg: ServerMsg;\n try {\n msg = JSON.parse(String(event.data)) as ServerMsg;\n } catch {\n if (isDevMode()) {\n console.warn('[@mmstack/mesh] dropped unparseable frame (expected JSON text)');\n }\n return;\n }\n for (const cb of [...messageCbs]) cb(msg);\n };\n ws.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n\n return {\n send: (msg) => {\n const frame = JSON.stringify(msg);\n if (ws.readyState === WebSocket.OPEN) ws.send(frame);\n else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => ws.close(),\n };\n };\n}\n\n/**\n * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop\n * tests, and handy for single-process demos or an SSR-side room.\n */\nexport function directTransport(\n relay: Relay,\n ctx: PrincipalCtx,\n): MeshTransportFactory {\n return () => {\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<() => void>();\n let open = true;\n\n const connection = relay.connect(\n {\n send: (msg) => {\n if (!open) return;\n for (const cb of [...messageCbs]) cb(msg);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n },\n ctx,\n );\n\n return {\n send: (msg) => {\n if (open) connection.receive(msg);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb();\n },\n };\n };\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport { MESH_PROTO_VERSION, type ServerMsg } from '@mmstack/mesh-protocol';\nimport {\n opSync,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSyncCheckpoint,\n} from '@mmstack/primitives';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\n/** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */\nexport type DataChannelLike = {\n send(frame: string): void;\n onMessage(cb: (frame: string) => void): () => void;\n onOpen(cb: () => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\n/**\n * Creates one peer link. `polite` assigns the perfect-negotiation role (derived\n * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads\n * through the relay; `signal` delivers the remote side's payloads.\n */\nexport type PeerConnector = (opt: {\n readonly remote: string;\n readonly polite: boolean;\n readonly sendSignal: (data: unknown) => void;\n}) => {\n readonly channel: DataChannelLike;\n signal(data: unknown): void;\n close(): void;\n};\n\n/** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */\nexport function rtcPeerConnector(config?: RTCConfiguration): PeerConnector {\n return ({ polite, sendSignal }) => {\n const pc = new RTCPeerConnection(config);\n const messageCbs = new Set<(frame: string) => void>();\n const openCbs = new Set<() => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n let dc: RTCDataChannel | null = null;\n let makingOffer = false;\n let ignoreOffer = false;\n\n const attach = (channel: RTCDataChannel): void => {\n dc = channel;\n channel.onmessage = (e) => {\n for (const cb of [...messageCbs]) cb(String(e.data));\n };\n channel.onopen = () => {\n for (const frame of pending.splice(0)) channel.send(frame);\n for (const cb of [...openCbs]) cb();\n };\n channel.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n };\n\n if (!polite) attach(pc.createDataChannel('mmstack-mesh'));\n else pc.ondatachannel = (e) => attach(e.channel);\n\n pc.onicecandidate = (e) => {\n if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });\n };\n pc.onnegotiationneeded = async () => {\n try {\n makingOffer = true;\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n } finally {\n makingOffer = false;\n }\n };\n\n return {\n channel: {\n send: (frame) => {\n if (dc && dc.readyState === 'open') dc.send(frame);\n else pending.push(frame);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n close: () => dc?.close(),\n },\n signal: async (data) => {\n const { description, ice } = (data ?? {}) as {\n description?: RTCSessionDescriptionInit;\n ice?: RTCIceCandidateInit;\n };\n if (description) {\n const collision =\n description.type === 'offer' &&\n (makingOffer || pc.signalingState !== 'stable');\n ignoreOffer = !polite && collision;\n if (ignoreOffer) return;\n await pc.setRemoteDescription(description);\n if (description.type === 'offer') {\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n }\n } else if (ice) {\n try {\n await pc.addIceCandidate(ice);\n } catch (err) {\n if (!ignoreOffer) throw err;\n }\n }\n },\n close: () => {\n dc?.close();\n pc.close();\n },\n };\n };\n}\n\ntype P2PMsg =\n | { t: 'hello'; wm: Record<string, number> }\n // the full checkpoint (root + register state + watermark), NOT a bare value: the covered\n // side must inherit supersession state or already-superseded stragglers would resurrect\n | { t: 'state'; state: OpSyncCheckpoint<object> }\n | { t: 'uptodate' }\n | { t: 'env'; env: OpEnvelope };\n\nexport type WebRtcMeshOptions = {\n readonly room: string;\n readonly writer: string;\n /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */\n readonly signaling: MeshTransportFactory;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policyVersion?: number;\n readonly injector?: Injector;\n};\n\nexport type WebRtcMeshRef = {\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins with an OPEN data channel. */\n readonly peers: Signal<readonly string[]>;\n close(): void;\n};\n\ntype Peer = {\n link: ReturnType<PeerConnector>;\n open: boolean;\n unsubs: (() => void)[];\n};\n\n/**\n * Peer-to-peer mesh sync: the relay only signals\n * and tracks membership; envelopes flow over WebRTC data channels and converge via the\n * per-path register map. Catch-up is pairwise: on channel open both sides exchange\n * watermarks; a side whose state is strictly covered hydrates from the other's FULL\n * checkpoint (root + per-path register state + watermark), so supersession and precedence\n * carry over intact: a late joiner is indistinguishable from a peer that saw every\n * envelope. Two peers that each hold envelopes the other lacks keep their convergent\n * go-forward guarantees but do not exchange the missed envelopes retroactively.\n */\nexport function webRtcMesh<T extends object>(\n source: WritableSignal<T>,\n opt: WebRtcMeshOptions,\n): WebRtcMeshRef {\n const injector = opt.injector ?? inject(Injector);\n const connector = opt.connector ?? rtcPeerConnector();\n const status = signal<'connecting' | 'live'>('connecting');\n const openPeers = signal<ReadonlySet<string>>(new Set());\n const peers = new Map<string, Peer>();\n let signalingUnsubs: (() => void)[] = [];\n let transport: MeshTransport | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n\n const sync = opSync(source, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion: opt.policyVersion,\n injector,\n });\n\n const covered = (\n mine: Record<string, number>,\n theirs: Record<string, number>,\n ): boolean => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);\n\n const sendTo = (peer: Peer, msg: P2PMsg): void => {\n peer.link.channel.send(JSON.stringify(msg));\n };\n\n const broadcast = (msg: P2PMsg): void => {\n for (const peer of peers.values()) {\n if (peer.open) sendTo(peer, msg);\n }\n };\n\n const dropPeer = (origin: string): void => {\n const peer = peers.get(origin);\n if (!peer) return;\n peers.delete(origin);\n for (const unsub of peer.unsubs) unsub();\n peer.link.close();\n openPeers.update((set) => {\n const next = new Set(set);\n next.delete(origin);\n return next;\n });\n };\n\n const ensurePeer = (origin: string): Peer => {\n let peer = peers.get(origin);\n if (peer) return peer;\n const link = connector({\n remote: origin,\n polite: sync.origin > origin,\n sendSignal: (data) =>\n transport?.send({ t: 'signal', room: opt.room, to: origin, data }),\n });\n peer = { link, open: false, unsubs: [] };\n peers.set(origin, peer);\n peer.unsubs.push(\n link.channel.onOpen(() => {\n peer!.open = true;\n openPeers.update((set) => new Set(set).add(origin));\n sendTo(peer!, { t: 'hello', wm: sync.watermark() });\n }),\n link.channel.onMessage((frame) => {\n let msg: P2PMsg;\n try {\n msg = JSON.parse(frame) as P2PMsg;\n } catch {\n return;\n }\n handlePeerMsg(peer!, msg);\n }),\n link.channel.onClose(() => dropPeer(origin)),\n );\n return peer;\n };\n\n const handlePeerMsg = (peer: Peer, msg: P2PMsg): void => {\n switch (msg.t) {\n case 'hello': {\n const snap = sync.snapshot();\n if (covered(snap.wm, msg.wm)) sendTo(peer, { t: 'uptodate' });\n else sendTo(peer, { t: 'state', state: snap });\n return;\n }\n case 'state': {\n if (covered(sync.watermark(), msg.state.wm)) {\n sync.hydrate(msg.state as OpSyncCheckpoint<T>);\n }\n return;\n }\n case 'uptodate':\n return;\n case 'env':\n sync.receive(msg.env);\n return;\n }\n };\n\n const handleSignaling = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome':\n for (const origin of msg.members) ensurePeer(origin);\n status.set('live');\n return;\n case 'member':\n if (msg.gone) dropPeer(msg.origin);\n else ensurePeer(msg.origin);\n return;\n case 'signal':\n ensurePeer(msg.from).link.signal(msg.data);\n return;\n case 'reject':\n close();\n return;\n }\n };\n\n const connectSignaling = (): void => {\n if (closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n const t = opt.signaling();\n transport = t;\n signalingUnsubs = [\n t.onMessage(handleSignaling),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n reconnectTimer = setTimeout(connectSignaling, 1000);\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion ?? 0,\n });\n };\n\n const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n unsubLocal();\n for (const origin of [...peers.keys()]) dropPeer(origin);\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport?.close();\n transport = null;\n sync.destroy();\n status.set('connecting');\n };\n\n injector.get(DestroyRef).onDestroy(close);\n connectSignaling();\n\n return {\n status: status.asReadonly(),\n peers: computed(() => [...openPeers()]),\n close,\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;;AAyGA,MAAM,iBAAiB,GAAG,GAAG;AAEvB,SAAU,WAAW,CACzB,GAA0B,EAAA;AAE1B,IAAA,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,GAAG;AAC3B,IAAA,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,IAAI;AAC/B,QAAA,GAAG,EAAE,CAAC,EAAc,EAAE,EAAU,KAAK,UAAU,CAAC,EAAE,EAAE,EAAE,CAAC;QACvD,KAAK,EAAE,CAAC,MAAe,KACrB,YAAY,CAAC,MAAuC,CAAC;KACxD;IAED,IAAI,MAAM,GAAe,YAAY;IACrC,MAAM,UAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACjD,IAAA,MAAM,OAAO,GAAG,IAAI,GAAG,EAAsB;AAC7C,IAAA,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB;AACvC,IAAA,MAAM,UAAU,GAAG,CAAC,GAAwC,KAC1D,CAAA,EAAG,GAAG,CAAC,MAAM,CAAA,CAAA,EAAI,GAAG,CAAC,OAAO,EAAE;IAChC,IAAI,OAAO,GAAG,CAAC;AACf,IAAA,IAAI,QAA4B;AAChC,IAAA,IAAI,KAAK,GAAuC,IAAI,GAAG,EAAE;AACzD,IA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 +20,7 @@
20
20
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/mesh/client",
21
21
  "peerDependencies": {
22
22
  "@angular/core": ">=21 <22",
23
- "@mmstack/primitives": ">=21.8 <22",
23
+ "@mmstack/primitives": ">=21.10 <22",
24
24
  "@mmstack/mesh-protocol": ">=0.4 <1"
25
25
  },
26
26
  "sideEffects": false,
@@ -1,6 +1,6 @@
1
- import { Injector, Signal, WritableSignal } from '@angular/core';
2
1
  import { ClientMsg, ServerMsg, Relay, PrincipalCtx, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
3
- import { MergePolicyEntry, AsyncStore, ForkStoreOptions, SyncedFork } from '@mmstack/primitives';
2
+ import { WritableSignalStore, StoreOp, ForkStoreOptions, SyncedFork, MergePolicyEntry, toStoreOptions, AsyncStore } from '@mmstack/primitives';
3
+ import { Injector, Signal, WritableSignal } from '@angular/core';
4
4
 
5
5
  /**
6
6
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
@@ -25,6 +25,124 @@ declare function webSocketTransport(url: string, protocols?: string | string[]):
25
25
  declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
26
26
 
27
27
  type MeshStatus = 'connecting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
28
+
29
+ /** A sequenced batch of another writer's ops, delivered in relay order. */
30
+ type SeatChange = {
31
+ readonly kind: 'change';
32
+ /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */
33
+ readonly seq: number;
34
+ readonly writer: string;
35
+ readonly ops: readonly StoreOp[];
36
+ };
37
+ /**
38
+ * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past
39
+ * the relay's retention, or a relay restart) without seeing the individual changes in
40
+ * between. Anything accumulated from prior `change` events — narration buffers, cached
41
+ * prompt prefixes — no longer extends the stream and must be rebuilt from current state.
42
+ */
43
+ type SeatResync = {
44
+ readonly kind: 'resync';
45
+ /** The seq the re-established state corresponds to. */
46
+ readonly seq: number;
47
+ };
48
+ type SeatEvent = SeatChange | SeatResync;
49
+ /** A base state provably derivable from the room's history alone — safe to cache. */
50
+ type StableSnapshot<T> = {
51
+ /** The relay seq this state is the fold of. */
52
+ readonly seq: number;
53
+ readonly doc: T;
54
+ };
55
+ type AgentSeatOptions = {
56
+ readonly room: string;
57
+ /** Opaque principal pseudonym — provided, never minted. One identity per seat. */
58
+ readonly writer: string;
59
+ readonly transport: MeshTransportFactory;
60
+ /** Per-path merge policies for rebase/convergence (`lww` default). */
61
+ readonly policies?: readonly MergePolicyEntry[];
62
+ /**
63
+ * Emit-side validation, symmetric with the relay's — an optimization, not the
64
+ * enforcement (the relay validates every envelope regardless). A violating write is
65
+ * never sent and ejects the seat exactly as the relay would have; the refused value
66
+ * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.
67
+ */
68
+ readonly policy?: OpPolicy;
69
+ /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */
70
+ readonly ctx?: Omit<PrincipalCtx, 'writer'>;
71
+ readonly policyVersion?: number;
72
+ readonly schemaVersion?: number;
73
+ /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */
74
+ readonly reconnect?: {
75
+ readonly maxDelayMs?: number;
76
+ };
77
+ /**
78
+ * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;
79
+ * pass your own to share proxy caches across several seats in one process.
80
+ */
81
+ readonly context?: toStoreOptions;
82
+ readonly onEject?: (reason: string) => void;
83
+ };
84
+ type AgentSeat<T extends object> = {
85
+ /** The live converging replica. Reads exactly like a local signal store. */
86
+ readonly doc: WritableSignalStore<T & Record<string, any>>;
87
+ status(): MeshStatus;
88
+ peers(): readonly PresenceState[];
89
+ /** The current document value — plain JSON-serializable data, for context assembly. */
90
+ snapshot(): T;
91
+ /**
92
+ * The current document, stamped with the relay seq it is provably the pure fold of
93
+ * or null when stability cannot be guaranteed
94
+ */
95
+ stableSnapshot(): StableSnapshot<T> | null;
96
+ /** Run local writes and emit them to the room as one envelope, like any peer's edit. */
97
+ write(fn: () => void): void;
98
+ /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */
99
+ setAtPath(path: string | readonly (string | number)[], value: unknown): void;
100
+ /**
101
+ * The room's sequenced history as it arrives: `change` events carry another writer's ops
102
+ * in strictly increasing seq order, so a listener may append them (narration, prompt
103
+ * suffixes) without any diffing. A `resync` event voids that guarantee — everything
104
+ * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).
105
+ * Own writes never echo here.
106
+ */
107
+ changes(cb: (event: SeatEvent) => void): () => void;
108
+ /**
109
+ * An isolated branch for a reviewable proposal. The fork observes the room as it is now;
110
+ * `commit()` emits its diff citing only those observed writes, so a room edit that lands
111
+ * while the fork is open survives as a concurrent value for the merge policy to resolve
112
+ * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the
113
+ * staged edits.
114
+ */
115
+ fork(opt?: ForkStoreOptions<T & Record<string, any>>): SyncedFork<T & Record<string, any>>;
116
+ /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */
117
+ setPresence(data: unknown): void;
118
+ close(): void;
119
+ };
120
+ /**
121
+ * A headless mesh peer: the same replica and wire contract `meshSync` implements in the
122
+ * browser, without Angular's injector or any browser API — for agents, server-side bridges,
123
+ * and device writers joining a room as first-class, attributed participants. Each call is
124
+ * one identity with its own replica; run several seats in one process for several
125
+ * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as
126
+ * to any human peer.
127
+ */
128
+ declare function agentSeat<T extends object>(initial: T, opt: AgentSeatOptions): AgentSeat<T>;
129
+ type PathSegment = string | number;
130
+ /**
131
+ * Applies `value` at a path on a signal-store node — the write shape a tool-calling model
132
+ * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as
133
+ * the path exists in the current value and finishes with one immutable set on the deepest
134
+ * real node, which also covers paths that do not exist yet (a fresh record key creates it).
135
+ * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer
136
+ * `seat.setAtPath`, which also emits immediately.
137
+ */
138
+ declare function setAtPath(node: unknown, path: string | readonly PathSegment[], value: unknown): void;
139
+ /**
140
+ * One store op as a plain-English line ("mira set plan.endDate to \"2026-10-11\""), for
141
+ * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
142
+ * `changes` stream: narrating each batch's ops yields an append-only account of the room.
143
+ */
144
+ declare function describeOp(op: StoreOp, writer: string): string;
145
+
28
146
  type MeshPeer = PresenceState;
29
147
  /**
30
148
  * A composed, user-facing health status for a synced store the surface that
@@ -194,5 +312,5 @@ type WebRtcMeshRef = {
194
312
  */
195
313
  declare function webRtcMesh<T extends object>(source: WritableSignal<T>, opt: WebRtcMeshOptions): WebRtcMeshRef;
196
314
 
197
- export { directTransport, meshSync, rtcPeerConnector, webRtcMesh, webSocketTransport };
198
- export type { DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerConnector, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };
315
+ export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
316
+ export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerConnector, SeatChange, SeatEvent, SeatResync, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };