@agentshouse/mdruntime 0.1.0-cd4f72ad5c517 → 0.1.0-cde2b99d2fcbc

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.
Files changed (166) hide show
  1. package/AGENTS.md +113 -33
  2. package/README.md +20 -10
  3. package/dist/adapter.d.ts +48 -14
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/attached-model.d.ts.map +1 -1
  6. package/dist/attached-model.js +15 -2
  7. package/dist/attempt.d.ts +16 -0
  8. package/dist/attempt.d.ts.map +1 -0
  9. package/dist/attempt.js +57 -0
  10. package/dist/binary.d.ts +23 -0
  11. package/dist/binary.d.ts.map +1 -0
  12. package/dist/binary.js +8 -0
  13. package/dist/bootstrap.d.ts +17 -5
  14. package/dist/bootstrap.d.ts.map +1 -1
  15. package/dist/bootstrap.js +88 -38
  16. package/dist/change-set.d.ts.map +1 -1
  17. package/dist/change-set.js +19 -12
  18. package/dist/change.d.ts +15 -0
  19. package/dist/change.d.ts.map +1 -1
  20. package/dist/change.js +26 -1
  21. package/dist/chat/acts.d.ts +34 -0
  22. package/dist/chat/acts.d.ts.map +1 -0
  23. package/dist/chat/acts.js +36 -0
  24. package/dist/chat/context.d.ts +3 -0
  25. package/dist/chat/context.d.ts.map +1 -0
  26. package/dist/chat/context.js +10 -0
  27. package/dist/chat/input.d.ts +9 -0
  28. package/dist/chat/input.d.ts.map +1 -0
  29. package/dist/chat/input.js +99 -0
  30. package/dist/chat/kit.d.ts +60 -0
  31. package/dist/chat/kit.d.ts.map +1 -0
  32. package/dist/chat/kit.js +123 -0
  33. package/dist/chat/lasting.d.ts +6 -0
  34. package/dist/chat/lasting.d.ts.map +1 -0
  35. package/dist/chat/lasting.js +19 -0
  36. package/dist/chat/list.d.ts +20 -0
  37. package/dist/chat/list.d.ts.map +1 -0
  38. package/dist/chat/list.js +59 -0
  39. package/dist/chat/markdown.d.ts +19 -0
  40. package/dist/chat/markdown.d.ts.map +1 -0
  41. package/dist/chat/markdown.js +187 -0
  42. package/dist/chat/message.d.ts +6 -0
  43. package/dist/chat/message.d.ts.map +1 -0
  44. package/dist/chat/message.js +192 -0
  45. package/dist/chat/messages.d.ts +21 -0
  46. package/dist/chat/messages.d.ts.map +1 -0
  47. package/dist/chat/messages.js +151 -0
  48. package/dist/chat/name.d.ts +6 -0
  49. package/dist/chat/name.d.ts.map +1 -0
  50. package/dist/chat/name.js +37 -0
  51. package/dist/chat/opened.d.ts +11 -0
  52. package/dist/chat/opened.d.ts.map +1 -0
  53. package/dist/chat/opened.js +17 -0
  54. package/dist/chat/overlay.d.ts +31 -0
  55. package/dist/chat/overlay.d.ts.map +1 -0
  56. package/dist/chat/overlay.js +97 -0
  57. package/dist/chat/parts.d.ts +57 -0
  58. package/dist/chat/parts.d.ts.map +1 -0
  59. package/dist/chat/parts.js +119 -0
  60. package/dist/chat/process.d.ts +20 -0
  61. package/dist/chat/process.d.ts.map +1 -0
  62. package/dist/chat/process.js +32 -0
  63. package/dist/chat/provider.d.ts +63 -0
  64. package/dist/chat/provider.d.ts.map +1 -0
  65. package/dist/chat/provider.js +645 -0
  66. package/dist/chat/question.d.ts +9 -0
  67. package/dist/chat/question.d.ts.map +1 -0
  68. package/dist/chat/question.js +80 -0
  69. package/dist/chat/questions.d.ts +31 -0
  70. package/dist/chat/questions.d.ts.map +1 -0
  71. package/dist/chat/questions.js +111 -0
  72. package/dist/chat/read.d.ts +5 -0
  73. package/dist/chat/read.d.ts.map +1 -0
  74. package/dist/chat/read.js +13 -0
  75. package/dist/chat/ready.d.ts +33 -0
  76. package/dist/chat/ready.d.ts.map +1 -0
  77. package/dist/chat/ready.js +91 -0
  78. package/dist/chat/style.d.ts +4 -0
  79. package/dist/chat/style.d.ts.map +1 -0
  80. package/dist/chat/style.js +302 -0
  81. package/dist/chat.d.ts +14 -0
  82. package/dist/chat.d.ts.map +1 -0
  83. package/dist/chat.js +8 -0
  84. package/dist/client.d.ts +14 -5
  85. package/dist/client.d.ts.map +1 -1
  86. package/dist/client.js +65 -15
  87. package/dist/collection.d.ts +6 -11
  88. package/dist/collection.d.ts.map +1 -1
  89. package/dist/collection.js +56 -19
  90. package/dist/connection.d.ts +21 -9
  91. package/dist/connection.d.ts.map +1 -1
  92. package/dist/connection.js +420 -114
  93. package/dist/conversation.d.ts +11 -3
  94. package/dist/conversation.d.ts.map +1 -1
  95. package/dist/conversation.js +47 -7
  96. package/dist/expectation.d.ts +21 -0
  97. package/dist/expectation.d.ts.map +1 -0
  98. package/dist/expectation.js +70 -0
  99. package/dist/failure.d.ts +13 -0
  100. package/dist/failure.d.ts.map +1 -0
  101. package/dist/failure.js +19 -0
  102. package/dist/host.d.ts +1 -0
  103. package/dist/host.d.ts.map +1 -1
  104. package/dist/host.js +9 -8
  105. package/dist/identity.d.ts +3 -0
  106. package/dist/identity.d.ts.map +1 -1
  107. package/dist/identity.js +13 -1
  108. package/dist/index.d.ts +9 -4
  109. package/dist/index.d.ts.map +1 -1
  110. package/dist/index.js +3 -0
  111. package/dist/memory.d.ts +4 -3
  112. package/dist/memory.d.ts.map +1 -1
  113. package/dist/memory.js +60 -20
  114. package/dist/model.d.ts +10 -2
  115. package/dist/model.d.ts.map +1 -1
  116. package/dist/model.js +2 -0
  117. package/dist/open.d.ts +2 -0
  118. package/dist/open.d.ts.map +1 -0
  119. package/dist/open.js +1 -0
  120. package/dist/outcome.d.ts +28 -3
  121. package/dist/outcome.d.ts.map +1 -1
  122. package/dist/outcome.js +41 -1
  123. package/dist/overlay.d.ts +14 -3
  124. package/dist/overlay.d.ts.map +1 -1
  125. package/dist/overlay.js +75 -37
  126. package/dist/query.d.ts +4 -0
  127. package/dist/query.d.ts.map +1 -1
  128. package/dist/query.js +5 -31
  129. package/dist/reach.d.ts +2 -0
  130. package/dist/reach.d.ts.map +1 -1
  131. package/dist/reach.js +43 -19
  132. package/dist/react.d.ts +26 -16
  133. package/dist/react.d.ts.map +1 -1
  134. package/dist/react.js +10 -8
  135. package/dist/read-side.d.ts.map +1 -1
  136. package/dist/read-side.js +9 -2
  137. package/dist/refresh.d.ts +10 -0
  138. package/dist/refresh.d.ts.map +1 -1
  139. package/dist/refresh.js +42 -38
  140. package/dist/replica.d.ts +8 -5
  141. package/dist/replica.d.ts.map +1 -1
  142. package/dist/replica.js +86 -55
  143. package/dist/room-draft.d.ts +26 -9
  144. package/dist/room-draft.d.ts.map +1 -1
  145. package/dist/room-draft.js +132 -23
  146. package/dist/rows.d.ts +5 -1
  147. package/dist/rows.d.ts.map +1 -1
  148. package/dist/rows.js +10 -2
  149. package/dist/save.d.ts +27 -1
  150. package/dist/save.d.ts.map +1 -1
  151. package/dist/save.js +340 -35
  152. package/dist/search.d.ts +3 -2
  153. package/dist/search.d.ts.map +1 -1
  154. package/dist/status.d.ts +2 -2
  155. package/dist/status.d.ts.map +1 -1
  156. package/dist/status.js +0 -8
  157. package/dist/store.d.ts +27 -4
  158. package/dist/store.d.ts.map +1 -1
  159. package/dist/store.js +218 -114
  160. package/dist/wire.d.ts +7 -3
  161. package/dist/wire.d.ts.map +1 -1
  162. package/dist/wire.js +15 -2
  163. package/package.json +17 -9
  164. package/dist/attachment.d.ts +0 -3
  165. package/dist/attachment.d.ts.map +0 -1
  166. package/dist/attachment.js +0 -8
