@agentshouse/mdruntime 0.1.0-c24bc09d750de → 0.1.0-c2682496ef6d0

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 (136) hide show
  1. package/AGENTS.md +262 -262
  2. package/dist/acquisition.d.ts +14 -0
  3. package/dist/acquisition.d.ts.map +1 -0
  4. package/dist/acquisition.js +24 -0
  5. package/dist/adapter.d.ts +38 -9
  6. package/dist/adapter.d.ts.map +1 -1
  7. package/dist/attempt.d.ts.map +1 -1
  8. package/dist/attempt.js +14 -1
  9. package/dist/bootstrap.d.ts +3 -2
  10. package/dist/bootstrap.d.ts.map +1 -1
  11. package/dist/bootstrap.js +32 -6
  12. package/dist/change-set.d.ts +2 -0
  13. package/dist/change-set.d.ts.map +1 -1
  14. package/dist/change-set.js +36 -10
  15. package/dist/chat/acts.d.ts +3 -4
  16. package/dist/chat/acts.d.ts.map +1 -1
  17. package/dist/chat/acts.js +10 -10
  18. package/dist/chat/kit.d.ts +2 -1
  19. package/dist/chat/kit.d.ts.map +1 -1
  20. package/dist/chat/kit.js +3 -3
  21. package/dist/chat/list.d.ts +8 -1
  22. package/dist/chat/list.d.ts.map +1 -1
  23. package/dist/chat/list.js +10 -6
  24. package/dist/chat/message.d.ts.map +1 -1
  25. package/dist/chat/message.js +2 -2
  26. package/dist/chat/messages.d.ts +1 -0
  27. package/dist/chat/messages.d.ts.map +1 -1
  28. package/dist/chat/messages.js +4 -0
  29. package/dist/chat/provider.d.ts +1 -1
  30. package/dist/chat/provider.d.ts.map +1 -1
  31. package/dist/chat/provider.js +51 -67
  32. package/dist/chat/ready.d.ts +1 -0
  33. package/dist/chat/ready.d.ts.map +1 -1
  34. package/dist/chat/ready.js +4 -4
  35. package/dist/chat/style.js +3 -3
  36. package/dist/client.d.ts +12 -8
  37. package/dist/client.d.ts.map +1 -1
  38. package/dist/client.js +12 -3
  39. package/dist/collection.d.ts +17 -3
  40. package/dist/collection.d.ts.map +1 -1
  41. package/dist/collection.js +230 -19
  42. package/dist/connection.d.ts +24 -7
  43. package/dist/connection.d.ts.map +1 -1
  44. package/dist/connection.js +1385 -325
  45. package/dist/conversation.d.ts +15 -7
  46. package/dist/conversation.d.ts.map +1 -1
  47. package/dist/conversation.js +368 -142
  48. package/dist/durability.d.ts +7 -1
  49. package/dist/durability.d.ts.map +1 -1
  50. package/dist/entry.d.ts +17 -0
  51. package/dist/entry.d.ts.map +1 -0
  52. package/dist/entry.js +156 -0
  53. package/dist/fence.d.ts +6 -0
  54. package/dist/fence.d.ts.map +1 -0
  55. package/dist/fence.js +10 -0
  56. package/dist/host.d.ts +17 -2
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/host.js +86 -9
  59. package/dist/identity.d.ts +2 -0
  60. package/dist/identity.d.ts.map +1 -1
  61. package/dist/identity.js +6 -0
  62. package/dist/index.d.ts +9 -6
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +2 -0
  65. package/dist/memory.d.ts +8 -2
  66. package/dist/memory.d.ts.map +1 -1
  67. package/dist/memory.js +29 -7
  68. package/dist/model.d.ts +4 -2
  69. package/dist/model.d.ts.map +1 -1
  70. package/dist/model.js +10 -1
  71. package/dist/observation.d.ts +5 -2
  72. package/dist/observation.d.ts.map +1 -1
  73. package/dist/observation.js +22 -11
  74. package/dist/outcome.d.ts +4 -0
  75. package/dist/outcome.d.ts.map +1 -1
  76. package/dist/outcome.js +1 -0
  77. package/dist/overlay.d.ts +2 -0
  78. package/dist/overlay.d.ts.map +1 -1
  79. package/dist/overlay.js +58 -55
  80. package/dist/query.d.ts +35 -3
  81. package/dist/query.d.ts.map +1 -1
  82. package/dist/query.js +8 -2
  83. package/dist/reach.d.ts +6 -3
  84. package/dist/reach.d.ts.map +1 -1
  85. package/dist/reach.js +17 -5
  86. package/dist/react.d.ts +7 -4
  87. package/dist/react.d.ts.map +1 -1
  88. package/dist/react.js +6 -4
  89. package/dist/read-side.d.ts +13 -6
  90. package/dist/read-side.d.ts.map +1 -1
  91. package/dist/read-side.js +285 -83
  92. package/dist/readiness.d.ts +53 -0
  93. package/dist/readiness.d.ts.map +1 -0
  94. package/dist/readiness.js +33 -0
  95. package/dist/reads.d.ts +11 -0
  96. package/dist/reads.d.ts.map +1 -0
  97. package/dist/reads.js +98 -0
  98. package/dist/recovery.d.ts +25 -0
  99. package/dist/recovery.d.ts.map +1 -0
  100. package/dist/recovery.js +197 -0
  101. package/dist/refresh.d.ts +4 -4
  102. package/dist/refresh.d.ts.map +1 -1
  103. package/dist/refresh.js +17 -10
  104. package/dist/replica.d.ts +1 -1
  105. package/dist/replica.d.ts.map +1 -1
  106. package/dist/replica.js +57 -20
  107. package/dist/room-draft.d.ts +13 -1
  108. package/dist/room-draft.d.ts.map +1 -1
  109. package/dist/room-draft.js +2 -2
  110. package/dist/rows.d.ts +5 -13
  111. package/dist/rows.d.ts.map +1 -1
  112. package/dist/rows.js +5 -13
  113. package/dist/save.d.ts +6 -2
  114. package/dist/save.d.ts.map +1 -1
  115. package/dist/save.js +42 -18
  116. package/dist/search.d.ts +36 -6
  117. package/dist/search.d.ts.map +1 -1
  118. package/dist/search.js +132 -46
  119. package/dist/seed.d.ts +16 -0
  120. package/dist/seed.d.ts.map +1 -0
  121. package/dist/seed.js +61 -0
  122. package/dist/shared.d.ts +11 -0
  123. package/dist/shared.d.ts.map +1 -0
  124. package/dist/shared.js +368 -0
  125. package/dist/status.d.ts +4 -0
  126. package/dist/status.d.ts.map +1 -1
  127. package/dist/store.d.ts +42 -11
  128. package/dist/store.d.ts.map +1 -1
  129. package/dist/store.js +276 -83
  130. package/dist/turn.d.ts +7 -0
  131. package/dist/turn.d.ts.map +1 -0
  132. package/dist/turn.js +45 -0
  133. package/dist/wire.d.ts +136 -32
  134. package/dist/wire.d.ts.map +1 -1
  135. package/dist/wire.js +48 -31
  136. package/package.json +6 -2
