@agentshouse/mdruntime 0.1.0-c49444f2a8fc6 → 0.1.0-c4c5934c45f21

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