@mmstack/mesh 22.1.0 → 22.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,8 +38,8 @@ store also participates in transition scopes, so a reconnect shows up as `pendin
38
38
 
39
39
  Reconnection is automatic, with exponential backoff. On reconnect the client resumes from a
40
40
  delta when possible, and re-applies any writes made while offline on top of whatever the room
41
- moved to in the meantime. A relay restart is detected through a room epoch, so a stale sequence
42
- number never corrupts state.
41
+ moved to in the meantime. A relay restart is detected through a room instance nonce, so a stale
42
+ sequence number never corrupts state.
43
43
 
44
44
  ## Conflict resolution
45
45
 
@@ -63,9 +63,9 @@ meshSync(board, {
63
63
  });
64
64
  ```
65
65
 
66
- `preserve` turns a clash into a `Conflicted` value holding both sides, so nothing is silently
67
- lost and a resolution is just a later write. See `@mmstack/primitives` for the full set of
68
- merge policies; they are the same ones the store uses for forks and tabs.
66
+ `preserve` turns a clash into a `Conflicted` value holding every side that clashed, not just two,
67
+ so nothing is silently lost and a resolution is just a later write. See `@mmstack/primitives` for
68
+ the full set of merge policies; they are the same ones the store uses for forks and tabs.
69
69
 
70
70
  The default is last-writer-wins on a leaf, which drops one side of a true clash on the same field.
71
71
  For a field where losing a write matters, set `preserve` on its path and resolve the `Conflicted`
@@ -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,44 +229,135 @@ 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
- Give the agent a fork of the synced store. Its writes stay on the fork, so nothing reaches the room
234
- until a person approves. `ops()` is the staged change as data, ready to render for review. `commit()`
235
- applies it onto the synced store, which then emits 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
- import { forkStore } from '@mmstack/primitives';
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
239
275
 
240
- const board = store<Board>(initialBoard());
241
- meshSync(board, { room: 'board-42', writer: userId, transport });
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
280
+ ```
281
+
282
+ The commit cites what the fork observed when it forked, so an edit that lands on the room while a
283
+ person reviews stays a concurrent value the merge policy decides, never silently overwritten by the
284
+ approval. Call `rebase()` to re-observe the room first when the proposal should apply on top of the
285
+ latest. The reviewer reads and writes normal store values, and the agent never touches the room
286
+ directly. This is the fit when a write should be seen before it lands.
287
+
288
+ ### Feed the model diffs, not the world
242
289
 
243
- const proposal = forkStore(board); // the agent's isolated branch, off the room
244
- runAgent(proposal.store); // it writes here
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
+ });
245
311
 
246
- const changes = proposal.ops(); // StoreOp[] for the reviewer to see
247
- proposal.commit(); // approve: merges onto board, which syncs
248
- // proposal.discard(); // reject: drops the staged writes
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
+ }
249
320
  ```
250
321
 
251
- The fork reconciles as the base moves, so a proposal stays current while a person looks at it. The
252
- reviewer reads and writes normal store values, and the agent never touches the room directly. This
253
- is the fit when a write should be seen before it lands.
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
+ ```
254
346
 
255
347
  ### Write as a peer
256
348
 
257
- An agent can also join the room directly, scoped by the relay ACL. Give it a narrower `ctx` and a
258
- `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`.
259
352
 
260
353
  ```ts
261
- meshSync(board, {
354
+ agentSeat(initialBoard(), {
262
355
  room: 'board-42',
263
356
  writer: agentId,
264
357
  transport,
265
358
  ctx: { kind: 'agent', claims: { scope: 'pricing' } },
266
359
  policy: pricingScopeOnly,
360
+ onEject: (reason) => log.warn('agent ejected', reason),
267
361
  });
268
362
  ```
269
363
 
@@ -299,7 +393,7 @@ meshSync(store, { room, writer, transport, schemaVersion: 2 });
299
393
  ```
300
394
 
301
395
  A migration is an envelope: a privileged writer (run from your deploy) emits a root set carrying the
302
- new `schemaVersion`. The relay bumps the room's schema and its epoch, so every watermark dies and
396
+ new `schemaVersion`. The relay bumps the room's schema and its instance nonce, so every watermark dies and
303
397
  clients re-hydrate into the new shape. A client older than the room is rejected with reason
304
398
  `schema`, and a client already connected when the migration lands stops applying and reports
305
399
  `outdated`. Because the migration rides the log, a compacted snapshot and `relay.hydrate` are