@agentshouse/mdruntime 0.1.0-cd3486bd400ed → 0.1.0-cd35ccee27a19

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