@agentshouse/mdruntime 0.1.0-c1954630fadb6 → 0.1.0-c1c2b722d3dcd

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