@agentshouse/mdruntime 0.1.0-c0ffc146f48dd → 0.1.0-c112fd663ab59

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