@agentshouse/mdruntime 0.1.0-c6bf34fa9e444 → 0.1.0-c6d3d5d8beeb0

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