@@ -3,17 +3,22 @@ import { cached, modelTypes, NO_MODEL, sameModel, } from './model.js';
3
3
  import { observing } from './observation.js';
4
4
  import { filterOf, identityOf, planOf, } from './query.js';
5
5
  import { createReadSide } from './read-side.js';
6
+ import { markdownPath, roomOfKey } from './rows.js';
6
7
  import { createSearchIndex, searchPlanOf, } from './search.js';
7
8
  import { bootstrapRoom } from './bootstrap.js';
8
9
  import { changeSet, mergeChangeSets } from './change-set.js';
9
10
  import { createConversationStore, } from './conversation.js';
10
- import { parseCollection, validRoot } from './collection.js';
11
+ import { queuedFile } from './change.js';
12
+ import { validRoot } from './collection.js';
13
+ import { runtimeError } from './failure.js';
11
14
  import { createLog } from './log.js';
15
+ import { binaryRecord } from './binary.js';
16
+ import { absentBinary, binaryAnswer, calledResult, historyAnswer, undeclared, UNCERTAIN, } from './outcome.js';
12
17
  import { refreshRoom } from './refresh.js';
13
- import { buildBatch } from './save.js';
14
- import { applyReturned, compositionOf, landed, readConfirmed, readReclassified, replicaOf, sameMembership, withdrawals, } from './replica.js';
15
- import { changedParts, changesOf, held, readParts, returnedInto, underneath, } from './room-draft.js';
16
- import { settled, same, saving, STARTING, transferring, } from './status.js';
18
+ import { buildBatch, joined, limitedIn, requeued } from './save.js';
19
+ import { applyReturned, compositionOf, confirmedOf, landed, readReclassified, replicaOf, sameMembership, withdrawals, } from './replica.js';
20
+ import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, readParts, returnedBy, returnedInto, staleWrite, underneath, withdrawnDrafts, } from './room-draft.js';
21
+ import { same, saving, STARTING, transferring, } from './status.js';
17
22
  import { detectStorageLoss, nextGeneration } from './durability.js';
18
23
  import { roomDraftRevision } from './identity.js';
19
24
  import { beneath, normalize } from './paths.js';
@@ -34,6 +39,7 @@ function declaredSelection(room) {
34
39
  selection.roots.every((other, at) => at === index || !within(other, root)));
35
40
  }
