@agentshouse/mdruntime 0.1.0-cc294e382554d → 0.1.0-cc2e934017fb1

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