@agentshouse/mdruntime 0.1.0-c30ed2b8e04d5 → 0.1.0-c315a76f079f0

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 (204) hide show
  1. package/AGENTS.md +277 -187
  2. package/README.md +20 -9
  3. package/dist/acquisition.d.ts +14 -0
  4. package/dist/acquisition.d.ts.map +1 -0
  5. package/dist/acquisition.js +24 -0
  6. package/dist/adapter.d.ts +118 -22
  7. package/dist/adapter.d.ts.map +1 -1
  8. package/dist/attached-model.d.ts.map +1 -1
  9. package/dist/attached-model.js +15 -2
  10. package/dist/attempt.d.ts +16 -0
  11. package/dist/attempt.d.ts.map +1 -0
  12. package/dist/attempt.js +70 -0
  13. package/dist/binary.d.ts +23 -0
  14. package/dist/binary.d.ts.map +1 -0
  15. package/dist/binary.js +8 -0
  16. package/dist/bootstrap.d.ts +18 -5
  17. package/dist/bootstrap.d.ts.map +1 -1
  18. package/dist/bootstrap.js +114 -37
  19. package/dist/change-set.d.ts +2 -0
  20. package/dist/change-set.d.ts.map +1 -1
  21. package/dist/change-set.js +49 -16
  22. package/dist/change.d.ts +15 -0
  23. package/dist/change.d.ts.map +1 -1
  24. package/dist/change.js +26 -1
  25. package/dist/chat/acts.d.ts +33 -0
  26. package/dist/chat/acts.d.ts.map +1 -0
  27. package/dist/chat/acts.js +36 -0
  28. package/dist/chat/context.d.ts +3 -0
  29. package/dist/chat/context.d.ts.map +1 -0
  30. package/dist/chat/context.js +10 -0
  31. package/dist/chat/input.d.ts +9 -0
  32. package/dist/chat/input.d.ts.map +1 -0
  33. package/dist/chat/input.js +99 -0
  34. package/dist/chat/kit.d.ts +61 -0
  35. package/dist/chat/kit.d.ts.map +1 -0
  36. package/dist/chat/kit.js +123 -0
  37. package/dist/chat/lasting.d.ts +6 -0
  38. package/dist/chat/lasting.d.ts.map +1 -0
  39. package/dist/chat/lasting.js +19 -0
  40. package/dist/chat/list.d.ts +27 -0
  41. package/dist/chat/list.d.ts.map +1 -0
  42. package/dist/chat/list.js +63 -0
  43. package/dist/chat/markdown.d.ts +20 -0
  44. package/dist/chat/markdown.d.ts.map +1 -0
  45. package/dist/chat/markdown.js +188 -0
  46. package/dist/chat/message.d.ts +6 -0
  47. package/dist/chat/message.d.ts.map +1 -0
  48. package/dist/chat/message.js +192 -0
  49. package/dist/chat/messages.d.ts +22 -0
  50. package/dist/chat/messages.d.ts.map +1 -0
  51. package/dist/chat/messages.js +155 -0
  52. package/dist/chat/name.d.ts +6 -0
  53. package/dist/chat/name.d.ts.map +1 -0
  54. package/dist/chat/name.js +37 -0
  55. package/dist/chat/opened.d.ts +11 -0
  56. package/dist/chat/opened.d.ts.map +1 -0
  57. package/dist/chat/opened.js +17 -0
  58. package/dist/chat/overlay.d.ts +31 -0
  59. package/dist/chat/overlay.d.ts.map +1 -0
  60. package/dist/chat/overlay.js +97 -0
  61. package/dist/chat/parts.d.ts +57 -0
  62. package/dist/chat/parts.d.ts.map +1 -0
  63. package/dist/chat/parts.js +119 -0
  64. package/dist/chat/process.d.ts +20 -0
  65. package/dist/chat/process.d.ts.map +1 -0
  66. package/dist/chat/process.js +32 -0
  67. package/dist/chat/provider.d.ts +63 -0
  68. package/dist/chat/provider.d.ts.map +1 -0
  69. package/dist/chat/provider.js +629 -0
  70. package/dist/chat/question.d.ts +9 -0
  71. package/dist/chat/question.d.ts.map +1 -0
  72. package/dist/chat/question.js +69 -0
  73. package/dist/chat/questions.d.ts +31 -0
  74. package/dist/chat/questions.d.ts.map +1 -0
  75. package/dist/chat/questions.js +111 -0
  76. package/dist/chat/read.d.ts +5 -0
  77. package/dist/chat/read.d.ts.map +1 -0
  78. package/dist/chat/read.js +13 -0
  79. package/dist/chat/ready.d.ts +34 -0
  80. package/dist/chat/ready.d.ts.map +1 -0
  81. package/dist/chat/ready.js +91 -0
  82. package/dist/chat/style.d.ts +4 -0
  83. package/dist/chat/style.d.ts.map +1 -0
  84. package/dist/chat/style.js +302 -0
  85. package/dist/chat.d.ts +14 -0
  86. package/dist/chat.d.ts.map +1 -0
  87. package/dist/chat.js +8 -0
  88. package/dist/client.d.ts +30 -14
  89. package/dist/client.d.ts.map +1 -1
  90. package/dist/client.js +77 -16
  91. package/dist/collection.d.ts +21 -12
  92. package/dist/collection.d.ts.map +1 -1
  93. package/dist/collection.js +271 -23
  94. package/dist/connection.d.ts +50 -17
  95. package/dist/connection.d.ts.map +1 -1
  96. package/dist/connection.js +1955 -424
  97. package/dist/conversation.d.ts +41 -14
  98. package/dist/conversation.d.ts.map +1 -1
  99. package/dist/conversation.js +574 -219
  100. package/dist/durability.d.ts +7 -1
  101. package/dist/durability.d.ts.map +1 -1
  102. package/dist/entry.d.ts +17 -0
  103. package/dist/entry.d.ts.map +1 -0
  104. package/dist/entry.js +156 -0
  105. package/dist/expectation.d.ts +21 -0
  106. package/dist/expectation.d.ts.map +1 -0
  107. package/dist/expectation.js +70 -0
  108. package/dist/failure.d.ts +13 -0
  109. package/dist/failure.d.ts.map +1 -0
  110. package/dist/failure.js +19 -0
  111. package/dist/fence.d.ts +6 -0
  112. package/dist/fence.d.ts.map +1 -0
  113. package/dist/fence.js +10 -0
  114. package/dist/host.d.ts +18 -2
  115. package/dist/host.d.ts.map +1 -1
  116. package/dist/host.js +101 -19
  117. package/dist/identity.d.ts +5 -0
  118. package/dist/identity.d.ts.map +1 -1
  119. package/dist/identity.js +19 -1
  120. package/dist/index.d.ts +16 -8
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js +5 -0
  123. package/dist/memory.d.ts +13 -4
  124. package/dist/memory.d.ts.map +1 -1
  125. package/dist/memory.js +106 -25
  126. package/dist/model.d.ts +17 -10
  127. package/dist/model.d.ts.map +1 -1
  128. package/dist/model.js +16 -4
  129. package/dist/observation.d.ts +5 -2
  130. package/dist/observation.d.ts.map +1 -1
  131. package/dist/observation.js +22 -11
  132. package/dist/open.d.ts +2 -0
  133. package/dist/open.d.ts.map +1 -0
  134. package/dist/open.js +1 -0
  135. package/dist/outcome.d.ts +38 -3
  136. package/dist/outcome.d.ts.map +1 -1
  137. package/dist/outcome.js +45 -1
  138. package/dist/overlay.d.ts +16 -3
  139. package/dist/overlay.d.ts.map +1 -1
  140. package/dist/overlay.js +118 -77
  141. package/dist/paths.d.ts +0 -1
  142. package/dist/paths.d.ts.map +1 -1
  143. package/dist/paths.js +0 -16
  144. package/dist/query.d.ts +40 -4
  145. package/dist/query.d.ts.map +1 -1
  146. package/dist/query.js +82 -35
  147. package/dist/reach.d.ts +8 -3
  148. package/dist/reach.d.ts.map +1 -1
  149. package/dist/reach.js +71 -39
  150. package/dist/react.d.ts +44 -0
  151. package/dist/react.d.ts.map +1 -0
  152. package/dist/react.js +66 -0
  153. package/dist/read-side.d.ts +13 -6
  154. package/dist/read-side.d.ts.map +1 -1
  155. package/dist/read-side.js +394 -129
  156. package/dist/readiness.d.ts +53 -0
  157. package/dist/readiness.d.ts.map +1 -0
  158. package/dist/readiness.js +33 -0
  159. package/dist/reads.d.ts +11 -0
  160. package/dist/reads.d.ts.map +1 -0
  161. package/dist/reads.js +98 -0
  162. package/dist/recovery.d.ts +25 -0
  163. package/dist/recovery.d.ts.map +1 -0
  164. package/dist/recovery.js +197 -0
  165. package/dist/refresh.d.ts +13 -3
  166. package/dist/refresh.d.ts.map +1 -1
  167. package/dist/refresh.js +49 -38
  168. package/dist/replica.d.ts +13 -6
  169. package/dist/replica.d.ts.map +1 -1
  170. package/dist/replica.js +143 -70
  171. package/dist/room-draft.d.ts +38 -9
  172. package/dist/room-draft.d.ts.map +1 -1
  173. package/dist/room-draft.js +134 -25
  174. package/dist/rows.d.ts +11 -14
  175. package/dist/rows.d.ts.map +1 -1
  176. package/dist/rows.js +87 -50
  177. package/dist/save.d.ts +33 -1
  178. package/dist/save.d.ts.map +1 -1
  179. package/dist/save.js +480 -89
  180. package/dist/search.d.ts +39 -8
  181. package/dist/search.d.ts.map +1 -1
  182. package/dist/search.js +132 -46
  183. package/dist/seed.d.ts +16 -0
  184. package/dist/seed.d.ts.map +1 -0
  185. package/dist/seed.js +61 -0
  186. package/dist/shared.d.ts +11 -0
  187. package/dist/shared.d.ts.map +1 -0
  188. package/dist/shared.js +368 -0
  189. package/dist/status.d.ts +6 -2
  190. package/dist/status.d.ts.map +1 -1
  191. package/dist/status.js +0 -8
  192. package/dist/store.d.ts +85 -18
  193. package/dist/store.d.ts.map +1 -1
  194. package/dist/store.js +565 -200
  195. package/dist/turn.d.ts +7 -0
  196. package/dist/turn.d.ts.map +1 -0
  197. package/dist/turn.js +45 -0
  198. package/dist/wire.d.ts +150 -33
  199. package/dist/wire.d.ts.map +1 -1
  200. package/dist/wire.js +64 -31
  201. package/package.json +31 -7
  202. package/dist/attachment.d.ts +0 -3
  203. package/dist/attachment.d.ts.map +0 -1
  204. package/dist/attachment.js +0 -8
@@ -1,25 +1,46 @@
1
1
  import { attachedModel } from './attached-model.js';
2
2
  import { cached, modelTypes, NO_MODEL, sameModel, } from './model.js';
3
- import { observing } from './observation.js';
4
- import { filterOf, identityOf, planOf, } from './query.js';
3
+ import { observing, whole } from './observation.js';
4
+ import { filterOf, identityOf, planOf, plain, queryKey, } from './query.js';
5
5
  import { createReadSide } from './read-side.js';
6
+ import { seededResult } from './seed.js';
7
+ import { markdownPath, roomOfKey } from './rows.js';
6
8
  import { createSearchIndex, searchPlanOf, } from './search.js';
7
9
  import { bootstrapRoom } from './bootstrap.js';
8
- import { changeSet, mergeChangeSets } from './change-set.js';
10
+ import { changeSet, entering, mergeChangeSets } from './change-set.js';
9
11
  import { createConversationStore, } from './conversation.js';
10
- import { parseCollection, validRoot } from './collection.js';
12
+ import { queuedFile } from './change.js';
13
+ import { indexReferrers, referencesIndexed, validRoot, } from './collection.js';
14
+ import { runtimeError } from './failure.js';
11
15
  import { createLog } from './log.js';
16
+ import { binaryRecord } from './binary.js';
17
+ import { absentBinary, binaryAnswer, binaryLinkAnswer, calledResult, failure, historyAnswer, undeclared, UNCERTAIN, } from './outcome.js';
18
+ import { createRecovery } from './recovery.js';
19
+ import { doorReads } from './reads.js';
12
20
  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';
21
+ import { buildBatch, joined, limitedIn, queuedDocuments, requeued, } from './save.js';
22
+ import { applyReturned, compositionOf, confirmedOf, landed, readReclassified, replicaOf, sameMembership, standing, } from './replica.js';
23
+ import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, readParts, returnedBy, returnedInto, staleWrite, underneath, withdrawnDrafts, } from './room-draft.js';
24
+ import { same, saving, STARTING, transferring, } from './status.js';
17
25
  import { detectStorageLoss, nextGeneration } from './durability.js';
18
- import { roomDraftRevision } from './identity.js';
26
+ import { demanded, narrower, WHOLE_DEMAND, wider } from './acquisition.js';
27
+ import { readinessOf, SETTLED_ROOMS, } from './readiness.js';
28
+ import { FencedMap } from './fence.js';
29
+ import { tally } from './shared.js';
30
+ import { inChunks, ROW_WEIGHT, yielded } from './turn.js';
31
+ import { identityTime, roomDraftRevision } from './identity.js';
19
32
  import { beneath, normalize } from './paths.js';
20
33
  import { openRuntimeStore, } from './store.js';
21
34
  import { unconfirmed } from './transfer.js';
22
35
  import { governs, holds, narrowed, planReach, } from './reach.js';
36
+ function roomsAlone(plan) {
37
+ return (plan.reach === null &&
38
+ plan.root.types === null &&
39
+ plan.root.where === null &&
40
+ plan.root.pathPrefix === null &&
41
+ plan.hop === null &&
42
+ plan.backlinks === null);
43
+ }
23
44
  function within(root, path) {
24
45
  return root === '' || beneath(root, path);
25
46
  }
@@ -33,22 +54,68 @@ function declaredSelection(room) {
33
54
  root !== '' &&
34
55
  selection.roots.every((other, at) => at === index || !within(other, root)));
35
56
  }
