@agentshouse/mdruntime 0.1.0-c30ed2b8e04d5 → 0.1.0-c36e0a098a0e3

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