@agentshouse/mdruntime 0.1.0-cef5833f6c689 → 0.1.0-cf04ede9fb796

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