@agentshouse/mdruntime 0.1.0-ca7c26c6bc27e → 0.1.0-ca92b54804c33

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