@@ -1,7 +1,8 @@
1
1
  import { conversationChangeSet } from './change-set.js';
2
2
  import { runtimeError } from './failure.js';
3
3
  import { declaredFile } from './file.js';
4
- import { chatDraftRevision } from './identity.js';
4
+ import { changeBatchIdentity, chatDraftRevision } from './identity.js';
5
+ import { OFFLINE } from './outcome.js';
5
6
  const QUIET = {
6
7
  turn: null,
7
8
  questions: [],
@@ -21,6 +22,17 @@ export function unheldView(conversation) {
21
22
  chatDraft: null,
22
23
  };
23
24
  }
25
+ export const SESSION_STARTED = 'Session started';
26
+ const NEW_CHAT = 'new:';
27
+ export function newChat(agent) {
28
+ return `${NEW_CHAT}${agent}`;
29
+ }
30
+ function creationOf(input) {
31
+ if (typeof input !== 'object' || input === null)
32
+ return null;
33
+ const { agent_id: agent, operation_id: operation } = input;
34
+ return typeof agent === 'string' && typeof operation === 'string' ? { agent, operation } : null;
35
+ }
24
36
  function startedTurn(turn, operation) {
25
37
  if (operation.op === 'begin')
26
38
  return { turn, started: operation.at, parts: [], context: null };
@@ -77,11 +89,15 @@ function ordered(left, right) {
77
89
  return left.identity < right.identity ? -1 : 1;
78
90
  return 0;
79
91
  }
80
- function merged(held, arriving) {
92
+ function windowOf(held, arriving, limit) {
81
93
  const byIdentity = new Map(held.map((message) => [message.identity, message]));
82
94
  for (const message of arriving)
83
95
  byIdentity.set(message.identity, message);
84
- return [...byIdentity.values()].sort(ordered);
96
+ const next = [...byIdentity.values()].sort(ordered);
97
+ return limit === undefined ? next : next.slice(Math.max(0, next.length - limit));
98
+ }
99
+ function newestOf(arriving, from) {
100
+ return arriving.reduce((top, message) => (top === null || message.position > top ? message.position : top), from);
85
101
  }
86
102
  function acceptedMessage(value) {
87
103
  if (typeof value !== 'object' || value === null)
@@ -140,14 +156,14 @@ function historyPages(result) {
140
156
  }
141
157
  return pages;
142
158
  }
143
- function turnOf(result) {
159
+ function answered(result, field) {
144
160
  if (result.kind !== 'action')
145
161
  return null;
146
162
  const answer = result.result;
147
163
  if (typeof answer !== 'object' || answer === null)
148
164
  return null;
149
- const record = answer;
150
- return typeof record.turn === 'string' ? record.turn : null;
165
+ const value = answer[field];
166
+ return typeof value === 'string' ? value : null;
151
167
  }
152
168
  function limitOf(options) {
153
169
  const { limit } = options;
@@ -158,16 +174,44 @@ function limitOf(options) {
158
174
  }
159
175
  return limit;
160
176
  }
177
+ const EXPIRED = { kind: 'rejected', code: 'expired', fields: {}, retryable: false };
178
+ function unwritten(draft) {
179
+ return draft.text === '' && draft.files.length === 0;
180
+ }
181
+ function pending(draft) {
182
+ return {
183
+ ...(draft.submitted === undefined ? {} : { submitted: draft.submitted }),
184
+ ...(draft.moves === undefined ? {} : { moves: draft.moves }),
185
+ };
186
+ }
187
+ function empty(draft) {
188
+ return unwritten(draft) && draft.submitted === undefined && draft.moves === undefined;
189
+ }
190
+ function withSubmitted(draft, submitted) {
191
+ const { submitted: _held, ...unsent } = draft;
192
+ return submitted.length === 0 ? unsent : { ...unsent, submitted };
193
+ }
194
+ function returned(draft, submission, others) {
195
+ return withSubmitted({
196
+ conversation: draft.conversation,
197
+ text: [submission.text, draft.text].filter((one) => one !== '').join('\n'),
198
+ files: [...submission.files, ...draft.files],
199
+ revision: chatDraftRevision(),
200
+ }, others);
201
+ }
161
202
  export function createConversationStore(deps) {
162
- const messages = new Map();
203
+ const stored = new Set();
163
204
  const reads = new Map();
205
+ const partials = new Set();
164
206
  const drafts = new Map();
165
207
  const sending = new Map();
166
208
  const behind = new Set();
209
+ const catching = new Map();
167
210
  const gaps = new Map();
168
211
  const lives = new Map();
169
212
  const views = new Map();
170
213
  const listing = new Map();
214
+ const creations = new Set();
171
215
  const listWatchers = new Set();
172
216
  let listKnown = false;
173
217
  const agentWatchers = new Set();
@@ -179,49 +223,51 @@ export function createConversationStore(deps) {
179
223
  function liveOf(conversation) {
180
224
  return lives.get(conversation) ?? QUIET;
181
225
  }
182
- function shownMessages(conversation, limit) {
183
- const held = messages.get(conversation) ?? [];
184
- const shown = limit === undefined ? held : held.slice(Math.max(0, held.length - limit));
185
- return shown.map(({ identity, turn, text, message }) => ({
186
- identity,
187
- turn,
188
- text,
189
- message: structuredClone(message),
190
- }));
191
- }
192
- function viewOf(conversation, limit, shown = shownMessages(conversation, limit)) {
226
+ function viewOf(conversation, held) {
193
227
  const draft = drafts.get(conversation);
194
228
  const facts = liveOf(conversation);
195
229
  return {
196
230
  conversation,
197
- messages: shown,
231
+ messages: held.map(({ identity, turn, text, message }) => ({
232
+ identity,
233
+ turn,
234
+ text,
235
+ message,
236
+ })),
198
237
  turn: structuredClone(facts.turn),
199
238
  questions: structuredClone(facts.questions),
200
239
  process: facts.process === null ? null : { ...facts.process },
201
240
  commands: structuredClone(facts.commands),
202
241
  options: structuredClone(facts.options),
203
- chatDraft: draft === undefined || draft.turn !== null || sending.get(conversation)?.draft === draft
242
+ chatDraft: draft === undefined || unwritten(draft)
204
243
  ? null
205
244
  : { text: draft.text, files: [...draft.files], revision: draft.revision },
206
245
  };
207
246
  }
208
- function emit(conversation, messagesChanged = true) {
247
+ function emit(conversation) {
209
248
  if (deps.closed())
210
249
  return;
211
250
  for (const view of views.values()) {
212
- if (view.conversation !== conversation)
251
+ if (view.conversation !== conversation || view.window === null)
213
252
  continue;
214
- if (messagesChanged)
215
- view.messages = null;
216
253
  const ready = [...view.watchers].filter((watcher) => watcher.ready);
217
254
  if (ready.length === 0)
218
255
  continue;
219
- view.messages ??= shownMessages(conversation, view.limit);
220
- const value = viewOf(conversation, view.limit, view.messages);
256
+ const value = viewOf(conversation, view.window);
221
257
  for (const watcher of ready)
222
258
  watcher.notify(value);
223
259
  }
224
260
  }
261
+ function slide(conversation, arriving) {
262
+ for (const view of views.values()) {
263
+ if (view.conversation !== conversation || view.window === null)
264
+ continue;
265
+ view.window = arriving === null ? [] : windowOf(view.window, arriving, view.limit);
266
+ }
267
+ }
268
+ function changesOf(conversation, arriving) {
269
+ return arriving.map(({ identity, text }) => ({ conversation, identity, text }));
270
+ }
225
271
  function stateOf(conversation) {
226
272
  const facts = liveOf(conversation);
227
273
  if (facts.questions.length > 0)
@@ -278,7 +324,10 @@ export function createConversationStore(deps) {
278
324
  const declaration = deps.agents();
279
325
  if (declaration === undefined)
280
326
  return;
281
- const { documents } = await deps.documents(declaration.locator);
327
+ const held = await deps.documents(declaration);
328
+ if ('pending' in held)
329
+ return;
330
+ const { documents } = held;
282
331
  const names = new Map();
283
332
  const retired = new Set();
284
333
  for (const document of documents) {
@@ -301,6 +350,12 @@ export function createConversationStore(deps) {
301
350
  if (named)
302
351
  emitList();
303
352
  emitAgents();
353
+ const ended = [...drafts.keys()].filter(retiredChat);
354
+ if (ended.length > 0)
355
+ await remove(ended);
356
+ }
357
+ function retiredChat(conversation) {
358
+ return (conversation.startsWith(NEW_CHAT) && retiredAgents.has(conversation.slice(NEW_CHAT.length)));
304
359
  }
305
360
  function agentsReady() {
306
361
  agentsRead ??= readAgents().catch(() => {
@@ -310,7 +365,7 @@ export function createConversationStore(deps) {
310
365
  }
311
366
  function live(conversation, change) {
312
367
  setLive(conversation, { ...liveOf(conversation), ...change });
313
- emit(conversation, false);
368
+ emit(conversation);
314
369
  }
315
370
  function relayed(conversation, turn, operation) {
316
371
  const held = liveOf(conversation).turn;
@@ -338,21 +393,25 @@ export function createConversationStore(deps) {
338
393
  }
339
394
  async function remove(leaving) {
340
395
  await deps.durably(async (local) => {
341
- await local.dropConversations(leaving);
342
396
  const removed = [];
343
- const changed = [];
344
397
  for (const conversation of leaving) {
345
- for (const message of messages.get(conversation) ?? []) {
346
- removed.push({ conversation, identity: message.identity });
398
+ for (const identity of await local.messageIdentities(conversation)) {
399
+ removed.push({ conversation, identity, text: null });
347
400
  }
348
- if (messages.has(conversation) || drafts.has(conversation) || lives.has(conversation)) {
401
+ }
402
+ await local.dropConversations(leaving);
403
+ const changed = [];
404
+ for (const conversation of leaving) {
405
+ if (stored.has(conversation) || drafts.has(conversation) || lives.has(conversation)) {
349
406
  changed.push(conversation);
350
407
  }
351
- messages.delete(conversation);
408
+ stored.delete(conversation);
352
409
  reads.delete(conversation);
410
+ partials.delete(conversation);
353
411
  drafts.delete(conversation);
354
412
  behind.delete(conversation);
355
413
  setLive(conversation, null);
414
+ slide(conversation, null);
356
415
  }
357
416
  if (changed.length > 0)
358
417
  deps.publish(conversationChangeSet(removed, changed));
@@ -370,30 +429,25 @@ export function createConversationStore(deps) {
370
429
  const advances = read !== undefined &&
371
430
  !behind.has(conversation) &&
372
431
  (read === null || message.position > read);
373
- const sealed = drafts.get(conversation)?.turn === message.turn;
432
+ await sealed(local, conversation, new Set([message.turn]));
374
433
  await local.keepMessages({
375
434
  conversation,
376
435
  messages: [message],
377
- ...(advances ? { read: message.position } : {}),
378
- sealed,
436
+ ...(advances ? { read: { at: message.position, partial: false } } : {}),
379
437
  });
380
- messages.set(conversation, merged(messages.get(conversation) ?? [], [message]));
438
+ stored.add(conversation);
381
439
  if (advances)
382
440
  reads.set(conversation, message.position);
383
- if (sealed)
384
- drafts.delete(conversation);
385
441
  sealTurns(conversation, new Set([message.turn]));
386
- deps.publish(conversationChangeSet([{ conversation, identity: message.identity }], [conversation]));
442
+ slide(conversation, [message]);
443
+ deps.publish(conversationChangeSet(changesOf(conversation, [message]), [conversation]));
387
444
  });
388
445
  }
389
- async function readHistories(conversations) {
446
+ async function readHistories(conversations, ended) {
390
447
  const generations = new Map(conversations.map((one) => [one, gaps.get(one) ?? 0]));
391
- const starts = new Map(conversations.map((one) => [one, reads.get(one)]));
392
- const arriving = new Map();
393
- const complete = new Set();
394
448
  let asking = conversations.map((conversation) => ({
395
449
  conversation,
396
- after: starts.get(conversation) ?? undefined,
450
+ after: reads.get(conversation) ?? undefined,
397
451
  }));
398
452
  while (asking.length > 0) {
399
453
  const result = await deps.call('conversation.history', {
@@ -405,46 +459,64 @@ export function createConversationStore(deps) {
405
459
  const pages = historyPages(result);
406
460
  if (pages === null)
407
461
  return result;
408
- const asked = new Set(asking.map(({ conversation }) => conversation));
462
+ const asked = new Map(asking.map(({ conversation, after }) => [conversation, after]));
409
463
  const following = [];
410
464
  for (const page of pages) {
411
465
  if (!asked.has(page.conversation))
412
466
  continue;
413
- arriving.set(page.conversation, [
414
- ...(arriving.get(page.conversation) ?? []),
415
- ...page.messages,
416
- ]);
417
- if (page.next === undefined)
418
- complete.add(page.conversation);
419
- else
467
+ await keepPage(page.conversation, page.messages, asked.get(page.conversation) ?? null, page.next, generations.get(page.conversation) ?? 0);
468
+ if (page.next !== undefined) {
420
469
  following.push({ conversation: page.conversation, after: page.next });
470
+ }
471
+ }
472
+ for (const { conversation } of asking) {
473
+ if (!following.some((next) => next.conversation === conversation))
474
+ ended(conversation);
421
475
  }
422
476
  asking = following;
423
477
  }
424
- for (const [conversation, held] of arriving) {
425
- if (!complete.has(conversation))
426
- continue;
427
- await keepHistory(conversation, held, starts.get(conversation), generations.get(conversation) ?? 0);
428
- }
429
478
  return null;
430
479
  }
431
- function keepHistory(conversation, arriving, from, generation) {
480
+ function caughtUp(conversations) {
481
+ const ends = new Map();
482
+ for (const conversation of conversations) {
483
+ const held = new Promise((end) => ends.set(conversation, end));
484
+ catching.set(conversation, held);
485
+ void held.then(() => {
486
+ if (catching.get(conversation) === held)
487
+ catching.delete(conversation);
488
+ });
489
+ }
490
+ const ended = (conversation) => ends.get(conversation)?.();
491
+ const read = readHistories(conversations, ended);
492
+ const endAll = () => {
493
+ for (const conversation of conversations)
494
+ ended(conversation);
495
+ };
496
+ read.then(endAll, endAll);
497
+ return read;
498
+ }
499
+ function keepPage(conversation, arriving, from, next, generation) {
432
500
  return deps.durably(async (local) => {
433
501
  if (!replicated.has(conversation))
434
502
  return;
435
- const newest = arriving.reduce((top, message) => (top === null || message.position > top ? message.position : top), from ?? null);
436
- const turn = drafts.get(conversation)?.turn;
437
- const sealed = arriving.some((message) => message.turn === turn);
438
- await local.keepMessages({ conversation, messages: arriving, read: newest, sealed });
439
- messages.set(conversation, merged(messages.get(conversation) ?? [], arriving));
440
- reads.set(conversation, newest);
441
- if (sealed)
442
- drafts.delete(conversation);
503
+ const whole = next === undefined;
504
+ const cursor = next ?? newestOf(arriving, from);
505
+ const partial = !whole && (partials.has(conversation) || !reads.has(conversation));
506
+ const sealing = await sealed(local, conversation, new Set(arriving.map((message) => message.turn)));
507
+ await local.keepMessages({ conversation, messages: arriving, read: { at: cursor, partial } });
508
+ stored.add(conversation);
509
+ reads.set(conversation, cursor);
510
+ if (partial)
511
+ partials.add(conversation);
512
+ else
513
+ partials.delete(conversation);
443
514
  sealTurns(conversation, new Set(arriving.map((message) => message.turn)));
444
- if ((gaps.get(conversation) ?? 0) === generation)
515
+ if (whole && (gaps.get(conversation) ?? 0) === generation)
445
516
  behind.delete(conversation);
446
- if (arriving.length > 0 || sealed) {
447
- deps.publish(conversationChangeSet(arriving.map((message) => ({ conversation, identity: message.identity })), [conversation]));
517
+ slide(conversation, arriving);
518
+ if (arriving.length > 0 || sealing || whole) {
519
+ deps.publish(conversationChangeSet(changesOf(conversation, arriving), [conversation]));
448
520
  }
449
521
  });
450
522
  }
@@ -457,7 +529,7 @@ export function createConversationStore(deps) {
457
529
  if (held === undefined)
458
530
  return;
459
531
  setLive(conversation, { ...QUIET, turn: held.turn });
460
- emit(conversation, false);
532
+ emit(conversation);
461
533
  return;
462
534
  }
463
535
  if (event.kind === 'turn') {
@@ -490,22 +562,126 @@ export function createConversationStore(deps) {
490
562
  if (sealTurns(conversation, new Set([arriving.turn])))
491
563
  emit(conversation);
492
564
  }
565
+ async function kept(local, conversation, following) {
566
+ if (following === null || empty(following)) {
567
+ await local.dropChatDraft(conversation);
568
+ drafts.delete(conversation);
569
+ }
570
+ else {
571
+ await local.keepChatDrafts([following]);
572
+ drafts.set(conversation, following);
573
+ }
574
+ }
575
+ async function sealed(local, conversation, turns) {
576
+ const held = drafts.get(conversation);
577
+ const submitted = held?.submitted ?? [];
578
+ const left = submitted.filter((one) => one.turn === null || !turns.has(one.turn));
579
+ if (held === undefined || left.length === submitted.length)
580
+ return false;
581
+ await kept(local, conversation, withSubmitted(held, left));
582
+ return true;
583
+ }
584
+ function moved(agent, operation, to) {
585
+ const from = newChat(agent);
586
+ return deps.durably(async (local) => {
587
+ const held = drafts.get(from);
588
+ const earlier = (held?.moves ?? []).filter((one) => !deps.expired(one));
589
+ if (earlier.includes(operation))
590
+ return;
591
+ const blank = {
592
+ conversation: from,
593
+ text: '',
594
+ files: [],
595
+ revision: chatDraftRevision(),
596
+ };
597
+ const { moves: _answered, ...unsent } = held ?? blank;
598
+ const taken = drafts.has(to) || empty(unsent) ? [] : [{ ...unsent, conversation: to }];
599
+ const left = { ...(taken.length === 0 ? unsent : blank), moves: [...earlier, operation] };
600
+ await local.keepChatDrafts([left, ...taken]);
601
+ drafts.set(from, left);
602
+ for (const one of taken)
603
+ drafts.set(to, one);
604
+ deps.publish(conversationChangeSet([], [from, to]));
605
+ });
606
+ }
493
607
  function withDraft(conversation, next) {
494
608
  return deps.durably(async (local) => {
495
- const following = next(drafts.get(conversation));
609
+ const following = await next(drafts.get(conversation), local);
496
610
  if (following === undefined)
497
611
  return;
498
- if (following === null) {
499
- await local.dropChatDraft(conversation);
500
- drafts.delete(conversation);
501
- }
502
- else {
503
- await local.keepChatDraft(following);
504
- drafts.set(conversation, following);
505
- }
612
+ await kept(local, conversation, following);
506
613
  deps.publish(conversationChangeSet([], [conversation]));
507
614
  });
508
615
  }
616
+ async function submitted(conversation, operation, draft) {
617
+ let submission;
618
+ let earlier = false;
619
+ await withDraft(conversation, (current) => {
620
+ submission = current?.submitted?.find((one) => one.operation === operation);
621
+ earlier = submission !== undefined;
622
+ if (submission !== undefined)
623
+ return undefined;
624
+ const said = draft ?? current;
625
+ submission = {
626
+ operation,
627
+ text: said?.text ?? '',
628
+ files: [...(said?.files ?? [])],
629
+ turn: null,
630
+ };
631
+ return {
632
+ conversation,
633
+ ...(draft === undefined || current === undefined
634
+ ? { text: '', files: [], revision: chatDraftRevision() }
635
+ : { text: current.text, files: current.files, revision: current.revision }),
636
+ submitted: [...(current?.submitted ?? []), submission],
637
+ };
638
+ });
639
+ return { submission: submission, earlier };
640
+ }
641
+ function forgotten(conversation, submission) {
642
+ return withDraft(conversation, (current) => {
643
+ const held = current?.submitted ?? [];
644
+ if (current === undefined || !held.includes(submission))
645
+ return undefined;
646
+ return withSubmitted(current, held.filter((one) => one !== submission));
647
+ });
648
+ }
649
+ async function dispatched(conversation, submission) {
650
+ const dispatch = {};
651
+ sending.set(submission.operation, dispatch);
652
+ try {
653
+ const files = await Promise.all(submission.files.map(async (file) => ({ ...(await declaredFile(file)), blob: file.blob })));
654
+ const result = await invoke('conversation.send', conversation, {
655
+ text: submission.text,
656
+ files,
657
+ operation_id: submission.operation,
658
+ });
659
+ if (result.kind === 'revoked-authorization')
660
+ return result;
661
+ if (result.kind !== 'action' && result.retryable) {
662
+ deps.unanswered();
663
+ return result;
664
+ }
665
+ const turn = answered(result, 'turn');
666
+ await withDraft(conversation, async (current, local) => {
667
+ const held = current?.submitted?.find((one) => one.operation === submission.operation);
668
+ if (current === undefined || held === undefined || held.turn !== null)
669
+ return undefined;
670
+ const others = current.submitted.filter((one) => one !== held);
671
+ if (result.kind !== 'action')
672
+ return returned(current, held, others);
673
+ const arrived = turn !== null && (await local.turnArrived(conversation, turn));
674
+ return withSubmitted(current, turn === null || arrived
675
+ ? others
676
+ : current.submitted.map((one) => (one === held ? { ...held, turn } : one)));
677
+ });
678
+ return result;
679
+ }
680
+ finally {
681
+ if (sending.get(submission.operation) === dispatch)
682
+ sending.delete(submission.operation);
683
+ }
684
+ }
509
685
  function invoke(name, conversation, extra = {}) {
510
686
  return deps.call(name, { conversation, ...extra });
511
687
  }
@@ -516,46 +692,34 @@ export function createConversationStore(deps) {
516
692
  },
517
693
  async read(conversation, options = {}) {
518
694
  const limit = limitOf(options);
519
- return deps.durably(() => Promise.resolve(viewOf(conversation, limit)));
695
+ return deps.durably(async (local) => structuredClone(viewOf(conversation, await local.messageWindow(conversation, limit))));
520
696
  },
521
- create(input) {
522
- return deps.call('conversation.create', input);
523
- },
524
- async send(conversation) {
525
- const draft = drafts.get(conversation);
526
- const pending = draft === undefined ? undefined : { draft };
527
- if (pending !== undefined) {
528
- sending.set(conversation, pending);
529
- deps.publish(conversationChangeSet([], [conversation]));
530
- }
531
- try {
532
- const files = await Promise.all((draft?.files ?? []).map(async (file) => ({
533
- ...(await declaredFile(file)),
534
- blob: file.blob,
535
- })));
536
- const result = await invoke('conversation.send', conversation, {
537
- text: draft?.text ?? '',
538
- files,
539
- });
540
- const turn = turnOf(result);
541
- if (turn === null || draft === undefined)
542
- return result;
543
- await withDraft(conversation, (current) => {
544
- if (current !== draft)
545
- return undefined;
546
- const sealed = (messages.get(conversation) ?? []).some((message) => message.turn === turn);
547
- return sealed ? null : { ...draft, turn };
548
- });
697
+ async create(input) {
698
+ const result = await deps.call('conversation.create', input);
699
+ const conversation = answered(result, 'conversation');
700
+ if (conversation === null)
549
701
  return result;
702
+ if (!listing.has(conversation))
703
+ creations.add(conversation);
704
+ const creation = creationOf(input);
705
+ if (creation !== null)
706
+ await moved(creation.agent, creation.operation, conversation);
707
+ return result;
708
+ },
709
+ async send(conversation, operation = changeBatchIdentity(), draft) {
710
+ if (deps.online()) {
711
+ const { submission, earlier } = await submitted(conversation, operation, draft);
712
+ if (!earlier || !deps.expired(operation))
713
+ return dispatched(conversation, submission);
714
+ await forgotten(conversation, submission);
715
+ return EXPIRED;
550
716
  }
551
- finally {
552
- if (pending !== undefined && sending.get(conversation) === pending) {
553
- sending.delete(conversation);
554
- if (drafts.get(conversation) === draft) {
555
- deps.publish(conversationChangeSet([], [conversation]));
556
- }
557
- }
717
+ if (draft !== undefined) {
718
+ await withDraft(conversation, (current) => current?.submitted?.some((one) => one.operation === operation) === true
719
+ ? undefined
720
+ : returned(current ?? { conversation, text: '', files: [], revision: '' }, { operation, ...draft, turn: null }, current?.submitted ?? []));
558
721
  }
722
+ return OFFLINE;
559
723
  },
560
724
  answer(conversation, answer) {
561
725
  return invoke('conversation.answer', conversation, { answer });
@@ -570,7 +734,12 @@ export function createConversationStore(deps) {
570
734
  const result = await invoke('conversation.cancel', conversation, { turn });
571
735
  if (result.kind !== 'action')
572
736
  return result;
573
- await withDraft(conversation, (current) => current === undefined || current.turn !== turn ? undefined : { ...current, turn: null });
737
+ await withDraft(conversation, (current) => {
738
+ const held = current?.submitted?.find((one) => one.turn === turn);
739
+ if (current === undefined || held === undefined)
740
+ return undefined;
741
+ return returned(current, held, current.submitted.filter((one) => one !== held));
742
+ });
574
743
  return result;
575
744
  },
576
745
  delete(conversation) {
@@ -579,33 +748,42 @@ export function createConversationStore(deps) {
579
748
  };
580
749
  const chatDraft = {
581
750
  write(conversation, draft, revision = chatDraftRevision()) {
582
- return withDraft(conversation, () => ({
751
+ return withDraft(conversation, (current) => ({
583
752
  conversation,
584
753
  text: draft.text,
585
754
  files: [...draft.files],
586
- turn: null,
587
755
  revision,
756
+ ...(current === undefined ? {} : pending(current)),
588
757
  }));
589
758
  },
590
759
  discard(conversation) {
591
- return withDraft(conversation, (current) => (current === undefined ? undefined : null));
760
+ return withDraft(conversation, (current) => current === undefined
761
+ ? undefined
762
+ : {
763
+ conversation,
764
+ text: '',
765
+ files: [],
766
+ revision: chatDraftRevision(),
767
+ ...pending(current),
768
+ });
592
769
  },
593
770
  };
594
771
  return {
595
772
  surface,
596
773
  chatDraft,
597
- hydrate(held, stored) {
598
- messages.clear();
774
+ hydrate(held, kept) {
775
+ stored.clear();
599
776
  reads.clear();
600
- for (const view of views.values())
601
- view.messages = null;
777
+ partials.clear();
602
778
  for (const entry of held) {
603
- messages.set(entry.conversation, [...entry.messages].sort(ordered));
779
+ stored.add(entry.conversation);
604
780
  if (entry.read !== undefined)
605
781
  reads.set(entry.conversation, entry.read);
782
+ if (entry.partial)
783
+ partials.add(entry.conversation);
606
784
  }
607
785
  drafts.clear();
608
- for (const record of stored)
786
+ for (const record of kept)
609
787
  drafts.set(record.conversation, record);
610
788
  },
611
789
  async reconcile() {
@@ -613,8 +791,10 @@ export function createConversationStore(deps) {
613
791
  return;
614
792
  const named = new Set(listing.keys());
615
793
  const leaving = [
616
- ...new Set([...replicated, ...messages.keys(), ...reads.keys(), ...drafts.keys()]),
617
- ].filter((conversation) => !named.has(conversation));
794
+ ...new Set([...replicated, ...stored, ...reads.keys(), ...drafts.keys()]),
795
+ ].filter((conversation) => !named.has(conversation) &&
796
+ !creations.has(conversation) &&
797
+ (!conversation.startsWith(NEW_CHAT) || retiredChat(conversation)));
618
798
  for (const conversation of named) {
619
799
  if (!replicated.has(conversation))
620
800
  behind.add(conversation);
@@ -625,22 +805,64 @@ export function createConversationStore(deps) {
625
805
  await remove(leaving);
626
806
  },
627
807
  async catchUp(progress) {
628
- const reading = [...behind].filter((conversation) => replicated.has(conversation)).sort();
629
- if (reading.length > 0 && !deps.closed()) {
630
- const failed = await readHistories(reading);
808
+ const owed = (conversation) => behind.has(conversation) && replicated.has(conversation);
809
+ const read = async (conversations) => {
810
+ if (conversations.length === 0 || deps.closed())
811
+ return;
812
+ const failed = await caughtUp(conversations);
631
813
  if (failed?.kind === 'transport-uncertainty')
632
814
  progress.reachable = false;
633
- }
815
+ };
816
+ const asking = [...behind].filter(owed).sort();
817
+ const awaited = asking.filter((conversation) => catching.has(conversation));
818
+ await Promise.all([
819
+ read(asking.filter((conversation) => !catching.has(conversation))),
820
+ Promise.all(awaited.map((conversation) => catching.get(conversation))).then(() => read(awaited.filter((conversation) => owed(conversation) && !catching.has(conversation)))),
821
+ ]);
634
822
  if (behind.size > 0)
635
823
  progress.complete = false;
636
824
  },
825
+ async resend(progress) {
826
+ for (const [conversation, held] of [...drafts]) {
827
+ for (const submission of held.submitted ?? []) {
828
+ if (submission.turn !== null || sending.has(submission.operation))
829
+ continue;
830
+ if (deps.closed())
831
+ return;
832
+ if (deps.expired(submission.operation)) {
833
+ await forgotten(conversation, submission);
834
+ continue;
835
+ }
836
+ const result = await dispatched(conversation, submission);
837
+ if (result.kind === 'revoked-authorization')
838
+ return;
839
+ if (result.kind === 'transport-uncertainty') {
840
+ progress.reachable = false;
841
+ return;
842
+ }
843
+ if (result.kind !== 'action' && result.retryable) {
844
+ progress.complete = false;
845
+ return;
846
+ }
847
+ }
848
+ }
849
+ },
637
850
  current() {
638
851
  return behind.size === 0;
639
852
  },
853
+ known() {
854
+ return listKnown;
855
+ },
640
856
  reconnected() {
641
857
  for (const conversation of replicated)
642
858
  gap(conversation);
643
859
  },
860
+ reopened() {
861
+ sending.clear();
862
+ },
863
+ lost() {
864
+ catching.clear();
865
+ },
644
866
  watch(conversation, options, deliver) {
645
867
  const limit = limitOf(options);
646
868
  const key = JSON.stringify([conversation, limit ?? null]);
@@ -648,18 +870,20 @@ export function createConversationStore(deps) {
648
870
  conversation,
649
871
  limit,
650
872
  watchers: new Set(),
651
- messages: null,
873
+ window: null,
652
874
  };
653
875
  views.set(key, view);
654
876
  const watcher = { notify: deliver, ready: false };
655
877
  view.watchers.add(watcher);
656
878
  void deps
657
- .durably(() => Promise.resolve())
879
+ .durably(async (local) => {
880
+ view.window ??= await local.messageWindow(conversation, limit);
881
+ })
658
882
  .then(() => {
659
883
  if (deps.closed() || !view.watchers.has(watcher))
660
884
  return;
661
885
  watcher.ready = true;
662
- watcher.notify(viewOf(conversation, limit));
886
+ watcher.notify(viewOf(conversation, view.window ?? []));
663
887
  })
664
888
  .catch(() => { });
665
889
  return () => {
@@ -706,12 +930,15 @@ export function createConversationStore(deps) {
706
930
  if (event.kind === 'list' || event.kind === 'listed' || event.kind === 'unlisted') {
707
931
  if (event.kind === 'list') {
708
932
  listing.clear();
709
- for (const entry of event.entries)
933
+ for (const entry of event.entries) {
710
934
  listing.set(entry.conversation, { ...entry });
935
+ creations.delete(entry.conversation);
936
+ }
711
937
  listKnown = true;
712
938
  }
713
939
  else if (event.kind === 'listed') {
714
940
  listing.set(event.entry.conversation, { ...event.entry });
941
+ creations.delete(event.entry.conversation);
715
942
  }
716
943
  else {
717
944
  listing.delete(event.conversation);
@@ -725,12 +952,11 @@ export function createConversationStore(deps) {
725
952
  heard(event);
726
953
  return false;
727
954
  },
728
- messages() {
729
- return [...messages].flatMap(([conversation, held]) => held.map(({ identity, text }) => ({ conversation, identity, text })));
955
+ searchable() {
956
+ return [...(listKnown ? listing.keys() : stored)].sort();
730
957
  },
731
- message(conversation, identity) {
732
- const held = messages.get(conversation)?.find((message) => message.identity === identity);
733
- return held === undefined ? null : { conversation, identity, text: held.text };
958
+ acquired(conversation) {
959
+ return reads.has(conversation) && !partials.has(conversation);
734
960
  },
735
961
  close() {
736
962
  views.clear();