@agentshouse/mdruntime 0.1.0-cef5833f6c689 → 0.1.0-cef76ea952695

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 (264) hide show
  1. package/README.md +9 -9
  2. package/dist/acceptance.d.ts +6 -0
  3. package/dist/acceptance.d.ts.map +1 -0
  4. package/dist/acceptance.js +385 -0
  5. package/dist/actions.d.ts +20 -0
  6. package/dist/actions.d.ts.map +1 -0
  7. package/dist/actions.js +251 -0
  8. package/dist/adapter.d.ts +28 -55
  9. package/dist/adapter.d.ts.map +1 -1
  10. package/dist/attached-model.d.ts +3 -10
  11. package/dist/attached-model.d.ts.map +1 -1
  12. package/dist/attached-model.js +21 -56
  13. package/dist/bootstrap.d.ts +8 -4
  14. package/dist/bootstrap.d.ts.map +1 -1
  15. package/dist/bootstrap.js +207 -76
  16. package/dist/cell.d.ts +6 -0
  17. package/dist/cell.d.ts.map +1 -0
  18. package/dist/cell.js +9 -0
  19. package/dist/change.d.ts +1 -0
  20. package/dist/change.d.ts.map +1 -1
  21. package/dist/change.js +4 -2
  22. package/dist/chat-types.d.ts +5 -0
  23. package/dist/chat-types.d.ts.map +1 -0
  24. package/dist/chat-types.js +13 -0
  25. package/dist/client.d.ts +18 -2
  26. package/dist/client.d.ts.map +1 -1
  27. package/dist/client.js +7 -2
  28. package/dist/compile.d.ts +5 -0
  29. package/dist/compile.d.ts.map +1 -1
  30. package/dist/compile.js +202 -80
  31. package/dist/connection.d.ts +5 -141
  32. package/dist/connection.d.ts.map +1 -1
  33. package/dist/connection.js +103 -5175
  34. package/dist/conversation-live.d.ts +135 -0
  35. package/dist/conversation-live.d.ts.map +1 -0
  36. package/dist/conversation-live.js +247 -0
  37. package/dist/conversation-row.d.ts +33 -0
  38. package/dist/conversation-row.d.ts.map +1 -0
  39. package/dist/conversation-row.js +53 -0
  40. package/dist/conversation.d.ts +30 -37
  41. package/dist/conversation.d.ts.map +1 -1
  42. package/dist/conversation.js +853 -864
  43. package/dist/discovery.d.ts +10 -0
  44. package/dist/discovery.d.ts.map +1 -0
  45. package/dist/discovery.js +175 -0
  46. package/dist/durability.d.ts +15 -0
  47. package/dist/durability.d.ts.map +1 -1
  48. package/dist/entry.d.ts.map +1 -1
  49. package/dist/entry.js +4 -3
  50. package/dist/expectation.d.ts +4 -2
  51. package/dist/expectation.d.ts.map +1 -1
  52. package/dist/expectation.js +33 -11
  53. package/dist/failure.d.ts +1 -0
  54. package/dist/failure.d.ts.map +1 -1
  55. package/dist/failure.js +3 -0
  56. package/dist/figures.d.ts +49 -0
  57. package/dist/figures.d.ts.map +1 -0
  58. package/dist/figures.js +197 -0
  59. package/dist/holdings.d.ts +29 -0
  60. package/dist/holdings.d.ts.map +1 -0
  61. package/dist/holdings.js +95 -0
  62. package/dist/host.d.ts +1 -0
  63. package/dist/host.d.ts.map +1 -1
  64. package/dist/host.js +11 -4
  65. package/dist/index.d.ts +20 -6
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +5 -1
  68. package/dist/install.d.ts +56 -0
  69. package/dist/install.d.ts.map +1 -0
  70. package/dist/install.js +556 -0
  71. package/dist/job.d.ts +1 -10
  72. package/dist/job.d.ts.map +1 -1
  73. package/dist/job.js +2 -23
  74. package/dist/lifecycle.d.ts +7 -0
  75. package/dist/lifecycle.d.ts.map +1 -0
  76. package/dist/lifecycle.js +270 -0
  77. package/dist/listing.d.ts +53 -0
  78. package/dist/listing.d.ts.map +1 -0
  79. package/dist/listing.js +176 -0
  80. package/dist/live.d.ts +4 -4
  81. package/dist/live.d.ts.map +1 -1
  82. package/dist/live.js +54 -16
  83. package/dist/locks.d.ts +9 -0
  84. package/dist/locks.d.ts.map +1 -0
  85. package/dist/locks.js +62 -0
  86. package/dist/log.d.ts +1 -0
  87. package/dist/log.d.ts.map +1 -1
  88. package/dist/lost.d.ts +5 -0
  89. package/dist/lost.d.ts.map +1 -0
  90. package/dist/lost.js +61 -0
  91. package/dist/media.d.ts +1 -1
  92. package/dist/media.d.ts.map +1 -1
  93. package/dist/media.js +3 -3
  94. package/dist/memory.d.ts +3 -1
  95. package/dist/memory.d.ts.map +1 -1
  96. package/dist/memory.js +45 -5
  97. package/dist/messages.d.ts +22 -1
  98. package/dist/messages.d.ts.map +1 -1
  99. package/dist/messages.js +75 -16
  100. package/dist/model.d.ts +1 -7
  101. package/dist/model.d.ts.map +1 -1
  102. package/dist/model.js +0 -6
  103. package/dist/models.d.ts +14 -0
  104. package/dist/models.d.ts.map +1 -0
  105. package/dist/models.js +197 -0
  106. package/dist/observation.d.ts.map +1 -1
  107. package/dist/observation.js +12 -17
  108. package/dist/opened.js +3 -3
  109. package/dist/opening.d.ts +4 -0
  110. package/dist/opening.d.ts.map +1 -0
  111. package/dist/opening.js +60 -0
  112. package/dist/outcome.d.ts +4 -1
  113. package/dist/outcome.d.ts.map +1 -1
  114. package/dist/outcome.js +3 -0
  115. package/dist/overlay.d.ts +1 -0
  116. package/dist/overlay.d.ts.map +1 -1
  117. package/dist/overlay.js +11 -0
  118. package/dist/parts.d.ts +11 -0
  119. package/dist/parts.d.ts.map +1 -0
  120. package/dist/parts.js +21 -0
  121. package/dist/paths.d.ts +1 -0
  122. package/dist/paths.d.ts.map +1 -1
  123. package/dist/paths.js +22 -0
  124. package/dist/preparation.d.ts +20 -0
  125. package/dist/preparation.d.ts.map +1 -0
  126. package/dist/preparation.js +233 -0
  127. package/dist/queries.d.ts +16 -0
  128. package/dist/queries.d.ts.map +1 -0
  129. package/dist/queries.js +272 -0
  130. package/dist/query.d.ts +10 -2
  131. package/dist/query.d.ts.map +1 -1
  132. package/dist/questions.d.ts +34 -0
  133. package/dist/questions.d.ts.map +1 -0
  134. package/dist/questions.js +122 -0
  135. package/dist/reach.d.ts +8 -6
  136. package/dist/reach.d.ts.map +1 -1
  137. package/dist/reach.js +160 -101
  138. package/dist/react.d.ts +11 -1
  139. package/dist/react.d.ts.map +1 -1
  140. package/dist/react.js +10 -1
  141. package/dist/read.d.ts +7 -0
  142. package/dist/read.d.ts.map +1 -0
  143. package/dist/read.js +17 -0
  144. package/dist/readiness.d.ts +0 -1
  145. package/dist/readiness.d.ts.map +1 -1
  146. package/dist/reads.d.ts +37 -0
  147. package/dist/reads.d.ts.map +1 -0
  148. package/dist/reads.js +174 -0
  149. package/dist/recovery.d.ts.map +1 -1
  150. package/dist/recovery.js +9 -1
  151. package/dist/refresh.d.ts +1 -1
  152. package/dist/refresh.d.ts.map +1 -1
  153. package/dist/refresh.js +8 -20
  154. package/dist/refusal.d.ts +5 -0
  155. package/dist/refusal.d.ts.map +1 -0
  156. package/dist/refusal.js +57 -0
  157. package/dist/replica.d.ts +7 -7
  158. package/dist/replica.d.ts.map +1 -1
  159. package/dist/replica.js +51 -19
  160. package/dist/room-draft.d.ts +1 -3
  161. package/dist/room-draft.d.ts.map +1 -1
  162. package/dist/room-draft.js +3 -3
  163. package/dist/room-drafts.d.ts +24 -0
  164. package/dist/room-drafts.d.ts.map +1 -0
  165. package/dist/room-drafts.js +217 -0
  166. package/dist/rows.d.ts +14 -5
  167. package/dist/rows.d.ts.map +1 -1
  168. package/dist/rows.js +50 -58
  169. package/dist/runtime.d.ts +43 -0
  170. package/dist/runtime.d.ts.map +1 -0
  171. package/dist/runtime.js +1 -0
  172. package/dist/save.d.ts +5 -1
  173. package/dist/save.d.ts.map +1 -1
  174. package/dist/save.js +34 -21
  175. package/dist/saves.d.ts +70 -0
  176. package/dist/saves.d.ts.map +1 -0
  177. package/dist/saves.js +1005 -0
  178. package/dist/seed.d.ts +11 -2
  179. package/dist/seed.d.ts.map +1 -1
  180. package/dist/seed.js +71 -1
  181. package/dist/shared.d.ts +1 -6
  182. package/dist/shared.d.ts.map +1 -1
  183. package/dist/shared.js +13 -95
  184. package/dist/shown.d.ts +31 -0
  185. package/dist/shown.d.ts.map +1 -0
  186. package/dist/shown.js +290 -0
  187. package/dist/socket/admission.d.ts +7 -0
  188. package/dist/socket/admission.d.ts.map +1 -0
  189. package/dist/socket/admission.js +39 -0
  190. package/dist/socket/answers.d.ts +6 -0
  191. package/dist/socket/answers.d.ts.map +1 -0
  192. package/dist/socket/answers.js +20 -0
  193. package/dist/socket/lanes.d.ts +20 -0
  194. package/dist/socket/lanes.d.ts.map +1 -0
  195. package/dist/socket/lanes.js +77 -0
  196. package/dist/socket/reads.d.ts +10 -0
  197. package/dist/socket/reads.d.ts.map +1 -0
  198. package/dist/socket/reads.js +31 -0
  199. package/dist/socket/rooms.d.ts +44 -0
  200. package/dist/socket/rooms.d.ts.map +1 -0
  201. package/dist/socket/rooms.js +90 -0
  202. package/dist/socket/session.d.ts +38 -0
  203. package/dist/socket/session.d.ts.map +1 -0
  204. package/dist/socket/session.js +23 -0
  205. package/dist/socket.d.ts +70 -0
  206. package/dist/socket.d.ts.map +1 -0
  207. package/dist/socket.js +175 -0
  208. package/dist/source.d.ts +61 -0
  209. package/dist/source.d.ts.map +1 -0
  210. package/dist/source.js +82 -0
  211. package/dist/status.d.ts +0 -2
  212. package/dist/status.d.ts.map +1 -1
  213. package/dist/status.js +0 -6
  214. package/dist/store/fences.d.ts +16 -0
  215. package/dist/store/fences.d.ts.map +1 -0
  216. package/dist/store/fences.js +26 -0
  217. package/dist/store/installs.d.ts +30 -0
  218. package/dist/store/installs.d.ts.map +1 -0
  219. package/dist/store/installs.js +34 -0
  220. package/dist/store/readiness.d.ts +10 -0
  221. package/dist/store/readiness.d.ts.map +1 -0
  222. package/dist/store/readiness.js +52 -0
  223. package/dist/store/records.d.ts +210 -0
  224. package/dist/store/records.d.ts.map +1 -0
  225. package/dist/store/records.js +428 -0
  226. package/dist/store/room-held.d.ts +8 -0
  227. package/dist/store/room-held.d.ts.map +1 -0
  228. package/dist/store/room-held.js +17 -0
  229. package/dist/store/space.d.ts +11 -0
  230. package/dist/store/space.d.ts.map +1 -0
  231. package/dist/store/space.js +41 -0
  232. package/dist/store/watchers.d.ts +17 -0
  233. package/dist/store/watchers.d.ts.map +1 -0
  234. package/dist/store/watchers.js +56 -0
  235. package/dist/store/writes.d.ts +24 -0
  236. package/dist/store/writes.d.ts.map +1 -0
  237. package/dist/store/writes.js +125 -0
  238. package/dist/store.d.ts +107 -152
  239. package/dist/store.d.ts.map +1 -1
  240. package/dist/store.js +143 -394
  241. package/dist/stored.d.ts +59 -65
  242. package/dist/stored.d.ts.map +1 -1
  243. package/dist/stored.js +255 -149
  244. package/dist/surface.d.ts +88 -0
  245. package/dist/surface.d.ts.map +1 -0
  246. package/dist/surface.js +224 -0
  247. package/dist/sync.d.ts +19 -0
  248. package/dist/sync.d.ts.map +1 -0
  249. package/dist/sync.js +532 -0
  250. package/dist/tables.d.ts +110 -50
  251. package/dist/tables.d.ts.map +1 -1
  252. package/dist/tables.js +205 -54
  253. package/dist/tallies.d.ts +18 -0
  254. package/dist/tallies.d.ts.map +1 -0
  255. package/dist/tallies.js +129 -0
  256. package/dist/validation.d.ts.map +1 -1
  257. package/dist/validation.js +4 -4
  258. package/dist/wire.d.ts +16 -1
  259. package/dist/wire.d.ts.map +1 -1
  260. package/dist/wire.js +6 -0
  261. package/package.json +3 -2
  262. package/dist/fence.d.ts +0 -6
  263. package/dist/fence.d.ts.map +0 -1
  264. package/dist/fence.js +0 -10
