@graview/ship 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,52 @@
1
- import { FieldRevisions, hidesFrom, hueFor, isUnset, participantKey, redact, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, } from "@graview/core";
1
+ import { argumentWords, FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, } from "@graview/core";
2
2
  import { bytesOf, conflictSentence, LIVE_WIRE } from "./live.js";
3
+ /** The longest `cid` a socket's call or undo may name: it is kept in `held` while the call is busy. */
4
+ const MAX_CID = 64;
5
+ /** A change the host's `admit` answered: thrown through the store, which puts the change back. */
6
+ class NotAdmitted extends Error {
7
+ answer;
8
+ constructor(answer) {
9
+ super("Not admitted by the host.");
10
+ this.answer = answer;
11
+ }
12
+ }
13
+ /** A client's claim of what its change came through: a short string, or none. */
14
+ const claimOfVia = (via) => (typeof via === "string" && via.length > 0 ? via.slice(0, 64) : undefined);
15
+ /**
16
+ * A STORE'S REFUSAL, SAID TO A PERSON (FR-46). The store's own sentences
17
+ * were written for a developer: `Invalid arguments for mutation "add"
18
+ * label: Too small…`, and an unknown act listed every act the app has.
19
+ * Arguments are said field by field in the words the form asked in, and
20
+ * an unknown act by the name the call gave; anything else is the
21
+ * refusal's own sentence, the policy's among them.
22
+ */
23
+ export function wireRefusalOf(store, error) {
24
+ const refusal = refusalOf(error);
25
+ if (error instanceof UnknownMutationError)
26
+ return { ...refusal, sentence: `This app has no act called “${error.mutation}”.` };
27
+ if (error instanceof InvalidArguments) {
28
+ const mutation = store.allMutations().find((one) => one.name === error.mutation);
29
+ const said = error.issues.map((issue) => {
30
+ const message = issue.message.replace(/^./, (first) => first.toLowerCase());
31
+ return issue.path.length > 0 ? `${argumentWords(store.schema, mutation, String(issue.path[0])).label} — ${message}` : message;
32
+ });
33
+ return { ...refusal, sentence: `“${mutation?.title ?? error.mutation}” was not made: ${said.join("; ")}.` };
34
+ }
35
+ return refusal;
36
+ }
3
37
  /** For whom an author acts, as a presence says it: the person's id and name, or nothing. */
4
38
  const forWhom = (author) => author.onBehalfOf?.id ? { onBehalfOf: author.onBehalfOf.id, ...(author.onBehalfOf.name ? { onBehalfOfName: author.onBehalfOf.name } : {}) } : {};
5
39
  /**
6
40
  * A PRESENCE AS THE SERVER BUILDS IT. Keyed by the seat — a client cannot
7
41
  * claim to be somebody else — with only the session taken from what it
8
42
  * said, and stamped with the server's clock. What it is, and for whom it
9
- * acts, are the seat's (FR-47): a claimed `kind`, `onBehalfOf` or `until`
10
- * is dropped, and the seat's name stands over a claimed one. `participant`
43
+ * acts, are the seat's (FR-47): a claimed `kind`, `onBehalfOf`, `until` or
44
+ * `held` is dropped, and the seat's name stands over a claimed one. `participant`
11
45
  * is the key the server already gave this socket (its welcome said it):
12
46
  * given, the claimed key is not read at all.
13
47
  */
14
48
  export function presenceFrom(told, seat, now = new Date(), participant) {
15
- const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, at: _at, ...said } = told;
49
+ const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, ...said } = told;
16
50
  // The session is what follows the seat's own `kind:id:` — an id may hold a colon (`shopper:bethan`).
17
51
  const own = `${seat.kind}:${seat.id ?? ""}:`;
18
52
  const session = claimed.startsWith(own) ? claimed.slice(own.length) : (claimed.split(":").at(-1) ?? "");
@@ -51,6 +85,27 @@ export function announcePresence(who, presence, ttlMs = VISITOR_PRESENCE_TTL_MS,
51
85
  const stamped = { ...presence, at: new Date(now).toISOString(), until: new Date(now + ttlMs).toISOString() };
52
86
  return [...who.filter((one) => one.participant !== presence.participant && (one.until === undefined || now < Date.parse(one.until))), stamped];
53
87
  }
88
+ /**
89
+ * WHO IS HERE, AS THE SOCKETS SAY IT: a presence whose participant one of
90
+ * the host's sockets holds is held by that socket (`held: "socket"`, and no
91
+ * `until` — it stands while the socket does); everybody else, a visitor
92
+ * with its `until` among them, as the host built them. A new list: the
93
+ * host's own is not changed.
94
+ */
95
+ function heldBySockets(who, peers) {
96
+ const held = new Set();
97
+ for (const peer of peers)
98
+ if (peer.participant)
99
+ held.add(peer.participant);
100
+ if (held.size === 0)
101
+ return [...who];
102
+ return who.map((presence) => {
103
+ if (!held.has(presence.participant))
104
+ return presence;
105
+ const { until: _until, ...standing } = presence;
106
+ return { ...standing, held: "socket" };
107
+ });
108
+ }
54
109
  /** A key for a socket that has not said one, minted by the server: the welcome tells the client what it is. */
55
110
  const mintSession = () => globalThis.crypto.randomUUID().slice(0, 8);
