@agentshouse/mdruntime 0.1.0-c0bed82db8d73 → 0.1.0-c0c0511ef12ee

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