@@ -1,32 +1,17 @@
1
1
  import { cursorOf, decodedCursor } from '@agentshouse/mdmodel';
2
+ import { applied, isTurn, standingState, } from '@agentshouse/session-content';
2
3
  import { conversationChangeSet } from './change-set.js';
3
- import { runtimeError } from './failure.js';
4
+ import { FACTS, QUIET, } from './conversation-live.js';
5
+ import { heldFacts } from './conversation-row.js';
6
+ import { runtimeError, uncaught } from './failure.js';
4
7
  import { refusedForSpace } from './durability.js';
5
8
  import { changeBatchIdentity, chatDraftRevision } from './identity.js';
6
9
  import { OFFLINE } from './outcome.js';
10
+ import { runningLine } from './parts.js';
11
+ import { record, text } from './read.js';
12
+ import { openQuestion, questionAsked } from './questions.js';
7
13
  import { untilAnswered } from './recovery.js';
8
14
  import { capped, FROM_START, messageOrder, precedes } from './windows.js';
9
- const QUIET = {
10
- turn: null,
11
- questions: [],
12
- process: null,
13
- commands: [],
14
- options: [],
15
- starting: null,
16
- subagents: [],
17
- link: null,
18
- deliveryUnknown: [],
19
- };
20
- const FACTS = [
21
- 'questions',
22
- 'process',
23
- 'commands',
24
- 'options',
25
- 'starting',
26
- 'subagents',
27
- 'link',
28
- 'deliveryUnknown',
29
- ];
30
15
  export function unheldView(conversation) {
31
16
  return {
32
17
  conversation,
@@ -38,7 +23,7 @@ export function unheldView(conversation) {
38
23
  commands: [],
39
24
  options: [],
40
25
  starting: null,
41
- subagents: [],
26
+ state: null,
42
27
  link: null,
43
28
  deliveryUnknown: [],
44
29
  chatDraft: null,
@@ -58,52 +43,15 @@ function creationOf(input) {
58
43
  }
59
44
  function startedTurn(turn, operation) {
60
45
  if (operation.op === 'begin')
61
- return { turn, started: operation.at, parts: [], context: null };
62
- if (operation.op === 'context') {
63
- return {
64
- turn,
65
- started: null,
66
- parts: [],
67
- context: { used: operation.used, window: operation.window },
68
- };
69
- }
70
- return operation.op === 'start' && operation.index === 0
71
- ? { turn, started: null, parts: [structuredClone(operation.part)], context: null }
72
- : null;
73
- }
74
- function changedFields(part, operation) {
75
- if (operation.op === 'append') {
76
- return { text: `${String(part.text ?? '')}${operation.text}` };
77
- }
78
- if (operation.op === 'status') {
79
- return { status: operation.status, result: structuredClone(operation.result) };
80
- }
81
- if (operation.op === 'count')
82
- return { count: operation.count };
83
- return { entries: structuredClone(operation.entries) };
46
+ return { turn, started: operation.at, parts: [] };
47
+ const parts = applied([], operation);
48
+ return parts === null ? null : { turn, started: null, parts };
84
49
  }
85
50
  function appliedTurn(held, operation) {
86
51
  if (operation.op === 'begin')
87
52
  return { ...held, started: operation.at };
88
- if (operation.op === 'context') {
89
- return { ...held, context: { used: operation.used, window: operation.window } };
90
- }
91
- if (operation.op === 'start') {
92
- if (operation.index !== 0 && operation.index !== held.parts.length)
93
- return null;
94
- return {
95
- ...held,
96
- parts: [...held.parts.slice(0, operation.index), structuredClone(operation.part)],
97
- };
98
- }
99
- const part = held.parts[operation.index];
100
- if (typeof part !== 'object' || part === null)
101
- return null;
102
- const changed = { ...part, ...changedFields(part, operation) };
103
- return {
104
- ...held,
105
- parts: held.parts.map((kept, at) => (at === operation.index ? changed : kept)),
106
- };
53
+ const parts = applied(held.parts, operation);
54
+ return parts === null ? null : { ...held, parts };
107
55
  }
108
56
  function windowOf(held, arriving, limit) {
109
57
  const byIdentity = new Map(held.map((message) => [message.identity, message]));
@@ -253,675 +201,785 @@ function returned(draft, submission, others) {
253
201
  revision: chatDraftRevision(),
254
202
  }, others);
255
203
  }
256
- export function createConversationStore(deps) {
257
- const stored = new Set();
258
- const reads = new Map();
259
- const partials = new Set();
260
- const drafts = new Map();
261
- const sending = new Map();
262
- const behind = new Set();
263
- const catching = new Map();
264
- const gaps = new Map();
265
- const lives = new Map();
266
- const unsent = new Map();
267
- const views = new Map();
268
- const listing = new Map();
269
- let relisting = null;
270
- let listCursor = null;
271
- const creations = new Set();
272
- const listWatchers = new Set();
273
- const unlisted = new Set();
274
- let listKnown = false;
275
- let listHeld = false;
276
- let listKept = false;
277
- const agentWatchers = new Set();
278
- const unnamed = new Set();
279
- let agentsShown = null;
280
- let listedAgents = null;
281
- let agentsReading = false;
282
- let replicated = new Set();
283
- let handedReplicated;
284
- function liveOf(conversation) {
285
- return lives.get(conversation) ?? QUIET;
204
+ function viewOf(alive, conversation, held, frame, draft, ended) {
205
+ const facts = alive.liveOf(conversation);
206
+ return {
207
+ conversation,
208
+ messages: held.map(({ identity, turn, text, message }) => ({
209
+ identity,
210
+ turn,
211
+ text,
212
+ message,
213
+ })),
214
+ ...frame,
215
+ turn: structuredClone(facts.turn),
216
+ questions: structuredClone(facts.questions),
217
+ process: facts.process === null ? null : { ...facts.process },
218
+ processEnded: ended,
219
+ commands: structuredClone(facts.commands),
220
+ options: structuredClone(facts.options),
221
+ starting: facts.starting,
222
+ state: sessionOf(facts, held, ended),
223
+ link: facts.link === null ? null : { ...facts.link },
224
+ deliveryUnknown: [...facts.deliveryUnknown],
225
+ chatDraft: draft === null || unwritten(draft) ? null : { text: draft.text, revision: draft.revision },
226
+ };
227
+ }
228
+ function sessionOf(facts, held, ended) {
229
+ if (facts.state !== null)
230
+ return structuredClone(facts.state);
231
+ const saved = [...held]
232
+ .reverse()
233
+ .map(({ message }) => record(message))
234
+ .find(({ content }) => isTurn(content));
235
+ const at = saved === undefined ? null : text(saved, 'accepted_at');
236
+ if (saved === undefined || !isTurn(saved.content) || at === null)
237
+ return null;
238
+ const down = facts.process?.running === false;
239
+ return structuredClone(standingState(saved.content.state, at, down ? at : ended));
240
+ }
241
+ function emit(alive, conversation) {
242
+ if (alive.deps.closed())
243
+ return;
244
+ for (const view of alive.views()) {
245
+ const { window, draft, ended } = view.held.now();
246
+ if (view.conversation !== conversation || window === null)
247
+ continue;
248
+ const ready = view.ready();
249
+ if (ready.length === 0)
250
+ continue;
251
+ const value = viewOf(alive, conversation, window, sharedFrame(view, window), draft, ended);
252
+ for (const watcher of ready)
253
+ watcher.notify(value);
286
254
  }
287
- function viewOf(conversation, held, frame) {
288
- const draft = drafts.get(conversation);
289
- const facts = liveOf(conversation);
290
- return {
291
- conversation,
292
- messages: held.map(({ identity, turn, text, message }) => ({
293
- identity,
294
- turn,
295
- text,
296
- message,
297
- })),
298
- ...frame,
299
- turn: structuredClone(facts.turn),
300
- questions: structuredClone(facts.questions),
301
- process: facts.process === null ? null : { ...facts.process },
302
- processEnded: listing.get(conversation)?.processEnded ?? null,
303
- commands: structuredClone(facts.commands),
304
- options: structuredClone(facts.options),
305
- starting: facts.starting,
306
- subagents: structuredClone(facts.subagents),
307
- link: facts.link === null ? null : { ...facts.link },
308
- deliveryUnknown: [...facts.deliveryUnknown],
309
- chatDraft: draft === undefined || unwritten(draft)
310
- ? null
311
- : { text: draft.text, revision: draft.revision },
312
- };
255
+ }
256
+ function sharedFrame(view, window) {
257
+ const { more, total } = view.held.now();
258
+ return frameOf(view.asked, window, more, total);
259
+ }
260
+ async function slide(alive, local, conversation, arriving) {
261
+ let count;
262
+ for (const view of alive.views()) {
263
+ const { held } = view;
264
+ const { window, total } = held.now();
265
+ if (view.conversation !== conversation || window === null)
266
+ continue;
267
+ if (arriving === null) {
268
+ held.set({ window: [], more: false, total: total === null ? null : 0 });
269
+ continue;
270
+ }
271
+ const joining = arriving.filter((message) => precedes(message, view.asked.before));
272
+ const next = windowOf(window, joining, view.asked.limit);
273
+ held.set({ window: next.messages, more: held.now().more || next.dropped });
274
+ if (held.now().total !== null && arriving.length > 0) {
275
+ count ??= await local.messageCount(conversation);
276
+ held.set({ total: count });
277
+ }
313
278
  }
314
- function emit(conversation) {
315
- if (deps.closed())
279
+ }
280
+ function stateOf(alive, conversation) {
281
+ const facts = alive.liveOf(conversation);
282
+ if (facts.questions.length > 0)
283
+ return 'asking';
284
+ return facts.turn === null ? 'idle' : 'working';
285
+ }
286
+ function rowOf(alive, conversation) {
287
+ const { turn, questions } = alive.liveOf(conversation);
288
+ return {
289
+ state: stateOf(alive, conversation),
290
+ started: turn?.started ?? null,
291
+ line: turn === null ? null : runningLine(turn.parts),
292
+ question: openQuestion(questions),
293
+ asked: questionAsked(questions),
294
+ };
295
+ }
296
+ async function entries(alive) {
297
+ const list = await heldList(alive);
298
+ if (list === null)
299
+ return null;
300
+ const held = list.length === 0
301
+ ? []
302
+ : await alive.deps.durably((local) => local.conversationRows(list.map(({ conversation }) => conversation)));
303
+ const rows = new Map(held.map((one) => [one.conversation, one]));
304
+ return list.map((entry) => ({
305
+ conversation: entry.conversation,
306
+ agent: { identity: entry.agent, name: entry.agentName, retired: entry.agentRetired },
307
+ name: entry.name,
308
+ created: entry.created,
309
+ finished: entry.finished,
310
+ outcome: entry.outcome,
311
+ waiting: entry.waiting,
312
+ ...rowOf(alive, entry.conversation),
313
+ ...heldFacts(rows.get(entry.conversation), entry),
314
+ }));
315
+ }
316
+ async function heldList(alive) {
317
+ const stored = (await (await alive.deps.local()).facts()).conversationList;
318
+ if (stored !== null)
319
+ return stored;
320
+ return !alive.known() && alive.deps.stream() !== undefined && alive.deps.online() ? null : [];
321
+ }
322
+ async function endedIn(alive, conversation) {
323
+ const list = await heldList(alive);
324
+ return list?.find((entry) => entry.conversation === conversation)?.processEnded ?? null;
325
+ }
326
+ function listChanged(alive, change) {
327
+ void alive.deps
328
+ .durably(async (local) => {
329
+ const { conversationList, conversationCursor } = await local.facts();
330
+ const kept = change.replacing ? [] : (conversationList ?? []);
331
+ const held = new Map(kept.map((entry) => [entry.conversation, entry]));
332
+ for (const entry of change.set) {
333
+ held.set(entry.conversation, { ...entry });
334
+ alive.created(entry.conversation);
335
+ }
336
+ if (change.gone !== null)
337
+ held.delete(change.gone);
338
+ const list = [...held.values()];
339
+ if (JSON.stringify(list) !== JSON.stringify(conversationList)) {
340
+ await local.fact('conversationList', list);
341
+ }
342
+ if (change.cursor !== undefined) {
343
+ if (change.cursor !== conversationCursor) {
344
+ await local.fact('conversationCursor', change.cursor);
345
+ }
346
+ alive.deps.stream()?.hold(change.cursor);
347
+ }
348
+ return list;
349
+ })
350
+ .catch(async () => (await (await alive.deps.local()).facts()).conversationList ?? [])
351
+ .then((list) => {
352
+ if (alive.deps.closed() || change.paged === true)
316
353
  return;
317
- for (const view of views.values()) {
318
- if (view.conversation !== conversation || view.window === null)
319
- continue;
320
- const ready = [...view.watchers].filter((watcher) => watcher.ready);
321
- if (ready.length === 0)
322
- continue;
323
- const value = viewOf(conversation, view.window, sharedFrame(view, view.window));
324
- for (const watcher of ready)
325
- watcher.notify(value);
354
+ endedAnew(alive, list);
355
+ if (change.cursor !== undefined) {
356
+ alive.held.set({ listKnown: true });
357
+ settleBehind(alive, list);
358
+ openingEnded(alive);
359
+ alive.deps.settled();
326
360
  }
361
+ emitList(alive);
362
+ if (!alive.known())
363
+ return;
364
+ retiredDrafts(alive, list);
365
+ const { replicated } = alive.held.now();
366
+ if (change.cursor === undefined &&
367
+ (list.length !== replicated.size ||
368
+ list.some(({ conversation }) => !replicated.has(conversation)))) {
369
+ alive.deps.again();
370
+ }
371
+ }, uncaught);
372
+ }
373
+ function endedAnew(alive, list) {
374
+ const entries = new Map(list.map((entry) => [entry.conversation, entry]));
375
+ for (const view of alive.views()) {
376
+ const ended = entries.get(view.conversation)?.processEnded ?? null;
377
+ const held = view.held.now();
378
+ if (held.window === null || ended === held.ended)
379
+ continue;
380
+ view.held.set({ ended });
381
+ emit(alive, view.conversation);
327
382
  }
328
- function sharedFrame(view, window) {
329
- return frameOf(view.asked, window, view.more, view.total);
330
- }
331
- async function slide(local, conversation, arriving) {
332
- let count;
333
- for (const view of views.values()) {
334
- if (view.conversation !== conversation || view.window === null)
335
- continue;
336
- if (arriving === null) {
337
- view.window = [];
338
- view.more = false;
339
- if (view.total !== null)
340
- view.total = 0;
383
+ }
384
+ function shownList(alive, work) {
385
+ const reading = heldList(alive);
386
+ alive.inOrder(async () => {
387
+ const list = await reading.catch((error) => {
388
+ uncaught(error);
389
+ return null;
390
+ });
391
+ if (list === null || alive.deps.closed())
392
+ return;
393
+ work(list);
394
+ });
395
+ }
396
+ async function told(alive) {
397
+ try {
398
+ while (alive.held.now().listOwed && !alive.deps.closed()) {
399
+ alive.held.set({ listOwed: false });
400
+ const value = await untilAnswered(() => entries(alive), alive.closing);
401
+ if (alive.deps.closed())
402
+ return;
403
+ if (value === null)
341
404
  continue;
342
- }
343
- const joining = arriving.filter((message) => precedes(message, view.asked.before));
344
- const next = windowOf(view.window, joining, view.asked.limit);
345
- view.window = next.messages;
346
- view.more ||= next.dropped;
347
- if (view.total !== null && arriving.length > 0) {
348
- count ??= await local.messageCount(conversation);
349
- view.total = count;
350
- }
405
+ alive.listeners.tell(value);
406
+ alive.listeners.welcome(value);
351
407
  }
352
408
  }
353
- function stateOf(conversation) {
354
- const facts = liveOf(conversation);
355
- if (facts.questions.length > 0)
356
- return 'asking';
357
- return facts.turn === null ? 'idle' : 'working';
409
+ finally {
410
+ alive.held.set({ listTelling: false });
358
411
  }
359
- function entries() {
360
- return [...listing.values()].map((entry) => ({
361
- conversation: entry.conversation,
362
- agent: { identity: entry.agent, name: entry.agentName },
363
- name: entry.name,
364
- created: entry.created,
365
- finished: entry.finished,
366
- outcome: entry.outcome,
367
- waiting: entry.waiting,
368
- state: stateOf(entry.conversation),
369
- started: lives.get(entry.conversation)?.turn?.started ?? null,
370
- }));
412
+ }
413
+ function tellList(alive) {
414
+ const { listeners } = alive;
415
+ if (alive.deps.closed() || (!listeners.told() && !listeners.waiting()))
416
+ return;
417
+ alive.held.set({ listOwed: true });
418
+ if (alive.held.now().listTelling)
419
+ return;
420
+ alive.held.set({ listTelling: true });
421
+ void told(alive).catch(() => { });
422
+ }
423
+ function tellSoon(alive) {
424
+ alive.rowSoon(() => tellList(alive));
425
+ }
426
+ function emitList(alive) {
427
+ if (alive.deps.closed())
428
+ return;
429
+ tellList(alive);
430
+ emitAgents(alive);
431
+ conversationsLearned(alive);
432
+ }
433
+ export function conversationsLearned(alive) {
434
+ if (alive.deps.closed())
435
+ return;
436
+ if (alive.listeners.waiting())
437
+ tellList(alive);
438
+ if (!alive.agentListeners.waiting())
439
+ return;
440
+ shownList(alive, (list) => alive.agentListeners.welcome(agents(alive, list)));
441
+ }
442
+ function agents(alive, list) {
443
+ const named = new Map();
444
+ for (const agent of alive.held.now().listedAgents ?? [])
445
+ named.set(agent.agent, agent);
446
+ for (const entry of list) {
447
+ named.set(entry.agent, { name: entry.agentName, retired: entry.agentRetired });
371
448
  }
372
- function keepList() {
373
- if (!listKnown || listKept)
449
+ return [...named]
450
+ .filter(([, agent]) => !agent.retired)
451
+ .map(([identity, agent]) => ({ identity, name: agent.name }))
452
+ .sort((left, right) => left.name === right.name
453
+ ? left.identity.localeCompare(right.identity)
454
+ : left.name.localeCompare(right.name));
455
+ }
456
+ function readAgents(alive) {
457
+ const stream = alive.deps.stream();
458
+ if (stream?.agents === undefined || !alive.deps.online() || alive.held.now().agentsReading)
459
+ return;
460
+ const { agents: read } = stream;
461
+ const { agentListeners } = alive;
462
+ alive.held.set({ agentsReading: true });
463
+ void alive.deps.recovery
464
+ .attempt('agents', async () => {
465
+ if (!alive.deps.online() || (!agentListeners.waiting() && !agentListeners.told())) {
466
+ return 'done';
467
+ }
468
+ const listed = await read();
469
+ if (listed === null)
470
+ return 'done';
471
+ alive.held.set({ listedAgents: listed });
472
+ emitAgents(alive);
473
+ return 'done';
474
+ })
475
+ .finally(() => {
476
+ alive.held.set({ agentsReading: false });
477
+ });
478
+ }
479
+ function emitAgents(alive) {
480
+ if (alive.deps.closed() || !alive.agentListeners.told())
481
+ return;
482
+ shownList(alive, (list) => {
483
+ const value = agents(alive, list);
484
+ const shown = JSON.stringify(value);
485
+ if (shown === alive.held.now().agentsShown)
374
486
  return;
375
- listKept = true;
376
- queueMicrotask(() => {
377
- listKept = false;
378
- if (deps.closed())
379
- return;
380
- const entries = [...listing.values()];
381
- const cursor = listCursor;
382
- void deps
383
- .durably(async (local) => {
384
- await local.fact('conversationList', entries);
385
- await local.fact('conversationCursor', cursor);
386
- })
387
- .catch(() => { });
487
+ alive.held.set({ agentsShown: shown });
488
+ alive.agentListeners.tell(value);
489
+ });
490
+ }
491
+ function setLive(alive, conversation, next) {
492
+ const before = rowOf(alive, conversation);
493
+ alive.holdLive(conversation, next);
494
+ const after = rowOf(alive, conversation);
495
+ if (after.state !== before.state || after.started !== before.started)
496
+ emitList(alive);
497
+ else if (after.line !== before.line ||
498
+ after.question !== before.question ||
499
+ after.asked !== before.asked)
500
+ tellSoon(alive);
501
+ }
502
+ function retiredChat(conversation, list) {
503
+ if (!conversation.startsWith(NEW_CHAT))
504
+ return false;
505
+ const agent = conversation.slice(NEW_CHAT.length);
506
+ return list.some((entry) => entry.agent === agent && entry.agentRetired);
507
+ }
508
+ function live(alive, conversation, change) {
509
+ alive.factsHeard(conversation, FACTS.filter((one) => one in change));
510
+ setLive(alive, conversation, { ...alive.liveOf(conversation), ...change });
511
+ emit(alive, conversation);
512
+ }
513
+ function openingEnded(alive) {
514
+ for (const [conversation, facts] of alive.factsTaken()) {
515
+ const held = alive.liveHeld(conversation);
516
+ if (held === undefined || facts.size === 0)
517
+ continue;
518
+ setLive(alive, conversation, {
519
+ turn: held.turn,
520
+ questions: facts.has('questions') ? QUIET.questions : held.questions,
521
+ process: facts.has('process') ? QUIET.process : held.process,
522
+ commands: facts.has('commands') ? QUIET.commands : held.commands,
523
+ options: facts.has('options') ? QUIET.options : held.options,
524
+ starting: facts.has('starting') ? QUIET.starting : held.starting,
525
+ state: facts.has('state') ? QUIET.state : held.state,
526
+ link: facts.has('link') ? QUIET.link : held.link,
527
+ deliveryUnknown: facts.has('deliveryUnknown') ? QUIET.deliveryUnknown : held.deliveryUnknown,
388
528
  });
529
+ emit(alive, conversation);
389
530
  }
390
- function listed(entry) {
391
- const ended = listing.get(entry.conversation)?.processEnded ?? null;
392
- listing.set(entry.conversation, { ...entry });
393
- creations.delete(entry.conversation);
394
- if (entry.processEnded !== ended)
395
- emit(entry.conversation);
396
- }
397
- function emitList() {
398
- if (deps.closed())
399
- return;
400
- if (listWatchers.size > 0) {
401
- const value = entries();
402
- for (const watcher of listWatchers)
403
- watcher(value);
404
- }
405
- emitAgents();
406
- learned();
407
- }
408
- function learned() {
409
- if (deps.closed())
410
- return;
411
- if (!listKnown && !listHeld && deps.stream() !== undefined && deps.online())
412
- return;
413
- if (unlisted.size > 0) {
414
- const value = entries();
415
- for (const watcher of [...unlisted]) {
416
- unlisted.delete(watcher);
417
- listWatchers.add(watcher);
418
- watcher(value);
531
+ }
532
+ function relayed(alive, conversation, turn, operation) {
533
+ const held = alive.liveOf(conversation).turn;
534
+ const next = held?.turn === turn ? appliedTurn(held, operation) : startedTurn(turn, operation);
535
+ if (next !== null)
536
+ live(alive, conversation, { turn: next });
537
+ }
538
+ function sealTurns(alive, conversation, turns) {
539
+ const held = alive.liveHeld(conversation);
540
+ if (held?.turn == null || !turns.has(held.turn.turn))
541
+ return false;
542
+ setLive(alive, conversation, { ...held, turn: null });
543
+ return true;
544
+ }
545
+ function handReplicated(alive) {
546
+ const stream = alive.deps.stream();
547
+ if (stream === undefined)
548
+ return;
549
+ const held = [...alive.held.now().replicated].sort();
550
+ const named = JSON.stringify(held);
551
+ if (named === alive.held.now().handedReplicated)
552
+ return;
553
+ alive.held.set({ handedReplicated: named });
554
+ stream.replicate(held);
555
+ }
556
+ async function remove(alive, leaving) {
557
+ await alive.deps.durably(async (local) => {
558
+ const kept = new Set([
559
+ ...(await local.conversations(leaving)).map(({ conversation }) => conversation),
560
+ ...(await local.chatDrafts())
561
+ .filter(({ conversation }) => leaving.includes(conversation))
562
+ .map(({ conversation }) => conversation),
563
+ ]);
564
+ await local.dropConversations(leaving);
565
+ const changed = [];
566
+ for (const conversation of leaving) {
567
+ if (kept.has(conversation) || alive.liveHeld(conversation) !== undefined) {
568
+ changed.push(conversation);
419
569
  }
570
+ shownDraft(alive, conversation, null);
571
+ alive.forget(conversation);
572
+ setLive(alive, conversation, null);
573
+ await slide(alive, local, conversation, null);
420
574
  }
421
- if (unnamed.size > 0) {
422
- const value = agents();
423
- for (const watcher of [...unnamed]) {
424
- unnamed.delete(watcher);
425
- agentWatchers.add(watcher);
426
- watcher(value);
427
- }
575
+ if (changed.length > 0)
576
+ alive.deps.publish(conversationChangeSet(changed));
577
+ });
578
+ }
579
+ function newestOfListed(alive, entry) {
580
+ if (entry === undefined)
581
+ return undefined;
582
+ const heard = alive.newestHeard(entry.conversation);
583
+ if (heard === undefined)
584
+ return entry.newest;
585
+ return entry.newest === null || heard > entry.newest ? heard : entry.newest;
586
+ }
587
+ function missed(alive, conversation, held, entry) {
588
+ const read = held?.read;
589
+ const newest = newestOfListed(alive, entry);
590
+ return (read === undefined ||
591
+ newest === undefined ||
592
+ held?.partial === true ||
593
+ (newest !== null && (read === null || newest > read)));
594
+ }
595
+ async function readsOf(local, conversations) {
596
+ return new Map((await local.conversations(conversations)).map((held) => [held.conversation, held]));
597
+ }
598
+ function retiredDrafts(alive, list) {
599
+ if (!list.some((entry) => entry.agentRetired))
600
+ return;
601
+ void alive.deps
602
+ .local()
603
+ .then((local) => local.chatDrafts())
604
+ .then((held) => {
605
+ if (!alive.deps.closed() &&
606
+ held.some(({ conversation }) => retiredChat(conversation, list))) {
607
+ alive.deps.again();
428
608
  }
429
- }
430
- function agents() {
431
- const named = new Map();
432
- for (const agent of listedAgents ?? [])
433
- named.set(agent.agent, agent);
434
- for (const entry of listing.values()) {
435
- named.set(entry.agent, { name: entry.agentName, retired: entry.agentRetired });
609
+ }, uncaught);
610
+ }
611
+ function settleBehind(alive, list) {
612
+ void alive.deps
613
+ .durably(async (local) => {
614
+ const entries = new Map(list.map((entry) => [entry.conversation, entry]));
615
+ const named = [...alive.held.now().replicated].filter((conversation) => entries.has(conversation));
616
+ const held = await readsOf(local, named);
617
+ let owed = false;
618
+ for (const conversation of named) {
619
+ if (!missed(alive, conversation, held.get(conversation), entries.get(conversation))) {
620
+ alive.caughtUpTo(conversation);
621
+ }
622
+ else if (!alive.behind(conversation)) {
623
+ alive.gapOpened(conversation);
624
+ owed = true;
625
+ }
436
626
  }
437
- return [...named]
438
- .filter(([, agent]) => !agent.retired)
439
- .map(([identity, agent]) => ({ identity, name: agent.name }))
440
- .sort((left, right) => left.name === right.name
441
- ? left.identity.localeCompare(right.identity)
442
- : left.name.localeCompare(right.name));
443
- }
444
- function readAgents() {
445
- const stream = deps.stream();
446
- if (stream?.agents === undefined || !deps.online() || agentsReading)
627
+ return owed;
628
+ })
629
+ .then((owed) => {
630
+ if (alive.deps.closed())
447
631
  return;
448
- agentsReading = true;
449
- void stream
450
- .agents()
451
- .then((read) => {
452
- if (read === null)
453
- return;
454
- listedAgents = read;
455
- emitAgents();
456
- }, () => { })
457
- .finally(() => {
458
- agentsReading = false;
632
+ alive.deps.settled();
633
+ if (owed)
634
+ alive.deps.again();
635
+ }, uncaught);
636
+ }
637
+ function keep(alive, conversation, message) {
638
+ return alive.deps.durably(async (local) => {
639
+ if (!alive.held.now().replicated.has(conversation))
640
+ return;
641
+ const read = (await readsOf(local, [conversation])).get(conversation)?.read;
642
+ const advances = read !== undefined &&
643
+ !alive.behind(conversation) &&
644
+ (read === null || message.position > read);
645
+ await sealed(alive, local, conversation, new Set([message.turn]));
646
+ await local.keepMessages({
647
+ conversation,
648
+ messages: [message],
649
+ ...(advances ? { read: { at: message.position, partial: false } } : {}),
459
650
  });
651
+ sealTurns(alive, conversation, new Set([message.turn]));
652
+ await slide(alive, local, conversation, [message]);
653
+ alive.deps.publish(conversationChangeSet([conversation]));
654
+ tellList(alive);
655
+ });
656
+ }
657
+ async function readHistories(alive, conversations, ended) {
658
+ const generations = new Map(conversations.map((one) => [one, alive.generation(one)]));
659
+ const held = await readsOf(await alive.deps.local(), conversations);
660
+ let waiting = conversations.map((conversation) => ({
661
+ conversation,
662
+ after: held.get(conversation)?.read ?? undefined,
663
+ }));
664
+ while (waiting.length > 0) {
665
+ const asking = waiting.slice(0, HISTORY_CONVERSATIONS);
666
+ const result = await alive.deps.history({
667
+ conversations: asking.map(({ conversation, after }) => ({
668
+ conversation,
669
+ ...(after === undefined ? {} : { after }),
670
+ })),
671
+ });
672
+ const pages = historyPages(result);
673
+ if (pages === null)
674
+ return result;
675
+ const asked = new Map(asking.map(({ conversation, after }) => [conversation, after]));
676
+ const following = [];
677
+ for (const page of pages) {
678
+ if (!asked.has(page.conversation))
679
+ continue;
680
+ await keepPage(alive, page.conversation, page.messages, asked.get(page.conversation) ?? null, page.next, generations.get(page.conversation) ?? 0);
681
+ if (page.next !== undefined) {
682
+ following.push({ conversation: page.conversation, after: page.next });
683
+ }
684
+ }
685
+ for (const { conversation } of asking) {
686
+ if (!following.some((next) => next.conversation === conversation))
687
+ ended(conversation);
688
+ }
689
+ waiting = [...waiting.slice(HISTORY_CONVERSATIONS), ...following];
460
690
  }
461
- function emitAgents() {
462
- if (deps.closed() || agentWatchers.size === 0)
463
- return;
464
- const value = agents();
465
- const shown = JSON.stringify(value);
466
- if (shown === agentsShown)
467
- return;
468
- agentsShown = shown;
469
- for (const watcher of agentWatchers)
470
- watcher(value);
691
+ return null;
692
+ }
693
+ function caughtUp(alive, conversations) {
694
+ const ends = new Map();
695
+ for (const conversation of conversations) {
696
+ alive.catchingUntil(conversation, new Promise((end) => ends.set(conversation, end)));
471
697
  }
472
- function setLive(conversation, next) {
473
- const before = stateOf(conversation);
474
- const began = lives.get(conversation)?.turn?.started;
475
- if (next === null)
476
- lives.delete(conversation);
477
- else
478
- lives.set(conversation, next);
479
- if (!listing.has(conversation))
698
+ const ended = (conversation) => ends.get(conversation)?.();
699
+ const read = readHistories(alive, conversations, ended);
700
+ const endAll = () => {
701
+ for (const conversation of conversations)
702
+ ended(conversation);
703
+ };
704
+ read.then(endAll, endAll);
705
+ return read;
706
+ }
707
+ function keepPage(alive, conversation, arriving, from, next, generation) {
708
+ return alive.deps.durably(async (local) => {
709
+ if (!alive.held.now().replicated.has(conversation))
480
710
  return;
481
- if (stateOf(conversation) !== before || next?.turn?.started !== began)
482
- emitList();
483
- }
484
- function retiredChat(conversation) {
485
- if (!conversation.startsWith(NEW_CHAT))
486
- return false;
487
- const agent = conversation.slice(NEW_CHAT.length);
488
- return [...listing.values()].some((entry) => entry.agent === agent && entry.agentRetired);
489
- }
490
- function live(conversation, change) {
491
- const owed = unsent.get(conversation);
492
- for (const fact of FACTS.filter((one) => one in change))
493
- owed?.delete(fact);
494
- setLive(conversation, { ...liveOf(conversation), ...change });
495
- emit(conversation);
496
- }
497
- function openingEnded() {
498
- const owed = [...unsent];
499
- unsent.clear();
500
- for (const [conversation, facts] of owed) {
501
- const held = lives.get(conversation);
502
- if (held === undefined || facts.size === 0)
503
- continue;
504
- setLive(conversation, {
505
- turn: held.turn,
506
- questions: facts.has('questions') ? QUIET.questions : held.questions,
507
- process: facts.has('process') ? QUIET.process : held.process,
508
- commands: facts.has('commands') ? QUIET.commands : held.commands,
509
- options: facts.has('options') ? QUIET.options : held.options,
510
- starting: facts.has('starting') ? QUIET.starting : held.starting,
511
- subagents: facts.has('subagents') ? QUIET.subagents : held.subagents,
512
- link: facts.has('link') ? QUIET.link : held.link,
513
- deliveryUnknown: facts.has('deliveryUnknown')
514
- ? QUIET.deliveryUnknown
515
- : held.deliveryUnknown,
516
- });
517
- emit(conversation);
711
+ const whole = next === undefined;
712
+ const cursor = next ?? newestOf(arriving, from);
713
+ const held = (await readsOf(local, [conversation])).get(conversation);
714
+ const partial = !whole && (held?.partial === true || held?.read === undefined);
715
+ const sealing = await sealed(alive, local, conversation, new Set(arriving.map((message) => message.turn)));
716
+ await local.keepMessages({ conversation, messages: arriving, read: { at: cursor, partial } });
717
+ sealTurns(alive, conversation, new Set(arriving.map((message) => message.turn)));
718
+ if (whole && alive.generation(conversation) === generation)
719
+ alive.caughtUpTo(conversation);
720
+ await slide(alive, local, conversation, arriving);
721
+ if (arriving.length > 0 || sealing || whole) {
722
+ alive.deps.publish(conversationChangeSet([conversation]));
518
723
  }
724
+ if (arriving.length > 0)
725
+ tellSoon(alive);
726
+ });
727
+ }
728
+ function heard(alive, event) {
729
+ const { conversation } = event;
730
+ if (event.kind === 'gap') {
731
+ if (alive.held.now().replicated.has(conversation))
732
+ alive.gapOpened(conversation);
733
+ if (alive.liveHeld(conversation) !== undefined)
734
+ alive.factsOwed(conversation);
735
+ return;
519
736
  }
520
- function relayed(conversation, turn, operation) {
521
- const held = liveOf(conversation).turn;
522
- const next = held?.turn === turn ? appliedTurn(held, operation) : startedTurn(turn, operation);
523
- if (next !== null)
524
- live(conversation, { turn: next });
737
+ if (event.kind === 'turn') {
738
+ relayed(alive, conversation, event.turn, event.operation);
739
+ return;
525
740
  }
526
- function sealTurns(conversation, turns) {
527
- const held = lives.get(conversation);
528
- if (held?.turn == null || !turns.has(held.turn.turn))
529
- return false;
530
- setLive(conversation, { ...held, turn: null });
531
- return true;
741
+ if (event.kind === 'questions') {
742
+ live(alive, conversation, { questions: structuredClone(event.questions) });
743
+ return;
532
744
  }
533
- function handReplicated() {
534
- const stream = deps.stream();
535
- if (stream === undefined)
536
- return;
537
- const held = [...replicated].sort();
538
- const named = JSON.stringify(held);
539
- if (named === handedReplicated)
540
- return;
541
- handedReplicated = named;
542
- stream.replicate(held);
745
+ if (event.kind === 'process') {
746
+ live(alive, conversation, { process: { running: event.running } });
747
+ return;
543
748
  }
544
- async function remove(leaving) {
545
- await deps.durably(async (local) => {
546
- await local.dropConversations(leaving);
547
- const changed = [];
548
- for (const conversation of leaving) {
549
- if (stored.has(conversation) || drafts.has(conversation) || lives.has(conversation)) {
550
- changed.push(conversation);
551
- }
552
- stored.delete(conversation);
553
- reads.delete(conversation);
554
- partials.delete(conversation);
555
- drafts.delete(conversation);
556
- behind.delete(conversation);
557
- unsent.delete(conversation);
558
- setLive(conversation, null);
559
- await slide(local, conversation, null);
560
- }
561
- if (changed.length > 0)
562
- deps.publish(conversationChangeSet(changed));
563
- });
749
+ if (event.kind === 'commands') {
750
+ live(alive, conversation, { commands: structuredClone(event.commands) });
751
+ return;
564
752
  }
565
- function missed(conversation) {
566
- const read = reads.get(conversation);
567
- const newest = listing.get(conversation)?.newest;
568
- return (read === undefined ||
569
- newest === undefined ||
570
- partials.has(conversation) ||
571
- (newest !== null && (read === null || newest > read)));
753
+ if (event.kind === 'options') {
754
+ live(alive, conversation, { options: structuredClone(event.options) });
755
+ return;
572
756
  }
573
- function noted(conversation, message) {
574
- const entry = listing.get(conversation);
575
- if (entry === undefined || (entry.newest !== null && entry.newest >= message.position))
576
- return;
577
- listing.set(conversation, { ...entry, newest: message.position });
757
+ if (event.kind === 'starting') {
758
+ live(alive, conversation, { starting: event.step });
759
+ return;
578
760
  }
579
- function gap(conversation) {
580
- gaps.set(conversation, (gaps.get(conversation) ?? 0) + 1);
581
- behind.add(conversation);
761
+ if (event.kind === 'state') {
762
+ live(alive, conversation, { state: structuredClone(event.state) });
763
+ return;
582
764
  }
583
- function keep(conversation, message) {
584
- return deps.durably(async (local) => {
585
- if (!replicated.has(conversation))
586
- return;
587
- const read = reads.get(conversation);
588
- const advances = read !== undefined &&
589
- !behind.has(conversation) &&
590
- (read === null || message.position > read);
591
- await sealed(local, conversation, new Set([message.turn]));
592
- await local.keepMessages({
593
- conversation,
594
- messages: [message],
595
- ...(advances ? { read: { at: message.position, partial: false } } : {}),
596
- });
597
- stored.add(conversation);
598
- if (advances)
599
- reads.set(conversation, message.position);
600
- sealTurns(conversation, new Set([message.turn]));
601
- await slide(local, conversation, [message]);
602
- deps.publish(conversationChangeSet([conversation]));
603
- });
765
+ if (event.kind === 'link') {
766
+ live(alive, conversation, { link: { connected: event.connected } });
767
+ return;
604
768
  }
605
- async function readHistories(conversations, ended) {
606
- const generations = new Map(conversations.map((one) => [one, gaps.get(one) ?? 0]));
607
- let waiting = conversations.map((conversation) => ({
608
- conversation,
609
- after: reads.get(conversation) ?? undefined,
610
- }));
611
- while (waiting.length > 0) {
612
- const asking = waiting.slice(0, HISTORY_CONVERSATIONS);
613
- const result = await deps.history({
614
- conversations: asking.map(({ conversation, after }) => ({
615
- conversation,
616
- ...(after === undefined ? {} : { after }),
617
- })),
618
- });
619
- const pages = historyPages(result);
620
- if (pages === null)
621
- return result;
622
- const asked = new Map(asking.map(({ conversation, after }) => [conversation, after]));
623
- const following = [];
624
- for (const page of pages) {
625
- if (!asked.has(page.conversation))
626
- continue;
627
- await keepPage(page.conversation, page.messages, asked.get(page.conversation) ?? null, page.next, generations.get(page.conversation) ?? 0);
628
- if (page.next !== undefined) {
629
- following.push({ conversation: page.conversation, after: page.next });
630
- }
631
- }
632
- for (const { conversation } of asking) {
633
- if (!following.some((next) => next.conversation === conversation))
634
- ended(conversation);
635
- }
636
- waiting = [...waiting.slice(HISTORY_CONVERSATIONS), ...following];
637
- }
638
- return null;
769
+ if (event.kind === 'deliveries') {
770
+ live(alive, conversation, { deliveryUnknown: [...event.unknown] });
771
+ return;
639
772
  }
640
- function caughtUp(conversations) {
641
- const ends = new Map();
642
- for (const conversation of conversations) {
643
- const held = new Promise((end) => ends.set(conversation, end));
644
- catching.set(conversation, held);
645
- void held.then(() => {
646
- if (catching.get(conversation) === held)
647
- catching.delete(conversation);
648
- });
773
+ const arriving = acceptedMessage(event.message);
774
+ if (arriving === null)
775
+ return;
776
+ alive.heardAt(conversation, arriving.position);
777
+ if (alive.held.now().replicated.has(conversation)) {
778
+ if (alive.deps.full()) {
779
+ alive.gapOpened(conversation);
780
+ return;
649
781
  }
650
- const ended = (conversation) => ends.get(conversation)?.();
651
- const read = readHistories(conversations, ended);
652
- const endAll = () => {
653
- for (const conversation of conversations)
654
- ended(conversation);
655
- };
656
- read.then(endAll, endAll);
657
- return read;
658
- }
659
- function keepPage(conversation, arriving, from, next, generation) {
660
- return deps.durably(async (local) => {
661
- if (!replicated.has(conversation))
662
- return;
663
- const whole = next === undefined;
664
- const cursor = next ?? newestOf(arriving, from);
665
- const partial = !whole && (partials.has(conversation) || !reads.has(conversation));
666
- const sealing = await sealed(local, conversation, new Set(arriving.map((message) => message.turn)));
667
- await local.keepMessages({ conversation, messages: arriving, read: { at: cursor, partial } });
668
- stored.add(conversation);
669
- reads.set(conversation, cursor);
670
- if (partial)
671
- partials.add(conversation);
782
+ void keep(alive, conversation, arriving).catch((error) => {
783
+ if (refusedForSpace(error))
784
+ alive.gapOpened(conversation);
672
785
  else
673
- partials.delete(conversation);
674
- sealTurns(conversation, new Set(arriving.map((message) => message.turn)));
675
- if (whole && (gaps.get(conversation) ?? 0) === generation)
676
- behind.delete(conversation);
677
- await slide(local, conversation, arriving);
678
- if (arriving.length > 0 || sealing || whole) {
679
- deps.publish(conversationChangeSet([conversation]));
680
- }
786
+ uncaught(error);
681
787
  });
788
+ return;
682
789
  }
683
- function heard(event) {
684
- const { conversation } = event;
685
- if (event.kind === 'gap') {
686
- if (replicated.has(conversation))
687
- gap(conversation);
688
- if (lives.has(conversation))
689
- unsent.set(conversation, new Set(FACTS));
690
- return;
691
- }
692
- if (event.kind === 'turn') {
693
- relayed(conversation, event.turn, event.operation);
694
- return;
695
- }
696
- if (event.kind === 'questions') {
697
- live(conversation, { questions: structuredClone(event.questions) });
698
- return;
699
- }
700
- if (event.kind === 'process') {
701
- live(conversation, { process: { running: event.running } });
702
- return;
703
- }
704
- if (event.kind === 'commands') {
705
- live(conversation, { commands: structuredClone(event.commands) });
706
- return;
707
- }
708
- if (event.kind === 'options') {
709
- live(conversation, { options: structuredClone(event.options) });
710
- return;
711
- }
712
- if (event.kind === 'starting') {
713
- live(conversation, { starting: event.step });
714
- return;
715
- }
716
- if (event.kind === 'subagents') {
717
- live(conversation, { subagents: structuredClone(event.subagents) });
718
- return;
719
- }
720
- if (event.kind === 'link') {
721
- live(conversation, { link: { connected: event.connected } });
722
- return;
723
- }
724
- if (event.kind === 'deliveries') {
725
- live(conversation, { deliveryUnknown: [...event.unknown] });
726
- return;
727
- }
728
- const arriving = acceptedMessage(event.message);
729
- if (arriving === null)
790
+ if (sealTurns(alive, conversation, new Set([arriving.turn])))
791
+ emit(alive, conversation);
792
+ }
793
+ async function kept(alive, local, conversation, following) {
794
+ const shown = following === null || empty(following) ? null : following;
795
+ if (shown === null)
796
+ await local.dropChatDraft(conversation);
797
+ else
798
+ await local.keepChatDrafts([shown]);
799
+ shownDraft(alive, conversation, shown);
800
+ }
801
+ function shownDraft(alive, conversation, draft) {
802
+ for (const view of alive.views()) {
803
+ if (view.conversation === conversation)
804
+ view.held.set({ draft });
805
+ }
806
+ }
807
+ async function draftAt(local, conversation) {
808
+ return (await local.chatDraft(conversation)) ?? undefined;
809
+ }
810
+ async function sealed(alive, local, conversation, turns) {
811
+ const held = await draftAt(local, conversation);
812
+ const submitted = held?.submitted ?? [];
813
+ const left = submitted.filter((one) => one.turn === null || !turns.has(one.turn));
814
+ if (held === undefined || left.length === submitted.length)
815
+ return false;
816
+ await kept(alive, local, conversation, withSubmitted(held, left));
817
+ return true;
818
+ }
819
+ function moved(alive, agent, operation, to) {
820
+ const from = newChat(agent);
821
+ return alive.deps.durably(async (local) => {
822
+ const held = await draftAt(local, from);
823
+ const earlier = held?.moves ?? [];
824
+ if (earlier.includes(operation))
730
825
  return;
731
- noted(conversation, arriving);
732
- if (replicated.has(conversation)) {
733
- if (deps.full()) {
734
- gap(conversation);
735
- return;
736
- }
737
- void keep(conversation, arriving).catch((error) => {
738
- if (refusedForSpace(error))
739
- gap(conversation);
740
- });
826
+ const blank = {
827
+ conversation: from,
828
+ text: '',
829
+ revision: chatDraftRevision(),
830
+ };
831
+ const { moves: _answered, ...unsent } = held ?? blank;
832
+ const taken = (await draftAt(local, to)) !== undefined || empty(unsent)
833
+ ? []
834
+ : [{ ...unsent, conversation: to }];
835
+ const left = { ...(taken.length === 0 ? unsent : blank), moves: [...earlier, operation] };
836
+ await local.keepChatDrafts([left, ...taken]);
837
+ shownDraft(alive, from, left);
838
+ for (const one of taken)
839
+ shownDraft(alive, to, one);
840
+ alive.deps.publish(conversationChangeSet([from, to]));
841
+ });
842
+ }
843
+ function withDraft(alive, conversation, next) {
844
+ return alive.deps.durably(async (local) => {
845
+ const following = await next(await draftAt(local, conversation), local);
846
+ if (following === undefined)
741
847
  return;
742
- }
743
- if (sealTurns(conversation, new Set([arriving.turn])))
744
- emit(conversation);
745
- }
746
- async function kept(local, conversation, following) {
747
- if (following === null || empty(following)) {
748
- await local.dropChatDraft(conversation);
749
- drafts.delete(conversation);
750
- }
751
- else {
752
- await local.keepChatDrafts([following]);
753
- drafts.set(conversation, following);
754
- }
755
- }
756
- async function sealed(local, conversation, turns) {
757
- const held = drafts.get(conversation);
758
- const submitted = held?.submitted ?? [];
759
- const left = submitted.filter((one) => one.turn === null || !turns.has(one.turn));
760
- if (held === undefined || left.length === submitted.length)
761
- return false;
762
- await kept(local, conversation, withSubmitted(held, left));
763
- return true;
764
- }
765
- function moved(agent, operation, to) {
766
- const from = newChat(agent);
767
- return deps.durably(async (local) => {
768
- const held = drafts.get(from);
769
- const earlier = held?.moves ?? [];
770
- if (earlier.includes(operation))
771
- return;
772
- const blank = {
773
- conversation: from,
774
- text: '',
775
- revision: chatDraftRevision(),
776
- };
777
- const { moves: _answered, ...unsent } = held ?? blank;
778
- const taken = drafts.has(to) || empty(unsent) ? [] : [{ ...unsent, conversation: to }];
779
- const left = { ...(taken.length === 0 ? unsent : blank), moves: [...earlier, operation] };
780
- await local.keepChatDrafts([left, ...taken]);
781
- drafts.set(from, left);
782
- for (const one of taken)
783
- drafts.set(to, one);
784
- deps.publish(conversationChangeSet([from, to]));
785
- });
786
- }
787
- function withDraft(conversation, next) {
788
- return deps.durably(async (local) => {
789
- const following = await next(drafts.get(conversation), local);
790
- if (following === undefined)
791
- return;
792
- await kept(local, conversation, following);
793
- deps.publish(conversationChangeSet([conversation]));
794
- });
795
- }
796
- async function submitted(conversation, operation, draft) {
797
- let submission;
798
- await withDraft(conversation, (current) => {
799
- submission = current?.submitted?.find((one) => one.operation === operation);
800
- if (submission !== undefined)
801
- return undefined;
802
- const said = draft ?? current;
803
- submission = { operation, text: said?.text ?? '', turn: null };
804
- return {
805
- conversation,
806
- ...(draft === undefined || current === undefined
807
- ? { text: '', revision: chatDraftRevision() }
808
- : { text: current.text, revision: current.revision }),
809
- submitted: [...(current?.submitted ?? []), submission],
810
- };
848
+ await kept(alive, local, conversation, following);
849
+ alive.deps.publish(conversationChangeSet([conversation]));
850
+ });
851
+ }
852
+ async function submitted(alive, conversation, operation, draft) {
853
+ let submission;
854
+ await withDraft(alive, conversation, (current) => {
855
+ submission = current?.submitted?.find((one) => one.operation === operation);
856
+ if (submission !== undefined)
857
+ return undefined;
858
+ const said = draft ?? current;
859
+ submission = { operation, text: said?.text ?? '', turn: null };
860
+ return {
861
+ conversation,
862
+ ...(draft === undefined || current === undefined
863
+ ? { text: '', revision: chatDraftRevision() }
864
+ : { text: current.text, revision: current.revision }),
865
+ submitted: [...(current?.submitted ?? []), submission],
866
+ };
867
+ });
868
+ return submission;
869
+ }
870
+ async function dispatched(alive, conversation, submission) {
871
+ const dispatch = alive.sendingBegan(submission.operation);
872
+ try {
873
+ const result = await invoke(alive, 'conversations/send', conversation, {
874
+ operation_id: submission.operation,
875
+ text: submission.text,
811
876
  });
812
- return submission;
813
- }
814
- async function dispatched(conversation, submission) {
815
- const dispatch = { answered: false };
816
- sending.set(submission.operation, dispatch);
817
- try {
818
- const result = await invoke('conversations/send', conversation, {
819
- operation_id: submission.operation,
820
- text: submission.text,
821
- });
822
- dispatch.answered = result.kind !== 'transport-uncertainty';
823
- if (result.kind === 'revoked-authorization')
824
- return result;
825
- if (result.kind !== 'action' && result.retryable) {
826
- deps.unanswered();
827
- return result;
828
- }
829
- const turn = answered(result, 'message_id');
830
- await withDraft(conversation, async (current, local) => {
831
- const held = current?.submitted?.find((one) => one.operation === submission.operation);
832
- if (current === undefined || held === undefined || held.turn !== null)
833
- return undefined;
834
- const others = current.submitted.filter((one) => one !== held);
835
- if (result.kind !== 'action')
836
- return returned(current, held, others);
837
- const arrived = turn !== null && (await local.turnArrived(conversation, turn));
838
- return withSubmitted(current, turn === null || arrived
839
- ? others
840
- : current.submitted.map((one) => (one === held ? { ...held, turn } : one)));
841
- });
877
+ dispatch.set({ answered: result.kind !== 'transport-uncertainty' });
878
+ if (result.kind === 'revoked-authorization')
879
+ return result;
880
+ if (result.kind !== 'action' && result.retryable) {
881
+ alive.deps.unanswered();
842
882
  return result;
843
883
  }
844
- finally {
845
- if (sending.get(submission.operation) === dispatch)
846
- sending.delete(submission.operation);
847
- }
884
+ const turn = answered(result, 'message_id');
885
+ await withDraft(alive, conversation, async (current, local) => {
886
+ const held = current?.submitted?.find((one) => one.operation === submission.operation);
887
+ if (current === undefined || held === undefined || held.turn !== null)
888
+ return undefined;
889
+ const others = current.submitted.filter((one) => one !== held);
890
+ if (result.kind !== 'action')
891
+ return returned(current, held, others);
892
+ const arrived = turn !== null && (await local.turnArrived(conversation, turn));
893
+ return withSubmitted(current, turn === null || arrived
894
+ ? others
895
+ : current.submitted.map((one) => (one === held ? { ...held, turn } : one)));
896
+ });
897
+ return result;
848
898
  }
849
- function invoke(name, conversation, extra = { operation_id: changeBatchIdentity() }) {
850
- return deps.call(name, { conversation_id: conversation, ...extra });
899
+ finally {
900
+ alive.sendingEnded(submission.operation, dispatch);
851
901
  }
852
- const surface = {
902
+ }
903
+ function invoke(alive, name, conversation, extra = { operation_id: changeBatchIdentity() }) {
904
+ return alive.deps.call(name, { conversation_id: conversation, ...extra });
905
+ }
906
+ export function conversationSurface(alive) {
907
+ return {
853
908
  list() {
854
909
  return new Promise((settle) => {
855
910
  const answer = (listed) => {
856
- unlisted.delete(answer);
857
- listWatchers.delete(answer);
911
+ alive.listeners.leave(answer);
858
912
  settle(listed);
859
913
  };
860
- unlisted.add(answer);
861
- learned();
914
+ alive.listeners.join(answer);
915
+ conversationsLearned(alive);
862
916
  });
863
917
  },
864
918
  async read(conversation, options = {}) {
865
919
  const { text, ...windowed } = options;
866
920
  const asked = askedOf(windowed);
867
921
  const phrase = phraseOf(text);
868
- return deps.durably(async (local) => {
922
+ return alive.deps.durably(async (local) => {
869
923
  const { messages, more } = await local.messageWindow(conversation, asked.limit, asked.before, phrase);
870
924
  const total = asked.total ? await local.messageCount(conversation, phrase) : null;
871
- return structuredClone(viewOf(conversation, messages, frameOf(asked, messages, more, total)));
925
+ return structuredClone(viewOf(alive, conversation, messages, frameOf(asked, messages, more, total), (await local.chatDraft(conversation)) ?? null, await endedIn(alive, conversation)));
872
926
  });
873
927
  },
874
928
  async create(input) {
875
- const result = await deps.call('conversations/create', input);
929
+ const result = await alive.deps.call('conversations/create', input);
876
930
  const conversation = answered(result, 'conversation_id');
877
931
  if (conversation === null)
878
932
  return result;
879
- if (!listing.has(conversation))
880
- creations.add(conversation);
933
+ const listed = (await heldList(alive)) ?? [];
934
+ if (!listed.some((entry) => entry.conversation === conversation)) {
935
+ alive.creating(conversation);
936
+ }
881
937
  const creation = creationOf(input);
882
938
  if (creation !== null)
883
- await moved(creation.agent, creation.operation, conversation);
939
+ await moved(alive, creation.agent, creation.operation, conversation);
884
940
  return result;
885
941
  },
886
942
  async send(conversation, operation = changeBatchIdentity(), draft) {
887
- if (deps.full())
943
+ if (alive.deps.full())
888
944
  return DURABLE_WRITE;
889
- if (deps.online()) {
890
- const held = await submitted(conversation, operation, draft).catch((error) => {
945
+ if (alive.deps.online()) {
946
+ const held = await submitted(alive, conversation, operation, draft).catch((error) => {
891
947
  if (refusedForSpace(error))
892
948
  return null;
893
949
  throw error;
894
950
  });
895
951
  if (held === null)
896
952
  return DURABLE_WRITE;
897
- return dispatched(conversation, held);
953
+ return dispatched(alive, conversation, held);
898
954
  }
899
955
  if (draft !== undefined) {
900
- await withDraft(conversation, (current) => current?.submitted?.some((one) => one.operation === operation) === true
956
+ await withDraft(alive, conversation, (current) => current?.submitted?.some((one) => one.operation === operation) === true
901
957
  ? undefined
902
958
  : returned(current ?? { conversation, text: '', revision: '' }, { operation, ...draft, turn: null }, current?.submitted ?? []));
903
959
  }
904
960
  return OFFLINE;
905
961
  },
906
962
  answer(conversation, answer) {
907
- return invoke('conversations/interaction/answer', conversation, {
963
+ return invoke(alive, 'conversations/interaction/answer', conversation, {
908
964
  operation_id: changeBatchIdentity(),
909
965
  ...answer,
910
966
  });
911
967
  },
912
968
  interrupt(conversation) {
913
- return invoke('conversations/interrupt', conversation);
969
+ return invoke(alive, 'conversations/interrupt', conversation);
914
970
  },
915
971
  kill(conversation) {
916
- return invoke('conversations/kill', conversation);
972
+ return invoke(alive, 'conversations/kill', conversation);
917
973
  },
918
974
  delete(conversation) {
919
- return invoke('conversations/delete', conversation);
975
+ return invoke(alive, 'conversations/delete', conversation);
920
976
  },
921
977
  };
922
- const chatDraft = {
978
+ }
979
+ export function chatDraftSurface(alive) {
980
+ return {
923
981
  write(conversation, draft, revision = chatDraftRevision()) {
924
- return withDraft(conversation, (current) => ({
982
+ return withDraft(alive, conversation, (current) => ({
925
983
  conversation,
926
984
  text: draft.text,
927
985
  revision,
@@ -929,7 +987,7 @@ export function createConversationStore(deps) {
929
987
  }));
930
988
  },
931
989
  prepend(conversation, draft) {
932
- return withDraft(conversation, (current) => ({
990
+ return withDraft(alive, conversation, (current) => ({
933
991
  conversation,
934
992
  ...(current === undefined ? { text: draft.text } : prepended(current, draft)),
935
993
  revision: chatDraftRevision(),
@@ -937,238 +995,169 @@ export function createConversationStore(deps) {
937
995
  }));
938
996
  },
939
997
  discard(conversation) {
940
- return withDraft(conversation, (current) => current === undefined
998
+ return withDraft(alive, conversation, (current) => current === undefined
941
999
  ? undefined
942
1000
  : { conversation, text: '', revision: chatDraftRevision(), ...pending(current) });
943
1001
  },
944
1002
  };
945
- return {
946
- surface,
947
- chatDraft,
948
- hydrate(held, kept, list, cursor) {
949
- if (list !== null && !listKnown) {
950
- listing.clear();
951
- for (const entry of list)
952
- listing.set(entry.conversation, { ...entry });
953
- listHeld = true;
954
- listCursor = cursor;
955
- deps.stream()?.hold(cursor);
956
- }
957
- stored.clear();
958
- reads.clear();
959
- partials.clear();
960
- for (const entry of held) {
961
- stored.add(entry.conversation);
962
- if (entry.read !== undefined)
963
- reads.set(entry.conversation, entry.read);
964
- if (entry.partial)
965
- partials.add(entry.conversation);
966
- }
967
- drafts.clear();
968
- for (const record of kept)
969
- drafts.set(record.conversation, record);
970
- if (listHeld)
971
- learned();
972
- },
973
- async reconcile() {
974
- if (!listKnown)
1003
+ }
1004
+ export async function conversationsOpened(alive, local) {
1005
+ const { conversationList, conversationCursor } = await local.facts();
1006
+ if (conversationList === null || alive.known())
1007
+ return;
1008
+ alive.deps.stream()?.hold(conversationCursor);
1009
+ conversationsLearned(alive);
1010
+ }
1011
+ export async function reconcileConversations(alive) {
1012
+ if (!alive.known())
1013
+ return;
1014
+ const local = await alive.deps.local();
1015
+ const [held, kept, { conversationList }] = await Promise.all([
1016
+ local.conversations(),
1017
+ local.chatDrafts(),
1018
+ local.facts(),
1019
+ ]);
1020
+ const list = conversationList ?? [];
1021
+ const entries = new Map(list.map((entry) => [entry.conversation, entry]));
1022
+ const named = new Set(entries.keys());
1023
+ const reads = new Map(held.map((one) => [one.conversation, one]));
1024
+ const { replicated } = alive.held.now();
1025
+ const leaving = [
1026
+ ...new Set([...replicated, ...reads.keys(), ...kept.map(({ conversation }) => conversation)]),
1027
+ ].filter((conversation) => !named.has(conversation) &&
1028
+ !alive.isCreating(conversation) &&
1029
+ (!conversation.startsWith(NEW_CHAT) || retiredChat(conversation, list)));
1030
+ for (const conversation of named) {
1031
+ if (!replicated.has(conversation) &&
1032
+ missed(alive, conversation, reads.get(conversation), entries.get(conversation))) {
1033
+ alive.fellBehind(conversation);
1034
+ }
1035
+ }
1036
+ alive.held.set({ replicated: named });
1037
+ handReplicated(alive);
1038
+ if (leaving.length > 0)
1039
+ await remove(alive, leaving);
1040
+ }
1041
+ export async function catchUpConversations(alive, progress) {
1042
+ if (alive.deps.full()) {
1043
+ if (!alive.current())
1044
+ progress.complete = false;
1045
+ return;
1046
+ }
1047
+ const owed = (conversation) => alive.behind(conversation) && alive.held.now().replicated.has(conversation);
1048
+ const read = async (conversations) => {
1049
+ if (conversations.length === 0 || alive.deps.closed())
1050
+ return;
1051
+ const failed = await caughtUp(alive, conversations);
1052
+ if (failed?.kind === 'transport-uncertainty')
1053
+ progress.reachable = false;
1054
+ };
1055
+ const asking = alive.behindAll().filter(owed).sort();
1056
+ const awaited = asking.filter((conversation) => alive.catching(conversation) !== undefined);
1057
+ await Promise.all([
1058
+ read(asking.filter((conversation) => alive.catching(conversation) === undefined)),
1059
+ Promise.all(awaited.map((conversation) => alive.catching(conversation))).then(() => read(awaited.filter((conversation) => owed(conversation) && alive.catching(conversation) === undefined))),
1060
+ ]);
1061
+ if (!alive.current())
1062
+ progress.complete = false;
1063
+ }
1064
+ export async function resendConversations(alive, progress) {
1065
+ const local = await alive.deps.local();
1066
+ const tried = new Set();
1067
+ for (const { conversation } of await local.chatDrafts()) {
1068
+ for (;;) {
1069
+ const submission = (await local.chatDraft(conversation))?.submitted?.find((one) => one.turn === null && !alive.sending(one.operation) && !tried.has(one.operation));
1070
+ if (submission === undefined)
1071
+ break;
1072
+ if (alive.deps.closed())
975
1073
  return;
976
- const named = new Set(listing.keys());
977
- const leaving = [
978
- ...new Set([...replicated, ...stored, ...reads.keys(), ...drafts.keys()]),
979
- ].filter((conversation) => !named.has(conversation) &&
980
- !creations.has(conversation) &&
981
- (!conversation.startsWith(NEW_CHAT) || retiredChat(conversation)));
982
- for (const conversation of named) {
983
- if (!replicated.has(conversation) && missed(conversation))
984
- behind.add(conversation);
985
- }
986
- replicated = named;
987
- handReplicated();
988
- if (leaving.length > 0)
989
- await remove(leaving);
990
- },
991
- async catchUp(progress) {
992
- if (deps.full()) {
993
- if (behind.size > 0)
994
- progress.complete = false;
1074
+ tried.add(submission.operation);
1075
+ const result = await dispatched(alive, conversation, submission);
1076
+ if (result.kind === 'revoked-authorization')
1077
+ return;
1078
+ if (result.kind === 'transport-uncertainty') {
1079
+ progress.reachable = false;
995
1080
  return;
996
1081
  }
997
- const owed = (conversation) => behind.has(conversation) && replicated.has(conversation);
998
- const read = async (conversations) => {
999
- if (conversations.length === 0 || deps.closed())
1000
- return;
1001
- const failed = await caughtUp(conversations);
1002
- if (failed?.kind === 'transport-uncertainty')
1003
- progress.reachable = false;
1004
- };
1005
- const asking = [...behind].filter(owed).sort();
1006
- const awaited = asking.filter((conversation) => catching.has(conversation));
1007
- await Promise.all([
1008
- read(asking.filter((conversation) => !catching.has(conversation))),
1009
- Promise.all(awaited.map((conversation) => catching.get(conversation))).then(() => read(awaited.filter((conversation) => owed(conversation) && !catching.has(conversation)))),
1010
- ]);
1011
- if (behind.size > 0)
1082
+ if (result.kind !== 'action' && result.retryable) {
1012
1083
  progress.complete = false;
1013
- },
1014
- async resend(progress) {
1015
- for (const [conversation, held] of [...drafts]) {
1016
- for (const submission of held.submitted ?? []) {
1017
- if (submission.turn !== null || sending.has(submission.operation))
1018
- continue;
1019
- if (deps.closed())
1020
- return;
1021
- const result = await dispatched(conversation, submission);
1022
- if (result.kind === 'revoked-authorization')
1023
- return;
1024
- if (result.kind === 'transport-uncertainty') {
1025
- progress.reachable = false;
1026
- return;
1027
- }
1028
- if (result.kind !== 'action' && result.retryable) {
1029
- progress.complete = false;
1030
- return;
1031
- }
1032
- }
1033
- }
1034
- },
1035
- current() {
1036
- return behind.size === 0;
1037
- },
1038
- known() {
1039
- return listKnown;
1040
- },
1041
- reopened() {
1042
- relisting = null;
1043
- for (const [operation, dispatch] of sending)
1044
- if (!dispatch.answered)
1045
- sending.delete(operation);
1046
- },
1047
- lost() {
1048
- catching.clear();
1049
- },
1050
- watch(conversation, options, deliver) {
1051
- const asked = askedOf(options);
1052
- const key = JSON.stringify([conversation, asked.limit, asked.after ?? null, asked.total]);
1053
- const view = views.get(key) ?? {
1054
- conversation,
1055
- asked,
1056
- watchers: new Set(),
1057
- window: null,
1058
- more: false,
1059
- total: null,
1060
- };
1061
- views.set(key, view);
1062
- const watcher = { notify: deliver, ready: false };
1063
- view.watchers.add(watcher);
1064
- const reading = new AbortController();
1065
- void untilAnswered(() => deps.durably(async (local) => {
1066
- if (view.window !== null)
1067
- return;
1068
- const { messages, more } = await local.messageWindow(conversation, asked.limit, asked.before);
1069
- view.window = messages;
1070
- view.more = more;
1071
- view.total = asked.total ? await local.messageCount(conversation) : null;
1072
- }), reading.signal)
1073
- .then(() => {
1074
- if (deps.closed() || !view.watchers.has(watcher))
1075
- return;
1076
- watcher.ready = true;
1077
- const window = view.window ?? [];
1078
- watcher.notify(viewOf(conversation, window, sharedFrame(view, window)));
1079
- })
1080
- .catch(() => { });
1081
- return () => {
1082
- reading.abort();
1083
- if (!view.watchers.delete(watcher))
1084
- return;
1085
- if (view.watchers.size === 0)
1086
- views.delete(key);
1087
- };
1088
- },
1089
- watchList(deliver) {
1090
- unlisted.add(deliver);
1091
- learned();
1092
- return () => {
1093
- unlisted.delete(deliver);
1094
- listWatchers.delete(deliver);
1095
- };
1096
- },
1097
- watchAgents(deliver) {
1098
- unnamed.add(deliver);
1099
- learned();
1100
- readAgents();
1101
- return () => {
1102
- unnamed.delete(deliver);
1103
- agentWatchers.delete(deliver);
1104
- };
1105
- },
1106
- learned,
1107
- changed(set) {
1108
- for (const conversation of set.conversations)
1109
- emit(conversation);
1110
- },
1111
- receive(event) {
1112
- if (deps.closed())
1113
- return false;
1114
- if (event.kind === 'list' || event.kind === 'listed' || event.kind === 'unlisted') {
1115
- if (event.kind === 'list') {
1116
- if (event.whole)
1117
- relisting ??= new Map();
1118
- for (const entry of event.entries) {
1119
- if (relisting === null)
1120
- listed(entry);
1121
- else
1122
- relisting.set(entry.conversation, { ...entry });
1123
- }
1124
- if (event.more)
1125
- return false;
1126
- if (relisting !== null) {
1127
- listing.clear();
1128
- for (const entry of relisting.values())
1129
- listed(entry);
1130
- relisting = null;
1131
- }
1132
- listCursor = event.cursor;
1133
- deps.stream()?.hold(event.cursor);
1134
- listKnown = true;
1135
- for (const conversation of replicated) {
1136
- if (!listing.has(conversation))
1137
- continue;
1138
- if (!missed(conversation))
1139
- behind.delete(conversation);
1140
- else if (!behind.has(conversation))
1141
- gap(conversation);
1142
- }
1143
- openingEnded();
1144
- }
1145
- else if (event.kind === 'listed') {
1146
- listed(event.entry);
1147
- relisting?.set(event.entry.conversation, { ...event.entry });
1148
- }
1149
- else {
1150
- listing.delete(event.conversation);
1151
- relisting?.delete(event.conversation);
1152
- }
1153
- keepList();
1154
- emitList();
1155
- return ((event.kind !== 'list' &&
1156
- listKnown &&
1157
- (listing.size !== replicated.size ||
1158
- [...listing.keys()].some((conversation) => !replicated.has(conversation)))) ||
1159
- (listKnown && [...drafts.keys()].some(retiredChat)));
1084
+ return;
1160
1085
  }
1161
- heard(event);
1162
- return false;
1163
- },
1164
- close() {
1165
- views.clear();
1166
- lives.clear();
1167
- unsent.clear();
1168
- listWatchers.clear();
1169
- unlisted.clear();
1170
- agentWatchers.clear();
1171
- unnamed.clear();
1172
- },
1086
+ }
1087
+ }
1088
+ }
1089
+ export function watchConversation(alive, conversation, options, deliver) {
1090
+ const asked = askedOf(options);
1091
+ const key = JSON.stringify([conversation, asked.limit, asked.after ?? null, asked.total]);
1092
+ const { view, watcher } = alive.viewJoined(key, conversation, asked, deliver);
1093
+ const { held } = view;
1094
+ const reading = new AbortController();
1095
+ void untilAnswered(() => alive.deps.durably(async (local) => {
1096
+ if (held.now().window !== null)
1097
+ return;
1098
+ const { messages, more } = await local.messageWindow(conversation, asked.limit, asked.before);
1099
+ held.set({ draft: (await local.chatDraft(conversation)) ?? null });
1100
+ held.set({ ended: await endedIn(alive, conversation) });
1101
+ held.set({ window: messages });
1102
+ held.set({ more });
1103
+ held.set({ total: asked.total ? await local.messageCount(conversation) : null });
1104
+ }), reading.signal)
1105
+ .then(() => {
1106
+ if (alive.deps.closed() || !view.admit(watcher))
1107
+ return;
1108
+ const { window, draft, ended } = held.now();
1109
+ const shown = window ?? [];
1110
+ watcher.notify(viewOf(alive, conversation, shown, sharedFrame(view, shown), draft, ended));
1111
+ })
1112
+ .catch(() => { });
1113
+ return () => {
1114
+ reading.abort();
1115
+ alive.viewLeft(key, view, watcher);
1173
1116
  };
1174
1117
  }
1118
+ export function watchConversationList(alive, deliver) {
1119
+ alive.listeners.join(deliver);
1120
+ conversationsLearned(alive);
1121
+ return () => alive.listeners.leave(deliver);
1122
+ }
1123
+ export function watchConversationAgents(alive, deliver) {
1124
+ alive.agentListeners.join(deliver);
1125
+ conversationsLearned(alive);
1126
+ readAgents(alive);
1127
+ return () => alive.agentListeners.leave(deliver);
1128
+ }
1129
+ export function conversationsChanged(alive, set) {
1130
+ for (const conversation of set.conversations)
1131
+ emit(alive, conversation);
1132
+ }
1133
+ export function receiveConversationEvent(alive, event) {
1134
+ if (alive.deps.closed())
1135
+ return;
1136
+ if (event.kind === 'list') {
1137
+ if (event.whole)
1138
+ alive.relistBegun();
1139
+ if (alive.relisting())
1140
+ alive.relistHeard(event.entries);
1141
+ if (event.more && alive.relisting())
1142
+ return;
1143
+ const whole = alive.relistTaken();
1144
+ listChanged(alive, {
1145
+ replacing: whole !== null,
1146
+ set: whole === null ? event.entries : [...whole.values()],
1147
+ gone: null,
1148
+ ...(event.more ? { paged: true } : { cursor: event.cursor }),
1149
+ });
1150
+ return;
1151
+ }
1152
+ if (event.kind === 'listed') {
1153
+ alive.relistHeard([event.entry]);
1154
+ listChanged(alive, { replacing: false, set: [event.entry], gone: null });
1155
+ return;
1156
+ }
1157
+ if (event.kind === 'unlisted') {
1158
+ alive.relistDropped(event.conversation);
1159
+ listChanged(alive, { replacing: false, set: [], gone: event.conversation });
1160
+ return;
1161
+ }
1162
+ heard(alive, event);
1163
+ }