56
111
  /**
@@ -80,19 +135,138 @@ export function presenceSeenBy(who, sees) {
80
135
  };
81
136
  });
82
137
  }
83
- export function wireOf(store) {
138
+ /**
139
+ * THE SHAPE OF A BATCH A CLIENT NAMES: what a `Store` mints by default,
140
+ * `batch:<tag>:<n>` for a change and `undo:<tag>:<n>` for a take-back,
141
+ * the tag 1–24 lowercase letters and digits and `n` up to 12 digits. A
142
+ * client names the batch its call lands in, so a call sent twice is
143
+ * answered once (FR-49) — and anything else a client names is refused
144
+ * `invalid`, so it cannot claim a batch the host mints for itself
145
+ * (`setup`, `migration:v2`) before the host does.
146
+ */
147
+ const CLIENT_BATCH = /^(?:batch|undo):[0-9a-z]{1,24}:[0-9]{1,12}$/;
148
+ /** Whether a client may name this batch: `batch:<tag>:<n>` or `undo:<tag>:<n>`, as a `Store` mints them. */
149
+ export function isClientBatch(batch) {
150
+ return typeof batch === "string" && CLIENT_BATCH.test(batch);
151
+ }
152
+ /** A tag for one minter, from the platform's random source. */
153
+ const mintTag = () => globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 12);
154
+ /**
155
+ * BATCH IDS NO CLIENT CAN NAME FIRST: `served:<kind>:<tag>:<n>`, outside
156
+ * the shape `isClientBatch` accepts. Hand it to the host's own store —
157
+ * `new Store({ batchIds: serverBatchIds() })`, or `openStore`'s
158
+ * `storeOptions` — so what the host lands itself (an agent's RPC, a
159
+ * migration, a seed) is in a batch no client could have claimed.
160
+ * `createStoreHandler` mints its own this way, and `liveProtocol` mints
161
+ * one for a call that names none.
162
+ */
163
+ export function serverBatchIds() {
164
+ const tag = mintTag();
165
+ let count = 0;
166
+ return (kind) => `served:${kind}:${tag}:${++count}`;
167
+ }
168
+ /**
169
+ * THE SAME SEAT. An op is the asking seat's own when its author is the
170
+ * same kind and id — and, for an agent, acts for the same person: Claude
171
+ * for Ada is not Claude for Bo.
172
+ */
173
+ export function authoredBy(author, seat) {
174
+ if (author.kind !== seat.kind || (author.id ?? "") !== (seat.id ?? ""))
175
+ return false;
176
+ return seat.kind !== "agent" || (author.onBehalfOf?.id ?? "") === (seat.onBehalfOf?.id ?? "");
177
+ }
178
+ /**
179
+ * THE KEY A STORE'S WITHHELD BATCHES ARE MINTED UNDER, when the host gives
180
+ * none: drawn once per store held, so every route and socket over one
181
+ * store says the same opaque batch for one batch.
182
+ */
183
+ const WITHHELD_KEYS = new WeakMap();
184
+ /**
185
+ * EACH STORE'S OPAQUE BATCHES, BY KEY: a keyed hash per batch, made once
186
+ * for every route and socket over the store rather than once per protocol
187
+ * made over it — a protocol is made again on every wake.
188
+ */
189
+ const OPAQUE_BATCHES = new WeakMap();
190
+ export function wireOf(store, withheldKey) {
84
191
  const sighted = (principal) => hidesFrom(store, principal);
85
- const shown = (principal, ops) => (sighted(principal) ? redact(ops, seesId(store, principal)) : [...ops]);
192
+ /*
193
+ * A WITHHELD OP SAYS NOBODY'S SESSION. Its batch is the one its author's
194
+ * client minted — `batch:<that browser's tag>:<n>` — which would tell a
195
+ * seat that may not see the change which session made it, and link it to
196
+ * the changes it may see. So it is served under `withheld:<16 hex>`, a
197
+ * keyed SHA-256 of the batch: the same for every op of one batch, and not
198
+ * one a seat can work back from, the key never leaving the server. The
199
+ * seat that made it is served its own.
200
+ */
201
+ let key = withheldKey;
202
+ if (key === undefined) {
203
+ key = WITHHELD_KEYS.get(store) ?? mintTag() + mintTag();
204
+ WITHHELD_KEYS.set(store, key);
205
+ }
206
+ let byKey = OPAQUE_BATCHES.get(store);
207
+ if (!byKey)
208
+ OPAQUE_BATCHES.set(store, (byKey = new Map()));
209
+ let opaque = byKey.get(key);
210
+ if (!opaque)
211
+ byKey.set(key, (opaque = new Map()));
212
+ const opaqueBatch = (batch) => {
213
+ let said = opaque.get(batch);
214
+ if (said === undefined) {
215
+ said = `withheld:${sha256Hex(`${key}\u0000${batch}`).slice(0, 16)}`;
216
+ opaque.set(batch, said);
217
+ }
218
+ return said;
219
+ };
220
+ const unattributed = (principal, served, authorOf) => served.map((op, at) => {
221
+ if (!op.withheld)
222
+ return op;
223
+ const author = authorOf(op, at);
224
+ return author && authoredBy(author, principal) ? op : { ...op, batch: opaqueBatch(op.batch) };
225
+ });
226
+ // Withheld in place (FR-16), no id the seat may not see in any of them (FR-55), and no session it may not see.
227
+ const shown = (principal, ops) => sighted(principal) ? unattributed(principal, redact(ops, seatLens(store, principal)), (_op, at) => ops[at]?.author) : [...ops];
86
228
  /*
87
229
  * EVERY FIELD'S REVISION (FR-05): the seq of the op that last wrote it,
88
230
  * read off the log once and caught up from wherever the log has grown
89
231
  * to since — no subscription, so nothing here goes stale while a host
90
232
  * sleeps, and a host that made this again reads the same revisions.
91
233
  */
92
- const revisions = FieldRevisions.of(store.log.all());
93
- let noted = store.log.length;
234
+ /*
235
+ * WHO EACH CLIENT TAG IS: the author of the first op landed under it,
236
+ * read off the log once and caught up as it grows — derived, so a host
237
+ * that wakes reads the same owners the sleeper had.
238
+ */
239
+ /*
240
+ * Both read on first asking, not when the protocol is made: a host makes
241
+ * it again on every wake, and most wakes are a message that names no
242
+ * batch and carries no base.
243
+ */
244
+ const owners = new Map();
245
+ const own = (ops) => {
246
+ for (const op of ops) {
247
+ if (!isClientBatch(op.batch))
248
+ continue;
249
+ const tag = op.batch.split(":")[1];
250
+ if (!owners.has(tag))
251
+ owners.set(tag, op.author);
252
+ }
253
+ };
254
+ let owned = store.log.horizon;
255
+ const tagOwner = (tag) => {
256
+ if (store.log.length > owned) {
257
+ own(store.log.opsFrom(owned));
258
+ owned = store.log.length;
259
+ }
260
+ return owners.get(tag);
261
+ };
262
+ let revisions;
263
+ let noted = 0;
94
264
  const current = () => {
95
- if (store.log.length > noted) {
265
+ if (!revisions) {
266
+ revisions = FieldRevisions.of(store.log.all());
267
+ noted = store.log.length;
268
+ }
269
+ else if (store.log.length > noted) {
96
270
  revisions.note(store.log.opsFrom(noted));
97
271
  noted = store.log.length;
98
272
  }
@@ -105,21 +279,60 @@ export function wireOf(store) {
105
279
  shown,
106
280
  since: (principal, seq) => shown(principal, store.log.opsFrom(Math.max(0, Math.floor(seq) + 1))),
107
281
  seenFor: (principal) => seenBy(store, principal),
282
+ seenLog(principal) {
283
+ const log = seenBy(store, principal).log.all();
284
+ if (!sighted(principal))
285
+ return [...log];
286
+ // The seat's log holds every op in its place: who made one is the store's op at the same place.
287
+ const all = store.log.all();
288
+ return unattributed(principal, log, (op, at) => (all[at]?.id === op.id ? all[at].author : all.find((one) => one.id === op.id)?.author));
289
+ },
108
290
  whoFor: (principal, who) => {
109
291
  // A visitor whose announced time has passed is never told of, though a host may still hold it.
110
292
  const now = Date.now();
111
293
  const standing = who.filter((presence) => presence.until === undefined || now < Date.parse(presence.until));
112
294
  return sighted(principal) ? presenceSeenBy(standing, seesId(store, principal)) : standing;
113
295
  },
114
- answered: (batch) => (typeof batch === "string" && batch.length > 0 ? store.log.all().filter((op) => op.batch === batch) : []),
296
+ claim(batch, seat) {
297
+ if (batch === undefined || batch === null || batch === "")
298
+ return {};
299
+ if (!isClientBatch(batch)) {
300
+ const said = typeof batch === "string" ? `“${batch.length > 40 ? `${batch.slice(0, 37)}…` : batch}”` : "a batch that is not a string";
301
+ return {
302
+ refusal: {
303
+ reason: "invalid",
304
+ sentence: `A client names its batch batch:<tag>:<n> or undo:<tag>:<n>, as a Store mints it; ${said} is not one. Send the change without a batch, or under one this client minted.`,
305
+ },
306
+ };
307
+ }
308
+ /*
309
+ * A TAG IS THE FIRST SEAT'S. A client's tag is in every op it lands,
310
+ * so a batch it has not sent yet — `batch:<tag>:<n+1>` — could be
311
+ * named first by anybody who saw one. The store's own minting tag is
312
+ * nobody's to name: what the host lands later would join it.
313
+ */
314
+ const tag = batch.split(":")[1];
315
+ if (tag === store.batchTag) {
316
+ return { refusal: { reason: "invalid", sentence: "That batch is under the server's own tag: send the change under a batch this client minted." } };
317
+ }
318
+ const owner = tagOwner(tag);
319
+ if (owner && !authoredBy(owner, seat)) {
320
+ return { refusal: { reason: "invalid", sentence: "That batch is under somebody else's tag: send the change under a batch this client minted." } };
321
+ }
322
+ const ops = store.log.all().filter((op) => op.batch === batch);
323
+ if (ops.some((op) => !authoredBy(op.author, seat))) {
324
+ return { refusal: { reason: "invalid", sentence: "That batch is somebody else's: send the change under a batch this client minted." } };
325
+ }
326
+ return ops.length > 0 ? { answered: ops } : {};
327
+ },
115
328
  horizonOf: () => (store.log.horizon > 0 ? { horizon: store.log.horizon } : {}),
116
329
  enabledModules: () => [...store.modules.enabled].sort(),
117
- conflictsOf(author, calls, base) {
330
+ conflictsOf(author, calls, base, via) {
118
331
  if (!Array.isArray(base) || base.length === 0)
119
332
  return [];
120
- const sees = sighted(author) ? seesId(store, author) : () => true;
121
- // A record the seat may not see is not there to have moved: the call itself is refused for naming it.
122
- const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && sees(entry.node));
333
+ const lens = sighted(author) ? seatLens(store, author) : undefined;
334
+ // A record the seat is not served is not there to have moved: the call itself is refused for naming it.
335
+ const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && (!lens || lens.shows(entry.node)));
123
336
  const revs = current();
124
337
  const stale = revs.stale(claimed);
125
338
  if (stale.length === 0)
@@ -127,14 +340,15 @@ export function wireOf(store) {
127
340
  /*
128
341
  * A conflict is a choice — keep theirs, or put yours over it — and only
129
342
  * a call that could still land offers one. A call the policy refuses,
130
- * or one that no longer runs on the graph as it is (somebody finished
131
- * it first), is refused for that, in its own sentence.
343
+ * one naming a record that is not there for this seat (a hidden record
344
+ * and an absent one alike, FR-55), or one that no longer runs on the
345
+ * graph as it is (somebody finished it first), is refused for that, in
346
+ * its own sentence. The preview is judged as the apply would be, by the
347
+ * seat and the channel (FR-56), so it refuses exactly those.
132
348
  */
133
- if (store.policy && calls.some((call) => !store.permits(call, author).ok))
134
- return [];
135
349
  const yours = new Map();
136
350
  try {
137
- for (const primitive of store.previewAll(calls).primitives) {
351
+ for (const primitive of store.previewAll(calls, { author, ...(via !== undefined ? { via } : {}) }).primitives) {
138
352
  if (primitive.op === "patch-node")
139
353
  for (const [field, value] of Object.entries(primitive.after))
140
354
  yours.set(`${primitive.id}\u0000${field}`, isUnset(value) ? undefined : value);
@@ -146,12 +360,15 @@ export function wireOf(store) {
146
360
  return stale.map((entry) => {
147
361
  const rev = revs.of(entry.node, entry.field);
148
362
  const wrote = rev >= store.log.horizon ? store.log.opsFrom(rev)[0] : undefined;
149
- const seen = wrote && sighted(author) ? redact([wrote], sees)[0] : wrote;
363
+ const seen = wrote && lens ? redact([wrote], lens)[0] : wrote;
364
+ // Theirs as the seat's view serves the record: a field naming what it may not see is cleared there too (FR-55).
365
+ const theirs = (lens ? seenBy(store, author) : store).graph.getNode(entry.node)?.[entry.field];
366
+ const mine = yours.get(`${entry.node}\u0000${entry.field}`);
150
367
  return {
151
368
  node: entry.node,
152
369
  field: entry.field,
153
- theirs: store.graph.getNode(entry.node)?.[entry.field],
154
- yours: yours.get(`${entry.node}\u0000${entry.field}`),
370
+ theirs,
371
+ yours: lens && namesUnseen(mine, lens.sees) ? undefined : mine,
155
372
  by: seen?.author.name ?? seen?.author.id ?? "Someone",
156
373
  rev,
157
374
  saw: entry.rev,
@@ -160,77 +377,294 @@ export function wireOf(store) {
160
377
  },
161
378
  };
162
379
  }
163
- const say = (peer, message) => {
380
+ const say = (peer, message) => sayText(peer, JSON.stringify(message));
381
+ const sayText = (peer, text) => {
164
382
  try {
165
- peer.send(JSON.stringify(message));
383
+ peer.send(text);
166
384
  }
167
385
  catch {
168
386
  // A socket that cannot be written to is closing; its close is what forgets it.
169
387
  }
170
388
  };
389
+ const aSight = () => ({ seats: new Map(), texts: new Map() });
390
+ /**
391
+ * A SEAT, NOT ITS TAB: the principal without its session — and without the
392
+ * session of the person an agent acts for. What a seat is served never
393
+ * depends on which tab asks, so its key never does either: the key a
394
+ * handler asks a host for (`seatKey`), and the one a sight is kept under.
395
+ */
396
+ export function seatOfTab(seat) {
397
+ const { session: _session, onBehalfOf, ...rest } = seat;
398
+ return { ...rest, ...(onBehalfOf ? { onBehalfOf: seatOfTab(onBehalfOf) } : {}) };
399
+ }
400
+ /** What a socket's seat is, as a key a sight is kept under: a host's key, or the seat written out — one per seat, however many tabs hold it. */
401
+ const seatKeyOf = (peer) => (typeof peer.seat === "string" ? `key:${peer.seat}` : `seat:${JSON.stringify(seatOfTab(peer.seat))}`);
402
+ /** What a socket whose seat the host lost is told, and the code it is closed with. */
403
+ const SEAT_LOST = "The host no longer knows who this socket is: open it again, and it reads who you are from the new one.";
404
+ const SEAT_LOST_CODE = 4000;
405
+ /** The host lost this socket's seat: told to open again, closed when it can be, and served nothing more. */
406
+ const lost = (peer) => {
407
+ delete peer.cursor;
408
+ say(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
409
+ try {
410
+ peer.close?.(SEAT_LOST_CODE, "Seat no longer known: open it again.");
411
+ }
412
+ catch {
413
+ // Already closing.
414
+ }
415
+ };
171
416
  /**
172
417
  * THE PROTOCOL OVER A STORE. Cheap to make, and safe to make again on
173
418
  * every wake: what it keeps is derived from the store.
174
419
  */
175
420
  export function liveProtocol(options) {
176
421
  const { store } = options;
177
- const wire = wireOf(store);
178
- /** Every op this socket has not been sent, down it now, as its seat sees them. */
179
- const catchUp = (peer, ops) => {
180
- if (peer.cursor === undefined)
422
+ const wire = wireOf(store, options.withheldKey);
423
+ /** A call that names no batch lands in one minted here, outside the shape a client may name. */
424
+ const mintServed = serverBatchIds();
425
+ /**
426
+ * OPS THAT LANDED AND ARE NOT DURABLE: a flush rejected them. Held back
427
+ * from every socket — nothing is sent past the first of them, so none is
428
+ * skipped — until a flush holds them. Derived: a host that wakes makes
429
+ * its store again from what is durable, where none of them is.
430
+ */
431
+ let unsaved = [];
432
+ /**
433
+ * OPS THAT LANDED AND ARE BEING FLUSHED: held back from every socket like
434
+ * the unsaved ones, so a change anybody else hears is a change that is
435
+ * written. Only with a `flush`: a host without one pushes at once.
436
+ */
437
+ let flying = [];
438
+ /** While the store takes a change (its subscribers hear it then): the seq its ops begin at, held back like the rest. */
439
+ let taking;
440
+ let flushing = Promise.resolve();
441
+ /** The first seq held back from every socket — not durable, or not yet — before `before`, when one is. */
442
+ const heldFrom = (before = Number.POSITIVE_INFINITY) => {
443
+ let first = taking !== undefined && taking < before ? taking : undefined;
444
+ for (const op of [...unsaved, ...flying])
445
+ if (op.seq < before && (first === undefined || op.seq < first))
446
+ first = op.seq;
447
+ return first;
448
+ };
449
+ /**
450
+ * THROUGH THE HOST'S FLUSH, ONE AT A TIME: `ops` and every op a failed
451
+ * flush left before them. Says whether they are durable now, and which
452
+ * ops became durable — for the host to publish.
453
+ */
454
+ const durable = (ops) => {
455
+ const turn = flushing.then(async () => {
456
+ const ids = new Set(unsaved.map((op) => op.id));
457
+ const handing = [...unsaved, ...ops.filter((op) => !ids.has(op.id))].sort((a, b) => a.seq - b.seq);
458
+ const handed = new Set(handing.map((op) => op.id));
459
+ try {
460
+ await options.flush?.(handing);
461
+ }
462
+ catch {
463
+ unsaved = handing;
464
+ flying = flying.filter((op) => !handed.has(op.id));
465
+ return { failed: true };
466
+ }
467
+ unsaved = unsaved.filter((op) => !handed.has(op.id));
468
+ flying = flying.filter((op) => !handed.has(op.id));
469
+ return { saved: handing };
470
+ });
471
+ flushing = turn.catch(() => { });
472
+ return turn;
473
+ };
474
+ /** Whether any of these ops is not durable yet. */
475
+ const unsavedIn = (ops) => unsaved.length > 0 && ops.some((op) => unsaved.some((one) => one.id === op.id));
476
+ const UNSAVED = "Your change could not be saved just now. It is kept, and sent again until it is.";
477
+ /** The principal a socket is: its seat, or what the host's `seatOf` says its key names — once per key in one sight. */
478
+ const principalOf = (peer, sight) => {
479
+ if (typeof peer.seat !== "string")
480
+ return peer.seat;
481
+ if (!sight)
482
+ return options.seatOf?.(peer.seat);
483
+ const key = seatKeyOf(peer);
484
+ if (!sight.seats.has(key))
485
+ sight.seats.set(key, options.seatOf?.(peer.seat));
486
+ return sight.seats.get(key);
487
+ };
488
+ /** The ops after this socket's cursor up to `last`, down it now, as its seat sees them — written once per seat and run in one sight. */
489
+ const sendUpTo = (peer, last, ops, known, sight) => {
490
+ if (peer.cursor === undefined || peer.cursor >= last)
181
491
  return;
182
- const last = wire.lastSeq();
183
- if (peer.cursor >= last)
492
+ const seat = known ?? principalOf(peer, sight);
493
+ if (!seat)
184
494
  return;
185
495
  const from = peer.cursor + 1;
186
- // The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
187
- const after = ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq === last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from);
188
496
  peer.cursor = last;
189
- if (after.length > 0)
190
- say(peer, { t: "ops", seq: last, ops: wire.shown(peer.seat, after) });
191
- };
192
- /** A call or an undo from a socket: judged as its seat, exactly as `POST /graview/ops` judges it. */
193
- const answer = async (peer, message) => {
194
- const cid = typeof message.cid === "string" ? message.cid : "";
195
- const author = peer.seat;
196
- const intent = typeof message.intent === "string" && message.intent.length > 0 ? message.intent : undefined;
197
- const batch = typeof message.batch === "string" && message.batch.length > 0 ? message.batch : undefined;
198
- catchUp(peer);
199
- // A client that lost its socket before the ack sends the call again under the same batch: `answered` says what it made.
200
- const already = wire.answered(batch);
201
- if (already.length > 0) {
202
- say(peer, { t: "ack", cid, seq: already.at(-1).seq, batch: batch, ops: wire.shown(author, already) });
203
- return { cursor: peer.cursor };
497
+ const key = sight ? `${seatKeyOf(peer)}\u0000${from}\u0000${last}` : undefined;
498
+ const kept = key !== undefined ? sight.texts.get(key) : undefined;
499
+ if (kept !== undefined) {
500
+ if (kept.length > 0)
501
+ sayText(peer, kept);
502
+ return;
204
503
  }
205
- const calls = message.t === "call" && Array.isArray(message.calls) ? message.calls : [];
206
- if (message.t === "call") {
207
- const conflicts = wire.conflictsOf(author, calls, message.base);
208
- if (conflicts.length > 0) {
209
- say(peer, { t: "conflict", cid, sentence: conflictSentence(conflicts), conflicts });
210
- return { cursor: peer.cursor };
211
- }
504
+ // The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
505
+ const after = (ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq >= last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from)).filter((op) => op.seq <= last);
506
+ const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: last, ops: wire.shown(seat, after) }) : "";
507
+ if (key !== undefined)
508
+ sight.texts.set(key, text);
509
+ if (text.length > 0)
510
+ sayText(peer, text);
511
+ };
512
+ /** Every op this socket has not been sent, down it now, as its seat sees them — up to the first that is not durable. */
513
+ const catchUp = (peer, ops, known, sight) => {
514
+ const held = heldFrom();
515
+ sendUpTo(peer, held === undefined ? wire.lastSeq() : Math.min(wire.lastSeq(), held - 1), ops, known, sight);
516
+ };
517
+ /** What the host's `limit` says of a change, before it is judged; nothing when it has none. */
518
+ const limitOf = async (seat, via, change, bytes) => options.limit ? options.limit({ seat, via, t: change.t, bytes, calls: change.t === "call" ? change.calls : [] }) : undefined;
519
+ /**
520
+ * ONE CHANGE, JUDGED AS ITS SEAT — the socket's and `POST /graview/ops`'s
521
+ * alike, so the two can never disagree. A stale write is a conflict and
522
+ * nothing is written (FR-05); then through the store, under the seat and
523
+ * the host's channel (never the client's, FR-52), in the batch the client
524
+ * named or one minted here; then flushed. `applied` runs between the
525
+ * store taking it and the flush, for the socket to move its cursor.
526
+ */
527
+ const land = async (seat, via, change, bytes, applied) => {
528
+ if (change.t === "call") {
529
+ const conflicts = wire.conflictsOf(seat, change.calls, change.base, via);
530
+ if (conflicts.length > 0)
531
+ return { conflicts };
212
532
  }
533
+ const batch = typeof change.batch === "string" && change.batch.length > 0 ? change.batch : mintServed(change.t === "undo" ? "undo" : "batch");
213
534
  let result;
535
+ // A host that publishes from the store's own subscription does so inside the apply: hold from here.
536
+ if (options.flush)
537
+ taking = wire.lastSeq() + 1;
214
538
  try {
215
- // The channel is the seat's, as the host said it when the socket opened: a client's own `via` is never read (FR-52).
216
- const applying = { author, via: peer.via, ...(intent ? { intent } : {}), ...(batch ? { batch } : {}) };
217
- result = message.t === "undo" ? store.undo(Array.isArray(message.batches) ? message.batches : [], applying) : store.applyAll(calls, applying);
539
+ // The host's caps on what it would do, asked of the store's own plan before anything is kept.
540
+ const admit = options.admit;
541
+ const admitting = admit
542
+ ? (planned) => {
543
+ const answer = admit({ seat, via, t: change.t, bytes, calls: change.t === "call" ? change.calls : [] }, planned);
544
+ if (answer)
545
+ throw new NotAdmitted(answer);
546
+ }
547
+ : undefined;
548
+ const applying = { author: seat, via, ...(change.intent ? { intent: change.intent } : {}), batch, ...(admitting ? { admit: admitting } : {}) };
549
+ result = change.t === "undo" ? store.undo(change.batches, applying) : store.applyAll(change.calls, applying);
218
550
  }
219
551
  catch (error) {
220
- say(peer, { t: "refused", cid, ...refusalOf(error) });
552
+ taking = undefined;
553
+ if (error instanceof NotAdmitted)
554
+ return { limited: error.answer };
555
+ const worded = options.refusal?.(error, change.calls, { seat, via });
556
+ return { refusal: worded ?? wireRefusalOf(store, error) };
557
+ }
558
+ // Being written: nobody else hears it until it is (`heldFrom`).
559
+ if (options.flush)
560
+ flying = [...flying, ...result.ops];
561
+ taking = undefined;
562
+ applied?.(result.ops);
563
+ const flushed = await durable(result.ops);
564
+ return { result, saved: "saved" in flushed ? flushed.saved : undefined };
565
+ };
566
+ /** A change as the socket's message says it. */
567
+ const changeOf = (message) => ({
568
+ t: message.t,
569
+ calls: message.t === "call" && Array.isArray(message.calls) ? message.calls : [],
570
+ batches: message.t === "undo" && Array.isArray(message.batches) ? message.batches : [],
571
+ intent: typeof message.intent === "string" && message.intent.length > 0 ? message.intent : undefined,
572
+ batch: message.batch,
573
+ base: message.t === "call" ? message.base : undefined,
574
+ claimed: claimOfVia(message.via),
575
+ });
576
+ /** What a change came through: the host's word, or a claim its `viaOf` accepts (FR-52). */
577
+ const viaFor = (peer, change) => {
578
+ const judged = options.viaOf?.(peer, change.claimed);
579
+ return typeof judged === "string" && judged.length > 0 ? judged : peer.via;
580
+ };
581
+ /**
582
+ * THE HOST'S WORD ON A SOCKET'S CALL (FR-45, FR-46) — its `limit`'s, or
583
+ * its `admit`'s: refused at a cap, unavailable for a while, or busy, when
584
+ * every later call waits behind it.
585
+ */
586
+ const sayLimited = (peer, cid, limited) => {
587
+ if ("refuse" in limited) {
588
+ delete peer.held;
589
+ say(peer, { t: "refused", cid, reason: "limit", sentence: limited.refuse });
590
+ }
591
+ else if ("unavailable" in limited) {
592
+ // Not for a while, and no wait to name: refused `unavailable`, which the client keeps and sends again, backing off.
593
+ delete peer.held;
594
+ say(peer, { t: "refused", cid, reason: "unavailable", sentence: limited.unavailable });
595
+ }
596
+ else {
597
+ const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
598
+ peer.held = { cid, until: Date.now() + retryAfter };
599
+ say(peer, { t: "busy", cid, retryAfter, ...(limited.sentence ? { sentence: limited.sentence } : {}) });
600
+ }
601
+ return { cursor: peer.cursor };
602
+ };
603
+ /** The same word over HTTP: 413 `limit`, 503 `unavailable`, or 429 with `Retry-After`. */
604
+ const limitedReply = (limited, said) => {
605
+ if ("refuse" in limited)
606
+ return reply(413, { error: limited.refuse, refused: true, reason: "limit", ...said });
607
+ if ("unavailable" in limited)
608
+ return reply(503, { error: limited.unavailable, refused: true, reason: "unavailable", ...said });
609
+ const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
610
+ return reply(429, { error: limited.sentence ?? `The store is busy: send it again in ${retryAfter} ms.`, busy: true, retryAfter }, { "retry-after": String(Math.ceil(retryAfter / 1000)) });
611
+ };
612
+ /** A call or an undo from a socket, past its claim and the host's limit: judged as its seat, exactly as `POST /graview/ops` judges it. */
613
+ const answer = async (peer, seat, cid, change, via, bytes) => {
614
+ catchUp(peer, undefined, seat);
615
+ const prior = peer.cursor;
616
+ /*
617
+ * Every op before this call's went down this socket before it landed;
618
+ * its own go in the ack. Unless one before it is held back as not
619
+ * durable: then the cursor stays, and they go down after the flush.
620
+ */
621
+ const landing = await land(seat, via, change, bytes, (own) => {
622
+ if (own.length === 0 || heldFrom(own[0].seq) === undefined)
623
+ peer.cursor = wire.lastSeq();
624
+ });
625
+ // What it would do is over the host's caps: nothing was kept.
626
+ if (landing.limited)
627
+ return sayLimited(peer, cid, landing.limited);
628
+ if (landing.conflicts) {
629
+ say(peer, { t: "conflict", cid, sentence: conflictSentence(landing.conflicts), conflicts: [...landing.conflicts] });
221
630
  return { cursor: peer.cursor };
222
631
  }
223
- // Every op before this call's went down this socket before it landed; its own go in the ack.
224
- peer.cursor = wire.lastSeq();
225
- const ops = wire.shown(author, result.ops);
226
- await options.flush?.();
227
- say(peer, { t: "ack", cid, seq: ops.at(-1)?.seq ?? peer.cursor, batch: result.batch, ops });
228
- return { cursor: peer.cursor, landed: result.ops };
632
+ if (landing.refusal) {
633
+ say(peer, { t: "refused", cid, ...landing.refusal });
634
+ return { cursor: peer.cursor };
635
+ }
636
+ const { result, saved } = landing;
637
+ if (!saved) {
638
+ // Not durable: refused `unavailable`, which the client keeps and sends again; nothing is acked and the cursor does not move.
639
+ peer.cursor = prior;
640
+ say(peer, { t: "refused", cid, reason: "unavailable", sentence: UNSAVED });
641
+ return { cursor: prior };
642
+ }
643
+ return acked(peer, seat, cid, result.batch, result.ops, saved);
644
+ };
645
+ /** The ack of ops that are durable: what was held back before them goes first, so none is skipped. */
646
+ const acked = (peer, seat, cid, batch, own, saved) => {
647
+ const first = own[0]?.seq;
648
+ if (first !== undefined) {
649
+ sendUpTo(peer, first - 1, undefined, seat);
650
+ peer.cursor = Math.max(peer.cursor, own.at(-1).seq);
651
+ }
652
+ const ops = wire.shown(seat, own);
653
+ say(peer, { t: "ack", cid, seq: ops.at(-1)?.seq ?? peer.cursor, batch, ops });
654
+ return { cursor: peer.cursor, ...(saved && saved.length > 0 ? { landed: saved } : {}) };
655
+ };
656
+ /** The host's build a socket — or a route's request — is served by (FR-44): its own, else the protocol's word for it. */
657
+ const buildFor = (peer) => peer.hostBuild ?? (typeof options.build === "function" ? options.build(peer) : options.build);
658
+ /** Which declaration, and which build, answered (FR-43, FR-44): on every route's answer a poll reads. */
659
+ const answering = (asked) => {
660
+ const build = buildFor({ seat: asked.seat, via: asked.via, ...(asked.build ? { hostBuild: asked.build } : {}) });
661
+ return { version: options.version ?? 1, ...(build ? { build } : {}) };
229
662
  };
663
+ const reply = (status, body, headers = {}) => ({ status, body, headers });
230
664
  return {
231
665
  store,
232
- open: (seat, via) => ({ seat, via }),
233
- async receive(peer, text, who = []) {
666
+ open: (seat, via, opening = {}) => ({ seat, via, ...(opening.build ? { hostBuild: opening.build.slice(0, 64) } : {}) }),
667
+ async receive(peer, text, who = [], peers = [peer]) {
234
668
  let message;
235
669
  try {
236
670
  message = JSON.parse(text);
@@ -242,6 +676,13 @@ export function liveProtocol(options) {
242
676
  const unchanged = () => (peer.cursor !== undefined ? { cursor: peer.cursor } : {});
243
677
  if (!message || typeof message !== "object")
244
678
  return unchanged();
679
+ // Who this socket is, on this message: its seat, or the principal its key names now.
680
+ const seat = principalOf(peer);
681
+ if (!seat) {
682
+ lost(peer);
683
+ return {};
684
+ }
685
+ const served = { seat, via: peer.via, ...(peer.hostBuild ? { hostBuild: peer.hostBuild } : {}) };
245
686
  switch (message.t) {
246
687
  case "hello": {
247
688
  /*
@@ -263,16 +704,29 @@ export function liveProtocol(options) {
263
704
  });
264
705
  return {};
265
706
  }
707
+ // The host's own half of the wire, numbered by the host: an older page reloads onto a build that speaks it.
708
+ const hostSpeaks = typeof message.hostProtocol === "number" && Number.isFinite(message.hostProtocol) ? message.hostProtocol : 0;
709
+ if (options.minHostProtocol !== undefined && hostSpeaks < options.minHostProtocol) {
710
+ delete peer.cursor;
711
+ say(peer, {
712
+ t: "reload",
713
+ reason: "This app was updated, and this page is from before it. Reload the page; changes not yet sent are offered again after it.",
714
+ protocol: options.minProtocol ?? WIRE_PROTOCOL,
715
+ hostProtocol: options.minHostProtocol,
716
+ });
717
+ return {};
718
+ }
266
719
  if (typeof message.build === "string" && message.build.length > 0)
267
720
  peer.build = message.build.slice(0, 64);
268
721
  const seq = typeof message.seq === "number" && Number.isFinite(message.seq) ? message.seq : undefined;
269
722
  peer.cursor = wire.lastSeq();
270
723
  // Its own key, built from the seat, so the client can leave itself out of who is here (FR-47).
271
- peer.participant ??= participantKey({ kind: peer.seat.kind, ...(peer.seat.id ? { id: peer.seat.id } : {}), session: mintSession() });
724
+ peer.participant ??= participantKey({ kind: seat.kind, ...(seat.id ? { id: seat.id } : {}), session: mintSession() });
272
725
  const participant = peer.participant;
273
- const said = { protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, version: options.version ?? 1, participant, ...(options.build ? { build: options.build } : {}) };
726
+ const build = buildFor(served);
727
+ const said = { protocol: WIRE_PROTOCOL, wire: LIVE_WIRE, version: options.version ?? 1, participant, ...(build ? { build } : {}) };
274
728
  if (seq === undefined) {
275
- const seen = wire.seenFor(peer.seat);
729
+ const seen = wire.seenFor(seat);
276
730
  say(peer, {
277
731
  t: "welcome",
278
732
  ...said,
@@ -281,7 +735,7 @@ export function liveProtocol(options) {
281
735
  state: {
282
736
  version: options.version ?? 1,
283
737
  snapshot: seen.snapshot(),
284
- log: seen.log.all(),
738
+ log: wire.seenLog(seat),
285
739
  migrated: [...(options.migrated ?? [])],
286
740
  enabledModules: wire.enabledModules(),
287
741
  ...wire.horizonOf(),
@@ -289,20 +743,62 @@ export function liveProtocol(options) {
289
743
  });
290
744
  }
291
745
  else {
292
- say(peer, { t: "welcome", ...said, seq: peer.cursor, ops: wire.since(peer.seat, seq) });
746
+ // Caught up to what is written: an op still being flushed, or one a flush failed, comes once it holds.
747
+ const held = heldFrom();
748
+ if (held !== undefined)
749
+ peer.cursor = Math.max(Math.floor(seq), held - 1);
750
+ say(peer, { t: "welcome", ...said, seq: peer.cursor, ops: wire.since(seat, seq).filter((op) => op.seq <= peer.cursor) });
293
751
  }
294
- const others = who.filter((presence) => presence.participant !== peer.participant);
752
+ const others = heldBySockets(who, [peer, ...peers]).filter((presence) => presence.participant !== peer.participant);
295
753
  if (others.length > 0)
296
- say(peer, { t: "presence", who: wire.whoFor(peer.seat, others) });
754
+ say(peer, { t: "presence", who: wire.whoFor(seat, others) });
297
755
  return { cursor: peer.cursor };
298
756
  }
299
757
  case "call":
300
758
  case "undo": {
301
759
  const cid = String(message.cid ?? "");
760
+ // A cid is kept while its call is busy: a long one would crowd the host's attachment.
761
+ if (cid.length > MAX_CID) {
762
+ say(peer, { t: "refused", cid, reason: "invalid", sentence: `A call's cid is at most ${MAX_CID} characters; this one is ${cid.length}. Name it again shorter.` });
763
+ return unchanged();
764
+ }
302
765
  if (peer.cursor === undefined) {
303
766
  say(peer, { t: "refused", cid, reason: "invalid", sentence: "Say hello first: the live wire answers calls once it knows what the client has." });
304
767
  return {};
305
768
  }
769
+ /*
770
+ * SENT AGAIN AFTER IT LANDED: answered with what it made, before the
771
+ * host is asked anything. A call whose ack was lost is never told
772
+ * busy, capped or unavailable for a change already made — and only
773
+ * ever with the asking seat's own ops (`claim`).
774
+ */
775
+ const change = changeOf(message);
776
+ const claim = wire.claim(message.batch, seat);
777
+ if (claim.refusal) {
778
+ catchUp(peer, undefined, seat);
779
+ if (peer.held?.cid === cid)
780
+ delete peer.held;
781
+ say(peer, { t: "refused", cid, ...claim.refusal });
782
+ return { cursor: peer.cursor };
783
+ }
784
+ if (claim.answered) {
785
+ if (peer.held?.cid === cid)
786
+ delete peer.held;
787
+ // Landed, but a flush failed it: flushed again, and acked only once it holds.
788
+ if (unsavedIn(claim.answered)) {
789
+ const flushed = await durable([]);
790
+ if (!("saved" in flushed)) {
791
+ catchUp(peer, undefined, seat);
792
+ say(peer, { t: "refused", cid, reason: "unavailable", sentence: UNSAVED });
793
+ return { cursor: peer.cursor };
794
+ }
795
+ catchUp(peer, undefined, seat);
796
+ return acked(peer, seat, cid, message.batch, claim.answered, flushed.saved);
797
+ }
798
+ catchUp(peer, undefined, seat);
799
+ say(peer, { t: "ack", cid, seq: claim.answered.at(-1).seq, batch: message.batch, ops: wire.shown(seat, claim.answered) });
800
+ return { cursor: peer.cursor };
801
+ }
306
802
  /*
307
803
  * BUSY IS NOT REFUSED (FR-45). A call made after one that was told
308
804
  * to wait waits too, whatever the rate says now: the client sends
@@ -313,28 +809,13 @@ export function liveProtocol(options) {
313
809
  say(peer, { t: "busy", cid, retryAfter: Math.max(0, peer.held.until - now) });
314
810
  return { cursor: peer.cursor };
315
811
  }
316
- const limited = options.limit
317
- ? await options.limit({
318
- seat: peer.seat,
319
- via: peer.via,
320
- t: message.t,
321
- bytes: bytesOf(text),
322
- calls: message.t === "call" && Array.isArray(message.calls) ? message.calls : [],
323
- })
324
- : undefined;
325
- if (limited && "refuse" in limited) {
326
- delete peer.held;
327
- say(peer, { t: "refused", cid, reason: "limit", sentence: limited.refuse });
328
- return { cursor: peer.cursor };
329
- }
330
- if (limited) {
331
- const retryAfter = Math.max(0, Math.ceil(limited.retryAfter));
332
- peer.held = { cid, until: now + retryAfter };
333
- say(peer, { t: "busy", cid, retryAfter, ...(limited.sentence ? { sentence: limited.sentence } : {}) });
334
- return { cursor: peer.cursor };
335
- }
812
+ const via = viaFor(served, change);
813
+ const bytes = bytesOf(text);
814
+ const limited = await limitOf(seat, via, change, bytes);
815
+ if (limited)
816
+ return sayLimited(peer, cid, limited);
336
817
  delete peer.held;
337
- return answer(peer, message);
818
+ return answer(peer, seat, cid, change, via, bytes);
338
819
  }
339
820
  case "here": {
340
821
  const told = message.presence;
@@ -342,7 +823,8 @@ export function liveProtocol(options) {
342
823
  say(peer, { t: "error", sentence: "A presence is a participant and a stop." });
343
824
  return unchanged();
344
825
  }
345
- const presence = presenceFrom(told, peer.seat, new Date(), peer.participant);
826
+ // Held by this socket: it stands while the socket does, with no heartbeat to keep it.
827
+ const presence = { ...presenceFrom(told, seat, new Date(), peer.participant), held: "socket" };
346
828
  peer.participant = presence.participant;
347
829
  return { ...unchanged(), presence };
348
830
  }
@@ -357,16 +839,109 @@ export function liveProtocol(options) {
357
839
  }
358
840
  },
359
841
  publish(ops, peers) {
360
- for (const peer of peers)
361
- catchUp(peer, ops);
362
- },
363
- tell(who, peers) {
842
+ const sight = aSight();
364
843
  for (const peer of peers) {
365
844
  if (peer.cursor === undefined)
366
845
  continue;
367
- say(peer, { t: "presence", who: wire.whoFor(peer.seat, who.filter((presence) => presence.participant !== peer.participant)) });
846
+ const seat = principalOf(peer, sight);
847
+ if (!seat)
848
+ lost(peer);
849
+ else
850
+ catchUp(peer, ops, seat, sight);
368
851
  }
369
852
  },
853
+ tell(said, peers) {
854
+ const sight = aSight();
855
+ const all = [...peers];
856
+ const who = heldBySockets(said, all);
857
+ for (const peer of all) {
858
+ if (peer.cursor === undefined)
859
+ continue;
860
+ const seat = principalOf(peer, sight);
861
+ if (!seat) {
862
+ lost(peer);
863
+ continue;
864
+ }
865
+ say(peer, { t: "presence", who: wire.whoFor(seat, who.filter((presence) => presence.participant !== peer.participant)) });
866
+ }
867
+ },
868
+ async post(text, asked) {
869
+ const said = answering(asked);
870
+ let body;
871
+ try {
872
+ body = text.length === 0 ? {} : JSON.parse(text);
873
+ }
874
+ catch {
875
+ return reply(400, { error: "A change is one JSON object: { calls } to make, or { undo } to take back.", reason: "invalid" });
876
+ }
877
+ if (!body || typeof body !== "object")
878
+ return reply(400, { error: "A change is one JSON object: { calls } to make, or { undo } to take back.", reason: "invalid" });
879
+ const undo = Array.isArray(body.undo) ? body.undo : undefined;
880
+ const change = {
881
+ t: undo ? "undo" : "call",
882
+ calls: !undo && Array.isArray(body.calls) ? body.calls : [],
883
+ batches: undo ?? [],
884
+ intent: typeof body.intent === "string" && body.intent.length > 0 ? body.intent : undefined,
885
+ batch: body.batch,
886
+ base: undo ? undefined : body.base,
887
+ claimed: claimOfVia(body.via),
888
+ };
889
+ const via = viaFor({ seat: asked.seat, via: asked.via, ...(asked.build ? { hostBuild: asked.build } : {}) }, change);
890
+ // Sent again after its answer was lost — or offered again on a new declaration, or after a reload (FR-43, FR-44, FR-49): only ever the asker's own ops.
891
+ const claim = wire.claim(change.batch, asked.seat);
892
+ if (claim.refusal)
893
+ return reply(409, { error: claim.refusal.sentence, refused: true, reason: claim.refusal.reason, ...said });
894
+ if (claim.answered) {
895
+ // Landed, but a flush failed it: flushed again, and answered only once it holds.
896
+ if (unsavedIn(claim.answered)) {
897
+ const flushed = await durable([]);
898
+ if (!("saved" in flushed))
899
+ return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
900
+ return { ...reply(200, { ops: wire.shown(asked.seat, claim.answered), batch: change.batch, ...said }), landed: flushed.saved };
901
+ }
902
+ return reply(200, { ops: wire.shown(asked.seat, claim.answered), batch: change.batch, ...said });
903
+ }
904
+ /*
905
+ * THE HOST'S LIMITS, BEFORE ANYTHING IS JUDGED. Busy is 429 and the
906
+ * change is kept to send again (FR-45); a hard cap is refused, `limit`,
907
+ * and the change is taken back (FR-46); unavailable is 503, kept.
908
+ */
909
+ const bytes = bytesOf(text);
910
+ const limited = await limitOf(asked.seat, via, change, bytes);
911
+ if (limited)
912
+ return limitedReply(limited, said);
913
+ const landing = await land(asked.seat, via, change, bytes);
914
+ // What it would do is over the host's caps (its `admit`): nothing was kept.
915
+ if (landing.limited)
916
+ return limitedReply(landing.limited, said);
917
+ // A stale write is a conflict, not a loss (FR-05): theirs and yours, by name, and nothing written.
918
+ if (landing.conflicts)
919
+ return reply(409, { error: conflictSentence(landing.conflicts), refused: true, conflict: true, conflicts: landing.conflicts, ...said });
920
+ // The policy's own sentence rather than a bare 403, because that sentence is the product.
921
+ if (landing.refusal) {
922
+ const { sentence, ...why } = landing.refusal;
923
+ return reply(409, { error: sentence, refused: true, ...why, ...said });
924
+ }
925
+ // Not durable: refused `unavailable`, which the client keeps and sends again.
926
+ if (!landing.saved)
927
+ return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
928
+ // An act may make what its own seat may not see: that op goes back withheld, as it would on a poll.
929
+ return { ...reply(200, { ops: wire.shown(asked.seat, landing.result.ops), batch: landing.result.batch, ...said }), landed: landing.saved };
930
+ },
931
+ state(asked) {
932
+ const seen = wire.seenFor(asked.seat);
933
+ return reply(200, {
934
+ ...answering(asked),
935
+ snapshot: seen.snapshot(),
936
+ log: wire.seenLog(asked.seat),
937
+ migrated: [...(options.migrated ?? [])],
938
+ enabledModules: wire.enabledModules(),
939
+ ...wire.horizonOf(),
940
+ });
941
+ },
942
+ since(seq, asked) {
943
+ return reply(200, { ops: wire.since(asked.seat, seq), ...answering(asked) });
944
+ },
370
945
  declared(peers) {
371
946
  for (const peer of peers) {
372
947
  if (peer.cursor === undefined)