@agentshouse/mdruntime 0.1.0-cd3ee807e46ae → 0.1.0-cd507e16e5fc0

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