36
41
  export function composeRuntime(options) {
42
+ const localSaves = options.adapter.localSaves === true;
37
43
  let authorization = options.authorization;
38
44
  let opening;
39
45
  let store;
@@ -44,6 +50,7 @@ export function composeRuntime(options) {
44
50
  let limits = [];
45
51
  let capabilities = [];
46
52
  const rooms = new Map();
53
+ const counted = new Map();
47
54
  const unreadable = new Set();
48
55
  const models = new Map();
49
56
  const liveModels = new Map();
@@ -82,6 +89,8 @@ export function composeRuntime(options) {
82
89
  let withdrawStream;
83
90
  const announced = new Map();
84
91
  let underway = null;
92
+ let streamed = null;
93
+ let handed = false;
85
94
  const submitting = new Map();
86
95
  const answering = new Map();
87
96
  let complete = false;
@@ -104,9 +113,14 @@ export function composeRuntime(options) {
104
113
  let haltedRefusal = false;
105
114
  let openSignals = 0;
106
115
  const serviceModeListeners = new Set();
116
+ let member = null;
117
+ const memberListeners = new Set();
118
+ const materialized = new Set();
119
+ let everyRoom = false;
120
+ const transfers = new Map();
107
121
  const conversations = createConversationStore({
108
122
  agents: declaredAgents,
109
- documents: (locator) => readSide.query(planOf({ rooms: [locator], select: 'all' }, roomFacts())),
123
+ documents: (locator) => rowsQuery(planOf({ rooms: [locator], select: 'all' }, roomFacts())),
110
124
  call: (name, input) => invokeAction(name, input),
111
125
  durably,
112
126
  stream: () => options.adapter.conversations,
@@ -182,7 +196,7 @@ export function composeRuntime(options) {
182
196
  }
183
197
  }
184
198
  function pending() {
185
- return [...replicas.values()].some((replica) => replica.queue.length > 0);
199
+ return !localSaves && [...replicas.values()].some((replica) => replica.queue.length > 0);
186
200
  }
187
201
  function attention() {
188
202
  const attentionRequired = [];
@@ -211,8 +225,24 @@ export function composeRuntime(options) {
211
225
  }
212
226
  return { attentionRequired, reset };
213
227
  }
228
+ function documentsIn(locator) {
229
+ const replica = replicas.get(locator);
230
+ if (replica === undefined)
231
+ return 0;
232
+ const roots = replica.confirmed.record.typedSelection?.roots ?? [];
233
+ let count = 0;
234
+ for (const path of Object.keys(replica.visible.documents)) {
235
+ if (markdownPath(path) && !roots.some((root) => beneath(root, path)))
236
+ count += 1;
237
+ }
238
+ return count;
239
+ }
214
240
  function listed() {
215
- return structuredClone([...rooms.values()]);
241
+ return structuredClone([...rooms.values()].map((room) => {
242
+ const documents = documentsIn(room.locator);
243
+ counted.set(room.locator, documents);
244
+ return { ...room, documents };
245
+ }));
216
246
  }
217
247
  function roomFacts(reach = null) {
218
248
  const held = [...rooms.values()]
@@ -244,6 +274,10 @@ export function composeRuntime(options) {
244
274
  for (const listener of storageLossListeners)
245
275
  listener(storageLoss);
246
276
  }
277
+ function emitMember() {
278
+ for (const listener of memberListeners)
279
+ listener(member);
280
+ }
247
281
  function moveTo(next) {
248
282
  if (closed)
249
283
  return;
@@ -263,6 +297,8 @@ export function composeRuntime(options) {
263
297
  listener(shown);
264
298
  }
265
299
  function entryOf(batch) {
300
+ if (localSaves)
301
+ return Object.freeze({ batch, state: 'local' });
266
302
  const state = pendings.get(batch.id);
267
303
  if (state?.accepted !== undefined) {
268
304
  return Object.freeze({ batch, state: 'accepted', roomVersion: state.accepted });
@@ -283,12 +319,47 @@ export function composeRuntime(options) {
283
319
  }
284
320
  }
285
321
  function applyChangeSet(set) {
322
+ const held = everyRoom
323
+ ? set
324
+ : { ...set, documents: set.documents.filter(({ locator }) => materialized.has(locator)) };
325
+ readSide.apply(held);
326
+ searchIndex.changed(held);
327
+ }
328
+ function materialize(locators) {
329
+ if (everyRoom)
330
+ return;
331
+ if (locators === null)
332
+ everyRoom = true;
333
+ const sets = [];
334
+ for (const locator of locators ?? [...replicas.keys()]) {
335
+ if (materialized.has(locator))
336
+ continue;
337
+ materialized.add(locator);
338
+ const replica = replicas.get(locator);
339
+ if (replica !== undefined)
340
+ sets.push(changeSet(locator, null, replica));
341
+ }
342
+ if (sets.length === 0)
343
+ return;
344
+ const set = mergeChangeSets(sets);
286
345
  readSide.apply(set);
287
346
  searchIndex.changed(set);
288
347
  }
348
+ function reachedRooms(plan) {
349
+ if (plan.rooms !== null)
350
+ return plan.rooms;
351
+ if (plan.reach === null)
352
+ return null;
353
+ return [...plan.reach.rooms, ...plan.reach.documents.map(roomOfKey)];
354
+ }
355
+ function rowsQuery(plan) {
356
+ materialize(reachedRooms(plan));
357
+ return readSide.query(plan);
358
+ }
289
359
  function publishChangeSet(set) {
290
360
  applyChangeSet(set);
291
- if (set.rooms.length > 0)
361
+ if (set.rooms.length > 0 ||
362
+ [...new Set(set.documents.map(({ locator }) => locator))].some((locator) => rooms.has(locator) && counted.get(locator) !== documentsIn(locator)))
292
363
  emitRooms();
293
364
  for (const locator of set.queues)
294
365
  emitQueue(locator);
@@ -362,10 +433,7 @@ export function composeRuntime(options) {
362
433
  model: revoked,
363
434
  selectionModel: revoked,
364
435
  };
365
- const read = readConfirmed(record, before.confirmed);
366
- replicas.set(locator, read.kind === 'staged'
367
- ? replicaOf(read.confirmed, before.queue, before)
368
- : { ...before, confirmed: { ...before.confirmed, record } });
436
+ replicas.set(locator, replicaOf(confirmedOf(record, before.confirmed), before.queue, before));
369
437
  }
370
438
  rooms.set(locator, {
371
439
  ...room,
@@ -382,7 +450,8 @@ export function composeRuntime(options) {
382
450
  }
383
451
  finally {
384
452
  refusal = {
385
- reason,
453
+ code: reason,
454
+ retryable: false,
386
455
  reauthorizationOffered: reason === 'revoked-authorization',
387
456
  refusal: provider,
388
457
  };
@@ -407,7 +476,6 @@ export function composeRuntime(options) {
407
476
  },
408
477
  providerOwnedPaths: room.providerOwnedPaths,
409
478
  roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,
410
- attachments: replicas.get(room.locator)?.confirmed.record.attachments ?? [],
411
479
  synchronizationAvailable,
412
480
  refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,
413
481
  });
@@ -432,7 +500,7 @@ export function composeRuntime(options) {
432
500
  emitRooms();
433
501
  }
434
502
  function unlistedHeld(listed) {
435
- return [...new Set([...rooms.keys(), ...roomDrafts.keys()])].filter((locator) => !listed.has(locator));
503
+ return [...new Set([...rooms.keys(), ...roomDrafts.keys(), ...transfers.keys()])].filter((locator) => !listed.has(locator));
436
504
  }
437
505
  async function dropUnlisted(listed, local) {
438
506
  if (unlistedHeld(listed).length === 0)
@@ -451,6 +519,7 @@ export function composeRuntime(options) {
451
519
  replicas.delete(locator);
452
520
  rooms.delete(locator);
453
521
  roomDrafts.delete(locator);
522
+ transfers.delete(locator);
454
523
  unreadable.delete(locator);
455
524
  stale.delete(locator);
456
525
  scopedRefusals.delete(locator);
@@ -487,7 +556,7 @@ export function composeRuntime(options) {
487
556
  return model;
488
557
  }
489
558
  async function hydrate(opened) {
490
- const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named] = await Promise.all([
559
+ const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named, known, staged,] = await Promise.all([
491
560
  opened.all(),
492
561
  opened.queues(),
493
562
  opened.roomDrafts(),
@@ -497,9 +566,15 @@ export function composeRuntime(options) {
497
566
  opened.lastCompleted(),
498
567
  opened.providerLimits(),
499
568
  opened.capabilities(),
569
+ opened.member(),
570
+ opened.transfers(),
500
571
  ]);
572
+ transfers.clear();
573
+ for (const record of staged)
574
+ transfers.set(record.locator, record);
501
575
  limits = declared;
502
576
  capabilities = named;
577
+ member = known;
503
578
  roomDrafts.clear();
504
579
  for (const record of kept)
505
580
  rememberRoomDraft(record);
@@ -519,14 +594,7 @@ export function composeRuntime(options) {
519
594
  const model = restored(modelKey(record.locator, 'collection'), record.model);
520
595
  const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
521
596
  const prior = previousReplicas.get(record.locator);
522
- const retyped = { ...record, model, selectionModel };
523
- const read = readConfirmed(retyped, prior?.confirmed);
524
- const confirmed = read.kind === 'staged'
525
- ? read.confirmed
526
- : {
527
- record: retyped,
528
- collection: parseCollection(retyped.documents, compositionOf(retyped)),
529
- };
597
+ const confirmed = confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
530
598
  replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? [], prior));
531
599
  const existing = rooms.get(record.locator);
532
600
  if (existing === undefined)
@@ -535,7 +603,6 @@ export function composeRuntime(options) {
535
603
  rooms.set(record.locator, {
536
604
  ...existing,
537
605
  roomVersion: record.roomVersion,
538
- attachments: record.attachments,
539
606
  operations: record.operations,
540
607
  replica: record.replica,
541
608
  model: modelTypes(model),
@@ -547,10 +614,6 @@ export function composeRuntime(options) {
547
614
  },
548
615
  });
549
616
  }
550
- if (read.kind === 'refused') {
551
- refusedSource(record, read);
552
- declarationRefusals.add(record.locator);
553
- }
554
617
  }
555
618
  return {
556
619
  lastCompleted,
@@ -563,6 +626,8 @@ export function composeRuntime(options) {
563
626
  applyChangeSet(read);
564
627
  if (replicas.size > 0)
565
628
  emitRooms();
629
+ if (member !== null)
630
+ emitMember();
566
631
  for (const locator of locators)
567
632
  emitQueue(locator);
568
633
  publishRoomDrafts(false);
@@ -610,10 +675,14 @@ export function composeRuntime(options) {
610
675
  return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
611
676
  }
612
677
  async function settle(local, locator, before, confirmed, queue, settling = {}) {
613
- const withdrawn = withdrawals(confirmed, queue, withdrawable);
678
+ const withdrawn = withdrawals(confirmed, queue, withdrawable, localSaves);
614
679
  const kept = queue.filter((batch) => !withdrawn.includes(batch));
680
+ const unqueued = withdrawn.map((batch) => ({
681
+ batch,
682
+ returned: localSaves || landed(batch, confirmed) ? null : returnedBy('withdrawn'),
683
+ }));
615
684
  const returning = [
616
- ...withdrawn.map((batch) => ({ batch, returned: { kind: 'withdrawn' } })).reverse(),
685
+ ...[...unqueued].reverse(),
617
686
  ...(settling.leaving === undefined ? [] : [settling.leaving]),
618
687
  ];
619
688
  const written = new Map();
@@ -634,6 +703,7 @@ export function composeRuntime(options) {
634
703
  await local.write({
635
704
  next: confirmed.record,
636
705
  previous: before?.confirmed.record ?? null,
706
+ ...(settling.stored === undefined ? {} : { stored: settling.stored }),
637
707
  queue: kept,
638
708
  previousQueue: before?.queue ?? [],
639
709
  roomDrafts: [...written.values()],
@@ -644,8 +714,10 @@ export function composeRuntime(options) {
644
714
  }
645
715
  for (const record of written.values())
646
716
  rememberRoomDraft(record);
647
- for (const batch of withdrawn)
648
- journal.record(`outcome ${locator} ${batch.id} withdrawn`);
717
+ for (const { batch, returned } of unqueued) {
718
+ const outcome = localSaves ? 'dropped' : returned === null ? 'landed' : 'withdrawn';
719
+ journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
720
+ }
649
721
  replicas.set(locator, replicaOf(confirmed, kept, before));
650
722
  return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {
651
723
  room: settling.room,
@@ -684,7 +756,8 @@ export function composeRuntime(options) {
684
756
  selection: taken(answers?.selection, held.selection, 'typed-selection'),
685
757
  };
686
758
  }
687
- function publish(local, room, confirmed, base) {
759
+ function publish(local, room, confirmed, landing = {}) {
760
+ const { base, stored } = landing;
688
761
  return exclusive(async () => {
689
762
  if (!continuing())
690
763
  return true;
@@ -701,7 +774,9 @@ export function composeRuntime(options) {
701
774
  const accepted = pendings.get(batch.id)?.accepted;
702
775
  return (accepted !== undefined && options.adapter.reached(room.locator, roomVersion, accepted));
703
776
  });
704
- const set = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true });
777
+ const set = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true, ...(stored === undefined ? {} : { stored }) });
778
+ if (stored !== undefined)
779
+ transfers.delete(room.locator);
705
780
  for (const batch of accepted)
706
781
  pendings.delete(batch.id);
707
782
  stale.delete(room.locator);
@@ -720,22 +795,40 @@ export function composeRuntime(options) {
720
795
  const replica = replicas.get(locator);
721
796
  const room = rooms.get(locator);
722
797
  if (replica === undefined || room === undefined) {
723
- throw new Error(`No Local Replica for ${locator}`);
798
+ throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
724
799
  }
725
800
  const saved = [];
726
801
  for (const { path, revision } of named) {
727
802
  const record = roomDrafts.get(locator)?.get(path);
728
803
  if (record === undefined || record.revision !== revision) {
729
- return { outcome: 'refused', rule: 'stale', file: path };
804
+ return { outcome: 'refused', code: 'stale', retryable: false, file: path };
730
805
  }
731
806
  if (!saved.some((draft) => draft.path === path))
732
807
  saved.push({ path, parts: record.parts });
733
808
  }
734
809
  const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
735
810
  if (changed.length > 0)
736
- return { outcome: 'refused', rule: 'changed-underneath', parts: changed };
811
+ return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
737
812
  const parts = saved.map(({ path, parts }) => changesOf(path, parts));
738
- const built = buildBatch({
813
+ const changes = parts.flatMap(({ changes }) => changes);
814
+ const requeue = requeued(replica.queue, changes, replica.visible, withdrawable, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
815
+ if (requeue.kind === 'refused')
816
+ return { outcome: 'refused', ...requeue.refusal };
817
+ const foreign = [...requeue.withdrawn.keys()].some((origin) => {
818
+ const writer = replica.queue.find((batch) => batch.id === origin)?.writtenBy;
819
+ return writer?.app !== writtenBy?.app || writer?.release !== writtenBy?.release;
820
+ });
821
+ if (foreign) {
822
+ return {
823
+ outcome: 'refused',
824
+ code: 'unknown-revision',
825
+ retryable: false,
826
+ file: [...requeue.queued].at(-1),
827
+ };
828
+ }
829
+ const withdrawing = requeue.withdrawn.size > 0;
830
+ const input = {
831
+ local: localSaves,
739
832
  baseRoomVersion: replica.confirmed.record.roomVersion,
740
833
  composition: compositionFor(replica.confirmed.record),
741
834
  operations: room.operations,
@@ -743,13 +836,67 @@ export function composeRuntime(options) {
743
836
  providerLimits: limits,
744
837
  handle: room.handle,
745
838
  visible: replica.visible,
746
- changes: parts.flatMap(({ changes }) => changes),
839
+ changes,
747
840
  bases: parts.flatMap(({ bases }) => bases),
748
841
  writtenBy,
842
+ };
843
+ const checked = withdrawing ? buildBatch({ ...input, queued: requeue.queued }) : null;
844
+ if (checked?.kind === 'refused')
845
+ return { outcome: 'refused', ...checked.refusal };
846
+ const owners = [...requeue.owners].flatMap((origin) => {
847
+ const batch = requeue.withdrawn.get(origin);
848
+ return batch === undefined || batch === null ? [] : [{ origin, batch }];
749
849
  });
750
- if (built.kind === 'refused')
850
+ if (owners.length > 1) {
851
+ return {
852
+ outcome: 'refused',
853
+ code: 'unknown-revision',
854
+ retryable: false,
855
+ file: [...requeue.queued].at(-1),
856
+ };
857
+ }
858
+ const built = !withdrawing
859
+ ? buildBatch(input)
860
+ : requeue.changes.length === 0
861
+ ? null
862
+ : buildBatch({
863
+ ...input,
864
+ visible: replicaOf(replica.confirmed, requeue.queue, replica).visible,
865
+ changes: requeue.changes,
866
+ });
867
+ if (built?.kind === 'refused')
751
868
  return { outcome: 'refused', ...built.refusal };
752
- const batches = [...replica.queue, built.batch];
869
+ const [owner] = owners;
870
+ const join = built === null || owner === undefined
871
+ ? null
872
+ : joined(requeue.queue, owner.batch, built.batch);
873
+ if (join?.kind === 'refused')
874
+ return { outcome: 'refused', ...join.refusal };
875
+ const withdrawn = new Map(requeue.withdrawn);
876
+ if (join !== null && owner !== undefined)
877
+ withdrawn.set(owner.origin, join.batch);
878
+ const drafted = new Map();
879
+ for (const [origin, replaced] of withdrawn) {
880
+ if (replaced === null)
881
+ continue;
882
+ const carried = withdrawnDrafts(pendings.get(origin)?.drafts ?? [], changes);
883
+ drafted.set(replaced.id, replaced === join?.batch
884
+ ? [
885
+ ...carried.map((held) => joinedDraft(held, saved)),
886
+ ...saved.filter((draft) => !carried.some((held) => held.path === draft.path)),
887
+ ]
888
+ : carried);
889
+ }
890
+ if (built !== null && join === null)
891
+ drafted.set(built.batch.id, saved);
892
+ const batches = join !== null ? join.queue : built === null ? requeue.queue : [...requeue.queue, built.batch];
893
+ for (const replaced of withdrawn.values()) {
894
+ if (replaced === null || !batches.includes(replaced))
895
+ continue;
896
+ const limited = limitedIn(batches, replaced, limits, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
897
+ if (limited !== null)
898
+ return { outcome: 'refused', ...limited };
899
+ }
753
900
  const consumed = saved.map(({ path }) => path);
754
901
  try {
755
902
  await local.write({
@@ -757,15 +904,20 @@ export function composeRuntime(options) {
757
904
  previous: replica.confirmed.record,
758
905
  queue: batches,
759
906
  previousQueue: replica.queue,
760
- saved,
907
+ saved: drafted,
761
908
  consumedRoomDrafts: consumed,
762
909
  });
763
910
  }
764
911
  catch {
765
- return { outcome: 'refused', rule: 'durable-write' };
912
+ return { outcome: 'refused', code: 'durable-write', retryable: true };
766
913
  }
767
- pendings.set(built.batch.id, { drafts: saved, submission: { state: 'waiting' }, lost: false });
768
- recorded = false;
914
+ for (const origin of withdrawn.keys())
915
+ pendings.delete(origin);
916
+ for (const [id, drafts] of drafted) {
917
+ pendings.set(id, { drafts, submission: { state: 'waiting' }, lost: false });
918
+ }
919
+ if (!localSaves)
920
+ recorded = false;
769
921
  for (const path of consumed)
770
922
  forgetRoomDraft(locator, path);
771
923
  replicas.set(locator, replicaOf(replica.confirmed, batches, replica));
@@ -773,9 +925,12 @@ export function composeRuntime(options) {
773
925
  queue: true,
774
926
  drafts: consumed,
775
927
  }));
776
- moveTo({ ...saving(status), ...attention() });
928
+ moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
777
929
  submitLater(locator);
778
- return { outcome: 'saved', identifier: built.batch.id };
930
+ const identifier = join?.batch.id ??
931
+ built?.batch.id ??
932
+ [...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
933
+ return { outcome: 'saved', identifier };
779
934
  }
780
935
  async function mark(local, locator, identifier, submission, lost) {
781
936
  const state = pendings.get(identifier);
@@ -801,16 +956,15 @@ export function composeRuntime(options) {
801
956
  }
802
957
  async function readHistory(locator, path, query = {}) {
803
958
  if (closed || refusal !== null)
804
- return { kind: 'transport-uncertainty' };
959
+ return UNCERTAIN;
805
960
  try {
806
961
  await ensureAuthorization();
807
962
  }
808
963
  catch {
809
- return { kind: 'transport-uncertainty' };
810
- }
811
- if (closed || authorization === undefined || refusal !== null) {
812
- return { kind: 'transport-uncertainty' };
964
+ return UNCERTAIN;
813
965
  }
966
+ if (closed || authorization === undefined || refusal !== null)
967
+ return UNCERTAIN;
814
968
  const transfer = ['transfer', 'history', locator, path];
815
969
  if (query.revision !== undefined)
816
970
  transfer.push(query.revision);
@@ -832,12 +986,96 @@ export function composeRuntime(options) {
832
986
  }
833
987
  if (result.kind === 'revoked-authorization')
834
988
  await refuse('revoked-authorization');
835
- return result;
989
+ return historyAnswer(result);
836
990
  }
837
991
  catch {
838
992
  journal.record('outcome history transport-uncertainty');
839
- return { kind: 'transport-uncertainty' };
993
+ return UNCERTAIN;
994
+ }
995
+ }
996
+ function queuedBlob(locator, path, localId) {
997
+ for (const batch of replicas.get(locator)?.queue ?? []) {
998
+ const change = batch.changes[queuedFile(batch, path, localId)];
999
+ if (change?.kind === 'binary')
1000
+ return change.blob;
1001
+ }
1002
+ return null;
1003
+ }
1004
+ async function readBinary(request) {
1005
+ if (closed || refusal !== null)
1006
+ return UNCERTAIN;
1007
+ try {
1008
+ await ensureAuthorization();
1009
+ }
1010
+ catch {
1011
+ return UNCERTAIN;
1012
+ }
1013
+ if (closed || authorization === undefined || refusal !== null)
1014
+ return UNCERTAIN;
1015
+ journal.record(request.kind === 'path'
1016
+ ? `transfer binary ${request.locator} ${request.path}`
1017
+ : `transfer binary ${request.fileRef}`);
1018
+ try {
1019
+ const result = await options.adapter.binary(authorization, request);
1020
+ journal.record(`outcome binary ${result.kind}`);
1021
+ if (result.kind === 'scoped-refusal') {
1022
+ const room = replicas.get(result.locator)?.confirmed.record;
1023
+ if (room !== undefined)
1024
+ await scoped(result, room, await openLocal());
1025
+ }
1026
+ if (result.kind === 'revoked-authorization')
1027
+ await refuse('revoked-authorization');
1028
+ return binaryAnswer(result);
840
1029
  }
1030
+ catch {
1031
+ journal.record('outcome binary transport-uncertainty');
1032
+ return UNCERTAIN;
1033
+ }
1034
+ }
1035
+ async function readBinaryPath(locator, path, revision) {
1036
+ await ready;
1037
+ if (revision !== undefined)
1038
+ return readBinary({ kind: 'path', locator, path, revision });
1039
+ const visible = replicas.get(locator)?.visible;
1040
+ const held = visible?.binaries[path];
1041
+ if (visible === undefined || held === undefined)
1042
+ return absentBinary(path);
1043
+ if (held.state === 'pending') {
1044
+ const blob = queuedBlob(locator, path, held.localId);
1045
+ return blob === null ? absentBinary(path) : { kind: 'binary', blob };
1046
+ }
1047
+ const record = binaryRecord(path, held, visible.revisions[path]);
1048
+ if (record.state !== 'accepted')
1049
+ return absentBinary(path);
1050
+ const replica = replicas.get(locator);
1051
+ const queued = (replica?.queue ?? []).flatMap((batch) => batch.changes);
1052
+ const holds = (at) => {
1053
+ const kept = replica?.confirmed.record.binaries[at];
1054
+ return (kept?.state === 'accepted' &&
1055
+ kept.fileRef === record.fileRef &&
1056
+ replica?.confirmed.record.revisions[at] === record.revision);
1057
+ };
1058
+ let confirmed = path;
1059
+ for (let index = queued.length - 1; index >= 0 && !holds(confirmed); index -= 1) {
1060
+ const change = queued[index];
1061
+ if (change.kind === 'move' && change.to === confirmed)
1062
+ confirmed = change.path;
1063
+ }
1064
+ return readBinary({
1065
+ kind: 'path',
1066
+ locator,
1067
+ path: confirmed,
1068
+ revision: record.revision,
1069
+ fileRef: record.fileRef,
1070
+ });
1071
+ }
1072
+ async function readBinaryReference(reference) {
1073
+ await ready;
1074
+ return readBinary({
1075
+ kind: 'reference',
1076
+ fileRef: reference.fileRef,
1077
+ referrer: reference.referrer,
1078
+ });
841
1079
  }
842
1080
  function declaredAgents() {
843
1081
  for (const capability of capabilities) {
@@ -858,18 +1096,17 @@ export function composeRuntime(options) {
858
1096
  async function invokeAction(name, input) {
859
1097
  await ready;
860
1098
  if (closed || refusal !== null)
861
- return { kind: 'transport-uncertainty' };
1099
+ return UNCERTAIN;
862
1100
  if (declaredAction(name) === undefined)
863
- return { kind: 'undeclared' };
1101
+ return undeclared(name);
864
1102
  try {
865
1103
  await ensureAuthorization();
866
1104
  }
867
1105
  catch {
868
- return { kind: 'transport-uncertainty' };
869
- }
870
- if (closed || authorization === undefined || refusal !== null) {
871
- return { kind: 'transport-uncertainty' };
1106
+ return UNCERTAIN;
872
1107
  }
1108
+ if (closed || authorization === undefined || refusal !== null)
1109
+ return UNCERTAIN;
873
1110
  journal.record(`transfer action ${name}`);
874
1111
  try {
875
1112
  const result = await options.adapter.action(authorization, { name, input });
@@ -883,11 +1120,11 @@ export function composeRuntime(options) {
883
1120
  journal.record(`outcome action ${result.kind}`);
884
1121
  if (result.kind === 'rejected')
885
1122
  journal.record(`refusal rejected ${result.code}`);
886
- return result;
1123
+ return calledResult(result);
887
1124
  }
888
1125
  catch {
889
1126
  journal.record('outcome action transport-uncertainty');
890
- return { kind: 'transport-uncertainty' };
1127
+ return UNCERTAIN;
891
1128
  }
892
1129
  }
893
1130
  function continuing() {
@@ -918,14 +1155,33 @@ export function composeRuntime(options) {
918
1155
  throw error;
919
1156
  }
920
1157
  }
921
- async function pullBootstrap(authorized, room) {
1158
+ function staging(local) {
1159
+ return {
1160
+ held: (locator) => transfers.get(locator) ?? null,
1161
+ staged: (record) => local.staged(record),
1162
+ stage: (record, page) => exclusive(async () => {
1163
+ if (!continuing())
1164
+ return false;
1165
+ await local.stage(record, page);
1166
+ transfers.set(record.locator, record);
1167
+ return true;
1168
+ }),
1169
+ abandon: (locator) => exclusive(async () => {
1170
+ if (!continuing())
1171
+ return;
1172
+ await local.abandon(locator);
1173
+ transfers.delete(locator);
1174
+ }),
1175
+ };
1176
+ }
1177
+ async function pullBootstrap(authorized, room, local) {
922
1178
  if (!continuing())
923
1179
  return unconfirmed;
924
1180
  try {
925
1181
  const result = await bootstrapRoom(options.adapter, authorized, room, {
926
1182
  collection: modelOf(room.locator),
927
1183
  selection: modelOf(room.locator, 'typed-selection'),
928
- }, (models, held) => remodel(room.locator, models, held), continuing);
1184
+ }, (models, held) => remodel(room.locator, models, held), continuing, staging(local));
929
1185
  const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;
930
1186
  journal.record(`transfer bootstrap ${room.locator} ${detail}`);
931
1187
  return result;
@@ -953,7 +1209,7 @@ export function composeRuntime(options) {
953
1209
  return null;
954
1210
  }
955
1211
  if (refreshed.kind === 'advanced') {
956
- if (!(await publish(local, room, refreshed.confirmed, held.confirmed))) {
1212
+ if (!(await publish(local, room, refreshed.confirmed, { base: held.confirmed }))) {
957
1213
  const now = replicas.get(room.locator)?.confirmed.record.roomVersion;
958
1214
  const reached = now !== undefined &&
959
1215
  options.adapter.reached(room.locator, now, refreshed.confirmed.record.roomVersion);
@@ -965,12 +1221,12 @@ export function composeRuntime(options) {
965
1221
  if (refreshed.kind !== 'beyond-horizon')
966
1222
  return refreshed;
967
1223
  }
968
- const bootstrapped = await pullBootstrap(authorized, room);
1224
+ const bootstrapped = await pullBootstrap(authorized, room, local);
969
1225
  if (!continuing())
970
1226
  return unconfirmed;
971
1227
  if (bootstrapped.kind !== 'staged')
972
1228
  return bootstrapped;
973
- await publish(local, room, bootstrapped.confirmed);
1229
+ await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored });
974
1230
  return null;
975
1231
  }
976
1232
  async function withhold(withheld, room, local, progress) {
@@ -1002,6 +1258,7 @@ export function composeRuntime(options) {
1002
1258
  function refusedSource(room, { refusal }) {
1003
1259
  sourceRefusals.set(room.locator, {
1004
1260
  code: refusal.rule,
1261
+ retryable: false,
1005
1262
  fields: {
1006
1263
  file: refusal.file,
1007
1264
  ...(refusal.location === undefined ? {} : { location: refusal.location }),
@@ -1016,8 +1273,16 @@ export function composeRuntime(options) {
1016
1273
  }
1017
1274
  function leaving(batch, result) {
1018
1275
  if (result.kind === 'expired')
1019
- return { batch, returned: { kind: 'expired' } };
1020
- return { batch, returned: { kind: result.kind, code: result.code, fields: result.fields } };
1276
+ return { batch, returned: returnedBy('expired') };
1277
+ return {
1278
+ batch,
1279
+ returned: {
1280
+ kind: result.kind,
1281
+ code: result.code,
1282
+ fields: result.fields,
1283
+ retryable: result.retryable,
1284
+ },
1285
+ };
1021
1286
  }
1022
1287
  function logAccepted(locator, submitted, accepted) {
1023
1288
  journal.record(`outcome ${locator} ${submitted.id} accepted ${accepted.roomVersion}` +
@@ -1035,7 +1300,7 @@ export function composeRuntime(options) {
1035
1300
  logAccepted(room.locator, submitted, accepted);
1036
1301
  const applied = options.adapter.reached(room.locator, held, accepted.roomVersion)
1037
1302
  ? { kind: 'staged', confirmed: current.confirmed }
1038
- : applyReturned(current.confirmed, accepted.documents, accepted.revisions, accepted.removals, accepted.attachments, options.adapter.follows(room.locator, held, accepted.roomVersion)
1303
+ : applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
1039
1304
  ? accepted.roomVersion
1040
1305
  : held, accepted.roomVersion);
1041
1306
  if (applied.kind !== 'staged') {
@@ -1181,7 +1446,8 @@ export function composeRuntime(options) {
1181
1446
  return;
1182
1447
  }
1183
1448
  const set = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
1184
- leaving: result.kind === 'expired' && landed(head, current.confirmed)
1449
+ leaving: (result.kind === 'expired' && landed(head, current.confirmed)) ||
1450
+ (result.kind === 'conflicted' && landed(head, current.confirmed, result.affected))
1185
1451
  ? { ...left, returned: null }
1186
1452
  : left,
1187
1453
  });
@@ -1242,7 +1508,7 @@ export function composeRuntime(options) {
1242
1508
  ...(attached === 'collection' ? { model: next } : { selectionModel: next }),
1243
1509
  };
1244
1510
  const reclassified = sameMembership(declared, held.confirmed.record)
1245
- ? readConfirmed(declared, held.confirmed)
1511
+ ? { kind: 'staged', confirmed: confirmedOf(declared, held.confirmed) }
1246
1512
  : readReclassified(declared, held.confirmed);
1247
1513
  const record = reclassified.kind === 'staged'
1248
1514
  ? declared
@@ -1250,7 +1516,9 @@ export function composeRuntime(options) {
1250
1516
  ...declared,
1251
1517
  typedSelection: held.confirmed.record.typedSelection,
1252
1518
  };
1253
- const read = reclassified.kind === 'deferred' ? readConfirmed(record, held.confirmed) : reclassified;
1519
+ const read = reclassified.kind === 'deferred'
1520
+ ? { kind: 'staged', confirmed: confirmedOf(record, held.confirmed) }
1521
+ : reclassified;
1254
1522
  await local.write({
1255
1523
  next: record,
1256
1524
  previous: held.confirmed.record,
@@ -1282,7 +1550,11 @@ export function composeRuntime(options) {
1282
1550
  });
1283
1551
  }
1284
1552
  async function scoped(result, room, local) {
1285
- scopedRefusals.set(room.locator, { code: result.code, fields: result.fields });
1553
+ scopedRefusals.set(room.locator, {
1554
+ code: result.code,
1555
+ fields: result.fields,
1556
+ retryable: result.retryable,
1557
+ });
1286
1558
  let scopedAway = room;
1287
1559
  if (result.scope === 'model')
1288
1560
  await retainModel(local, room, 'collection', {
@@ -1319,7 +1591,6 @@ export function composeRuntime(options) {
1319
1591
  roomVersion: record.roomVersion,
1320
1592
  documents: record.documents,
1321
1593
  revisions: record.revisions,
1322
- attachments: record.attachments,
1323
1594
  },
1324
1595
  ];
1325
1596
  });
@@ -1330,8 +1601,10 @@ export function composeRuntime(options) {
1330
1601
  const outcome = prepared[index];
1331
1602
  return outcome?.status === 'fulfilled' && outcome.value;
1332
1603
  });
1333
- if (attempt === 'opened')
1604
+ if (attempt === 'opened') {
1334
1605
  options.adapter.roomStream?.hold(heldRooms(ready));
1606
+ handed = true;
1607
+ }
1335
1608
  const loaded = await Promise.allSettled(ready
1336
1609
  .filter((room) => attempt === 'unstreamed' || !replicas.has(room.locator))
1337
1610
  .map((room) => loadRoom(room, local, progress)));
@@ -1397,14 +1670,14 @@ export function composeRuntime(options) {
1397
1670
  async function reload(room, local, progress) {
1398
1671
  if (discoveryPaused || authorization === undefined)
1399
1672
  return;
1400
- const bootstrapped = await pullBootstrap(authorization, room);
1673
+ const bootstrapped = await pullBootstrap(authorization, room, local);
1401
1674
  if (!continuing())
1402
1675
  return;
1403
1676
  if (bootstrapped.kind !== 'staged') {
1404
1677
  await withhold(bootstrapped, room, local, progress);
1405
1678
  return;
1406
1679
  }
1407
- await publish(local, room, bootstrapped.confirmed);
1680
+ await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored });
1408
1681
  await caughtUp(room, local, progress);
1409
1682
  }
1410
1683
  async function discoverRooms(local, progress, attempt) {
@@ -1434,15 +1707,16 @@ export function composeRuntime(options) {
1434
1707
  }
1435
1708
  progress.reachable = false;
1436
1709
  progress.complete = false;
1437
- if (attempt === 'opened') {
1438
- options.adapter.roomStream?.hold(heldRooms([...discovered.values()]));
1439
- }
1440
1710
  notifyReady();
1441
1711
  return;
1442
1712
  }
1443
1713
  if (result.kind === 'contract-unavailable') {
1444
1714
  journal.record(`connection contract unavailable ${result.code}`);
1445
- await refuse('missing-required-guarantee', { code: result.code, fields: result.fields });
1715
+ await refuse('missing-required-guarantee', {
1716
+ code: result.code,
1717
+ fields: result.fields,
1718
+ retryable: result.retryable,
1719
+ });
1446
1720
  notifyReady();
1447
1721
  return;
1448
1722
  }
@@ -1483,6 +1757,12 @@ export function composeRuntime(options) {
1483
1757
  limits = result.providerLimits;
1484
1758
  await local.declare(limits, capabilities);
1485
1759
  }
1760
+ const signedIn = result.member ?? null;
1761
+ if (JSON.stringify(signedIn) !== JSON.stringify(member)) {
1762
+ await local.keepMember(signedIn);
1763
+ member = signedIn;
1764
+ emitMember();
1765
+ }
1486
1766
  await applyDiscovery(result.rooms, local);
1487
1767
  await synchronize(result.rooms, local, progress, attempt);
1488
1768
  }
@@ -1512,9 +1792,12 @@ export function composeRuntime(options) {
1512
1792
  }
1513
1793
  const progress = { complete: true, reachable: true };
1514
1794
  underway = attempt === 'opened' ? progress : null;
1795
+ if (attempt === 'opened')
1796
+ streamed = progress;
1515
1797
  complete = false;
1516
1798
  recorded = false;
1517
1799
  moveTo(transferring(status));
1800
+ handed = false;
1518
1801
  try {
1519
1802
  const local = await openLocal();
1520
1803
  if (closed)
@@ -1526,16 +1809,22 @@ export function composeRuntime(options) {
1526
1809
  }
1527
1810
  catch {
1528
1811
  progress.complete = false;
1529
- if (attempt === 'opened') {
1530
- options.adapter.roomStream?.hold(heldRooms([...discovered.values()]));
1531
- }
1812
+ if (attempt === 'opened' && !handed)
1813
+ progress.reachable = false;
1532
1814
  }
1533
1815
  finally {
1534
1816
  notifyReady();
1535
1817
  }
1536
- if (attempt === 'opened')
1818
+ if (attempt !== 'opened') {
1819
+ await finishOpening(progress);
1537
1820
  return;
1538
- await finishOpening(progress);
1821
+ }
1822
+ if (handed || closed || progress.reachable)
1823
+ return;
1824
+ underway = null;
1825
+ journal.record('connection reopen');
1826
+ await rest(progress);
1827
+ options.adapter.roomStream?.reopen();
1539
1828
  });
1540
1829
  }
1541
1830
  function closedSocket(revoked) {
@@ -1545,9 +1834,14 @@ export function composeRuntime(options) {
1545
1834
  void refuse('revoked-authorization');
1546
1835
  return;
1547
1836
  }
1548
- if (opened || status.providerUnreachable)
1549
- return;
1550
- moveTo({ ...status, providerUnreachable: true });
1837
+ complete = false;
1838
+ if (streamed !== null)
1839
+ streamed.complete = false;
1840
+ moveTo({
1841
+ ...status,
1842
+ state: status.state === 'synced' ? 'syncing' : status.state,
1843
+ providerUnreachable: status.providerUnreachable || !opened,
1844
+ });
1551
1845
  }
1552
1846
  function applyOpening(expired) {
1553
1847
  return task(async () => {
@@ -1602,6 +1896,8 @@ export function composeRuntime(options) {
1602
1896
  }
1603
1897
  }
1604
1898
  function submitLater(locator) {
1899
+ if (localSaves)
1900
+ return;
1605
1901
  const running = submitting.get(locator);
1606
1902
  if (running !== undefined) {
1607
1903
  running.again = true;
@@ -1681,7 +1977,7 @@ export function composeRuntime(options) {
1681
1977
  }
1682
1978
  }
1683
1979
  moveTo({
1684
- state: pending() ? 'pending' : synced ? 'synced' : 'syncing',
1980
+ state: pending() ? 'pending' : synced && complete ? 'synced' : 'syncing',
1685
1981
  lastCompleted,
1686
1982
  providerUnreachable: !progress.reachable,
1687
1983
  ...attention(),
@@ -1790,20 +2086,15 @@ export function composeRuntime(options) {
1790
2086
  show();
1791
2087
  return;
1792
2088
  }
1793
- const resting = status;
1794
- const progress = { complete: false, reachable: !resting.providerUnreachable };
1795
- moveTo(transferring(resting));
2089
+ const progress = { complete: false, reachable: !status.providerUnreachable };
2090
+ moveTo(transferring(status));
1796
2091
  try {
1797
2092
  await conversations.catchUp(progress);
1798
2093
  }
1799
2094
  catch {
1800
2095
  progress.reachable = false;
1801
2096
  }
1802
- finally {
1803
- if (!closed) {
1804
- moveTo(settled(resting, progress, resting.lastCompleted, pending(), attention()));
1805
- }
1806
- }
2097
+ await rest(progress);
1807
2098
  }
1808
2099
  function close() {
1809
2100
  if (closed)
@@ -1825,6 +2116,7 @@ export function composeRuntime(options) {
1825
2116
  storageLossListeners.clear();
1826
2117
  statusListeners.clear();
1827
2118
  serviceModeListeners.clear();
2119
+ memberListeners.clear();
1828
2120
  readSide.close();
1829
2121
  queueSubscriptions.clear();
1830
2122
  roomDraftListeners.clear();
@@ -1856,13 +2148,16 @@ export function composeRuntime(options) {
1856
2148
  return planOf(input, roomFacts(reach), planReach(reach));
1857
2149
  }
1858
2150
  function watchPlan(plan, deliver) {
2151
+ materialize(reachedRooms(plan));
1859
2152
  return readSide.watch(plan, identityOf(plan), deliver);
1860
2153
  }
1861
2154
  async function searched(input, reach) {
1862
2155
  const plan = searchPlanOf(input);
1863
2156
  const selected = plan.documents === undefined && reach === null
1864
2157
  ? null
1865
- : (await readSide.query(filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)))).documents;
2158
+ : (await rowsQuery(filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)))).documents;
2159
+ if (selected === null)
2160
+ materialize(null);
1866
2161
  return searchIndex.search(reach === null || reach.conversations ? plan : { ...plan, conversations: [] }, selected);
1867
2162
  }
1868
2163
  const watch = (topic, input, deliver) => {
@@ -1888,6 +2183,8 @@ export function composeRuntime(options) {
1888
2183
  }
1889
2184
  if (topic === 'conversations')
1890
2185
  return conversations.watchList(deliver);
2186
+ if (topic === 'agents')
2187
+ return conversations.watchAgents(deliver);
1891
2188
  if (topic === 'presentation') {
1892
2189
  const listener = {
1893
2190
  app: input[0],
@@ -1942,6 +2239,13 @@ export function composeRuntime(options) {
1942
2239
  serviceModeListeners.delete(deliver);
1943
2240
  };
1944
2241
  }
2242
+ if (topic === 'member') {
2243
+ memberListeners.add(deliver);
2244
+ deliver(member);
2245
+ return () => {
2246
+ memberListeners.delete(deliver);
2247
+ };
2248
+ }
1945
2249
  if (topic === 'queue') {
1946
2250
  const queue = { locator: input[0], notify: deliver };
1947
2251
  queueSubscriptions.add(queue);
@@ -1959,7 +2263,7 @@ export function composeRuntime(options) {
1959
2263
  rooms() {
1960
2264
  return listed();
1961
2265
  },
1962
- query: ((input) => readSide.query(planned(input, null))),
2266
+ query: ((input) => rowsQuery(planned(input, null))),
1963
2267
  search: (input) => searched(input, null),
1964
2268
  types(locator) {
1965
2269
  return {
@@ -1988,20 +2292,20 @@ export function composeRuntime(options) {
1988
2292
  return exclusive(async () => {
1989
2293
  const parts = readParts(input);
1990
2294
  if (path === '' || normalize(path) !== path)
1991
- throw new Error('room-draft-malformed');
2295
+ throw runtimeError('room-draft-malformed');
1992
2296
  const local = await openLocal();
1993
2297
  const current = roomDrafts.get(room)?.get(path);
1994
2298
  if ((current?.revision ?? null) !== revision) {
1995
- return {
1996
- outcome: 'stale',
1997
- current: current === undefined ? null : roomDraftOf(current),
1998
- };
2299
+ return staleWrite(current === undefined ? null : roomDraftOf(current));
1999
2300
  }
2301
+ const file = parts.file === undefined
2302
+ ? undefined
2303
+ : await heldFile(parts.file.blob, binaryBase(replicas.get(room)?.visible, path));
2000
2304
  const record = {
2001
2305
  locator: room,
2002
2306
  path,
2003
2307
  revision: roomDraftRevision(),
2004
- parts: held(current?.parts, parts),
2308
+ parts: held(current?.parts, parts, file),
2005
2309
  returned: current?.returned ?? null,
2006
2310
  };
2007
2311
  await local.keepRoomDraft(record);
@@ -2015,10 +2319,7 @@ export function composeRuntime(options) {
2015
2319
  const local = await openLocal();
2016
2320
  const current = roomDrafts.get(room)?.get(path);
2017
2321
  if (current === undefined || current.revision !== revision) {
2018
- return {
2019
- outcome: 'stale',
2020
- current: current === undefined ? null : roomDraftOf(current),
2021
- };
2322
+ return staleWrite(current === undefined ? null : roomDraftOf(current));
2022
2323
  }
2023
2324
  await local.discardRoomDraft(room, path);
2024
2325
  forgetRoomDraft(room, path);
@@ -2053,6 +2354,10 @@ export function composeRuntime(options) {
2053
2354
  history(locator, path, query) {
2054
2355
  return readHistory(locator, path, query);
2055
2356
  },
2357
+ binaryFile: {
2358
+ read: readBinaryPath,
2359
+ readReference: readBinaryReference,
2360
+ },
2056
2361
  call(name, input) {
2057
2362
  return invokeAction(name, input);
2058
2363
  },
@@ -2085,8 +2390,9 @@ export function composeRuntime(options) {
2085
2390
  const reachable = {
2086
2391
  md,
2087
2392
  watch,
2393
+ referrerScope: (referrer) => options.adapter.referrerScope(referrer),
2088
2394
  plan: planned,
2089
- query: (plan) => readSide.query(plan),
2395
+ query: (plan) => rowsQuery(plan),
2090
2396
  watchPlan,
2091
2397
  search: searched,
2092
2398
  };