@agentshouse/mdruntime 0.1.0-c7fd3d0e03135 → 0.1.0-c835af48a82d3

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