57
+ const OPENING_LANE = 'opening';
58
+ const CONVERSATION_LANE = 'conversations';
59
+ const ROOM_READS = 256;
60
+ const ROOM_ATTEMPTS = 16;
61
+ function operationOf(input) {
62
+ const operation = input?.operation_id;
63
+ return typeof operation === 'string' ? operation : null;
64
+ }
65
+ const outside = new Map();
66
+ function outsideOf(roots) {
67
+ const key = JSON.stringify(roots);
68
+ const held = outside.get(key);
69
+ if (held !== undefined)
70
+ return held;
71
+ const counted = (path) => (roots.some((root) => beneath(root, path)) ? 0 : 1);
72
+ const made = {
73
+ documents: (path) => (markdownPath(path) ? counted(path) : 0),
74
+ binaries: counted,
75
+ };
76
+ outside.set(key, made);
77
+ return made;
78
+ }
79
+ function abandonedOn(signal) {
80
+ return new Promise((resolve) => {
81
+ if (signal.aborted)
82
+ resolve(null);
83
+ else
84
+ signal.addEventListener('abort', () => resolve(null), { once: true });
85
+ });
86
+ }
87
+ function roomLane(locator) {
88
+ return `room ${locator}`;
89
+ }
36
90
  export function composeRuntime(options) {
91
+ const localSaves = options.adapter.localSaves === true;
37
92
  let authorization = options.authorization;
38
93
  let opening;
39
94
  let store;
40
- const replicas = new Map();
95
+ const fences = new Map();
96
+ const isFenced = (locator) => fences.has(locator);
97
+ let fencings = 0;
98
+ const lastFenced = new Map();
99
+ const fencedSince = (locator, since) => fences.has(locator) || (lastFenced.get(locator) ?? 0) > since;
100
+ let discoveries = 0;
101
+ const replicas = new FencedMap(isFenced);
102
+ const queuesWithoutReplica = new FencedMap(isFenced);
41
103
  const pendings = new Map();
42
- const roomDrafts = new Map();
104
+ const seeds = new Map();
105
+ const seedWatchers = new Map();
106
+ const roomDrafts = new FencedMap(isFenced);
43
107
  const presentations = new Map();
44
108
  let limits = [];
45
109
  let capabilities = [];
46
- const rooms = new Map();
110
+ const rooms = new FencedMap(isFenced);
111
+ const counted = new Map();
47
112
  const unreadable = new Set();
48
- const models = new Map();
49
- const liveModels = new Map();
113
+ const isModelFenced = (key) => isFenced(key.slice(key.indexOf(' ') + 1));
114
+ const models = new FencedMap(isModelFenced);
115
+ const liveModels = new FencedMap(isModelFenced);
50
116
  const invalidModels = new Set();
51
117
  const discovered = new Map();
118
+ const reads = doorReads(options.adapter, (locator) => discovered.get(locator), () => generation);
52
119
  let roomsListed = false;
53
120
  const scopedRefusals = new Map();
54
121
  const sourceRefusals = new Map();
@@ -76,18 +143,29 @@ export function composeRuntime(options) {
76
143
  let status = STARTING;
77
144
  let shown = STARTING;
78
145
  let discoveryPaused = false;
79
- let resetTimer;
80
146
  let closed = false;
81
147
  let stopping = false;
82
148
  let withdrawStream;
83
149
  const announced = new Map();
84
150
  let underway = null;
85
- const submitting = new Map();
151
+ let streamed = null;
152
+ let handed = false;
153
+ const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
154
+ const repairing = new Set();
155
+ const calling = new Set();
156
+ const repairable = new Map();
157
+ let outcomeRetention = null;
86
158
  const answering = new Map();
87
159
  let complete = false;
88
160
  let recorded = false;
89
161
  const stale = new Set();
90
- let chain = Promise.resolve();
162
+ let generation = 0;
163
+ let discovering = null;
164
+ let opened = null;
165
+ const owed = new Set();
166
+ const lanes = new Map();
167
+ let roomReads = { generation, free: ROOM_READS, waiting: [] };
168
+ const working = new Set();
91
169
  let mutations = Promise.resolve();
92
170
  const roomListeners = new Set();
93
171
  const refusalListeners = new Set();
@@ -98,27 +176,49 @@ export function composeRuntime(options) {
98
176
  const presentationListeners = new Set();
99
177
  const readSide = createReadSide();
100
178
  let withdrawConversations;
101
- let currencyQueued = false;
179
+ let currencyQueued = null;
102
180
  let socketOpen = false;
103
181
  let serviceMode = 'open';
104
182
  let haltedRefusal = false;
105
183
  let openSignals = 0;
106
184
  const serviceModeListeners = new Set();
185
+ let member = null;
186
+ const memberListeners = new Set();
187
+ const prepared = new Set();
188
+ const projecting = new Set();
189
+ const unpreparedDemand = new Set();
190
+ const unindexable = new Set();
191
+ let preparing = false;
192
+ let demand = WHOLE_DEMAND;
193
+ let narrowing = null;
194
+ let targets = {};
195
+ let persistence = options.shell.persistence;
196
+ let capacity = null;
197
+ const paused = new Set();
198
+ let rechecking = null;
199
+ const readinessWatches = new Set();
200
+ let readinessQueued = false;
201
+ const catching = new Set();
202
+ const transfers = new FencedMap(isFenced);
107
203
  const conversations = createConversationStore({
108
- cards: declaredCards,
109
- documents: (locator) => readSide.query(planOf({ rooms: [locator], select: 'all' }, roomFacts())),
204
+ agents: declaredAgents,
205
+ documents: ({ locator }) => rowsQuery(planOf({ rooms: [locator], select: { fields: 'all' } }, roomFacts())),
110
206
  call: (name, input) => invokeAction(name, input),
111
207
  durably,
112
208
  stream: () => options.adapter.conversations,
113
209
  publish: publishChangeSet,
210
+ online: () => !status.providerUnreachable && refusal === null,
114
211
  closed: () => closed,
212
+ unanswered: resendLater,
213
+ expired: (operation) => pastHorizon(operation),
115
214
  });
116
215
  const searchIndex = createSearchIndex({
117
- documents: () => readSide.documents(),
216
+ room: (room) => readSide.room(room),
118
217
  document: (room, path) => readSide.document(room, path),
119
- messages: () => conversations.messages(),
120
- message: (conversation, identity) => conversations.message(conversation, identity),
121
218
  });
219
+ const roomsToIndex = new Set();
220
+ const conversationsToIndex = new Set();
221
+ let indexing = false;
122
222
  const journal = createLog();
123
223
  let notifyReady = () => { };
124
224
  const ready = new Promise((resolve) => {
@@ -173,6 +273,15 @@ export function composeRuntime(options) {
173
273
  const value = presentations.get(app);
174
274
  return value === undefined ? null : structuredClone(value);
175
275
  }
276
+ function keepPresentation(app, next) {
277
+ return exclusive(async () => {
278
+ const local = await openLocal();
279
+ const stored = next(presentations.get(app));
280
+ await local.present({ app, value: stored });
281
+ presentations.set(app, stored);
282
+ publishChangeSet(changeSet('', null, null, { presentation: app }));
283
+ });
284
+ }
176
285
  function emitPresentation(app) {
177
286
  if (closed)
178
287
  return;
@@ -182,7 +291,9 @@ export function composeRuntime(options) {
182
291
  }
183
292
  }
184
293
  function pending() {
185
- return [...replicas.values()].some((replica) => replica.queue.length > 0);
294
+ return (!localSaves &&
295
+ (queuesWithoutReplica.size > 0 ||
296
+ [...replicas.values()].some((replica) => replica.queue.length > 0)));
186
297
  }
187
298
  function attention() {
188
299
  const attentionRequired = [];
@@ -195,9 +306,16 @@ export function composeRuntime(options) {
195
306
  returned: structuredClone(record.returned),
196
307
  });
197
308
  }
309
+ for (const [room, refusal] of sourceRefusals)
310
+ attentionRequired.push({ room, refusal: structuredClone(refusal) });
198
311
  attentionRequired.sort((left, right) => {
199
312
  if (left.room !== right.room)
200
313
  return left.room < right.room ? -1 : 1;
314
+ if ('refusal' in left || 'refusal' in right) {
315
+ if ('refusal' in left && 'refusal' in right)
316
+ return 0;
317
+ return 'refusal' in left ? -1 : 1;
318
+ }
201
319
  if (left.path !== right.path)
202
320
  return left.path < right.path ? -1 : 1;
203
321
  return 0;
@@ -211,8 +329,21 @@ export function composeRuntime(options) {
211
329
  }
212
330
  return { attentionRequired, reset };
213
331
  }
332
+ function documentsIn(locator) {
333
+ const replica = replicas.get(locator);
334
+ if (replica === undefined)
335
+ return 0;
336
+ const roots = replica.confirmed.record.typedSelection?.roots ?? [];
337
+ const weighed = outsideOf(roots);
338
+ return (tally(replica.visible.documents, weighed.documents) +
339
+ tally(replica.visible.binaries, weighed.binaries));
340
+ }
214
341
  function listed() {
215
- return structuredClone([...rooms.values()]);
342
+ return structuredClone([...rooms.values()].map((room) => {
343
+ const documents = documentsIn(room.locator);
344
+ counted.set(room.locator, documents);
345
+ return { ...room, documents };
346
+ }));
216
347
  }
217
348
  function roomFacts(reach = null) {
218
349
  const held = [...rooms.values()]
@@ -232,18 +363,26 @@ export function composeRuntime(options) {
232
363
  return { listed: roomsListed, rooms: held };
233
364
  }
234
365
  function emitRooms() {
366
+ readSide.recover();
367
+ queueReadiness();
235
368
  const value = listed();
236
369
  for (const listener of roomListeners)
237
370
  listener(value);
238
371
  }
239
372
  function emitRefusal() {
373
+ queueReadiness();
240
374
  for (const listener of refusalListeners)
241
375
  listener(refusal);
242
376
  }
243
377
  function emitStorageLoss() {
378
+ queueReadiness();
244
379
  for (const listener of storageLossListeners)
245
380
  listener(storageLoss);
246
381
  }
382
+ function emitMember() {
383
+ for (const listener of memberListeners)
384
+ listener(member);
385
+ }
247
386
  function moveTo(next) {
248
387
  if (closed)
249
388
  return;
@@ -253,7 +392,8 @@ export function composeRuntime(options) {
253
392
  function show() {
254
393
  if (closed)
255
394
  return;
256
- const next = status.state === 'synced' && !conversations.current()
395
+ queueReadiness();
396
+ const next = status.state === 'synced' && demand.conversations && !conversations.current()
257
397
  ? { ...status, state: 'syncing' }
258
398
  : status;
259
399
  if (same(shown, next))
@@ -263,6 +403,8 @@ export function composeRuntime(options) {
263
403
  listener(shown);
264
404
  }
265
405
  function entryOf(batch) {
406
+ if (localSaves)
407
+ return Object.freeze({ batch, state: 'local' });
266
408
  const state = pendings.get(batch.id);
267
409
  if (state?.accepted !== undefined) {
268
410
  return Object.freeze({ batch, state: 'accepted', roomVersion: state.accepted });
@@ -270,10 +412,7 @@ export function composeRuntime(options) {
270
412
  return Object.freeze({ batch, ...(state?.submission ?? { state: 'waiting' }) });
271
413
  }
272
414
  function entriesOf(locator) {
273
- const replica = replicas.get(locator);
274
- if (replica === undefined)
275
- return [];
276
- return replica.queue.map(entryOf);
415
+ return (replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? []).map(entryOf);
277
416
  }
278
417
  function emitQueue(locator) {
279
418
  const entries = entriesOf(locator);
@@ -283,12 +422,524 @@ export function composeRuntime(options) {
283
422
  }
284
423
  }
285
424
  function applyChangeSet(set) {
286
- readSide.apply(set);
287
- searchIndex.changed(set);
425
+ const held = {
426
+ ...set,
427
+ documents: set.documents.filter(({ locator }) => prepared.has(locator) || projecting.has(locator)),
428
+ };
429
+ readSide.apply(held);
430
+ searchIndex.changed(held);
431
+ }
432
+ async function referenced(locator) {
433
+ for (;;) {
434
+ const record = replicas.get(locator)?.confirmed.record;
435
+ if (record === undefined || closed)
436
+ return;
437
+ const held = { text: record.documents, binaries: record.binaries };
438
+ const composition = compositionOf(record);
439
+ if (referencesIndexed(held, composition))
440
+ return;
441
+ await indexReferrers(held, composition);
442
+ }
443
+ }
444
+ async function prepareReplica(locator) {
445
+ await referenced(locator);
446
+ const replica = replicas.get(locator);
447
+ if (replica === undefined || closed || prepared.has(locator))
448
+ return;
449
+ const visible = replica.visible;
450
+ const paths = [
451
+ ...new Set([...Object.keys(visible.documents), ...Object.keys(visible.binaries)]),
452
+ ];
453
+ const entered = [];
454
+ projecting.add(locator);
455
+ try {
456
+ await inChunks(paths, (path) => ROW_WEIGHT + (visible.documents[path]?.length ?? 0), (chunk) => {
457
+ const current = replicas.get(locator);
458
+ if (current === undefined || closed)
459
+ return;
460
+ const set = entering(locator, current, chunk);
461
+ readSide.apply(set);
462
+ entered.push(set);
463
+ });
464
+ if (!replicas.has(locator) || closed)
465
+ return;
466
+ prepared.add(locator);
467
+ }
468
+ finally {
469
+ projecting.delete(locator);
470
+ }
471
+ conversations.changed(mergeChangeSets(entered));
472
+ readSide.recover();
473
+ queueReadiness();
474
+ }
475
+ function unprepared() {
476
+ return [...unpreparedDemand, ...replicas.keys()].find((locator) => !prepared.has(locator) && !unindexable.has(locator));
477
+ }
478
+ function unbuilt(locator, error) {
479
+ unindexable.add(locator);
480
+ journal.record(`index failed ${locator} ${error instanceof Error ? error.name : 'unknown'}`);
481
+ queueReadiness();
482
+ }
483
+ function prepare(locators = []) {
484
+ for (const locator of locators)
485
+ unpreparedDemand.add(locator);
486
+ if (preparing)
487
+ return;
488
+ preparing = true;
489
+ void (async () => {
490
+ try {
491
+ for (let waiting = unprepared(); waiting !== undefined; waiting = unprepared()) {
492
+ await yielded();
493
+ if (closed)
494
+ return;
495
+ unpreparedDemand.delete(waiting);
496
+ await prepareReplica(waiting).catch((error) => unbuilt(waiting, error));
497
+ }
498
+ }
499
+ finally {
500
+ preparing = false;
501
+ }
502
+ })();
503
+ }
504
+ function reachedRooms(plan) {
505
+ const reach = plan.reach;
506
+ const reached = reach === null ? null : new Set([...reach.rooms, ...reach.documents.map(roomOfKey)]);
507
+ const named = plan.rooms ??
508
+ (reached === null
509
+ ? [...new Set([...rooms.keys(), ...replicas.keys(), ...queuesWithoutReplica.keys()])]
510
+ : [...reached]);
511
+ return [...new Set(named)].filter((locator) => reached === null || reached.has(locator)).sort();
512
+ }
513
+ function awaited(locator) {
514
+ return (!roomsListed ||
515
+ (rooms.has(locator) && discovered.get(locator)?.replica.admission === 'admitted'));
516
+ }
517
+ function covered(plan) {
518
+ const locators = reachedRooms(plan);
519
+ if (locators.length === 0 && plan.rooms === null && plan.reach === null && !roomsListed) {
520
+ return { pending: [] };
521
+ }
522
+ const pending = [];
523
+ const coverage = [];
524
+ const overlay = [];
525
+ for (const locator of locators) {
526
+ const replica = replicas.get(locator);
527
+ if (replica === undefined) {
528
+ if (awaited(locator))
529
+ pending.push({ room: locator, awaits: 'acquisition' });
530
+ continue;
531
+ }
532
+ if (!prepared.has(locator)) {
533
+ pending.push({ room: locator, awaits: 'preparation' });
534
+ continue;
535
+ }
536
+ coverage.push({
537
+ room: locator,
538
+ generation: replica.confirmed.record.transfer,
539
+ current: !(catching.has(locator) || owed.has(locator) || transfers.has(locator)),
540
+ });
541
+ for (const batch of replica.queue)
542
+ overlay.push(batch.id);
543
+ }
544
+ if (pending.length > 0)
545
+ return { pending };
546
+ return { coverage: { rooms: coverage, indexes: [], overlay } };
547
+ }
548
+ function awaitPreparation(cover) {
549
+ if (!('pending' in cover))
550
+ return;
551
+ const waiting = cover.pending.filter(({ awaits }) => awaits === 'preparation');
552
+ if (waiting.length > 0)
553
+ prepare(waiting.map(({ room }) => room));
554
+ }
555
+ function acquires(room) {
556
+ return (demanded(demand, room) ||
557
+ (replicas.get(room.locator)?.queue.length ?? 0) > 0 ||
558
+ queuesWithoutReplica.has(room.locator));
559
+ }
560
+ function acquiredLocators() {
561
+ return [...discovered.values()]
562
+ .filter(acquires)
563
+ .map((room) => room.locator)
564
+ .sort();
565
+ }
566
+ function heldLocators(acquired) {
567
+ return demand.whole ? acquired : [...new Set([...acquired, ...demand.rooms])].sort();
568
+ }
569
+ function heldDemand(acquired) {
570
+ if (demand.whole)
571
+ return null;
572
+ return {
573
+ rooms: heldLocators(acquired.map((room) => room.locator)),
574
+ conversations: demand.conversations,
575
+ };
576
+ }
577
+ function applyDemand(next) {
578
+ const before = heldLocators(acquiredLocators());
579
+ const { whole, conversations: conversed } = demand;
580
+ demand = next;
581
+ const after = heldLocators(acquiredLocators());
582
+ queueReadiness();
583
+ if (!conversed && next.conversations)
584
+ scheduleCurrency();
585
+ if (JSON.stringify(before) === JSON.stringify(after) &&
586
+ whole === next.whole &&
587
+ conversed === next.conversations)
588
+ return;
589
+ journal.record(`acquisition ${next.whole ? 'whole' : after.length}`);
590
+ if (options.adapter.roomStream === undefined)
591
+ void sync('unstreamed');
592
+ else if (socketOpen)
593
+ options.adapter.roomStream.reopen();
594
+ }
595
+ function acquire(next) {
596
+ if (closed)
597
+ return;
598
+ if (narrowing !== null)
599
+ clearTimeout(narrowing);
600
+ narrowing = null;
601
+ const widening = wider(next, demand);
602
+ if (!widening && !narrower(next, demand))
603
+ return;
604
+ if (widening || !roomsListed) {
605
+ applyDemand(next);
606
+ return;
607
+ }
608
+ // A narrower demand waits five seconds, so a tab that reloads returns before the stream reopens twice.
609
+ narrowing = setTimeout(() => {
610
+ narrowing = null;
611
+ applyDemand(next);
612
+ }, 5_000);
613
+ }
614
+ function requiredRooms(reach) {
615
+ if (reach === null)
616
+ return { listed: roomsListed, rooms: [...rooms.keys()].sort() };
617
+ const named = [...new Set(reach.rooms)].sort();
618
+ if (roomsListed)
619
+ return { listed: true, rooms: named.filter((room) => rooms.has(room)) };
620
+ return { listed: named.every((room) => replicas.has(room)), rooms: named };
621
+ }
622
+ function roomState(locator, search) {
623
+ if (sourceRefusals.has(locator))
624
+ return 'refused';
625
+ const listedRoom = discovered.get(locator);
626
+ if (roomsListed &&
627
+ (listedRoom === undefined ||
628
+ listedRoom.replica.admission !== 'admitted' ||
629
+ unreadable.has(locator)))
630
+ return 'unadmitted';
631
+ if (!replicas.has(locator))
632
+ return 'acquiring';
633
+ if (!prepared.has(locator))
634
+ return 'preparing';
635
+ if (search && !searchIndex.rooms().has(locator))
636
+ return 'indexing';
637
+ return 'complete';
638
+ }
639
+ function conversationCoverage(reach, search) {
640
+ const declared = reach === null || reach.conversations;
641
+ if (!declared || options.adapter.conversations === undefined || declaredAgents() === undefined)
642
+ return 'undeclared';
643
+ if (!conversations.known() || !conversations.current())
644
+ return 'acquiring';
645
+ if (!search)
646
+ return 'complete';
647
+ const unindexed = conversations
648
+ .searchable()
649
+ .filter((one) => conversations.acquired(one) && !searchIndex.conversations().has(one));
650
+ if (unindexed.length === 0)
651
+ return 'complete';
652
+ index([], unindexed);
653
+ return 'indexing';
654
+ }
655
+ function connectionOf() {
656
+ if (socketOpen)
657
+ return 'connected';
658
+ if (status.providerUnreachable)
659
+ return 'unreachable';
660
+ return options.adapter.roomStream === undefined && status.lastCompleted !== null
661
+ ? 'connected'
662
+ : 'connecting';
663
+ }
664
+ function refusedIn(locators) {
665
+ return locators.flatMap((room) => {
666
+ const held = sourceRefusals.get(room);
667
+ if (held === undefined)
668
+ return [];
669
+ const { file, location } = held.fields;
670
+ return [
671
+ {
672
+ room,
673
+ file: typeof file === 'string' ? file : '',
674
+ rule: held.code,
675
+ location: typeof location === 'string' ? location : null,
676
+ },
677
+ ];
678
+ });
679
+ }
680
+ function readinessFor(port, reach) {
681
+ const required = requiredRooms(reach);
682
+ const search = port.search === 'required';
683
+ const coverage = required.rooms.map((room) => ({ room, state: roomState(room, search) }));
684
+ const building = (state) => coverage
685
+ .filter((room) => room.state === state && !unindexable.has(room.room))
686
+ .map(({ room }) => room);
687
+ const preparing = building('preparing');
688
+ if (preparing.length > 0)
689
+ prepare(preparing);
690
+ const indexing = building('indexing');
691
+ if (indexing.length > 0)
692
+ index(indexing, []);
693
+ return readinessOf({
694
+ code: port.code,
695
+ coverage: {
696
+ listed: required.listed,
697
+ rooms: coverage,
698
+ conversations: conversationCoverage(reach, search),
699
+ search: search ? 'required' : 'unused',
700
+ },
701
+ persistence,
702
+ connection: connectionOf(),
703
+ house: refusal !== null ? 'refused' : writesHeld() ? 'write-halted' : 'open',
704
+ capacity: capacity !== null &&
705
+ coverage.some(({ room, state }) => paused.has(room) || !SETTLED_ROOMS.has(state))
706
+ ? capacity
707
+ : port.capacity,
708
+ refused: refusedIn(required.rooms),
709
+ lost: storageLoss !== null,
710
+ established: targets[port.target]?.established === true,
711
+ });
712
+ }
713
+ function establish(name) {
714
+ targets = { ...targets, [name]: { established: true } };
715
+ queueReadiness();
716
+ void durably((local) => local.keepTargets(targets)).catch(() => {
717
+ journal.record(`target record failed ${name}`);
718
+ });
719
+ }
720
+ function deliverReadiness(watch) {
721
+ if (!readinessWatches.has(watch))
722
+ return;
723
+ const readiness = readinessFor(watch.port, watch.reach);
724
+ if (readiness.ready && targets[watch.port.target]?.established !== true) {
725
+ establish(watch.port.target);
726
+ }
727
+ const shown = JSON.stringify(readiness);
728
+ if (shown === watch.last)
729
+ return;
730
+ watch.last = shown;
731
+ watch.deliver(structuredClone(readiness));
732
+ }
733
+ function queueReadiness() {
734
+ if (readinessQueued || closed || readinessWatches.size === 0)
735
+ return;
736
+ readinessQueued = true;
737
+ queueMicrotask(() => {
738
+ readinessQueued = false;
739
+ if (closed)
740
+ return;
741
+ for (const watch of [...readinessWatches])
742
+ deliverReadiness(watch);
743
+ });
744
+ }
745
+ function watchReadiness(port, reach, deliver) {
746
+ const watch = { port, reach, deliver, last: null };
747
+ readinessWatches.add(watch);
748
+ void openLocal().then(() => deliverReadiness(watch), () => deliverReadiness(watch));
749
+ return () => {
750
+ readinessWatches.delete(watch);
751
+ };
752
+ }
753
+ function layerBytes(layer) {
754
+ let bytes = 0;
755
+ for (const [path, text] of Object.entries(layer.documents))
756
+ bytes += (path.length + text.length) * 2;
757
+ return bytes;
758
+ }
759
+ function grownBy(next, previous) {
760
+ if (previous === undefined)
761
+ return layerBytes(next);
762
+ const documents = Object.fromEntries(Object.entries(next.documents).filter(([path, text]) => previous.documents[path] !== text));
763
+ return layerBytes({ ...next, documents });
764
+ }
765
+ function exceeded(error) {
766
+ return (typeof error === 'object' &&
767
+ error !== null &&
768
+ error.name === 'QuotaExceededError');
769
+ }
770
+ async function estimated() {
771
+ const estimate = options.shell.estimate === undefined ? null : await options.shell.estimate();
772
+ return estimate === null ? null : Math.max(0, estimate.quota - estimate.usage);
773
+ }
774
+ function pause(locator, cause) {
775
+ paused.add(locator);
776
+ capacity = cause;
777
+ journal.record(`capacity ${cause.cause} ${locator} ${cause.needed} ${cause.available ?? '-'}`);
778
+ queueReadiness();
779
+ if (rechecking !== null)
780
+ return;
781
+ // A paused preparation measures the browser's space again each minute, so space freed elsewhere resumes it without a retry.
782
+ rechecking = setInterval(() => {
783
+ void recheck();
784
+ }, 60_000);
785
+ }
786
+ async function recheck() {
787
+ const held = capacity;
788
+ if (held === null || closed)
789
+ return;
790
+ const available = await estimated().catch(() => null);
791
+ if (available === null || available < (held.needed ?? 0))
792
+ return;
793
+ if (held.cause === 'quota-exceeded' && (held.available === null || available <= held.available))
794
+ return;
795
+ resume();
796
+ }
797
+ function resume() {
798
+ if (rechecking !== null)
799
+ clearInterval(rechecking);
800
+ rechecking = null;
801
+ if (paused.size === 0 && capacity === null)
802
+ return;
803
+ paused.clear();
804
+ capacity = null;
805
+ journal.record('capacity resumed');
806
+ queueReadiness();
807
+ if (!closed && authorization !== undefined)
808
+ void sync('unstreamed');
809
+ }
810
+ async function reclaimed(local) {
811
+ const unreferenced = [...transfers.keys()].filter((locator) => {
812
+ const room = discovered.get(locator);
813
+ return room === undefined || !acquires(room);
814
+ });
815
+ for (const locator of unreferenced) {
816
+ await local.abandon(locator);
817
+ transfers.delete(locator);
818
+ }
819
+ if (unreferenced.length > 0)
820
+ journal.record(`capacity reclaimed ${unreferenced.length}`);
821
+ return unreferenced.length > 0;
822
+ }
823
+ async function admitted(local, locator, needed) {
824
+ if (paused.has(locator))
825
+ return false;
826
+ let available = await estimated().catch(() => null);
827
+ if (available === null || available >= needed)
828
+ return true;
829
+ if (await reclaimed(local))
830
+ available = await estimated().catch(() => null);
831
+ if (available === null || available >= needed)
832
+ return true;
833
+ pause(locator, { cause: 'insufficient-space', needed, available });
834
+ return false;
835
+ }
836
+ async function exceededOn(locator, bytes) {
837
+ const available = await estimated().catch(() => null);
838
+ pause(locator, { cause: 'quota-exceeded', needed: bytes, available });
839
+ }
840
+ function seedRoomHeld(room, version) {
841
+ return prepared.has(room) && reachedBy(room, version);
842
+ }
843
+ function seedHeld(at) {
844
+ return Object.entries(at).every(([room, version]) => (roomsListed && !rooms.has(room)) || seedRoomHeld(room, version));
845
+ }
846
+ function seedApplies(plan) {
847
+ const seed = seeds.get(plan.key);
848
+ if (seed === undefined)
849
+ return null;
850
+ if (!seedHeld(seed.at))
851
+ return seed;
852
+ seeds.delete(plan.key);
853
+ return null;
854
+ }
855
+ function seedBehind(plan, cover) {
856
+ const seed = seedApplies(plan);
857
+ if (seed === null || 'pending' in cover)
858
+ return cover;
859
+ return {
860
+ pending: Object.entries(seed.at)
861
+ .filter(([room, version]) => !seedRoomHeld(room, version))
862
+ .map(([room]) => ({ room, awaits: 'acquisition' })),
863
+ };
864
+ }
865
+ function seed(entry) {
866
+ if (seedHeld(entry.at))
867
+ return;
868
+ for (const { query, rows } of entry.queries) {
869
+ const key = queryKey(query);
870
+ seeds.set(key, { rows, at: entry.at });
871
+ for (const shown of seedWatchers.get(key) ?? [])
872
+ shown();
873
+ }
874
+ }
875
+ async function rowsQuery(plan) {
876
+ const before = covered(plan);
877
+ awaitPreparation(before);
878
+ const seeded = seedApplies(plan);
879
+ if (seeded !== null)
880
+ return seededResult(seeded).result;
881
+ if ('pending' in before)
882
+ return before;
883
+ const { rows, at: cover } = await readSide.query(plan, () => covered(plan));
884
+ awaitPreparation(cover);
885
+ if ('pending' in cover)
886
+ return cover;
887
+ return 'groups' in rows
888
+ ? { groups: rows.groups, coverage: cover.coverage }
889
+ : { documents: rows.documents, coverage: cover.coverage };
890
+ }
891
+ async function indexConversation(conversation) {
892
+ searchIndex.indexMessages(conversation, [], false);
893
+ let after = null;
894
+ for (;;) {
895
+ const batch = await durably((local) => local.messagesAfter(conversation, after));
896
+ if (closed)
897
+ return;
898
+ searchIndex.indexMessages(conversation, batch.map(({ identity, text }) => ({ conversation, identity, text })), batch.length === 0);
899
+ if (batch.length === 0)
900
+ return;
901
+ after = batch[batch.length - 1].identity;
902
+ }
903
+ }
904
+ function indexNext() {
905
+ const room = [...roomsToIndex].find((locator) => !searchIndex.rooms().has(locator) && !unindexable.has(locator));
906
+ if (room !== undefined) {
907
+ roomsToIndex.delete(room);
908
+ return () => prepared.has(room)
909
+ ? searchIndex.indexRoom(room).catch((error) => unbuilt(room, error))
910
+ : undefined;
911
+ }
912
+ const conversation = [...conversationsToIndex].find((one) => !searchIndex.conversations().has(one));
913
+ if (conversation === undefined)
914
+ return null;
915
+ conversationsToIndex.delete(conversation);
916
+ return () => indexConversation(conversation);
917
+ }
918
+ function index(rooms, named) {
919
+ for (const room of rooms)
920
+ roomsToIndex.add(room);
921
+ for (const conversation of named)
922
+ conversationsToIndex.add(conversation);
923
+ if (indexing)
924
+ return;
925
+ indexing = true;
926
+ void (async () => {
927
+ try {
928
+ for (let unit = indexNext(); unit !== null && !closed; unit = indexNext()) {
929
+ await yielded();
930
+ await unit();
931
+ queueReadiness();
932
+ }
933
+ }
934
+ finally {
935
+ indexing = false;
936
+ }
937
+ })().catch(() => { });
288
938
  }
289
939
  function publishChangeSet(set) {
290
940
  applyChangeSet(set);
291
- if (set.rooms.length > 0)
941
+ if (set.rooms.length > 0 ||
942
+ [...new Set(set.documents.map(({ locator }) => locator))].some((locator) => rooms.has(locator) && counted.get(locator) !== documentsIn(locator)))
292
943
  emitRooms();
293
944
  for (const locator of set.queues)
294
945
  emitQueue(locator);
@@ -299,39 +950,8 @@ export function composeRuntime(options) {
299
950
  for (const app of set.presentations)
300
951
  emitPresentation(app);
301
952
  conversations.changed(set);
302
- const cards = declaredCards();
303
- if (cards !== undefined && set.documents.some((change) => change.locator === cards.locator)) {
304
- scheduleCurrency();
305
- }
306
- }
307
- function stopTimer() {
308
- if (resetTimer === undefined)
309
- return;
310
- clearTimeout(resetTimer);
311
- resetTimer = undefined;
312
- }
313
- function armTimer() {
314
- stopTimer();
315
- if (closed || stopping)
316
- return;
317
- let earliest = null;
318
- for (const { submission } of pendings.values()) {
319
- if (submission.state !== 'reset')
320
- continue;
321
- const at = Date.parse(submission.reset);
322
- if (earliest === null || at < earliest)
323
- earliest = at;
324
- }
325
- if (earliest === null)
326
- return;
327
- // A Save House held back goes again only once the reset its answer named has passed.
328
- resetTimer = setTimeout(() => {
329
- resetTimer = undefined;
330
- submitAll();
331
- }, Math.max(0, earliest - Date.now()));
332
953
  }
333
954
  async function refuse(reason, provider = null) {
334
- stopTimer();
335
955
  discoveryPaused = true;
336
956
  try {
337
957
  if (reason === 'revoked-authorization') {
@@ -339,10 +959,7 @@ export function composeRuntime(options) {
339
959
  const revoked = { status: 'unavailable', reason: 'revoked' };
340
960
  try {
341
961
  const local = await openLocal();
342
- await local.revokeModels([...replicas.values()].map((replica) => ({
343
- record: replica.confirmed.record,
344
- queue: replica.queue,
345
- })));
962
+ await local.revokeModels([...replicas.values()].map((replica) => replica.confirmed.record));
346
963
  }
347
964
  catch {
348
965
  journal.record('model revocation persistence failed');
@@ -366,10 +983,7 @@ export function composeRuntime(options) {
366
983
  model: revoked,
367
984
  selectionModel: revoked,
368
985
  };
369
- const read = readConfirmed(record, before.confirmed);
370
- replicas.set(locator, read.kind === 'staged'
371
- ? replicaOf(read.confirmed, before.queue, before)
372
- : { ...before, confirmed: { ...before.confirmed, record } });
986
+ replicas.set(locator, replicaOf(confirmedOf(record, before.confirmed), before.queue, before));
373
987
  }
374
988
  rooms.set(locator, {
375
989
  ...room,
@@ -386,7 +1000,8 @@ export function composeRuntime(options) {
386
1000
  }
387
1001
  finally {
388
1002
  refusal = {
389
- reason,
1003
+ code: reason,
1004
+ retryable: false,
390
1005
  reauthorizationOffered: reason === 'revoked-authorization',
391
1006
  refusal: provider,
392
1007
  };
@@ -399,6 +1014,7 @@ export function composeRuntime(options) {
399
1014
  rooms.set(room.locator, {
400
1015
  name: room.name,
401
1016
  locator: room.locator,
1017
+ handle: room.handle,
402
1018
  operations: room.operations,
403
1019
  replica: room.replica,
404
1020
  model: modelTypes(modelOf(room.locator)),
@@ -410,19 +1026,31 @@ export function composeRuntime(options) {
410
1026
  },
411
1027
  providerOwnedPaths: room.providerOwnedPaths,
412
1028
  roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,
413
- attachments: replicas.get(room.locator)?.confirmed.record.attachments ?? [],
414
1029
  synchronizationAvailable,
415
1030
  refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,
416
1031
  });
417
1032
  }
418
- async function applyDiscovery(listed, local) {
1033
+ async function applyDiscovery(found, started) {
1034
+ for (const room of found) {
1035
+ const fence = fences.get(room.locator);
1036
+ if (fence !== undefined && fence.erased && fence.at < started)
1037
+ fences.delete(room.locator);
1038
+ }
1039
+ await loseRooms(found
1040
+ .filter((room) => room.replica.admission !== 'admitted' && heldLocally(room.locator))
1041
+ .map((room) => room.locator));
1042
+ const listed = found.filter((room) => !fences.has(room.locator));
419
1043
  const listedLocators = new Set(listed.map((room) => room.locator));
420
1044
  for (const locator of listedLocators)
421
1045
  scopedRefusals.delete(locator);
422
1046
  discovered.clear();
423
1047
  for (const room of listed)
424
1048
  discovered.set(room.locator, room);
425
- await dropUnlisted(listedLocators, local);
1049
+ const unlisted = unlistedHeld(new Set(found.map((room) => room.locator)));
1050
+ if (options.adapter.exhaustiveDiscovery === true)
1051
+ await loseRooms(unlisted);
1052
+ else
1053
+ unlistedKept(unlisted);
426
1054
  for (const room of listed) {
427
1055
  const held = replicas.get(room.locator)?.confirmed.record;
428
1056
  if (held !== undefined && held.replica.selection !== room.replica.selection) {
@@ -433,43 +1061,91 @@ export function composeRuntime(options) {
433
1061
  }
434
1062
  roomsListed = true;
435
1063
  emitRooms();
1064
+ return listed;
436
1065
  }
437
- function unlistedHeld(listed) {
438
- return [...new Set([...rooms.keys(), ...roomDrafts.keys()])].filter((locator) => !listed.has(locator));
1066
+ function heldLocally(locator) {
1067
+ return (replicas.has(locator) ||
1068
+ roomDrafts.has(locator) ||
1069
+ transfers.has(locator) ||
1070
+ queuesWithoutReplica.has(locator));
439
1071
  }
440
- async function dropUnlisted(listed, local) {
441
- if (unlistedHeld(listed).length === 0)
442
- return;
443
- await exclusive(async () => {
444
- const unlisted = unlistedHeld(listed);
445
- await local.dropRooms(unlisted);
446
- const removed = unlisted.map((locator) => changeSet(locator, replicas.get(locator) ?? null, null, {
447
- room: true,
448
- queue: true,
449
- drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],
450
- }));
451
- for (const locator of unlisted) {
452
- for (const batch of replicas.get(locator)?.queue ?? [])
453
- pendings.delete(batch.id);
454
- replicas.delete(locator);
1072
+ function unlistedHeld(listed) {
1073
+ return [
1074
+ ...new Set([
1075
+ ...rooms.keys(),
1076
+ ...roomDrafts.keys(),
1077
+ ...transfers.keys(),
1078
+ ...queuesWithoutReplica.keys(),
1079
+ ]),
1080
+ ].filter((locator) => !listed.has(locator));
1081
+ }
1082
+ function unlistedKept(unlisted) {
1083
+ for (const locator of unlisted) {
1084
+ const held = replicas.get(locator)?.confirmed.record;
1085
+ if (held !== undefined)
1086
+ list(held, false);
1087
+ else
455
1088
  rooms.delete(locator);
456
- roomDrafts.delete(locator);
457
- unreadable.delete(locator);
458
- stale.delete(locator);
459
- scopedRefusals.delete(locator);
460
- sourceRefusals.delete(locator);
461
- declarationRefusals.delete(locator);
462
- for (const attached of ['collection', 'typed-selection']) {
463
- const key = modelKey(locator, attached);
464
- models.delete(key);
465
- liveModels.delete(key);
466
- invalidModels.delete(key);
467
- }
468
- journal.record(`room unlisted ${locator}`);
1089
+ }
1090
+ }
1091
+ function fence(locators) {
1092
+ const fresh = [...new Set(locators)].filter((locator) => !fences.has(locator));
1093
+ const removed = fresh.map((locator) => changeSet(locator, replicas.get(locator) ?? null, null, {
1094
+ room: true,
1095
+ queue: true,
1096
+ drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],
1097
+ }));
1098
+ for (const locator of fresh) {
1099
+ fences.set(locator, { at: discoveries, erased: false });
1100
+ lastFenced.set(locator, ++fencings);
1101
+ for (const batch of replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [])
1102
+ pendings.delete(batch.id);
1103
+ replicas.delete(locator);
1104
+ queuesWithoutReplica.delete(locator);
1105
+ rooms.delete(locator);
1106
+ roomDrafts.delete(locator);
1107
+ transfers.delete(locator);
1108
+ catching.delete(locator);
1109
+ discovered.delete(locator);
1110
+ announced.delete(locator);
1111
+ unreadable.delete(locator);
1112
+ stale.delete(locator);
1113
+ repairable.delete(locator);
1114
+ unindexable.delete(locator);
1115
+ paused.delete(locator);
1116
+ scopedRefusals.delete(locator);
1117
+ sourceRefusals.delete(locator);
1118
+ declarationRefusals.delete(locator);
1119
+ for (const attached of ['collection', 'typed-selection']) {
1120
+ const key = modelKey(locator, attached);
1121
+ models.delete(key);
1122
+ liveModels.delete(key);
1123
+ invalidModels.delete(key);
469
1124
  }
470
- publishChangeSet(mergeChangeSets(removed));
471
- moveTo({ ...status, ...attention() });
472
- });
1125
+ journal.record(`room lost ${locator}`);
1126
+ }
1127
+ if (fresh.length === 0)
1128
+ return fresh;
1129
+ publishChangeSet(mergeChangeSets(removed));
1130
+ for (const locator of fresh)
1131
+ prepared.delete(locator);
1132
+ searchIndex.forget(fresh);
1133
+ readSide.recover();
1134
+ moveTo({ ...status, ...attention() });
1135
+ return fresh;
1136
+ }
1137
+ async function erased(local, locators) {
1138
+ await local.erase(locators);
1139
+ for (const locator of locators) {
1140
+ const held = fences.get(locator);
1141
+ if (held !== undefined)
1142
+ held.erased = true;
1143
+ }
1144
+ }
1145
+ async function loseRooms(locators) {
1146
+ const fresh = fence(locators);
1147
+ if (fresh.length > 0)
1148
+ await durably((local) => erased(local, fresh));
473
1149
  }
474
1150
  function restored(key, persisted) {
475
1151
  const prior = models.get(key);
@@ -490,7 +1166,7 @@ export function composeRuntime(options) {
490
1166
  return model;
491
1167
  }
492
1168
  async function hydrate(opened) {
493
- const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named] = await Promise.all([
1169
+ const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named, known, staged, heldTargets,] = await Promise.all([
494
1170
  opened.all(),
495
1171
  opened.queues(),
496
1172
  opened.roomDrafts(),
@@ -500,9 +1176,17 @@ export function composeRuntime(options) {
500
1176
  opened.lastCompleted(),
501
1177
  opened.providerLimits(),
502
1178
  opened.capabilities(),
1179
+ opened.member(),
1180
+ opened.transfers(),
1181
+ opened.targets(),
503
1182
  ]);
1183
+ targets = heldTargets;
1184
+ transfers.clear();
1185
+ for (const record of staged)
1186
+ transfers.set(record.locator, record);
504
1187
  limits = declared;
505
1188
  capabilities = named;
1189
+ member = known;
506
1190
  roomDrafts.clear();
507
1191
  for (const record of kept)
508
1192
  rememberRoomDraft(record);
@@ -518,18 +1202,17 @@ export function composeRuntime(options) {
518
1202
  }
519
1203
  const previousReplicas = new Map(replicas);
520
1204
  replicas.clear();
1205
+ queuesWithoutReplica.clear();
1206
+ const replicated = new Set(records.map((record) => record.locator));
1207
+ for (const [locator, queue] of queuedBatches) {
1208
+ if (!replicated.has(locator))
1209
+ queuesWithoutReplica.set(locator, queue);
1210
+ }
521
1211
  for (const record of records) {
522
1212
  const model = restored(modelKey(record.locator, 'collection'), record.model);
523
1213
  const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
524
1214
  const prior = previousReplicas.get(record.locator);
525
- const retyped = { ...record, model, selectionModel };
526
- const read = readConfirmed(retyped, prior?.confirmed);
527
- const confirmed = read.kind === 'staged'
528
- ? read.confirmed
529
- : {
530
- record: retyped,
531
- collection: parseCollection(retyped.documents, compositionOf(retyped)),
532
- };
1215
+ const confirmed = confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
533
1216
  replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? [], prior));
534
1217
  const existing = rooms.get(record.locator);
535
1218
  if (existing === undefined)
@@ -538,7 +1221,6 @@ export function composeRuntime(options) {
538
1221
  rooms.set(record.locator, {
539
1222
  ...existing,
540
1223
  roomVersion: record.roomVersion,
541
- attachments: record.attachments,
542
1224
  operations: record.operations,
543
1225
  replica: record.replica,
544
1226
  model: modelTypes(model),
@@ -550,10 +1232,6 @@ export function composeRuntime(options) {
550
1232
  },
551
1233
  });
552
1234
  }
553
- if (read.kind === 'refused') {
554
- refusedSource(record, read);
555
- declarationRefusals.add(record.locator);
556
- }
557
1235
  }
558
1236
  return {
559
1237
  lastCompleted,
@@ -564,16 +1242,26 @@ export function composeRuntime(options) {
564
1242
  async function readState(opened) {
565
1243
  const { lastCompleted, locators, read } = await hydrate(opened);
566
1244
  applyChangeSet(read);
1245
+ prepare();
567
1246
  if (replicas.size > 0)
568
1247
  emitRooms();
1248
+ if (member !== null)
1249
+ emitMember();
569
1250
  for (const locator of locators)
570
1251
  emitQueue(locator);
571
1252
  publishRoomDrafts(false);
572
1253
  return lastCompleted;
573
1254
  }
574
1255
  async function open() {
575
- const opened = await openRuntimeStore();
1256
+ if (closed)
1257
+ throw new Error('runtime closed');
1258
+ const opened = await openRuntimeStore(isFenced);
576
1259
  store = opened;
1260
+ const interrupted = await opened.fences();
1261
+ for (const locator of interrupted) {
1262
+ fences.set(locator, { at: discoveries, erased: false });
1263
+ lastFenced.set(locator, ++fencings);
1264
+ }
577
1265
  const kept = options.shell.generation;
578
1266
  const storedGeneration = await opened.generation();
579
1267
  const loss = detectStorageLoss(storedGeneration, kept);
@@ -587,6 +1275,8 @@ export function composeRuntime(options) {
587
1275
  emitStorageLoss();
588
1276
  }
589
1277
  const lastCompleted = await readState(opened);
1278
+ if (interrupted.length > 0)
1279
+ await erased(opened, interrupted);
590
1280
  moveTo({ ...status, lastCompleted, ...attention() });
591
1281
  return opened;
592
1282
  }
@@ -613,10 +1303,16 @@ export function composeRuntime(options) {
613
1303
  return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
614
1304
  }
615
1305
  async function settle(local, locator, before, confirmed, queue, settling = {}) {
616
- const withdrawn = withdrawals(confirmed, queue, withdrawable);
617
- const kept = queue.filter((batch) => !withdrawn.includes(batch));
1306
+ const previousQueue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
1307
+ const { withdrawn, kept } = standing(confirmed, queue, withdrawable, localSaves);
1308
+ const founded = kept.filter((batch) => !queue.includes(batch));
1309
+ const queueChanged = kept.length !== previousQueue.length || founded.length > 0;
1310
+ const unqueued = withdrawn.map((batch) => ({
1311
+ batch,
1312
+ returned: localSaves || landed(batch, confirmed) ? null : returnedBy('withdrawn'),
1313
+ }));
618
1314
  const returning = [
619
- ...withdrawn.map((batch) => ({ batch, returned: { kind: 'withdrawn' } })).reverse(),
1315
+ ...[...unqueued].reverse(),
620
1316
  ...(settling.leaving === undefined ? [] : [settling.leaving]),
621
1317
  ];
622
1318
  const written = new Map();
@@ -634,27 +1330,49 @@ export function composeRuntime(options) {
634
1330
  });
635
1331
  }
636
1332
  }
637
- await local.write({
638
- next: confirmed.record,
639
- previous: before?.confirmed.record ?? null,
640
- queue: kept,
641
- previousQueue: before?.queue ?? [],
642
- roomDrafts: [...written.values()],
643
- });
644
- for (const batch of before?.queue ?? []) {
645
- if (!kept.includes(batch))
1333
+ await local.keepAuthored({ locator, queue: kept, founded, roomDrafts: [...written.values()] });
1334
+ const staying = new Set(kept.map((batch) => batch.id));
1335
+ for (const batch of previousQueue) {
1336
+ if (!staying.has(batch.id))
646
1337
  pendings.delete(batch.id);
647
1338
  }
648
1339
  for (const record of written.values())
649
1340
  rememberRoomDraft(record);
650
- for (const batch of withdrawn)
651
- journal.record(`outcome ${locator} ${batch.id} withdrawn`);
652
- replicas.set(locator, replicaOf(confirmed, kept, before));
653
- return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {
654
- room: settling.room,
655
- queue: kept.length !== (before?.queue.length ?? 0),
656
- drafts: [...written.keys()],
657
- });
1341
+ try {
1342
+ await local.write({
1343
+ next: confirmed.record,
1344
+ previous: before?.confirmed.record ?? null,
1345
+ ...(settling.stored === undefined ? {} : { stored: settling.stored }),
1346
+ });
1347
+ }
1348
+ catch (error) {
1349
+ const held = before === undefined ? null : replicaOf(before.confirmed, kept, before);
1350
+ if (held !== null)
1351
+ replicas.set(locator, held);
1352
+ else if (kept.length > 0)
1353
+ queuesWithoutReplica.set(locator, kept);
1354
+ else
1355
+ queuesWithoutReplica.delete(locator);
1356
+ publishChangeSet(changeSet(locator, before ?? null, held, {
1357
+ queue: queueChanged,
1358
+ drafts: [...written.keys()],
1359
+ }));
1360
+ moveTo({ ...status, ...attention() });
1361
+ throw error;
1362
+ }
1363
+ return () => {
1364
+ queuesWithoutReplica.delete(locator);
1365
+ for (const { batch, returned } of unqueued) {
1366
+ const outcome = localSaves ? 'dropped' : returned === null ? 'landed' : 'withdrawn';
1367
+ journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
1368
+ }
1369
+ replicas.set(locator, replicaOf(confirmed, kept, before));
1370
+ return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {
1371
+ room: settling.room,
1372
+ queue: queueChanged,
1373
+ drafts: [...written.keys()],
1374
+ });
1375
+ };
658
1376
  }
659
1377
  function adoptModels(locator, record) {
660
1378
  for (const [attached, model] of [
@@ -687,10 +1405,16 @@ export function composeRuntime(options) {
687
1405
  selection: taken(answers?.selection, held.selection, 'typed-selection'),
688
1406
  };
689
1407
  }
690
- function publish(local, room, confirmed, base) {
1408
+ function publish(local, room, confirmed, landing, live) {
1409
+ const { base, stored } = landing;
691
1410
  return exclusive(async () => {
692
- if (!continuing())
1411
+ if (stored !== undefined) {
1412
+ await indexReferrers({ text: confirmed.record.documents, binaries: confirmed.record.binaries }, compositionOf(confirmed.record));
1413
+ }
1414
+ if (!live()) {
1415
+ caughtUpTo(room.locator);
693
1416
  return true;
1417
+ }
694
1418
  const prior = replicas.get(room.locator);
695
1419
  if (base !== undefined &&
696
1420
  (prior?.confirmed.record.roomVersion !== base.record.roomVersion ||
@@ -698,76 +1422,183 @@ export function composeRuntime(options) {
698
1422
  return false;
699
1423
  }
700
1424
  adoptModels(room.locator, confirmed.record);
701
- const queue = prior?.queue ?? [];
1425
+ const queue = prior?.queue ?? queuesWithoutReplica.get(room.locator) ?? [];
702
1426
  const roomVersion = confirmed.record.roomVersion;
703
1427
  const accepted = queue.filter((batch) => {
704
1428
  const accepted = pendings.get(batch.id)?.accepted;
705
1429
  return (accepted !== undefined && options.adapter.reached(room.locator, roomVersion, accepted));
706
1430
  });
707
- const set = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true });
1431
+ let settled;
1432
+ try {
1433
+ settled = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true, ...(stored === undefined ? {} : { stored }) });
1434
+ }
1435
+ catch (error) {
1436
+ if (!exceeded(error))
1437
+ throw error;
1438
+ await exceededOn(room.locator, grownBy(confirmed.record, prior?.confirmed.record));
1439
+ caughtUpTo(room.locator);
1440
+ return true;
1441
+ }
1442
+ const set = settled();
1443
+ if (stored !== undefined) {
1444
+ transfers.delete(room.locator);
1445
+ catching.delete(room.locator);
1446
+ }
708
1447
  for (const batch of accepted)
709
1448
  pendings.delete(batch.id);
710
1449
  stale.delete(room.locator);
1450
+ unindexable.delete(room.locator);
711
1451
  if (unreadable.delete(room.locator))
712
1452
  scopedRefusals.delete(room.locator);
713
1453
  sourceRefusals.delete(room.locator);
714
1454
  declarationRefusals.delete(room.locator);
715
1455
  list(room, true);
1456
+ if (prior === undefined)
1457
+ prepared.add(room.locator);
716
1458
  publishChangeSet(set);
717
1459
  moveTo({ ...status, ...attention() });
1460
+ options.adapter.roomStream?.published(room.locator, roomVersion);
718
1461
  return true;
719
1462
  });
720
1463
  }
721
1464
  async function saveRoomDrafts(locator, named, writtenBy) {
722
1465
  const local = await openLocal();
1466
+ await referenced(locator);
723
1467
  const replica = replicas.get(locator);
724
1468
  const room = rooms.get(locator);
725
1469
  if (replica === undefined || room === undefined) {
726
- throw new Error(`No Local Replica for ${locator}`);
1470
+ throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
727
1471
  }
728
1472
  const saved = [];
729
1473
  for (const { path, revision } of named) {
730
1474
  const record = roomDrafts.get(locator)?.get(path);
731
1475
  if (record === undefined || record.revision !== revision) {
732
- return { outcome: 'refused', rule: 'stale', file: path };
1476
+ return { outcome: 'refused', code: 'stale', retryable: false, file: path };
733
1477
  }
734
1478
  if (!saved.some((draft) => draft.path === path))
735
1479
  saved.push({ path, parts: record.parts });
736
1480
  }
737
1481
  const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
738
1482
  if (changed.length > 0)
739
- return { outcome: 'refused', rule: 'changed-underneath', parts: changed };
1483
+ return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
740
1484
  const parts = saved.map(({ path, parts }) => changesOf(path, parts));
741
- const built = buildBatch({
1485
+ const changes = parts.flatMap(({ changes }) => changes);
1486
+ const requeue = requeued(replica.queue, changes, replica.visible, withdrawable, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
1487
+ if (requeue.kind === 'refused')
1488
+ return { outcome: 'refused', ...requeue.refusal };
1489
+ const foreign = [...requeue.withdrawn.keys()].some((origin) => {
1490
+ const writer = replica.queue.find((batch) => batch.id === origin)?.writtenBy;
1491
+ return writer?.app !== writtenBy?.app || writer?.release !== writtenBy?.release;
1492
+ });
1493
+ if (foreign) {
1494
+ return {
1495
+ outcome: 'refused',
1496
+ code: 'unknown-revision',
1497
+ retryable: false,
1498
+ file: [...requeue.queued].at(-1),
1499
+ };
1500
+ }
1501
+ const withdrawing = requeue.withdrawn.size > 0;
1502
+ const input = {
1503
+ local: localSaves,
742
1504
  baseRoomVersion: replica.confirmed.record.roomVersion,
743
1505
  composition: compositionFor(replica.confirmed.record),
744
1506
  operations: room.operations,
745
1507
  providerOwnedPaths: room.providerOwnedPaths,
746
1508
  providerLimits: limits,
1509
+ handle: room.handle,
747
1510
  visible: replica.visible,
748
- changes: parts.flatMap(({ changes }) => changes),
1511
+ changes,
749
1512
  bases: parts.flatMap(({ bases }) => bases),
1513
+ queued: queuedDocuments(replica.queue),
750
1514
  writtenBy,
1515
+ clean: {
1516
+ text: replica.confirmed.record.documents,
1517
+ binaries: replica.confirmed.record.binaries,
1518
+ composition: compositionOf(replica.confirmed.record),
1519
+ },
1520
+ };
1521
+ const checked = withdrawing
1522
+ ? buildBatch({ ...input, queued: new Set([...input.queued, ...requeue.queued]) })
1523
+ : null;
1524
+ if (checked?.kind === 'refused')
1525
+ return { outcome: 'refused', ...checked.refusal };
1526
+ const owners = [...requeue.owners].flatMap((origin) => {
1527
+ const batch = requeue.withdrawn.get(origin);
1528
+ return batch === undefined || batch === null ? [] : [{ origin, batch }];
751
1529
  });
752
- if (built.kind === 'refused')
1530
+ if (owners.length > 1) {
1531
+ return {
1532
+ outcome: 'refused',
1533
+ code: 'unknown-revision',
1534
+ retryable: false,
1535
+ file: [...requeue.queued].at(-1),
1536
+ };
1537
+ }
1538
+ const built = !withdrawing
1539
+ ? buildBatch(input)
1540
+ : requeue.changes.length === 0
1541
+ ? null
1542
+ : buildBatch({
1543
+ ...input,
1544
+ visible: replicaOf(replica.confirmed, requeue.queue, replica).visible,
1545
+ changes: requeue.changes,
1546
+ queued: queuedDocuments(requeue.queue),
1547
+ });
1548
+ if (built?.kind === 'refused')
753
1549
  return { outcome: 'refused', ...built.refusal };
754
- const batches = [...replica.queue, built.batch];
1550
+ const [owner] = owners;
1551
+ const join = built === null || owner === undefined
1552
+ ? null
1553
+ : joined(requeue.queue, owner.batch, built.batch);
1554
+ if (join?.kind === 'refused')
1555
+ return { outcome: 'refused', ...join.refusal };
1556
+ const withdrawn = new Map(requeue.withdrawn);
1557
+ if (join !== null && owner !== undefined)
1558
+ withdrawn.set(owner.origin, join.batch);
1559
+ const drafted = new Map();
1560
+ for (const [origin, replaced] of withdrawn) {
1561
+ if (replaced === null)
1562
+ continue;
1563
+ const carried = withdrawnDrafts(pendings.get(origin)?.drafts ?? [], changes);
1564
+ drafted.set(replaced.id, replaced === join?.batch
1565
+ ? [
1566
+ ...carried.map((held) => joinedDraft(held, saved)),
1567
+ ...saved.filter((draft) => !carried.some((held) => held.path === draft.path)),
1568
+ ]
1569
+ : carried);
1570
+ }
1571
+ if (built !== null && join === null)
1572
+ drafted.set(built.batch.id, saved);
1573
+ const batches = join !== null ? join.queue : built === null ? requeue.queue : [...requeue.queue, built.batch];
1574
+ for (const replaced of withdrawn.values()) {
1575
+ if (replaced === null || !batches.includes(replaced))
1576
+ continue;
1577
+ const limited = limitedIn(batches, replaced, limits, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
1578
+ if (limited !== null)
1579
+ return { outcome: 'refused', ...limited };
1580
+ }
755
1581
  const consumed = saved.map(({ path }) => path);
756
1582
  try {
757
- await local.write({
758
- next: replica.confirmed.record,
759
- previous: replica.confirmed.record,
1583
+ await local.keepAuthored({
1584
+ locator,
760
1585
  queue: batches,
761
- previousQueue: replica.queue,
762
- saved,
1586
+ saved: drafted,
763
1587
  consumedRoomDrafts: consumed,
764
1588
  });
765
1589
  }
766
1590
  catch {
767
- return { outcome: 'refused', rule: 'durable-write' };
1591
+ return { outcome: 'refused', code: 'durable-write', retryable: true };
1592
+ }
1593
+ if (fences.has(locator))
1594
+ throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1595
+ for (const origin of withdrawn.keys())
1596
+ pendings.delete(origin);
1597
+ for (const [id, drafts] of drafted) {
1598
+ pendings.set(id, { drafts, submission: { state: 'waiting' }, lost: false });
768
1599
  }
769
- pendings.set(built.batch.id, { drafts: saved, submission: { state: 'waiting' }, lost: false });
770
- recorded = false;
1600
+ if (!localSaves)
1601
+ recorded = false;
771
1602
  for (const path of consumed)
772
1603
  forgetRoomDraft(locator, path);
773
1604
  replicas.set(locator, replicaOf(replica.confirmed, batches, replica));
@@ -775,9 +1606,12 @@ export function composeRuntime(options) {
775
1606
  queue: true,
776
1607
  drafts: consumed,
777
1608
  }));
778
- moveTo({ ...saving(status), ...attention() });
1609
+ moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
779
1610
  submitLater(locator);
780
- return { outcome: 'saved', identifier: built.batch.id };
1611
+ const identifier = join?.batch.id ??
1612
+ built?.batch.id ??
1613
+ [...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
1614
+ return { outcome: 'saved', identifier };
781
1615
  }
782
1616
  async function mark(local, locator, identifier, submission, lost) {
783
1617
  const state = pendings.get(identifier);
@@ -787,6 +1621,8 @@ export function composeRuntime(options) {
787
1621
  return;
788
1622
  }
789
1623
  await local.submit(locator, identifier, submission, lost);
1624
+ if (fences.has(locator))
1625
+ return;
790
1626
  pendings.set(identifier, { ...state, submission, lost });
791
1627
  const replica = replicas.get(locator);
792
1628
  if (replica !== undefined)
@@ -797,22 +1633,24 @@ export function composeRuntime(options) {
797
1633
  if (!continuing())
798
1634
  throw new Error('connection refused');
799
1635
  await local.keepUpload(locator, identifier, upload);
1636
+ if (fences.has(locator))
1637
+ throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
800
1638
  pendings.set(identifier, { ...pendings.get(identifier), upload });
801
1639
  if (!continuing())
802
1640
  throw new Error('connection refused');
803
1641
  }
804
1642
  async function readHistory(locator, path, query = {}) {
805
1643
  if (closed || refusal !== null)
806
- return { kind: 'transport-uncertainty' };
1644
+ return UNCERTAIN;
807
1645
  try {
808
1646
  await ensureAuthorization();
809
1647
  }
810
1648
  catch {
811
- return { kind: 'transport-uncertainty' };
812
- }
813
- if (closed || authorization === undefined || refusal !== null) {
814
- return { kind: 'transport-uncertainty' };
1649
+ return UNCERTAIN;
815
1650
  }
1651
+ if (closed || authorization === undefined || refusal !== null)
1652
+ return UNCERTAIN;
1653
+ const since = fencings;
816
1654
  const transfer = ['transfer', 'history', locator, path];
817
1655
  if (query.revision !== undefined)
818
1656
  transfer.push(query.revision);
@@ -827,6 +1665,8 @@ export function composeRuntime(options) {
827
1665
  ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),
828
1666
  });
829
1667
  journal.record(`outcome history ${result.kind}`);
1668
+ if (fencedSince(locator, since))
1669
+ return failure({ kind: 'room-not-readable', locator });
830
1670
  if (result.kind === 'scoped-refusal') {
831
1671
  const room = replicas.get(result.locator)?.confirmed.record;
832
1672
  if (room !== undefined)
@@ -834,17 +1674,130 @@ export function composeRuntime(options) {
834
1674
  }
835
1675
  if (result.kind === 'revoked-authorization')
836
1676
  await refuse('revoked-authorization');
837
- return result;
1677
+ return historyAnswer(result);
838
1678
  }
839
1679
  catch {
840
1680
  journal.record('outcome history transport-uncertainty');
841
- return { kind: 'transport-uncertainty' };
1681
+ return UNCERTAIN;
1682
+ }
1683
+ }
1684
+ function queuedBlob(locator, path, localId) {
1685
+ for (const batch of replicas.get(locator)?.queue ?? []) {
1686
+ const change = batch.changes[queuedFile(batch, path, localId)];
1687
+ if (change?.kind === 'binary')
1688
+ return change.blob;
1689
+ }
1690
+ return null;
1691
+ }
1692
+ function binaryRoom(request) {
1693
+ if (request.kind === 'path')
1694
+ return request.locator;
1695
+ const scope = options.adapter.referrerScope(request.referrer);
1696
+ return scope?.kind === 'room' ? scope.locator : null;
1697
+ }
1698
+ async function transferBinary(request, transfer, answer) {
1699
+ if (closed || refusal !== null)
1700
+ return UNCERTAIN;
1701
+ try {
1702
+ await ensureAuthorization();
1703
+ }
1704
+ catch {
1705
+ return UNCERTAIN;
1706
+ }
1707
+ if (closed || authorization === undefined || refusal !== null)
1708
+ return UNCERTAIN;
1709
+ const since = fencings;
1710
+ journal.record(request.kind === 'path'
1711
+ ? `transfer binary ${request.locator} ${request.path}`
1712
+ : `transfer binary ${request.fileRef}`);
1713
+ try {
1714
+ const result = await transfer(authorization);
1715
+ const settled = result;
1716
+ journal.record(`outcome binary ${settled.kind}`);
1717
+ const locator = binaryRoom(request);
1718
+ if (locator !== null && fencedSince(locator, since))
1719
+ return failure({ kind: 'room-not-readable', locator });
1720
+ if (settled.kind === 'scoped-refusal') {
1721
+ const room = replicas.get(settled.locator)?.confirmed.record;
1722
+ if (room !== undefined)
1723
+ await scoped(settled, room, await openLocal());
1724
+ }
1725
+ if (settled.kind === 'revoked-authorization')
1726
+ await refuse('revoked-authorization');
1727
+ return answer(result);
1728
+ }
1729
+ catch {
1730
+ journal.record('outcome binary transport-uncertainty');
1731
+ return UNCERTAIN;
842
1732
  }
843
1733
  }
844
- function declaredCards() {
1734
+ function readBinary(request) {
1735
+ return transferBinary(request, (held) => options.adapter.binary(held, request), binaryAnswer);
1736
+ }
1737
+ function binaryPath(locator, path, revision) {
1738
+ if (revision !== undefined)
1739
+ return { kind: 'path', locator, path, revision };
1740
+ const visible = replicas.get(locator)?.visible;
1741
+ const held = visible?.binaries[path];
1742
+ if (visible === undefined || held === undefined)
1743
+ return null;
1744
+ if (held.state === 'pending')
1745
+ return { kind: 'pending', localId: held.localId };
1746
+ const record = binaryRecord(path, held, visible.revisions[path]);
1747
+ if (record.state !== 'accepted')
1748
+ return null;
1749
+ const replica = replicas.get(locator);
1750
+ const queued = (replica?.queue ?? []).flatMap((batch) => batch.changes);
1751
+ const holds = (at) => {
1752
+ const kept = replica?.confirmed.record.binaries[at];
1753
+ return (kept?.state === 'accepted' &&
1754
+ kept.fileRef === record.fileRef &&
1755
+ replica?.confirmed.record.revisions[at] === record.revision);
1756
+ };
1757
+ let confirmed = path;
1758
+ for (let index = queued.length - 1; index >= 0 && !holds(confirmed); index -= 1) {
1759
+ const change = queued[index];
1760
+ if (change.kind === 'move' && change.to === confirmed)
1761
+ confirmed = change.path;
1762
+ }
1763
+ return {
1764
+ kind: 'path',
1765
+ locator,
1766
+ path: confirmed,
1767
+ revision: record.revision,
1768
+ fileRef: record.fileRef,
1769
+ };
1770
+ }
1771
+ async function readBinaryPath(locator, path, revision) {
1772
+ await ready;
1773
+ const asked = binaryPath(locator, path, revision);
1774
+ if (asked === null)
1775
+ return absentBinary(path);
1776
+ if (asked.kind === 'pending') {
1777
+ const blob = queuedBlob(locator, path, asked.localId);
1778
+ return blob === null ? absentBinary(path) : { kind: 'binary', blob };
1779
+ }
1780
+ return readBinary(asked);
1781
+ }
1782
+ async function linkBinaryPath(locator, path, revision) {
1783
+ await ready;
1784
+ const asked = binaryPath(locator, path, revision);
1785
+ if (asked === null || asked.kind === 'pending')
1786
+ return absentBinary(path);
1787
+ return transferBinary(asked, (held) => options.adapter.link(held, asked), binaryLinkAnswer);
1788
+ }
1789
+ async function readBinaryReference(reference) {
1790
+ await ready;
1791
+ return readBinary({
1792
+ kind: 'reference',
1793
+ fileRef: reference.fileRef,
1794
+ referrer: reference.referrer,
1795
+ });
1796
+ }
1797
+ function declaredAgents() {
845
1798
  for (const capability of capabilities) {
846
- if (capability.conversationCards !== undefined)
847
- return capability.conversationCards;
1799
+ if (capability.conversationAgents !== undefined)
1800
+ return capability.conversationAgents;
848
1801
  }
849
1802
  return undefined;
850
1803
  }
@@ -857,21 +1810,21 @@ export function composeRuntime(options) {
857
1810
  }
858
1811
  return undefined;
859
1812
  }
860
- async function invokeAction(name, input) {
1813
+ async function invokeAction(name, input, dispatching) {
861
1814
  await ready;
862
1815
  if (closed || refusal !== null)
863
- return { kind: 'transport-uncertainty' };
1816
+ return UNCERTAIN;
864
1817
  if (declaredAction(name) === undefined)
865
- return { kind: 'undeclared' };
1818
+ return undeclared(name);
866
1819
  try {
867
1820
  await ensureAuthorization();
868
1821
  }
869
1822
  catch {
870
- return { kind: 'transport-uncertainty' };
871
- }
872
- if (closed || authorization === undefined || refusal !== null) {
873
- return { kind: 'transport-uncertainty' };
1823
+ return UNCERTAIN;
874
1824
  }
1825
+ if (closed || authorization === undefined || refusal !== null)
1826
+ return UNCERTAIN;
1827
+ await dispatching?.();
875
1828
  journal.record(`transfer action ${name}`);
876
1829
  try {
877
1830
  const result = await options.adapter.action(authorization, { name, input });
@@ -885,12 +1838,66 @@ export function composeRuntime(options) {
885
1838
  journal.record(`outcome action ${result.kind}`);
886
1839
  if (result.kind === 'rejected')
887
1840
  journal.record(`refusal rejected ${result.code}`);
1841
+ return calledResult(result);
1842
+ }
1843
+ catch {
1844
+ journal.record('outcome action transport-uncertainty');
1845
+ return UNCERTAIN;
1846
+ }
1847
+ }
1848
+ function unsettled(result) {
1849
+ return result.kind !== 'action' && result.retryable;
1850
+ }
1851
+ async function recoveredAction(name, input) {
1852
+ const operation = operationOf(input);
1853
+ if (operation === null)
1854
+ return invokeAction(name, input);
1855
+ const kept = async () => (await openLocal()).keepCall({ operation, name, input });
1856
+ calling.add(operation);
1857
+ try {
1858
+ let result = await invokeAction(name, input, kept);
1859
+ if (unsettled(result)) {
1860
+ await recovery.attempt(`action ${operation}`, async () => {
1861
+ if (closed || refusal !== null)
1862
+ return 'done';
1863
+ if (!socketOpen)
1864
+ return 'again';
1865
+ result = await invokeAction(name, input, kept);
1866
+ return unsettled(result) ? 'again' : 'done';
1867
+ }, { again: true });
1868
+ }
1869
+ if (!unsettled(result))
1870
+ await (await openLocal()).dropCall(operation);
888
1871
  return result;
889
1872
  }
890
- catch {
891
- journal.record('outcome action transport-uncertainty');
892
- return { kind: 'transport-uncertainty' };
1873
+ finally {
1874
+ calling.delete(operation);
1875
+ }
1876
+ }
1877
+ async function resendCalls(signal) {
1878
+ if (!socketOpen || closed || stopping)
1879
+ return 'done';
1880
+ const local = await openLocal();
1881
+ for (const held of await local.calls()) {
1882
+ if (calling.has(held.operation))
1883
+ continue;
1884
+ if (closed || signal.aborted)
1885
+ return 'done';
1886
+ if (pastHorizon(held.operation)) {
1887
+ await local.dropCall(held.operation);
1888
+ continue;
1889
+ }
1890
+ calling.add(held.operation);
1891
+ try {
1892
+ if (unsettled(await invokeAction(held.name, held.input)))
1893
+ return 'again';
1894
+ await local.dropCall(held.operation);
1895
+ }
1896
+ finally {
1897
+ calling.delete(held.operation);
1898
+ }
893
1899
  }
1900
+ return 'done';
894
1901
  }
895
1902
  function continuing() {
896
1903
  return !closed && !discoveryPaused;
@@ -906,11 +1913,12 @@ export function composeRuntime(options) {
906
1913
  options.adapter.reached(locator, written, roomVersion) &&
907
1914
  !options.adapter.reached(locator, roomVersion, written));
908
1915
  }
909
- async function pullRefresh(authorized, confirmed) {
910
- if (!continuing())
1916
+ async function pullRefresh(authorized, confirmed, live) {
1917
+ if (!live())
911
1918
  return unconfirmed;
1919
+ const turn = generation;
912
1920
  try {
913
- const result = await refreshRoom(options.adapter, authorized, confirmed, (models, held) => remodel(confirmed.record.locator, models, held), continuing);
1921
+ const result = await refreshRoom(reads, authorized, confirmed, (models, held) => (live() ? remodel(confirmed.record.locator, models, held) : held), live);
914
1922
  const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;
915
1923
  journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);
916
1924
  return result;
@@ -919,34 +1927,106 @@ export function composeRuntime(options) {
919
1927
  journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);
920
1928
  throw error;
921
1929
  }
1930
+ finally {
1931
+ reads.finished(confirmed.record.locator, turn);
1932
+ }
922
1933
  }
923
- async function pullBootstrap(authorized, room) {
924
- if (!continuing())
1934
+ function staging(local, live) {
1935
+ return {
1936
+ held: (locator) => transfers.get(locator) ?? null,
1937
+ staged: (record) => local.staged(record),
1938
+ stage: (record, page) => exclusive(async () => {
1939
+ if (!live())
1940
+ return false;
1941
+ const bytes = layerBytes(page);
1942
+ if (!(await admitted(local, record.locator, bytes)))
1943
+ return false;
1944
+ try {
1945
+ await local.stage(record, page);
1946
+ }
1947
+ catch (error) {
1948
+ if (!exceeded(error))
1949
+ throw error;
1950
+ await exceededOn(record.locator, bytes);
1951
+ return false;
1952
+ }
1953
+ transfers.set(record.locator, record);
1954
+ readSide.recover();
1955
+ return true;
1956
+ }),
1957
+ abandon: (locator) => exclusive(async () => {
1958
+ if (!live())
1959
+ return;
1960
+ await local.abandon(locator);
1961
+ transfers.delete(locator);
1962
+ readSide.recover();
1963
+ }),
1964
+ };
1965
+ }
1966
+ function reusable(room) {
1967
+ const record = replicas.get(room.locator)?.confirmed.record;
1968
+ if (record === undefined || record.replica.selection !== room.replica.selection)
1969
+ return null;
1970
+ return { documents: record.documents, revisions: record.revisions };
1971
+ }
1972
+ async function pullBootstrap(authorized, room, local, live) {
1973
+ if (!live())
925
1974
  return unconfirmed;
1975
+ const turn = generation;
1976
+ if (replicas.has(room.locator)) {
1977
+ catching.add(room.locator);
1978
+ readSide.recover();
1979
+ }
926
1980
  try {
927
- const result = await bootstrapRoom(options.adapter, authorized, room, {
1981
+ const result = await bootstrapRoom(reads, authorized, room, {
928
1982
  collection: modelOf(room.locator),
929
1983
  selection: modelOf(room.locator, 'typed-selection'),
930
- }, (models, held) => remodel(room.locator, models, held), continuing);
1984
+ }, (models, held) => (live() ? remodel(room.locator, models, held) : held), live, staging(local, live), reusable(room));
931
1985
  const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;
932
1986
  journal.record(`transfer bootstrap ${room.locator} ${detail}`);
1987
+ if (result.kind !== 'staged')
1988
+ caughtUpTo(room.locator);
933
1989
  return result;
934
1990
  }
935
1991
  catch (error) {
936
1992
  journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);
1993
+ caughtUpTo(room.locator);
937
1994
  throw error;
938
1995
  }
1996
+ finally {
1997
+ reads.finished(room.locator, turn);
1998
+ }
1999
+ }
2000
+ function caughtUpTo(locator) {
2001
+ if (catching.delete(locator))
2002
+ readSide.recover();
2003
+ }
2004
+ function behind(room) {
2005
+ const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
2006
+ return (held !== undefined &&
2007
+ [announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later)));
2008
+ }
2009
+ async function advance(room, local, authorized, live) {
2010
+ const carried = reads.carried(room.locator);
2011
+ const withheld = await advanceOnce(room, local, authorized, live);
2012
+ if (withheld !== null || reads.carried(room.locator) === carried || !behind(room)) {
2013
+ return withheld;
2014
+ }
2015
+ return advanceOnce(room, local, authorized, live);
939
2016
  }
940
- async function advance(room, local, authorized) {
2017
+ async function advanceOnce(room, local, authorized, live) {
2018
+ await referenced(room.locator);
2019
+ if (!live() || paused.has(room.locator))
2020
+ return unconfirmed;
941
2021
  const held = replicas.get(room.locator);
942
2022
  if (held !== undefined) {
943
- const refreshed = await pullRefresh(authorized, held.confirmed);
944
- if (!continuing())
2023
+ const refreshed = await pullRefresh(authorized, held.confirmed, live);
2024
+ if (!live())
945
2025
  return unconfirmed;
946
2026
  if (refreshed.kind === 'still-current') {
947
- if (sourceRefusals.has(room.locator))
948
- return unconfirmed;
949
2027
  stale.delete(room.locator);
2028
+ if (sourceRefusals.has(room.locator))
2029
+ return null;
950
2030
  if (unreadable.delete(room.locator)) {
951
2031
  scopedRefusals.delete(room.locator);
952
2032
  list(room, true);
@@ -955,28 +2035,45 @@ export function composeRuntime(options) {
955
2035
  return null;
956
2036
  }
957
2037
  if (refreshed.kind === 'advanced') {
958
- if (!(await publish(local, room, refreshed.confirmed, held.confirmed))) {
2038
+ if (!(await publish(local, room, refreshed.confirmed, { base: held.confirmed }, live))) {
959
2039
  const now = replicas.get(room.locator)?.confirmed.record.roomVersion;
960
2040
  const reached = now !== undefined &&
961
2041
  options.adapter.reached(room.locator, now, refreshed.confirmed.record.roomVersion);
962
- return reached ? null : advance(room, local, authorized);
2042
+ return reached ? null : advance(room, local, authorized, live);
963
2043
  }
964
2044
  await retainModel(local, room, 'collection', modelOf(room.locator));
965
2045
  return null;
966
2046
  }
967
2047
  if (refreshed.kind !== 'beyond-horizon')
968
2048
  return refreshed;
2049
+ if (opened !== null) {
2050
+ owed.add(room.locator);
2051
+ readSide.recover();
2052
+ return unconfirmed;
2053
+ }
969
2054
  }
970
- const bootstrapped = await pullBootstrap(authorized, room);
971
- if (!continuing())
2055
+ const bootstrapped = await pullBootstrap(authorized, room, local, live);
2056
+ if (!live())
972
2057
  return unconfirmed;
973
2058
  if (bootstrapped.kind !== 'staged')
974
2059
  return bootstrapped;
975
- await publish(local, room, bootstrapped.confirmed);
2060
+ await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
976
2061
  return null;
977
2062
  }
978
2063
  async function withhold(withheld, room, local, progress) {
979
- stale.add(room.locator);
2064
+ if (withheld.kind === 'unconfirmed')
2065
+ return;
2066
+ if (withheld.kind === 'refused')
2067
+ stale.delete(room.locator);
2068
+ else
2069
+ stale.add(room.locator);
2070
+ if (withheld.kind === 'transport-uncertainty' || withheld.kind === 'retryable-refusal') {
2071
+ const reset = withheld.kind === 'retryable-refusal' ? withheld.reset : undefined;
2072
+ repairable.set(room.locator, reset);
2073
+ repairLater(room.locator, reset === undefined ? { again: true } : { at: Date.parse(reset) });
2074
+ }
2075
+ else
2076
+ repairable.delete(room.locator);
980
2077
  if (withheld.kind === 'scoped-refusal') {
981
2078
  await scoped(withheld, room, local);
982
2079
  }
@@ -1001,6 +2098,7 @@ export function composeRuntime(options) {
1001
2098
  function refusedSource(room, { refusal }) {
1002
2099
  sourceRefusals.set(room.locator, {
1003
2100
  code: refusal.rule,
2101
+ retryable: false,
1004
2102
  fields: {
1005
2103
  file: refusal.file,
1006
2104
  ...(refusal.location === undefined ? {} : { location: refusal.location }),
@@ -1011,12 +2109,21 @@ export function composeRuntime(options) {
1011
2109
  unreadable.add(room.locator);
1012
2110
  list(room, false);
1013
2111
  emitRooms();
2112
+ moveTo({ ...status, ...attention() });
1014
2113
  journal.record(`source refused ${room.locator} ${refusal.rule} ${refusal.file}`);
1015
2114
  }
1016
2115
  function leaving(batch, result) {
1017
2116
  if (result.kind === 'expired')
1018
- return { batch, returned: { kind: 'expired' } };
1019
- return { batch, returned: { kind: result.kind, code: result.code, fields: result.fields } };
2117
+ return { batch, returned: returnedBy('expired') };
2118
+ return {
2119
+ batch,
2120
+ returned: {
2121
+ kind: result.kind,
2122
+ code: result.code,
2123
+ fields: result.fields,
2124
+ retryable: result.retryable,
2125
+ },
2126
+ };
1020
2127
  }
1021
2128
  function logAccepted(locator, submitted, accepted) {
1022
2129
  journal.record(`outcome ${locator} ${submitted.id} accepted ${accepted.roomVersion}` +
@@ -1024,6 +2131,7 @@ export function composeRuntime(options) {
1024
2131
  (accepted.time === undefined ? '' : ` time ${accepted.time}`));
1025
2132
  }
1026
2133
  async function adoptAccepted(room, local, submitted, accepted) {
2134
+ await referenced(room.locator);
1027
2135
  if (!continuing())
1028
2136
  return unconfirmed;
1029
2137
  const current = replicas.get(room.locator);
@@ -1034,22 +2142,23 @@ export function composeRuntime(options) {
1034
2142
  logAccepted(room.locator, submitted, accepted);
1035
2143
  const applied = options.adapter.reached(room.locator, held, accepted.roomVersion)
1036
2144
  ? { kind: 'staged', confirmed: current.confirmed }
1037
- : applyReturned(current.confirmed, accepted.documents, accepted.revisions, accepted.removals, accepted.attachments, options.adapter.follows(room.locator, held, accepted.roomVersion)
2145
+ : applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
1038
2146
  ? accepted.roomVersion
1039
2147
  : held, accepted.roomVersion);
1040
2148
  if (applied.kind !== 'staged') {
1041
2149
  const state = pendings.get(submitted.id);
1042
2150
  await local.accept(room.locator, submitted.id, accepted.roomVersion);
1043
- if (state !== undefined)
2151
+ if (state !== undefined && !fences.has(room.locator))
1044
2152
  pendings.set(submitted.id, { ...state, accepted: accepted.roomVersion });
1045
2153
  emitQueue(room.locator);
1046
2154
  return applied;
1047
2155
  }
1048
- const set = await settle(local, room.locator, current, applied.confirmed, current.queue.filter((batch) => batch.id !== submitted.id), { room: true });
2156
+ const settled = await settle(local, room.locator, current, applied.confirmed, current.queue.filter((batch) => batch.id !== submitted.id), { room: true });
1049
2157
  pendings.delete(submitted.id);
1050
2158
  unreadable.delete(room.locator);
1051
2159
  sourceRefusals.delete(room.locator);
1052
2160
  declarationRefusals.delete(room.locator);
2161
+ const set = settled();
1053
2162
  list(room, true);
1054
2163
  publishChangeSet(set);
1055
2164
  moveTo({ ...status, ...attention() });
@@ -1063,14 +2172,14 @@ export function composeRuntime(options) {
1063
2172
  refusedSource(room, failed);
1064
2173
  return false;
1065
2174
  }
1066
- async function submitRoom(room, local, authorized, progress) {
1067
- while (continuing() && authorization !== undefined) {
2175
+ async function submitRoom(room, local, authorized, progress, signal) {
2176
+ while (continuing() && authorization !== undefined && !signal.aborted) {
1068
2177
  const replica = replicas.get(room.locator);
1069
2178
  const head = replica?.queue[0];
1070
2179
  if (replica === undefined || head === undefined)
1071
- return;
2180
+ return 'done';
1072
2181
  if (pendings.get(head.id)?.accepted !== undefined)
1073
- return;
2182
+ return 'done';
1074
2183
  const state = pendings.get(head.id);
1075
2184
  const { submission, lost: earlier } = state ?? {
1076
2185
  submission: { state: 'waiting' },
@@ -1078,24 +2187,30 @@ export function composeRuntime(options) {
1078
2187
  };
1079
2188
  if (submission.state === 'reset' && Date.now() < Date.parse(submission.reset)) {
1080
2189
  progress.complete = false;
1081
- return;
2190
+ return { at: Date.parse(submission.reset) };
1082
2191
  }
1083
2192
  if (writesHeld()) {
1084
2193
  progress.complete = false;
1085
2194
  journal.record(`submission ${room.locator} ${head.id} held`);
1086
- return;
2195
+ return 'done';
1087
2196
  }
1088
2197
  const lost = earlier || submission.state === 'submitted';
2198
+ if (lost && pastHorizon(head.id)) {
2199
+ await discardPending(room, local, signal);
2200
+ return 'done';
2201
+ }
1089
2202
  let result;
1090
2203
  journal.record(`submission ${room.locator} ${head.id}`);
1091
2204
  await exclusive(() => mark(local, room.locator, head.id, { state: 'submitted' }, lost));
1092
- if (discoveryPaused)
1093
- return;
1094
- if (writesHeld()) {
2205
+ if (discoveryPaused || fences.has(room.locator))
2206
+ return 'done';
2207
+ if (signal.aborted || writesHeld()) {
1095
2208
  await exclusive(() => mark(local, room.locator, head.id, submission, earlier));
2209
+ if (signal.aborted)
2210
+ return 'done';
1096
2211
  progress.complete = false;
1097
2212
  journal.record(`submission ${room.locator} ${head.id} held`);
1098
- return;
2213
+ return 'done';
1099
2214
  }
1100
2215
  const opensBefore = openSignals;
1101
2216
  const answered = awaitingAnswer(room.locator);
@@ -1111,32 +2226,36 @@ export function composeRuntime(options) {
1111
2226
  progress.complete = false;
1112
2227
  if (continuing())
1113
2228
  progress.reachable = false;
1114
- return;
2229
+ return 'again';
2230
+ }
2231
+ if (signal.aborted) {
2232
+ answered();
2233
+ return 'done';
1115
2234
  }
1116
2235
  if (result.kind !== 'accepted' || !continuing())
1117
2236
  answered();
1118
2237
  if (!continuing())
1119
- return;
2238
+ return 'done';
1120
2239
  if (result.kind === 'transport-uncertainty') {
1121
2240
  progress.complete = false;
1122
2241
  progress.reachable = false;
1123
- return;
2242
+ return 'again';
1124
2243
  }
1125
2244
  if (result.kind === 'room-not-readable') {
1126
2245
  progress.complete = false;
1127
2246
  unreadable.add(room.locator);
1128
2247
  list(room, false);
1129
2248
  emitRooms();
1130
- return;
2249
+ return 'done';
1131
2250
  }
1132
2251
  if (result.kind === 'revoked-authorization') {
1133
2252
  await refuse('revoked-authorization');
1134
- return;
2253
+ return 'done';
1135
2254
  }
1136
2255
  if (result.kind === 'scoped-refusal') {
1137
2256
  await scoped(result, room, local);
1138
2257
  progress.complete = false;
1139
- return;
2258
+ return 'done';
1140
2259
  }
1141
2260
  if (result.kind === 'write-halted') {
1142
2261
  journal.record(`outcome ${room.locator} ${head.id} write-halted`);
@@ -1145,16 +2264,24 @@ export function composeRuntime(options) {
1145
2264
  continue;
1146
2265
  haltedRefusal = true;
1147
2266
  progress.complete = false;
1148
- return;
2267
+ return 'done';
1149
2268
  }
1150
2269
  if (result.kind === 'conflicted' ||
1151
2270
  result.kind === 'rejected' ||
1152
2271
  result.kind === 'expired' ||
1153
2272
  result.kind === 'retryable-refusal') {
2273
+ if (result.kind === 'expired' && lost && result.restored !== true) {
2274
+ journal.record(`outcome ${room.locator} ${head.id} expired`);
2275
+ await discardPending(room, local, signal);
2276
+ return 'done';
2277
+ }
1154
2278
  if (result.kind === 'expired') {
1155
- const withheld = await advance(room, local, authorized);
1156
- if (withheld !== null)
1157
- return withhold(withheld, room, local, progress);
2279
+ await exclusive(() => mark(local, room.locator, head.id, { state: 'waiting' }, false));
2280
+ const withheld = await advance(room, local, authorized, continuing);
2281
+ if (withheld !== null) {
2282
+ await withhold(withheld, room, local, progress);
2283
+ return 'done';
2284
+ }
1158
2285
  }
1159
2286
  journal.record(`outcome ${room.locator} ${head.id} ${result.kind}` +
1160
2287
  (result.kind === 'conflicted' && result.roomVersion !== undefined
@@ -1167,8 +2294,7 @@ export function composeRuntime(options) {
1167
2294
  const reset = result.reset;
1168
2295
  progress.complete = false;
1169
2296
  await exclusive(() => mark(local, room.locator, head.id, reset === undefined ? { state: 'waiting' } : { state: 'reset', reset }, lost));
1170
- armTimer();
1171
- return;
2297
+ return reset === undefined ? 'again' : { at: Date.parse(reset) };
1172
2298
  }
1173
2299
  if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {
1174
2300
  const left = leaving(head, result);
@@ -1179,36 +2305,82 @@ export function composeRuntime(options) {
1179
2305
  if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {
1180
2306
  return;
1181
2307
  }
1182
- const set = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
1183
- leaving: result.kind === 'expired' && landed(head, current.confirmed)
2308
+ const settled = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
2309
+ leaving: (result.kind === 'expired' && landed(head, current.confirmed)) ||
2310
+ (result.kind === 'conflicted' && landed(head, current.confirmed, result.affected))
1184
2311
  ? { ...left, returned: null }
1185
2312
  : left,
1186
2313
  });
1187
- publishChangeSet(set);
2314
+ publishChangeSet(settled());
1188
2315
  moveTo({ ...status, ...attention() });
1189
2316
  });
1190
2317
  if (result.kind === 'expired')
1191
2318
  continue;
1192
- const withheld = await advance(room, local, authorized);
1193
- if (withheld !== null)
1194
- return withhold(withheld, room, local, progress);
2319
+ const withheld = await advance(room, local, authorized, continuing);
2320
+ if (withheld !== null) {
2321
+ await withhold(withheld, room, local, progress);
2322
+ return 'done';
2323
+ }
1195
2324
  continue;
1196
2325
  }
1197
2326
  const kept = await adopted(room, local, head, result).finally(answered);
1198
2327
  if (!kept) {
1199
2328
  progress.complete = false;
1200
- return;
2329
+ return 'done';
1201
2330
  }
1202
2331
  }
2332
+ return 'done';
2333
+ }
2334
+ function pastHorizon(identity) {
2335
+ return (outcomeRetention !== null && identityTime(identity) + outcomeRetention * 1000 <= Date.now());
2336
+ }
2337
+ async function discardPending(room, local, signal) {
2338
+ const { locator } = room;
2339
+ const discarded = await exclusive(async () => {
2340
+ if (fences.has(locator))
2341
+ return false;
2342
+ const before = replicas.get(locator);
2343
+ const queue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
2344
+ fences.set(locator, { at: discoveries, erased: false });
2345
+ lastFenced.set(locator, ++fencings);
2346
+ try {
2347
+ await local.discard(locator);
2348
+ }
2349
+ finally {
2350
+ fences.delete(locator);
2351
+ }
2352
+ for (const batch of queue)
2353
+ pendings.delete(batch.id);
2354
+ queuesWithoutReplica.delete(locator);
2355
+ const after = before === undefined ? null : replicaOf(before.confirmed, [], before);
2356
+ if (after !== null)
2357
+ replicas.set(locator, after);
2358
+ journal.record(`room discarded ${locator}`);
2359
+ publishChangeSet(changeSet(locator, before ?? null, after, { queue: true }));
2360
+ moveTo({ ...status, ...attention() });
2361
+ return true;
2362
+ });
2363
+ if (!discarded)
2364
+ return;
2365
+ const progress = { complete: true, reachable: true };
2366
+ await roomTask(locator, async (live) => {
2367
+ await Promise.race([
2368
+ reload(room, local, progress, () => live() && !signal.aborted),
2369
+ abandonedOn(signal),
2370
+ ]);
2371
+ });
2372
+ if (signal.aborted)
2373
+ return;
2374
+ await rest(progress);
1203
2375
  }
1204
2376
  function awaitingAnswer(locator) {
1205
2377
  let release = () => { };
1206
2378
  const awaited = new Promise((resolve) => {
1207
2379
  release = resolve;
1208
2380
  });
1209
- answering.set(locator, awaited);
2381
+ answering.set(locator, { generation, answered: awaited });
1210
2382
  return () => {
1211
- if (answering.get(locator) === awaited)
2383
+ if (answering.get(locator)?.answered === awaited)
1212
2384
  answering.delete(locator);
1213
2385
  release();
1214
2386
  };
@@ -1241,7 +2413,7 @@ export function composeRuntime(options) {
1241
2413
  ...(attached === 'collection' ? { model: next } : { selectionModel: next }),
1242
2414
  };
1243
2415
  const reclassified = sameMembership(declared, held.confirmed.record)
1244
- ? readConfirmed(declared, held.confirmed)
2416
+ ? { kind: 'staged', confirmed: confirmedOf(declared, held.confirmed) }
1245
2417
  : readReclassified(declared, held.confirmed);
1246
2418
  const record = reclassified.kind === 'staged'
1247
2419
  ? declared
@@ -1249,12 +2421,10 @@ export function composeRuntime(options) {
1249
2421
  ...declared,
1250
2422
  typedSelection: held.confirmed.record.typedSelection,
1251
2423
  };
1252
- const read = reclassified.kind === 'deferred' ? readConfirmed(record, held.confirmed) : reclassified;
1253
- await local.write({
1254
- next: record,
1255
- previous: held.confirmed.record,
1256
- queue: held.queue,
1257
- });
2424
+ const read = reclassified.kind === 'deferred'
2425
+ ? { kind: 'staged', confirmed: confirmedOf(record, held.confirmed) }
2426
+ : reclassified;
2427
+ await local.write({ next: record, previous: held.confirmed.record });
1258
2428
  if (read.kind === 'staged') {
1259
2429
  replicas.set(room.locator, replicaOf(read.confirmed, held.queue, held));
1260
2430
  if (declarationRefusals.delete(room.locator)) {
@@ -1281,7 +2451,16 @@ export function composeRuntime(options) {
1281
2451
  });
1282
2452
  }
1283
2453
  async function scoped(result, room, local) {
1284
- scopedRefusals.set(room.locator, { code: result.code, fields: result.fields });
2454
+ if ((result.scope === 'content' || result.scope === 'sync') && !result.retryable) {
2455
+ journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
2456
+ await loseRooms([room.locator]);
2457
+ return;
2458
+ }
2459
+ scopedRefusals.set(room.locator, {
2460
+ code: result.code,
2461
+ fields: result.fields,
2462
+ retryable: result.retryable,
2463
+ });
1285
2464
  let scopedAway = room;
1286
2465
  if (result.scope === 'model')
1287
2466
  await retainModel(local, room, 'collection', {
@@ -1318,22 +2497,27 @@ export function composeRuntime(options) {
1318
2497
  roomVersion: record.roomVersion,
1319
2498
  documents: record.documents,
1320
2499
  revisions: record.revisions,
1321
- attachments: record.attachments,
1322
2500
  },
1323
2501
  ];
1324
2502
  });
1325
2503
  }
1326
- async function synchronize(listed, local, progress, attempt) {
1327
- const prepared = await Promise.allSettled(listed.map((room) => prepareRoom(room, local, progress)));
1328
- const ready = listed.filter((_, index) => {
2504
+ async function synchronize(listed, local, progress, attempt, live) {
2505
+ const acquired = listed.filter(acquires);
2506
+ const prepared = await Promise.allSettled(acquired.map((room) => prepareRoom(room, local, progress)));
2507
+ if (!live())
2508
+ return;
2509
+ const ready = acquired.filter((_, index) => {
1329
2510
  const outcome = prepared[index];
1330
2511
  return outcome?.status === 'fulfilled' && outcome.value;
1331
2512
  });
1332
- if (attempt === 'opened')
1333
- options.adapter.roomStream?.hold(heldRooms(ready));
2513
+ if (attempt === 'opened') {
2514
+ options.adapter.roomStream?.hold(heldRooms(ready), heldDemand(acquired));
2515
+ handed = true;
2516
+ }
2517
+ discovering?.release();
1334
2518
  const loaded = await Promise.allSettled(ready
1335
2519
  .filter((room) => attempt === 'unstreamed' || !replicas.has(room.locator))
1336
- .map((room) => loadRoom(room, local, progress)));
2520
+ .map((room) => roomTask(room.locator, (held) => loadRoom(room, local, progress, held))));
1337
2521
  const failed = [...prepared, ...loaded].find((room) => room.status === 'rejected');
1338
2522
  if (failed !== undefined)
1339
2523
  throw failed.reason;
@@ -1355,21 +2539,12 @@ export function composeRuntime(options) {
1355
2539
  await retainModel(local, room, 'collection', modelOf(room.locator));
1356
2540
  if (discoveryPaused || authorization === undefined)
1357
2541
  return false;
1358
- if (room.replica.admission !== 'admitted') {
1359
- if (replicas.has(room.locator))
1360
- progress.complete = false;
1361
- return false;
1362
- }
1363
- return true;
2542
+ return room.replica.admission === 'admitted';
1364
2543
  }
1365
- async function caughtUp(room, local, progress) {
1366
- const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
1367
- if (held === undefined || authorization === undefined)
1368
- return;
1369
- const behind = [announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later));
1370
- if (!behind)
2544
+ async function caughtUp(room, local, progress, live) {
2545
+ if (authorization === undefined || !live() || !behind(room))
1371
2546
  return;
1372
- const withheld = await advance(room, local, authorization);
2547
+ const withheld = await advance(room, local, authorization, live);
1373
2548
  if (withheld !== null)
1374
2549
  await withhold(withheld, room, local, progress);
1375
2550
  }
@@ -1379,39 +2554,46 @@ export function composeRuntime(options) {
1379
2554
  return model.status === 'unavailable' && model.reason === 'revoked';
1380
2555
  });
1381
2556
  }
1382
- async function loadRoom(room, local, progress) {
1383
- if (discoveryPaused || authorization === undefined)
2557
+ async function loadRoom(room, local, progress, live) {
2558
+ if (!live() || authorization === undefined)
1384
2559
  return;
1385
2560
  if (replicas.has(room.locator) && revoked(room.locator)) {
1386
- await reload(room, local, progress);
2561
+ await reload(room, local, progress, live);
1387
2562
  return;
1388
2563
  }
1389
- const withheld = await advance(room, local, authorization);
2564
+ const withheld = await advance(room, local, authorization, live);
1390
2565
  if (withheld !== null) {
1391
2566
  await withhold(withheld, room, local, progress);
1392
2567
  return;
1393
2568
  }
1394
- await caughtUp(room, local, progress);
2569
+ await caughtUp(room, local, progress, live);
1395
2570
  }
1396
- async function reload(room, local, progress) {
1397
- if (discoveryPaused || authorization === undefined)
1398
- return;
1399
- const bootstrapped = await pullBootstrap(authorization, room);
1400
- if (!continuing())
1401
- return;
1402
- if (bootstrapped.kind !== 'staged') {
1403
- await withhold(bootstrapped, room, local, progress);
1404
- return;
2571
+ async function reload(room, local, progress, live) {
2572
+ try {
2573
+ if (!live() || authorization === undefined)
2574
+ return;
2575
+ const bootstrapped = await pullBootstrap(authorization, room, local, live);
2576
+ if (!live())
2577
+ return;
2578
+ if (bootstrapped.kind !== 'staged') {
2579
+ await withhold(bootstrapped, room, local, progress);
2580
+ return;
2581
+ }
2582
+ await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
2583
+ await caughtUp(room, local, progress, live);
2584
+ }
2585
+ finally {
2586
+ caughtUpTo(room.locator);
1405
2587
  }
1406
- await publish(local, room, bootstrapped.confirmed);
1407
- await caughtUp(room, local, progress);
1408
2588
  }
1409
- async function discoverRooms(local, progress, attempt) {
2589
+ async function discoverRooms(local, progress, attempt, live) {
1410
2590
  if (closed || authorization === undefined) {
1411
2591
  notifyReady();
1412
2592
  return;
1413
2593
  }
1414
2594
  moveTo(transferring(status));
2595
+ discoveries += 1;
2596
+ const started = discoveries;
1415
2597
  let result;
1416
2598
  try {
1417
2599
  result = await options.adapter.discover(authorization);
@@ -1419,7 +2601,8 @@ export function composeRuntime(options) {
1419
2601
  catch {
1420
2602
  result = { kind: 'transport-uncertainty' };
1421
2603
  }
1422
- if (closed) {
2604
+ if (!live()) {
2605
+ progress.complete = false;
1423
2606
  notifyReady();
1424
2607
  return;
1425
2608
  }
@@ -1433,15 +2616,16 @@ export function composeRuntime(options) {
1433
2616
  }
1434
2617
  progress.reachable = false;
1435
2618
  progress.complete = false;
1436
- if (attempt === 'opened') {
1437
- options.adapter.roomStream?.hold(heldRooms([...discovered.values()]));
1438
- }
1439
2619
  notifyReady();
1440
2620
  return;
1441
2621
  }
1442
2622
  if (result.kind === 'contract-unavailable') {
1443
2623
  journal.record(`connection contract unavailable ${result.code}`);
1444
- await refuse('missing-required-guarantee', { code: result.code, fields: result.fields });
2624
+ await refuse('missing-required-guarantee', {
2625
+ code: result.code,
2626
+ fields: result.fields,
2627
+ retryable: result.retryable,
2628
+ });
1445
2629
  notifyReady();
1446
2630
  return;
1447
2631
  }
@@ -1476,14 +2660,20 @@ export function composeRuntime(options) {
1476
2660
  }
1477
2661
  const previousCapabilities = capabilities;
1478
2662
  capabilities = result.capabilities;
2663
+ outcomeRetention = result.retention.outcome;
1479
2664
  notifyReady();
1480
2665
  if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits) ||
1481
2666
  JSON.stringify(result.capabilities) !== JSON.stringify(previousCapabilities)) {
1482
2667
  limits = result.providerLimits;
1483
2668
  await local.declare(limits, capabilities);
1484
2669
  }
1485
- await applyDiscovery(result.rooms, local);
1486
- await synchronize(result.rooms, local, progress, attempt);
2670
+ const signedIn = result.member ?? null;
2671
+ if (JSON.stringify(signedIn) !== JSON.stringify(member)) {
2672
+ await local.keepMember(signedIn);
2673
+ member = signedIn;
2674
+ emitMember();
2675
+ }
2676
+ await synchronize(await applyDiscovery(result.rooms, started), local, progress, attempt, live);
1487
2677
  }
1488
2678
  async function ensureAuthorization() {
1489
2679
  if (authorization !== undefined)
@@ -1497,76 +2687,175 @@ export function composeRuntime(options) {
1497
2687
  throw error;
1498
2688
  }
1499
2689
  }
1500
- function task(work) {
2690
+ async function admittedRead(work) {
2691
+ if (roomReads.generation !== generation) {
2692
+ roomReads = { generation, free: ROOM_READS, waiting: [] };
2693
+ }
2694
+ const reads = roomReads;
2695
+ while (reads.free === 0)
2696
+ await new Promise((admit) => reads.waiting.push(admit));
2697
+ reads.free -= 1;
2698
+ try {
2699
+ await work();
2700
+ }
2701
+ finally {
2702
+ reads.free += 1;
2703
+ reads.waiting.shift()?.();
2704
+ }
2705
+ }
2706
+ function roomTask(locator, work) {
2707
+ return task(roomLane(locator), (live) => admittedRead(() => work(live)));
2708
+ }
2709
+ function task(lane, work) {
1501
2710
  if (stopping)
1502
- return chain;
1503
- chain = chain.then(work, work).catch(() => undefined);
1504
- return chain;
2711
+ return Promise.resolve();
2712
+ const held = lanes.get(lane);
2713
+ const current = held?.generation === generation ? held : { generation, chain: Promise.resolve() };
2714
+ const turn = current.generation;
2715
+ const live = () => turn === generation && continuing();
2716
+ const run = current.chain.then(() => work(live)).catch(() => undefined);
2717
+ current.chain = run;
2718
+ lanes.set(lane, current);
2719
+ working.add(run);
2720
+ void run.finally(() => working.delete(run));
2721
+ return run;
1505
2722
  }
1506
2723
  function sync(attempt) {
1507
- return task(async () => {
1508
- if (closed || stopping || discoveryPaused) {
2724
+ return task(OPENING_LANE, async (live) => {
2725
+ if (!live()) {
1509
2726
  notifyReady();
1510
2727
  return;
1511
2728
  }
1512
2729
  const progress = { complete: true, reachable: true };
1513
- underway = attempt === 'opened' ? progress : null;
2730
+ const gate = discover();
2731
+ if (attempt === 'opened')
2732
+ opened = generation;
2733
+ underway = attempt === 'opened' ? { generation, progress } : null;
2734
+ if (attempt === 'opened')
2735
+ streamed = progress;
1514
2736
  complete = false;
1515
2737
  recorded = false;
1516
2738
  moveTo(transferring(status));
2739
+ handed = false;
1517
2740
  try {
1518
2741
  const local = await openLocal();
1519
- if (closed)
2742
+ if (!live())
1520
2743
  return;
1521
2744
  await ensureAuthorization();
1522
- if (closed)
2745
+ if (!live())
1523
2746
  return;
1524
- await discoverRooms(local, progress, attempt);
2747
+ await discoverRooms(local, progress, attempt, live);
1525
2748
  }
1526
2749
  catch {
1527
2750
  progress.complete = false;
1528
- if (attempt === 'opened') {
1529
- options.adapter.roomStream?.hold(heldRooms([...discovered.values()]));
1530
- }
2751
+ if (attempt === 'opened' && !handed)
2752
+ progress.reachable = false;
1531
2753
  }
1532
2754
  finally {
2755
+ gate.release();
1533
2756
  notifyReady();
1534
2757
  }
1535
- if (attempt === 'opened')
2758
+ if (!live())
2759
+ return;
2760
+ if (attempt !== 'opened') {
2761
+ await finishOpening(progress, live);
2762
+ return;
2763
+ }
2764
+ if (handed || closed || progress.reachable)
2765
+ return;
2766
+ underway = null;
2767
+ opened = null;
2768
+ journal.record('connection reopen');
2769
+ await rest(progress, live);
2770
+ options.adapter.roomStream?.reopen();
2771
+ });
2772
+ }
2773
+ function rediscover() {
2774
+ return task(OPENING_LANE, async (live) => {
2775
+ if (!live() || !socketOpen)
2776
+ return;
2777
+ const progress = { complete: true, reachable: true };
2778
+ const gate = discover();
2779
+ moveTo(transferring(status));
2780
+ try {
2781
+ const local = await openLocal();
2782
+ if (!live())
2783
+ return;
2784
+ await ensureAuthorization();
2785
+ if (!live())
2786
+ return;
2787
+ await discoverRooms(local, progress, 'authorized', live);
2788
+ }
2789
+ catch {
2790
+ progress.complete = false;
2791
+ }
2792
+ finally {
2793
+ gate.release();
2794
+ notifyReady();
2795
+ }
2796
+ if (!live())
1536
2797
  return;
1537
- await finishOpening(progress);
2798
+ if (!progress.complete)
2799
+ complete = false;
2800
+ await rest(progress, live);
1538
2801
  });
1539
2802
  }
1540
- function closedSocket(revoked) {
2803
+ function closedSocket(revoked, lost) {
1541
2804
  const opened = socketOpen;
1542
2805
  socketOpen = false;
2806
+ if (lost) {
2807
+ reads.lost();
2808
+ conversations.lost();
2809
+ }
1543
2810
  if (revoked) {
1544
2811
  void refuse('revoked-authorization');
1545
2812
  return;
1546
2813
  }
1547
- if (opened || status.providerUnreachable)
1548
- return;
1549
- moveTo({ ...status, providerUnreachable: true });
2814
+ complete = false;
2815
+ if (streamed !== null)
2816
+ streamed.complete = false;
2817
+ moveTo({
2818
+ ...status,
2819
+ state: status.state === 'synced' ? 'syncing' : status.state,
2820
+ providerUnreachable: status.providerUnreachable || !opened,
2821
+ });
1550
2822
  }
1551
2823
  function applyOpening(expired) {
1552
- return task(async () => {
1553
- const progress = underway;
2824
+ const progress = underway?.generation === generation ? underway.progress : null;
2825
+ const cycle = progress ?? { complete: true, reachable: true };
2826
+ const replacing = reloadNow((room) => expired.includes(room.locator), cycle);
2827
+ if (opened === generation)
2828
+ opened = null;
2829
+ return task(OPENING_LANE, async (live) => {
1554
2830
  underway = null;
1555
- if (closed || stopping)
2831
+ if (!live())
1556
2832
  return;
1557
2833
  if (progress === null) {
1558
- await reloadExpired(expired);
2834
+ await replacing;
2835
+ await rest(cycle, live);
1559
2836
  return;
1560
2837
  }
2838
+ await roomsCarried(expired);
2839
+ if (!live())
2840
+ return;
2841
+ const replaced = new Set(owed);
2842
+ owed.clear();
1561
2843
  try {
1562
2844
  const local = await openLocal();
1563
2845
  const held = [...discovered.values()].filter((room) => replicas.has(room.locator));
1564
- const reloading = held.filter((room) => expired.includes(room.locator) || revoked(room.locator));
1565
- const reloaded = await Promise.allSettled(reloading.map((room) => reload(room, local, progress)));
2846
+ const reloading = held.filter((room) => !expired.includes(room.locator) &&
2847
+ (replaced.has(room.locator) || revoked(room.locator)));
2848
+ for (const room of reloading)
2849
+ catching.add(room.locator);
2850
+ readSide.recover();
2851
+ const reloads = Promise.allSettled(reloading.map((room) => roomTask(room.locator, (current) => reload(room, local, progress, current))));
2852
+ const reloaded = [...(await reloads), ...(await replacing)];
1566
2853
  if (progress.reachable) {
1567
- for (const room of held)
1568
- if (!reloading.includes(room))
2854
+ for (const room of held) {
2855
+ if (!expired.includes(room.locator) && !reloading.includes(room)) {
1569
2856
  await confirmModels(room, local);
2857
+ }
2858
+ }
1570
2859
  }
1571
2860
  const failed = reloaded.find((outcome) => outcome.status === 'rejected');
1572
2861
  if (failed !== undefined)
@@ -1576,21 +2865,21 @@ export function composeRuntime(options) {
1576
2865
  progress.complete = false;
1577
2866
  progress.reachable = false;
1578
2867
  }
1579
- await finishOpening(progress);
2868
+ if (live())
2869
+ await finishOpening(progress, live);
1580
2870
  });
1581
2871
  }
1582
- async function reloadExpired(expired) {
1583
- const progress = { complete: true, reachable: true };
2872
+ async function reloadNow(replaced, progress) {
1584
2873
  try {
1585
2874
  const local = await openLocal();
1586
- await Promise.allSettled([...discovered.values()]
1587
- .filter((room) => replicas.has(room.locator) && expired.includes(room.locator))
1588
- .map((room) => reload(room, local, progress)));
2875
+ return await Promise.allSettled([...discovered.values()]
2876
+ .filter((room) => replicas.has(room.locator) && replaced(room))
2877
+ .map((room) => roomTask(room.locator, (live) => reload(room, local, progress, live))));
1589
2878
  }
1590
2879
  catch {
1591
2880
  progress.reachable = false;
2881
+ return [];
1592
2882
  }
1593
- await rest(progress);
1594
2883
  }
1595
2884
  async function confirmModels(room, local) {
1596
2885
  for (const attached of ['collection', 'typed-selection']) {
@@ -1601,38 +2890,96 @@ export function composeRuntime(options) {
1601
2890
  }
1602
2891
  }
1603
2892
  function submitLater(locator) {
1604
- const running = submitting.get(locator);
1605
- if (running !== undefined) {
1606
- running.again = true;
2893
+ if (localSaves)
1607
2894
  return;
2895
+ void recovery.attempt(`submit ${locator}`, (signal) => submitPass(locator, signal));
2896
+ }
2897
+ async function submitPass(locator, signal) {
2898
+ const room = discovered.get(locator);
2899
+ if (closed || stopping || discoveryPaused || room === undefined)
2900
+ return 'done';
2901
+ const progress = { complete: true, reachable: true };
2902
+ let next;
2903
+ try {
2904
+ await ensureAuthorization();
2905
+ if (authorization === undefined)
2906
+ return 'done';
2907
+ next = await submitRoom(room, await openLocal(), authorization, progress, signal);
1608
2908
  }
1609
- const run = { again: false, done: Promise.resolve() };
1610
- submitting.set(locator, run);
1611
- run.done = (async () => {
1612
- try {
1613
- do {
1614
- run.again = false;
1615
- const room = discovered.get(locator);
1616
- if (closed || stopping || discoveryPaused || room === undefined)
1617
- return;
1618
- const progress = { complete: true, reachable: true };
1619
- try {
1620
- await ensureAuthorization();
1621
- if (authorization === undefined)
1622
- return;
1623
- await submitRoom(room, await openLocal(), authorization, progress);
1624
- }
1625
- catch {
1626
- progress.reachable = false;
1627
- }
1628
- armTimer();
1629
- await rest(progress);
1630
- } while (run.again);
1631
- }
1632
- finally {
1633
- submitting.delete(locator);
1634
- }
1635
- })();
2909
+ catch {
2910
+ progress.reachable = false;
2911
+ next = 'again';
2912
+ }
2913
+ if (signal.aborted)
2914
+ return 'done';
2915
+ await rest(progress);
2916
+ return next === 'again' && !socketOpen ? 'done' : next;
2917
+ }
2918
+ function repairLater(locator, when) {
2919
+ if (!socketOpen || repairing.has(locator))
2920
+ return;
2921
+ void recovery.attempt(`repair ${locator}`, (signal) => repairPass(locator, signal), when);
2922
+ }
2923
+ async function repairPass(locator, signal) {
2924
+ const room = discovered.get(locator);
2925
+ if (!socketOpen || closed || stopping || discoveryPaused || !stale.has(locator))
2926
+ return 'done';
2927
+ if (room === undefined || room.replica.admission !== 'admitted')
2928
+ return 'done';
2929
+ const progress = { complete: true, reachable: true };
2930
+ repairing.add(locator);
2931
+ try {
2932
+ const local = await openLocal();
2933
+ await roomTask(locator, async (live) => {
2934
+ const current = () => live() && !signal.aborted;
2935
+ if (!current() || authorization === undefined)
2936
+ return;
2937
+ const withheld = await Promise.race([
2938
+ advance(room, local, authorization, current),
2939
+ abandonedOn(signal),
2940
+ ]);
2941
+ if (withheld !== null && current())
2942
+ await withhold(withheld, room, local, progress);
2943
+ });
2944
+ }
2945
+ catch {
2946
+ stale.add(locator);
2947
+ progress.reachable = false;
2948
+ }
2949
+ finally {
2950
+ repairing.delete(locator);
2951
+ }
2952
+ if (signal.aborted)
2953
+ return 'done';
2954
+ await rest(progress);
2955
+ if (!stale.has(locator)) {
2956
+ if ((replicas.get(locator)?.queue.length ?? 0) > 0)
2957
+ submitLater(locator);
2958
+ return 'done';
2959
+ }
2960
+ if (!repairable.has(locator))
2961
+ return 'done';
2962
+ const reset = repairable.get(locator);
2963
+ return reset === undefined ? 'again' : { at: Date.parse(reset) };
2964
+ }
2965
+ function resendLater() {
2966
+ if (!socketOpen)
2967
+ return;
2968
+ void recovery.attempt('resend', resendPass, { again: true });
2969
+ }
2970
+ async function resendPass(signal) {
2971
+ if (!socketOpen || closed || stopping || discoveryPaused)
2972
+ return 'done';
2973
+ const reading = { complete: true, reachable: true };
2974
+ try {
2975
+ await conversations.resend(reading);
2976
+ }
2977
+ catch {
2978
+ reading.reachable = false;
2979
+ }
2980
+ if (signal.aborted)
2981
+ return 'done';
2982
+ return reading.reachable && reading.complete ? 'done' : 'again';
1636
2983
  }
1637
2984
  function submitAll() {
1638
2985
  for (const [locator, replica] of replicas) {
@@ -1640,31 +2987,44 @@ export function composeRuntime(options) {
1640
2987
  submitLater(locator);
1641
2988
  }
1642
2989
  }
1643
- async function finishOpening(progress) {
2990
+ async function finishOpening(progress, live) {
1644
2991
  try {
1645
- if (closed || discoveryPaused) {
2992
+ if (!live()) {
1646
2993
  progress.complete = false;
1647
2994
  return;
1648
2995
  }
2996
+ reads.applied();
1649
2997
  submitAll();
2998
+ for (const locator of stale)
2999
+ if (repairable.has(locator))
3000
+ repairLater(locator, {});
1650
3001
  await conversations.reconcile();
1651
3002
  if (status.providerUnreachable)
1652
3003
  conversations.reconnected();
1653
3004
  const reading = { complete: true, reachable: true };
1654
- await conversations.catchUp(reading);
1655
- if (!reading.reachable)
3005
+ if (demand.conversations)
3006
+ await conversations.catchUp(reading);
3007
+ if (progress.reachable && reading.reachable)
3008
+ await conversations.resend(reading);
3009
+ if (progress.reachable)
3010
+ void recovery.attempt('calls', resendCalls);
3011
+ if (!reading.reachable) {
1656
3012
  progress.reachable = false;
3013
+ resendLater();
3014
+ }
1657
3015
  }
1658
3016
  catch {
1659
3017
  progress.complete = false;
1660
3018
  }
1661
3019
  finally {
1662
- complete = progress.complete;
1663
- await rest(progress);
3020
+ if (live()) {
3021
+ complete = progress.complete;
3022
+ await rest(progress, live);
3023
+ }
1664
3024
  }
1665
3025
  }
1666
- async function rest(progress) {
1667
- if (closed)
3026
+ async function rest(progress, live = () => !closed) {
3027
+ if (!live())
1668
3028
  return;
1669
3029
  let lastCompleted = status.lastCompleted;
1670
3030
  let synced = complete && stale.size === 0 && !pending();
@@ -1672,6 +3032,8 @@ export function composeRuntime(options) {
1672
3032
  const completedAt = new Date().toISOString();
1673
3033
  try {
1674
3034
  await (await openLocal()).complete(completedAt);
3035
+ if (!live())
3036
+ return;
1675
3037
  recorded = true;
1676
3038
  lastCompleted = completedAt;
1677
3039
  }
@@ -1680,46 +3042,74 @@ export function composeRuntime(options) {
1680
3042
  }
1681
3043
  }
1682
3044
  moveTo({
1683
- state: pending() ? 'pending' : synced ? 'synced' : 'syncing',
3045
+ state: pending() ? 'pending' : synced && complete ? 'synced' : 'syncing',
1684
3046
  lastCompleted,
1685
3047
  providerUnreachable: !progress.reachable,
1686
3048
  ...attention(),
1687
3049
  });
1688
3050
  }
3051
+ function discover() {
3052
+ let release = () => { };
3053
+ const done = new Promise((resolve) => {
3054
+ release = resolve;
3055
+ });
3056
+ discovering = { generation, done, release };
3057
+ return discovering;
3058
+ }
1689
3059
  function applyRoom(locator, roomVersion) {
1690
3060
  announced.set(locator, roomVersion);
1691
- return task(async () => {
1692
- await answering.get(locator);
1693
- if (closed || stopping || discoveryPaused || authorization === undefined)
3061
+ return task(roomLane(locator), async (live) => {
3062
+ if (discovering?.generation === generation)
3063
+ await discovering.done;
3064
+ const saving = answering.get(locator);
3065
+ if (saving?.generation === generation)
3066
+ await saving.answered;
3067
+ if (!live() || authorization === undefined)
1694
3068
  return;
1695
3069
  const room = discovered.get(locator);
1696
3070
  const held = replicas.get(locator);
1697
- if (room === undefined || room.replica.admission !== 'admitted')
3071
+ if (room === undefined || room.replica.admission !== 'admitted' || !acquires(room))
1698
3072
  return;
1699
3073
  if (held !== undefined &&
1700
3074
  (held.confirmed.record.replica.selection !== room.replica.selection ||
1701
3075
  options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion))) {
1702
3076
  return;
1703
3077
  }
1704
- const during = underway;
3078
+ const during = underway?.generation === generation ? underway.progress : null;
1705
3079
  const progress = during ?? { complete: true, reachable: true };
1706
3080
  if (during === null)
1707
3081
  moveTo(transferring(status));
1708
3082
  try {
1709
3083
  const local = await openLocal();
1710
- const withheld = await advance(room, local, authorization);
1711
- if (withheld !== null)
1712
- await withhold(withheld, room, local, progress);
3084
+ await admittedRead(async () => {
3085
+ if (!live() || authorization === undefined)
3086
+ return;
3087
+ const withheld = await advance(room, local, authorization, live);
3088
+ if (withheld !== null)
3089
+ await withhold(withheld, room, local, progress);
3090
+ });
1713
3091
  }
1714
3092
  catch {
1715
3093
  stale.add(locator);
1716
3094
  }
1717
3095
  finally {
1718
3096
  if (during === null)
1719
- await rest(progress);
3097
+ await rest(progress, live);
1720
3098
  }
1721
3099
  });
1722
3100
  }
3101
+ function roomsCarried(replacing) {
3102
+ const replaced = new Set(replacing.map(roomLane));
3103
+ return Promise.all([...lanes]
3104
+ .filter(([lane, held]) => lane !== OPENING_LANE && !replaced.has(lane) && held.generation === generation)
3105
+ .map(([, held]) => held.chain));
3106
+ }
3107
+ const receipts = {
3108
+ heads: async () => (await openLocal()).receivedHeads(),
3109
+ parts: async (key, count) => (await openLocal()).receivedParts(key, count),
3110
+ keep: async (key, head, part) => (await openLocal()).keepReceived(key, head, part),
3111
+ drop: async (keys) => (await openLocal()).dropReceived(keys),
3112
+ };
1723
3113
  function observeStream() {
1724
3114
  const stream = options.adapter.roomStream;
1725
3115
  if (stream === undefined || withdrawStream !== undefined)
@@ -1729,15 +3119,21 @@ export function composeRuntime(options) {
1729
3119
  return;
1730
3120
  if (event.kind === 'opened') {
1731
3121
  socketOpen = true;
3122
+ generation += 1;
3123
+ reads.opened();
3124
+ conversations.reopened();
3125
+ recovery.resume();
1732
3126
  void sync('opened');
1733
3127
  }
1734
3128
  else if (event.kind === 'closed')
1735
- closedSocket(event.revoked);
3129
+ closedSocket(event.revoked, event.lost);
1736
3130
  else if (event.kind === 'opening')
1737
3131
  void applyOpening(event.expired);
3132
+ else if (event.kind === 'authority-changed')
3133
+ void rediscover();
1738
3134
  else
1739
3135
  void applyRoom(event.locator, event.roomVersion);
1740
- });
3136
+ }, receipts);
1741
3137
  }
1742
3138
  function writesHeld() {
1743
3139
  return serviceMode === 'write-halted' || haltedRefusal;
@@ -1752,6 +3148,7 @@ export function composeRuntime(options) {
1752
3148
  haltedRefusal = false;
1753
3149
  if (mode !== serviceMode) {
1754
3150
  serviceMode = mode;
3151
+ queueReadiness();
1755
3152
  journal.record(`service mode ${mode}`);
1756
3153
  for (const listener of serviceModeListeners)
1757
3154
  listener(mode);
@@ -1764,7 +3161,12 @@ export function composeRuntime(options) {
1764
3161
  if (stream === undefined || withdrawConversations !== undefined)
1765
3162
  return;
1766
3163
  withdrawConversations = stream.observe((event) => {
1767
- conversations.receive(event);
3164
+ if (event.kind === 'list' || event.kind === 'listed' || event.kind === 'unlisted')
3165
+ queueReadiness();
3166
+ if (conversations.receive(event)) {
3167
+ void ready.then(scheduleCurrency);
3168
+ return;
3169
+ }
1768
3170
  if (event.kind !== 'gap' || conversations.current())
1769
3171
  return;
1770
3172
  show();
@@ -1772,46 +3174,47 @@ export function composeRuntime(options) {
1772
3174
  });
1773
3175
  }
1774
3176
  function scheduleCurrency() {
1775
- if (currencyQueued || closed || stopping)
3177
+ if (currencyQueued === generation || closed || stopping)
1776
3178
  return;
1777
- currencyQueued = true;
1778
- void task(runCurrency);
3179
+ currencyQueued = generation;
3180
+ void task(CONVERSATION_LANE, runCurrency);
1779
3181
  }
1780
- async function runCurrency() {
1781
- currencyQueued = false;
1782
- if (closed || stopping || discoveryPaused)
3182
+ async function runCurrency(live) {
3183
+ if (currencyQueued === generation)
3184
+ currencyQueued = null;
3185
+ if (!live())
1783
3186
  return;
1784
3187
  await conversations.reconcile();
1785
- if (conversations.current()) {
3188
+ if (conversations.current() || !demand.conversations) {
1786
3189
  show();
1787
3190
  return;
1788
3191
  }
1789
- const resting = status;
1790
- const progress = { complete: false, reachable: !resting.providerUnreachable };
1791
- moveTo(transferring(resting));
3192
+ const progress = { complete: false, reachable: !status.providerUnreachable };
3193
+ moveTo(transferring(status));
1792
3194
  try {
1793
3195
  await conversations.catchUp(progress);
1794
3196
  }
1795
3197
  catch {
1796
3198
  progress.reachable = false;
1797
3199
  }
1798
- finally {
1799
- if (!closed) {
1800
- moveTo(settled(resting, progress, resting.lastCompleted, pending(), attention()));
1801
- }
1802
- }
3200
+ await rest(progress, live);
1803
3201
  }
1804
3202
  function close() {
1805
3203
  if (closed)
1806
3204
  return;
1807
3205
  closed = true;
3206
+ if (narrowing !== null)
3207
+ clearTimeout(narrowing);
3208
+ if (rechecking !== null)
3209
+ clearInterval(rechecking);
3210
+ readinessWatches.clear();
1808
3211
  withdrawStream?.();
1809
3212
  withdrawStream = undefined;
1810
3213
  withdrawConversations?.();
1811
3214
  withdrawConversations = undefined;
1812
3215
  withdrawServiceMode?.();
1813
3216
  conversations.close();
1814
- stopTimer();
3217
+ void recovery.retire();
1815
3218
  store?.close();
1816
3219
  void opening?.then((opened) => {
1817
3220
  opened.close();
@@ -1821,6 +3224,7 @@ export function composeRuntime(options) {
1821
3224
  storageLossListeners.clear();
1822
3225
  statusListeners.clear();
1823
3226
  serviceModeListeners.clear();
3227
+ memberListeners.clear();
1824
3228
  readSide.close();
1825
3229
  queueSubscriptions.clear();
1826
3230
  roomDraftListeners.clear();
@@ -1828,9 +3232,8 @@ export function composeRuntime(options) {
1828
3232
  }
1829
3233
  async function stop() {
1830
3234
  stopping = true;
1831
- stopTimer();
1832
- await chain.catch(() => undefined);
1833
- await Promise.all([...submitting.values()].map((run) => run.done));
3235
+ await recovery.retire();
3236
+ await Promise.all(working);
1834
3237
  await mutations;
1835
3238
  close();
1836
3239
  }
@@ -1852,14 +3255,101 @@ export function composeRuntime(options) {
1852
3255
  return planOf(input, roomFacts(reach), planReach(reach));
1853
3256
  }
1854
3257
  function watchPlan(plan, deliver) {
1855
- return readSide.watch(plan, identityOf(plan), deliver);
3258
+ let seeded = false;
3259
+ let pending = true;
3260
+ const shown = () => {
3261
+ const seed = seeds.get(plan.key);
3262
+ if (seed === undefined || seeded || !pending)
3263
+ return;
3264
+ seeded = true;
3265
+ deliver(seededResult(seed));
3266
+ };
3267
+ const watchers = seedWatchers.get(plan.key) ?? new Set();
3268
+ seedWatchers.set(plan.key, watchers);
3269
+ watchers.add(shown);
3270
+ const stop = readSide.watch(plan, identityOf(plan), () => {
3271
+ const cover = covered(plan);
3272
+ awaitPreparation(cover);
3273
+ return seedBehind(plan, cover);
3274
+ }, (message) => {
3275
+ const answered = message;
3276
+ pending = whole(answered) && 'pending' in answered.result;
3277
+ if (pending && seeds.has(plan.key)) {
3278
+ shown();
3279
+ return;
3280
+ }
3281
+ seeded = false;
3282
+ deliver(message);
3283
+ });
3284
+ return () => {
3285
+ watchers.delete(shown);
3286
+ if (watchers.size === 0)
3287
+ seedWatchers.delete(plan.key);
3288
+ stop();
3289
+ };
1856
3290
  }
1857
3291
  async function searched(input, reach) {
1858
3292
  const plan = searchPlanOf(input);
1859
- const selected = plan.documents === undefined && reach === null
1860
- ? null
1861
- : (await readSide.query(filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)))).documents;
1862
- return searchIndex.search(reach === null || reach.conversations ? plan : { ...plan, conversations: [] }, selected);
3293
+ const filter = filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach));
3294
+ for (;;) {
3295
+ const cover = covered(filter);
3296
+ awaitPreparation(cover);
3297
+ const pending = 'pending' in cover ? [...cover.pending] : [];
3298
+ const awaited = new Set('pending' in cover ? cover.pending.map(({ room }) => room) : []);
3299
+ const held = covered({
3300
+ ...filter,
3301
+ rooms: reachedRooms(filter).filter((room) => !awaited.has(room)),
3302
+ });
3303
+ const covering = 'pending' in held ? [] : held.coverage.rooms;
3304
+ const unindexed = covering
3305
+ .filter(({ room }) => !searchIndex.rooms().has(room))
3306
+ .map(({ room }) => room);
3307
+ for (const room of unindexed)
3308
+ pending.push({ room, awaits: 'index' });
3309
+ const listed = conversations.searchable();
3310
+ const named = reach !== null && !reach.conversations
3311
+ ? []
3312
+ : (plan.conversations ?? listed).filter((one) => listed.includes(one) && conversations.acquired(one));
3313
+ const waiting = named.filter((one) => !searchIndex.conversations().has(one));
3314
+ for (const conversation of waiting)
3315
+ pending.push({ conversation, awaits: 'index' });
3316
+ if (unindexed.length > 0 || waiting.length > 0)
3317
+ index(unindexed, waiting);
3318
+ const complete = pending.length === 0 && !('pending' in cover);
3319
+ const answering = complete
3320
+ ? filter
3321
+ : {
3322
+ ...filter,
3323
+ rooms: covering
3324
+ .filter(({ room }) => searchIndex.rooms().has(room))
3325
+ .map(({ room }) => room),
3326
+ };
3327
+ const answered = covered(answering);
3328
+ if ('pending' in answered)
3329
+ continue;
3330
+ const searchedConversations = named.filter((one) => searchIndex.conversations().has(one));
3331
+ const seen = searchIndex.changes();
3332
+ await searchIndex.caughtUp();
3333
+ const selected = roomsAlone(answering) ? null : await rowsQuery(answering);
3334
+ if (selected !== null && 'pending' in selected)
3335
+ continue;
3336
+ if (searchIndex.changes() !== seen ||
3337
+ JSON.stringify(covered(answering)) !== JSON.stringify(answered))
3338
+ continue;
3339
+ const hits = searchIndex.search(plan, selected === null ? null : selected.documents, searchedConversations, answering.rooms === null ? null : new Set(answering.rooms), plan.collection
3340
+ ? new Map(answered.coverage.rooms.map(({ room }) => [
3341
+ room,
3342
+ replicas.get(room)?.confirmed.record.typedSelection?.roots ?? [],
3343
+ ]))
3344
+ : null);
3345
+ const coverage = {
3346
+ rooms: answered.coverage.rooms,
3347
+ conversations: searchedConversations,
3348
+ index: searchIndex.generation(),
3349
+ overlay: answered.coverage.overlay,
3350
+ };
3351
+ return complete ? { ...hits, coverage } : { pending, ...hits, coverage };
3352
+ }
1863
3353
  }
1864
3354
  const watch = (topic, input, deliver) => {
1865
3355
  if (topic === 'room-drafts') {
@@ -1882,6 +3372,10 @@ export function composeRuntime(options) {
1882
3372
  if (topic === 'conversation') {
1883
3373
  return conversations.watch(input[0], input[1], deliver);
1884
3374
  }
3375
+ if (topic === 'conversations')
3376
+ return conversations.watchList(deliver);
3377
+ if (topic === 'agents')
3378
+ return conversations.watchAgents(deliver);
1885
3379
  if (topic === 'presentation') {
1886
3380
  const listener = {
1887
3381
  app: input[0],
@@ -1901,6 +3395,9 @@ export function composeRuntime(options) {
1901
3395
  presentationListeners.delete(listener);
1902
3396
  };
1903
3397
  }
3398
+ if (topic === 'readiness') {
3399
+ return watchReadiness({ target: '', code: 'stored', capacity: null, search: 'unused' }, null, deliver);
3400
+ }
1904
3401
  if (topic === 'rooms') {
1905
3402
  roomListeners.add(deliver);
1906
3403
  deliver(listed());
@@ -1936,6 +3433,13 @@ export function composeRuntime(options) {
1936
3433
  serviceModeListeners.delete(deliver);
1937
3434
  };
1938
3435
  }
3436
+ if (topic === 'member') {
3437
+ memberListeners.add(deliver);
3438
+ deliver(member);
3439
+ return () => {
3440
+ memberListeners.delete(deliver);
3441
+ };
3442
+ }
1939
3443
  if (topic === 'queue') {
1940
3444
  const queue = { locator: input[0], notify: deliver };
1941
3445
  queueSubscriptions.add(queue);
@@ -1953,7 +3457,7 @@ export function composeRuntime(options) {
1953
3457
  rooms() {
1954
3458
  return listed();
1955
3459
  },
1956
- query: ((input) => readSide.query(planned(input, null))),
3460
+ query: ((input) => rowsQuery(planned(input, null))),
1957
3461
  search: (input) => searched(input, null),
1958
3462
  types(locator) {
1959
3463
  return {
@@ -1982,20 +3486,20 @@ export function composeRuntime(options) {
1982
3486
  return exclusive(async () => {
1983
3487
  const parts = readParts(input);
1984
3488
  if (path === '' || normalize(path) !== path)
1985
- throw new Error('room-draft-malformed');
3489
+ throw runtimeError('room-draft-malformed');
1986
3490
  const local = await openLocal();
1987
3491
  const current = roomDrafts.get(room)?.get(path);
1988
3492
  if ((current?.revision ?? null) !== revision) {
1989
- return {
1990
- outcome: 'stale',
1991
- current: current === undefined ? null : roomDraftOf(current),
1992
- };
3493
+ return staleWrite(current === undefined ? null : roomDraftOf(current));
1993
3494
  }
3495
+ const file = parts.file === undefined
3496
+ ? undefined
3497
+ : await heldFile(parts.file.blob, binaryBase(replicas.get(room)?.visible, path));
1994
3498
  const record = {
1995
3499
  locator: room,
1996
3500
  path,
1997
3501
  revision: roomDraftRevision(),
1998
- parts: held(current?.parts, parts),
3502
+ parts: held(current?.parts, parts, file),
1999
3503
  returned: current?.returned ?? null,
2000
3504
  };
2001
3505
  await local.keepRoomDraft(record);
@@ -2009,10 +3513,7 @@ export function composeRuntime(options) {
2009
3513
  const local = await openLocal();
2010
3514
  const current = roomDrafts.get(room)?.get(path);
2011
3515
  if (current === undefined || current.revision !== revision) {
2012
- return {
2013
- outcome: 'stale',
2014
- current: current === undefined ? null : roomDraftOf(current),
2015
- };
3516
+ return staleWrite(current === undefined ? null : roomDraftOf(current));
2016
3517
  }
2017
3518
  await local.discardRoomDraft(room, path);
2018
3519
  forgetRoomDraft(room, path);
@@ -2032,13 +3533,13 @@ export function composeRuntime(options) {
2032
3533
  });
2033
3534
  },
2034
3535
  write(app, value) {
2035
- return exclusive(async () => {
2036
- const local = await openLocal();
2037
- const stored = structuredClone(value);
2038
- await local.present({ app, value: stored });
2039
- presentations.set(app, stored);
2040
- publishChangeSet(changeSet('', null, null, { presentation: app }));
2041
- });
3536
+ return keepPresentation(app, () => structuredClone(value));
3537
+ },
3538
+ edit(app, members) {
3539
+ return keepPresentation(app, (held) => Object.fromEntries([
3540
+ ...Object.entries(plain(held) ? held : {}).filter(([member]) => !Object.hasOwn(members, member)),
3541
+ ...Object.entries(structuredClone(members)).filter(([, value]) => value !== null),
3542
+ ]));
2042
3543
  },
2043
3544
  },
2044
3545
  save(room, named, writtenBy) {
@@ -2047,8 +3548,13 @@ export function composeRuntime(options) {
2047
3548
  history(locator, path, query) {
2048
3549
  return readHistory(locator, path, query);
2049
3550
  },
3551
+ binaryFile: {
3552
+ read: readBinaryPath,
3553
+ link: linkBinaryPath,
3554
+ readReference: readBinaryReference,
3555
+ },
2050
3556
  call(name, input) {
2051
- return invokeAction(name, input);
3557
+ return recoveredAction(name, input);
2052
3558
  },
2053
3559
  reached(locator, roomVersion, path) {
2054
3560
  return path === undefined
@@ -2059,30 +3565,55 @@ export function composeRuntime(options) {
2059
3565
  return journal.export();
2060
3566
  },
2061
3567
  persistence() {
2062
- return options.shell.persistentStorage;
3568
+ return persistence === 'granted';
3569
+ },
3570
+ async retry() {
3571
+ journal.record('retry');
3572
+ unindexable.clear();
3573
+ queueReadiness();
3574
+ resume();
2063
3575
  },
2064
3576
  observe: observing(watch),
2065
3577
  async reauthorize() {
2066
3578
  if (refusal === null || !refusal.reauthorizationOffered)
2067
3579
  return;
2068
3580
  journal.record('connection reauthorize');
2069
- await chain.catch(() => undefined);
3581
+ await Promise.all([...lanes.values()]
3582
+ .filter((held) => held.generation === generation)
3583
+ .map((held) => held.chain));
2070
3584
  await mutations;
2071
3585
  authorization = undefined;
2072
3586
  discoveryPaused = false;
2073
3587
  if (options.adapter.roomStream === undefined)
2074
3588
  await sync('unstreamed');
2075
3589
  else
2076
- await task(ensureAuthorization);
3590
+ await task(OPENING_LANE, ensureAuthorization);
2077
3591
  },
2078
3592
  };
2079
3593
  const reachable = {
2080
3594
  md,
2081
3595
  watch,
3596
+ referrerScope: (referrer) => options.adapter.referrerScope(referrer),
2082
3597
  plan: planned,
2083
- query: (plan) => readSide.query(plan),
3598
+ query: (plan) => rowsQuery(plan),
2084
3599
  watchPlan,
2085
3600
  search: searched,
3601
+ watchReadiness,
3602
+ };
3603
+ return {
3604
+ md,
3605
+ seed,
3606
+ stop,
3607
+ lose: loseRooms,
3608
+ watch,
3609
+ acquire,
3610
+ persisted(answer) {
3611
+ if (answer === persistence)
3612
+ return;
3613
+ persistence = answer;
3614
+ journal.record(`persistence ${answer}`);
3615
+ queueReadiness();
3616
+ },
3617
+ within: (reach, port) => narrowed(reachable, reach, port),
2086
3618
  };
2087
- return { md, stop, watch, within: (reach) => narrowed(reachable, reach) };
2088
3619
  }