@animalabs/agent-framework 0.31.0 → 0.33.0

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 (298) hide show
  1. package/README.md +204 -14
  2. package/dist/src/admission/admit.d.ts +18 -0
  3. package/dist/src/admission/admit.d.ts.map +1 -1
  4. package/dist/src/admission/admit.js +16 -3
  5. package/dist/src/admission/admit.js.map +1 -1
  6. package/dist/src/agent.d.ts +185 -78
  7. package/dist/src/agent.d.ts.map +1 -1
  8. package/dist/src/agent.js +279 -102
  9. package/dist/src/agent.js.map +1 -1
  10. package/dist/src/api/mcp-server-core.d.ts.map +1 -1
  11. package/dist/src/api/mcp-server-core.js +50 -12
  12. package/dist/src/api/mcp-server-core.js.map +1 -1
  13. package/dist/src/api/server.d.ts.map +1 -1
  14. package/dist/src/api/server.js +4 -20
  15. package/dist/src/api/server.js.map +1 -1
  16. package/dist/src/code-execution/isolate/scripts.d.ts +12 -8
  17. package/dist/src/code-execution/isolate/scripts.d.ts.map +1 -1
  18. package/dist/src/code-execution/isolate/scripts.js +24 -0
  19. package/dist/src/code-execution/isolate/scripts.js.map +1 -1
  20. package/dist/src/config-checks.d.ts +7 -0
  21. package/dist/src/config-checks.d.ts.map +1 -1
  22. package/dist/src/config-checks.js +14 -0
  23. package/dist/src/config-checks.js.map +1 -1
  24. package/dist/src/context-manager-errors.d.ts +25 -0
  25. package/dist/src/context-manager-errors.d.ts.map +1 -0
  26. package/dist/src/context-manager-errors.js +31 -0
  27. package/dist/src/context-manager-errors.js.map +1 -0
  28. package/dist/src/context-options.d.ts +67 -0
  29. package/dist/src/context-options.d.ts.map +1 -0
  30. package/dist/src/context-options.js +85 -0
  31. package/dist/src/context-options.js.map +1 -0
  32. package/dist/src/deferred-import.d.ts +93 -0
  33. package/dist/src/deferred-import.d.ts.map +1 -0
  34. package/dist/src/deferred-import.js +177 -0
  35. package/dist/src/deferred-import.js.map +1 -0
  36. package/dist/src/dendrite/audience.d.ts +223 -0
  37. package/dist/src/dendrite/audience.d.ts.map +1 -0
  38. package/dist/src/dendrite/audience.js +202 -0
  39. package/dist/src/dendrite/audience.js.map +1 -0
  40. package/dist/src/dendrite/index.d.ts +5 -3
  41. package/dist/src/dendrite/index.d.ts.map +1 -1
  42. package/dist/src/dendrite/index.js +2 -1
  43. package/dist/src/dendrite/index.js.map +1 -1
  44. package/dist/src/dendrite/presets.d.ts +10 -5
  45. package/dist/src/dendrite/presets.d.ts.map +1 -1
  46. package/dist/src/dendrite/presets.js +17 -5
  47. package/dist/src/dendrite/presets.js.map +1 -1
  48. package/dist/src/dendrite/registry.d.ts +62 -7
  49. package/dist/src/dendrite/registry.d.ts.map +1 -1
  50. package/dist/src/dendrite/registry.js +179 -10
  51. package/dist/src/dendrite/registry.js.map +1 -1
  52. package/dist/src/dendrite/types.d.ts +91 -8
  53. package/dist/src/dendrite/types.d.ts.map +1 -1
  54. package/dist/src/foreign-rounds.d.ts +69 -0
  55. package/dist/src/foreign-rounds.d.ts.map +1 -0
  56. package/dist/src/foreign-rounds.js +152 -0
  57. package/dist/src/foreign-rounds.js.map +1 -0
  58. package/dist/src/framework.d.ts +1977 -820
  59. package/dist/src/framework.d.ts.map +1 -1
  60. package/dist/src/framework.js +7571 -3457
  61. package/dist/src/framework.js.map +1 -1
  62. package/dist/src/gate/event-gate.d.ts +85 -15
  63. package/dist/src/gate/event-gate.d.ts.map +1 -1
  64. package/dist/src/gate/event-gate.js +421 -47
  65. package/dist/src/gate/event-gate.js.map +1 -1
  66. package/dist/src/gate/index.d.ts +1 -1
  67. package/dist/src/gate/index.d.ts.map +1 -1
  68. package/dist/src/gate/index.js.map +1 -1
  69. package/dist/src/gate/rule-scope.d.ts +30 -0
  70. package/dist/src/gate/rule-scope.d.ts.map +1 -0
  71. package/dist/src/gate/rule-scope.js +41 -0
  72. package/dist/src/gate/rule-scope.js.map +1 -0
  73. package/dist/src/gate/suppress-script-worker.d.ts +2 -0
  74. package/dist/src/gate/suppress-script-worker.d.ts.map +1 -0
  75. package/dist/src/gate/suppress-script-worker.js +103 -0
  76. package/dist/src/gate/suppress-script-worker.js.map +1 -0
  77. package/dist/src/gate/suppress-scripts.d.ts +105 -0
  78. package/dist/src/gate/suppress-scripts.d.ts.map +1 -0
  79. package/dist/src/gate/suppress-scripts.js +403 -0
  80. package/dist/src/gate/suppress-scripts.js.map +1 -0
  81. package/dist/src/gate/suppression-review.d.ts +143 -0
  82. package/dist/src/gate/suppression-review.d.ts.map +1 -0
  83. package/dist/src/gate/suppression-review.js +463 -0
  84. package/dist/src/gate/suppression-review.js.map +1 -0
  85. package/dist/src/gate/suppression-stats.d.ts +125 -0
  86. package/dist/src/gate/suppression-stats.d.ts.map +1 -0
  87. package/dist/src/gate/suppression-stats.js +214 -0
  88. package/dist/src/gate/suppression-stats.js.map +1 -0
  89. package/dist/src/gate/types.d.ts +135 -7
  90. package/dist/src/gate/types.d.ts.map +1 -1
  91. package/dist/src/gate/wake-onboarding.d.ts +119 -0
  92. package/dist/src/gate/wake-onboarding.d.ts.map +1 -0
  93. package/dist/src/gate/wake-onboarding.js +277 -0
  94. package/dist/src/gate/wake-onboarding.js.map +1 -0
  95. package/dist/src/held-writes.d.ts +31 -23
  96. package/dist/src/held-writes.d.ts.map +1 -1
  97. package/dist/src/held-writes.js +44 -59
  98. package/dist/src/held-writes.js.map +1 -1
  99. package/dist/src/index.d.ts +5 -2
  100. package/dist/src/index.d.ts.map +1 -1
  101. package/dist/src/index.js +3 -0
  102. package/dist/src/index.js.map +1 -1
  103. package/dist/src/jsonrpc-envelope.d.ts +69 -0
  104. package/dist/src/jsonrpc-envelope.d.ts.map +1 -0
  105. package/dist/src/jsonrpc-envelope.js +66 -0
  106. package/dist/src/jsonrpc-envelope.js.map +1 -0
  107. package/dist/src/mcpl/channel-registry.d.ts +131 -15
  108. package/dist/src/mcpl/channel-registry.d.ts.map +1 -1
  109. package/dist/src/mcpl/channel-registry.js +290 -46
  110. package/dist/src/mcpl/channel-registry.js.map +1 -1
  111. package/dist/src/mcpl/checkpoint-manager.d.ts +2 -4
  112. package/dist/src/mcpl/checkpoint-manager.d.ts.map +1 -1
  113. package/dist/src/mcpl/checkpoint-manager.js.map +1 -1
  114. package/dist/src/mcpl/feature-set-manager.d.ts +2 -4
  115. package/dist/src/mcpl/feature-set-manager.d.ts.map +1 -1
  116. package/dist/src/mcpl/feature-set-manager.js.map +1 -1
  117. package/dist/src/mcpl/inbound-source.d.ts +2 -1
  118. package/dist/src/mcpl/inbound-source.d.ts.map +1 -1
  119. package/dist/src/mcpl/inbound-source.js +2 -1
  120. package/dist/src/mcpl/inbound-source.js.map +1 -1
  121. package/dist/src/mcpl/inference-router.d.ts +6 -6
  122. package/dist/src/mcpl/inference-router.d.ts.map +1 -1
  123. package/dist/src/mcpl/inference-router.js.map +1 -1
  124. package/dist/src/mcpl/push-coalescer.d.ts +132 -22
  125. package/dist/src/mcpl/push-coalescer.d.ts.map +1 -1
  126. package/dist/src/mcpl/push-coalescer.js +105 -15
  127. package/dist/src/mcpl/push-coalescer.js.map +1 -1
  128. package/dist/src/mcpl/push-handler.d.ts +9 -7
  129. package/dist/src/mcpl/push-handler.d.ts.map +1 -1
  130. package/dist/src/mcpl/push-handler.js.map +1 -1
  131. package/dist/src/mcpl/server-connection.d.ts +13 -10
  132. package/dist/src/mcpl/server-connection.d.ts.map +1 -1
  133. package/dist/src/mcpl/server-connection.js +134 -56
  134. package/dist/src/mcpl/server-connection.js.map +1 -1
  135. package/dist/src/mcpl/tool-classes.d.ts.map +1 -1
  136. package/dist/src/mcpl/tool-classes.js +3 -0
  137. package/dist/src/mcpl/tool-classes.js.map +1 -1
  138. package/dist/src/mcpl/types.d.ts +8 -2
  139. package/dist/src/mcpl/types.d.ts.map +1 -1
  140. package/dist/src/mcpl/types.js.map +1 -1
  141. package/dist/src/module-registry.d.ts +24 -1
  142. package/dist/src/module-registry.d.ts.map +1 -1
  143. package/dist/src/module-registry.js +68 -18
  144. package/dist/src/module-registry.js.map +1 -1
  145. package/dist/src/modules/discord/index.d.ts +45 -8
  146. package/dist/src/modules/discord/index.d.ts.map +1 -1
  147. package/dist/src/modules/discord/index.js +237 -86
  148. package/dist/src/modules/discord/index.js.map +1 -1
  149. package/dist/src/modules/history/index.d.ts +59 -0
  150. package/dist/src/modules/history/index.d.ts.map +1 -1
  151. package/dist/src/modules/history/index.js +432 -67
  152. package/dist/src/modules/history/index.js.map +1 -1
  153. package/dist/src/modules/history/semantic.d.ts +6 -5
  154. package/dist/src/modules/history/semantic.d.ts.map +1 -1
  155. package/dist/src/modules/history/semantic.js +15 -22
  156. package/dist/src/modules/history/semantic.js.map +1 -1
  157. package/dist/src/modules/workspace/disk-agreement.d.ts +1 -1
  158. package/dist/src/modules/workspace/disk-agreement.js +1 -1
  159. package/dist/src/modules/workspace/index.d.ts +28 -7
  160. package/dist/src/modules/workspace/index.d.ts.map +1 -1
  161. package/dist/src/modules/workspace/index.js +76 -22
  162. package/dist/src/modules/workspace/index.js.map +1 -1
  163. package/dist/src/notice-tags.d.ts +10 -1
  164. package/dist/src/notice-tags.d.ts.map +1 -1
  165. package/dist/src/notice-tags.js +10 -1
  166. package/dist/src/notice-tags.js.map +1 -1
  167. package/dist/src/operator-log.d.ts +36 -3
  168. package/dist/src/operator-log.d.ts.map +1 -1
  169. package/dist/src/operator-log.js +2 -2
  170. package/dist/src/operator-log.js.map +1 -1
  171. package/dist/src/presentation.d.ts +746 -0
  172. package/dist/src/presentation.d.ts.map +1 -0
  173. package/dist/src/presentation.js +1435 -0
  174. package/dist/src/presentation.js.map +1 -0
  175. package/dist/src/prose-drafts.d.ts +15 -11
  176. package/dist/src/prose-drafts.d.ts.map +1 -1
  177. package/dist/src/prose-drafts.js +16 -12
  178. package/dist/src/prose-drafts.js.map +1 -1
  179. package/dist/src/read-marks.d.ts +192 -0
  180. package/dist/src/read-marks.d.ts.map +1 -0
  181. package/dist/src/read-marks.js +242 -0
  182. package/dist/src/read-marks.js.map +1 -0
  183. package/dist/src/recovery/offline-branch.d.ts +91 -6
  184. package/dist/src/recovery/offline-branch.d.ts.map +1 -1
  185. package/dist/src/recovery/offline-branch.js +273 -29
  186. package/dist/src/recovery/offline-branch.js.map +1 -1
  187. package/dist/src/recovery/recover-cli.js +22 -3
  188. package/dist/src/recovery/recover-cli.js.map +1 -1
  189. package/dist/src/send-tools.d.ts +5 -9
  190. package/dist/src/send-tools.d.ts.map +1 -1
  191. package/dist/src/send-tools.js +40 -7
  192. package/dist/src/send-tools.js.map +1 -1
  193. package/dist/src/stored-injections.d.ts +2 -2
  194. package/dist/src/stored-injections.js +2 -2
  195. package/dist/src/stored-removal.d.ts +17 -4
  196. package/dist/src/stored-removal.d.ts.map +1 -1
  197. package/dist/src/stored-removal.js +29 -5
  198. package/dist/src/stored-removal.js.map +1 -1
  199. package/dist/src/tool-result-guard.d.ts +12 -1
  200. package/dist/src/tool-result-guard.d.ts.map +1 -1
  201. package/dist/src/tool-result-guard.js +42 -8
  202. package/dist/src/tool-result-guard.js.map +1 -1
  203. package/dist/src/tune-out/coordinator.d.ts +1159 -79
  204. package/dist/src/tune-out/coordinator.d.ts.map +1 -1
  205. package/dist/src/tune-out/coordinator.js +3709 -363
  206. package/dist/src/tune-out/coordinator.js.map +1 -1
  207. package/dist/src/tune-out/tools.d.ts +114 -17
  208. package/dist/src/tune-out/tools.d.ts.map +1 -1
  209. package/dist/src/tune-out/tools.js +87 -27
  210. package/dist/src/tune-out/tools.js.map +1 -1
  211. package/dist/src/tune-out/window-anchor.d.ts +143 -0
  212. package/dist/src/tune-out/window-anchor.d.ts.map +1 -0
  213. package/dist/src/tune-out/window-anchor.js +202 -0
  214. package/dist/src/tune-out/window-anchor.js.map +1 -0
  215. package/dist/src/types/agent.d.ts +86 -31
  216. package/dist/src/types/agent.d.ts.map +1 -1
  217. package/dist/src/types/events.d.ts +2 -0
  218. package/dist/src/types/events.d.ts.map +1 -1
  219. package/dist/src/types/framework.d.ts +43 -21
  220. package/dist/src/types/framework.d.ts.map +1 -1
  221. package/dist/src/types/module.d.ts +180 -69
  222. package/dist/src/types/module.d.ts.map +1 -1
  223. package/dist/src/types/trace.d.ts +510 -36
  224. package/dist/src/types/trace.d.ts.map +1 -1
  225. package/package.json +3 -3
  226. package/src/admission/admit.ts +32 -3
  227. package/src/agent.ts +323 -120
  228. package/src/api/mcp-server-core.ts +54 -17
  229. package/src/api/server.ts +4 -23
  230. package/src/code-execution/isolate/scripts.ts +28 -3
  231. package/src/config-checks.ts +14 -0
  232. package/src/context-manager-errors.ts +37 -0
  233. package/src/context-options.ts +96 -0
  234. package/src/deferred-import.ts +239 -0
  235. package/src/dendrite/audience.ts +315 -0
  236. package/src/dendrite/index.ts +14 -2
  237. package/src/dendrite/presets.ts +18 -6
  238. package/src/dendrite/registry.ts +209 -12
  239. package/src/dendrite/types.ts +92 -8
  240. package/src/foreign-rounds.ts +199 -0
  241. package/src/framework.ts +7814 -3585
  242. package/src/gate/event-gate.ts +428 -65
  243. package/src/gate/index.ts +3 -0
  244. package/src/gate/rule-scope.ts +45 -0
  245. package/src/gate/suppress-script-worker.ts +89 -0
  246. package/src/gate/suppress-scripts.ts +414 -0
  247. package/src/gate/suppression-review.ts +517 -0
  248. package/src/gate/suppression-stats.ts +314 -0
  249. package/src/gate/types.ts +141 -7
  250. package/src/gate/wake-onboarding.ts +309 -0
  251. package/src/held-writes.ts +49 -60
  252. package/src/index.ts +9 -2
  253. package/src/jsonrpc-envelope.ts +81 -0
  254. package/src/mcpl/channel-registry.ts +353 -85
  255. package/src/mcpl/checkpoint-manager.ts +3 -2
  256. package/src/mcpl/feature-set-manager.ts +2 -1
  257. package/src/mcpl/inbound-source.ts +2 -1
  258. package/src/mcpl/inference-router.ts +7 -4
  259. package/src/mcpl/push-coalescer.ts +193 -34
  260. package/src/mcpl/push-handler.ts +10 -5
  261. package/src/mcpl/server-connection.ts +141 -60
  262. package/src/mcpl/tool-classes.ts +3 -0
  263. package/src/mcpl/types.ts +8 -2
  264. package/src/module-registry.ts +73 -17
  265. package/src/modules/discord/index.ts +229 -81
  266. package/src/modules/history/index.ts +439 -70
  267. package/src/modules/history/semantic.ts +15 -21
  268. package/src/modules/workspace/disk-agreement.ts +1 -1
  269. package/src/modules/workspace/index.ts +85 -23
  270. package/src/notice-tags.ts +10 -1
  271. package/src/operator-log.ts +36 -3
  272. package/src/presentation.ts +1676 -0
  273. package/src/prose-drafts.ts +16 -12
  274. package/src/read-marks.ts +328 -0
  275. package/src/recovery/offline-branch.ts +346 -32
  276. package/src/recovery/recover-cli.ts +21 -3
  277. package/src/send-tools.ts +40 -7
  278. package/src/stored-injections.ts +2 -2
  279. package/src/stored-removal.ts +31 -7
  280. package/src/tool-result-guard.ts +41 -7
  281. package/src/tune-out/coordinator.ts +4089 -457
  282. package/src/tune-out/tools.ts +160 -43
  283. package/src/tune-out/window-anchor.ts +277 -0
  284. package/src/types/agent.ts +90 -31
  285. package/src/types/events.ts +2 -0
  286. package/src/types/framework.ts +43 -21
  287. package/src/types/module.ts +181 -68
  288. package/src/types/trace.ts +542 -40
  289. package/dist/src/reasoning-loss-notice.d.ts +0 -23
  290. package/dist/src/reasoning-loss-notice.d.ts.map +0 -1
  291. package/dist/src/reasoning-loss-notice.js +0 -52
  292. package/dist/src/reasoning-loss-notice.js.map +0 -1
  293. package/dist/src/reasoning-loss.d.ts +0 -24
  294. package/dist/src/reasoning-loss.d.ts.map +0 -1
  295. package/dist/src/reasoning-loss.js +0 -102
  296. package/dist/src/reasoning-loss.js.map +0 -1
  297. package/src/reasoning-loss-notice.ts +0 -64
  298. package/src/reasoning-loss.ts +0 -120
@@ -0,0 +1,1676 @@
1
+ /**
2
+ * The presentation index (#291): which stored rows each agent's window
3
+ * holds, and when a row enters it.
4
+ *
5
+ * The store's record keeps every write in the order it arrived. An agent's
6
+ * window is another order over the same rows: the rows presented to it, in
7
+ * the order its requests carry them (context-manager's window index,
8
+ * `presentRows`; a row presented at rest is in the window before a request
9
+ * has carried it). While one agent writes one slot, and nothing else writes
10
+ * it during that agent's turns, the two orders are the same. Once others
11
+ * write it during a turn (another agent sharing the slot, a module), or one
12
+ * agent reads another's, they differ: a row
13
+ * another agent stored during my turn sits inside my turn in the record, but
14
+ * my requests carried it only at my next tool boundary or turn start, so a
15
+ * compile that sent it where the record has it would change my turn's prefix
16
+ * (the prompt cache misses, and a reply's signed thinking is sent under a
17
+ * prefix it wasn't minted under).
18
+ *
19
+ * This module decides who each stored row is presented to and when, through
20
+ * each live agent's own context manager. It reads the row's audience stamp
21
+ * (dendrite/audience.ts), the slot the row is stored in, and the registry's
22
+ * slots and observe edges (bearingOf), and presents:
23
+ *
24
+ * - an agent's own rows as they are written, through the own-row sink
25
+ * (storeOwnRow, Agent and ToolResultGuard call it once the row is stored),
26
+ * or at its next presentation point when a writer held one back;
27
+ * - another writer's rows meant for it (arrivals) at its turn start, at its
28
+ * tool boundary as a prefix the live stream can carry, at its turn's end,
29
+ * and at once while it has no turn alive (present at rest);
30
+ * - nothing of others' while the host is quiesced (frozen) or under a
31
+ * surgery hold, which freeze every window but for an agent's own rows (a
32
+ * hold by its own refusals: under it every agent is turn-alive and no
33
+ * turn starts);
34
+ * - the arrivals a rollback's cut took out of an agent's window only at its
35
+ * next turn start (holdUntilStart), so the cut holds until it speaks.
36
+ *
37
+ * Arrivals are read from the index itself (getUnpresentedMessages filtered
38
+ * by bearingOf), never from the store's head: a crashed turn's arrivals and
39
+ * rows imported at boot are arrivals by construction. A shared derivation's
40
+ * inheritance isn't an arrival: it reaches the child through the window it
41
+ * was derived with, and bearingOf reads an unstamped row at or before the
42
+ * derivation's checkpoint (derivedAt) as elsewhere. The one scalar kept is
43
+ * a memo of where a scan may start, reset whenever the branch, the index
44
+ * length or the reader's facts moved under it.
45
+ *
46
+ * The module presents only for an agent it has taken on (adopt) whose
47
+ * manager is in presented mode: it never calls presentRows on a manager in
48
+ * legacy mode but for the deliberate write-down at adopt, and again at a
49
+ * rebase after the store's branch moved to a branch whose window index for
50
+ * that manager was never written (one made before the write-down), since
51
+ * any presentRows there writes the whole record down and switches the mode.
52
+ * The rows of the record the write-down took in that carry an audience
53
+ * stamp and are elsewhere to the agent (another agent's own rows, mail
54
+ * stamped for others, a held row) are then taken out (retractForeign), so a
55
+ * window written down after other agents' windows holds only the rows an
56
+ * earlier release stored unstamped and the agent's own and its arrivals
57
+ * (decision 1).
58
+ * Nothing in it throws into a writer: a failed presentation is traced and
59
+ * its rows stay out of the window for the next point. A fresh turn start's
60
+ * also fails the start (presentAtStart).
61
+ *
62
+ * It never imports framework.ts, which imports it.
63
+ */
64
+ import type { ContentBlock } from '@animalabs/membrane';
65
+ import { continuesBody, MessageStore, type ContextManager, type MessageId, type MessageMetadata, type StoredMessage } from '@animalabs/context-manager';
66
+ import { audienceOf, heldFromResidents, observedRowFor, suppressedRow } from './dendrite/audience.js';
67
+ import { sameSlot, type AgentRegistry } from './dendrite/registry.js';
68
+ import type { AgentName, AgentRecord, MessageSlotRef, ObserveEdge } from './dendrite/types.js';
69
+ import type { WindowOrdinal } from './read-marks.js';
70
+ import { isAnotherAgentsInjection } from './stored-injections.js';
71
+ import { nameAsStored } from './text-as-stored.js';
72
+ import type { PresentationRetractReason, TraceEventInput } from './types/trace.js';
73
+
74
+ export { heldFromResidents, suppressedRow } from './dendrite/audience.js';
75
+
76
+ // ============================================================================
77
+ // Pure pieces the tool boundary and the drain share
78
+ // ============================================================================
79
+
80
+ /** Whether a stored row can join a live stream at a tool boundary: no tool
81
+ * blocks (the membrane's tool cycle) and not named as the agent itself (it
82
+ * would render as an assistant turn, a prefill). The #286 cut. */
83
+ export function isInjectableMidTurn(msg: { participant: string; content: ContentBlock[] }, agent: { isOwnParticipant(participant: string): boolean }): boolean {
84
+ // Exact, as membrane's role test is: a participant the request assigns
85
+ // the assistant role (the agent's name, and for a derived agent the
86
+ // voice it inherited) renders as the assistant. It's the name as sent,
87
+ // which the boundary takes as the store keeps it.
88
+ return !agent.isOwnParticipant(nameAsStored(msg.participant))
89
+ && !msg.content.some((b) => b.type === 'tool_use' || b.type === 'tool_result');
90
+ }
91
+
92
+ /** What later compiles render from the store for the copies of one write
93
+ * that landed: one copy as it is, and two or more, the shards of a sharded
94
+ * body, as context-manager's autobiographical strategy (the one that
95
+ * shards on ingest) joins a body's consecutive shards: their non-text
96
+ * blocks, then one text block of their joined text. The join is that
97
+ * strategy's `mergeAdjacentBodyGroupRaw`, which context-manager doesn't
98
+ * export, so the rule is copied here. */
99
+ export function asCompiled(landed: ReadonlyArray<{ content: ContentBlock[] }>): ContentBlock[] {
100
+ if (landed.length === 1) return landed[0]!.content;
101
+ const blocks = landed.flatMap((m) => m.content);
102
+ const text = blocks.filter((b) => b.type === 'text').map((b) => (b as { text: string }).text).join('');
103
+ return [...blocks.filter((b) => b.type !== 'text'), { type: 'text', text } as ContentBlock];
104
+ }
105
+
106
+ // ============================================================================
107
+ // Positions in a window
108
+ // ============================================================================
109
+
110
+ /** A place in one agent's window on one branch: an index ordinal
111
+ * (ContextManager.ordinalOf, indexLength), never a store sequence. */
112
+ export type Position = WindowOrdinal;
113
+
114
+ /** Where an agent's window stood: its branch and its index length then. */
115
+ export interface WindowMark {
116
+ readonly branch: string;
117
+ readonly position: Position;
118
+ }
119
+
120
+ /** The row's place in `cm`'s window, or undefined for a row out of it (and every row in legacy mode). */
121
+ export function positionIn(cm: Pick<ContextManager, 'ordinalOf'>, id: MessageId): Position | undefined {
122
+ return cm.ordinalOf(id) as Position | undefined;
123
+ }
124
+
125
+ /** The place the next row presented in `cm`'s window will take (its index length, exclusive; 0 in legacy mode). */
126
+ export function windowEnd(cm: Pick<ContextManager, 'indexLength'>): Position {
127
+ return cm.indexLength() as Position;
128
+ }
129
+
130
+ /** Where `cm`'s window stands now, or null in legacy mode, where the window is the record and has no index. */
131
+ export function windowMarkOf(cm: Pick<ContextManager, 'windowMode' | 'indexLength' | 'currentBranch'>): WindowMark | null {
132
+ if (cm.windowMode() !== 'presented') return null;
133
+ return { branch: cm.currentBranch().name, position: windowEnd(cm) };
134
+ }
135
+
136
+ // ============================================================================
137
+ // The audience rule
138
+ // ============================================================================
139
+
140
+ /**
141
+ * What a row in one agent's merged record is to that agent: its own row,
142
+ * an arrival (a row meant for it that another writer stored), or elsewhere
143
+ * (a row it is never presented: another agent's own round, mail for a
144
+ * co-resident, a held row for a resident, a row a suppress rule hid).
145
+ */
146
+ export type Bearing = 'own' | 'arrival' | 'elsewhere';
147
+
148
+ /** A slot an agent observes: the slot its edge reads, the edge, and the slot's owners. */
149
+ export interface ObservedSlot {
150
+ readonly slot: MessageSlotRef;
151
+ readonly edge: ObserveEdge;
152
+ readonly owners: readonly AgentName[];
153
+ }
154
+
155
+ /** What bearingOf needs to know of a reader, read from the registry (readerFacts). */
156
+ export interface ReaderFacts {
157
+ readonly name: AgentName;
158
+ /** The slot its own rows are stored in (registry.ownSlotOf). */
159
+ readonly ownSlot: MessageSlotRef | undefined;
160
+ /** The slots it observes, each through its edge. */
161
+ readonly observed: readonly ObservedSlot[];
162
+ /** Whether its window leaves held rows out: an agent whose own slot is the
163
+ * residents' slot, on the host's branch or a branch of its own (a shared
164
+ * fork, which carries the residents' view filter). */
165
+ readonly hidesHeld: boolean;
166
+ /** For a shared derivation, the parent's checkpoint: a row with no stamp
167
+ * at or before it is the parent's inheritance, not the child's arrival. */
168
+ readonly derivedAt?: number;
169
+ }
170
+
171
+ /** The registry queries readerFacts reads. */
172
+ export type ReaderRegistry = Pick<AgentRegistry, 'get' | 'ownSlotOf' | 'observedSlotOf' | 'slotOwners'>;
173
+
174
+ /** A reader's facts as the registry has them now. An agent it doesn't know has no slot and observes nothing. */
175
+ export function readerFacts(registry: ReaderRegistry, name: AgentName): ReaderFacts {
176
+ return factsOf(registry, name, registry.get(name), registry.ownSlotOf(name));
177
+ }
178
+
179
+ /**
180
+ * A reader's facts as the registry recorded them: its live record, else its
181
+ * newest ended one (registry.inspect). For a reader that has left, as a
182
+ * released fork or run has by the time its window is read for what it
183
+ * never read (AgentFramework.releasedWindow): readerFacts reads live
184
+ * records only, and would know nothing of it.
185
+ */
186
+ export function recordedReaderFacts(
187
+ registry: Pick<AgentRegistry, 'inspect' | 'observedSlotOf' | 'slotOwners'>,
188
+ name: AgentName,
189
+ ): ReaderFacts {
190
+ const record = registry.inspect(name);
191
+ return factsOf(registry, name, record, record?.ownSlot ? { ...record.ownSlot } : undefined);
192
+ }
193
+
194
+ /** A reader's facts from its record and its own slot (readerFacts, recordedReaderFacts). */
195
+ function factsOf(
196
+ registry: Pick<AgentRegistry, 'observedSlotOf' | 'slotOwners'>,
197
+ name: AgentName,
198
+ record: AgentRecord | undefined,
199
+ ownSlot: MessageSlotRef | undefined,
200
+ ): ReaderFacts {
201
+ const observed: ObservedSlot[] = [];
202
+ for (const edge of record?.relationships.observes ?? []) {
203
+ const slot = registry.observedSlotOf(edge);
204
+ if (slot) observed.push({ slot, edge, owners: registry.slotOwners(slot) });
205
+ }
206
+ const derivedAt = record?.inherit?.mode === 'shared' ? record.inherit.atSequence : undefined;
207
+ return {
208
+ name,
209
+ ownSlot,
210
+ observed,
211
+ hidesHeld: ownSlot?.namespace === null,
212
+ ...(derivedAt !== undefined ? { derivedAt } : {}),
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Where a row bearingOf weighs is stored, as its caller read it: `'own'`,
218
+ * the reader's own slot (the own message store of its context, which
219
+ * getMessage and getAllMessages read), or another slot by its ref (an
220
+ * auxiliary view of its context, by namespace, or the own slot of the
221
+ * agent that wrote the row: slotOfRow, afterStore).
222
+ */
223
+ export type RowSlot = 'own' | MessageSlotRef;
224
+
225
+ /**
226
+ * What one row is to one reader, from the row's stamp, the reader's facts,
227
+ * and `slot`, the slot the row is stored in: the reader's own (`'own'`, or
228
+ * a ref sameSlot as its `ownSlot`), else a slot it may observe. undefined,
229
+ * a slot its caller couldn't name, is elsewhere.
230
+ *
231
+ * A row a suppress rule hid (suppressedRow) is elsewhere to every reader,
232
+ * in any slot: no view the framework sets renders it.
233
+ *
234
+ * In its own slot, with `stamp = audienceOf(metadata)`:
235
+ * - its own row (`ownRowOf` names it): own;
236
+ * - another agent's own row: an arrival when one of the reader's edges
237
+ * names that agent and reads this slot (observesOwnRows: a resident's
238
+ * `AgentConfig.observes`, the relationship decision 1 says another
239
+ * agent's rounds reach an agent only through), unless it is that agent's
240
+ * stored context injection, which the reader's view leaves out;
241
+ * elsewhere otherwise, as it is for every resident by default;
242
+ * - a row whose audience names it: an arrival, unless it is held and the
243
+ * reader leaves held rows out, or it is another agent's stored injection,
244
+ * which the reader's view leaves out too (what the reader's own view
245
+ * leaves out is never its arrival: main's #853 asks that view, agentSees,
246
+ * at a tool boundary);
247
+ * - a row stamped otherwise (mail for a co-resident, a held row): elsewhere;
248
+ * - a row with no stamp (stored by a host's writer that doesn't stamp): an
249
+ * arrival for the slot's owners, as it reads today, unless it is a shared
250
+ * derivation's inheritance (at or before `derivedAt`), held for a reader
251
+ * that leaves held rows out, or another agent's stored injection.
252
+ *
253
+ * In another slot: an arrival when an edge of the reader's that reads that
254
+ * slot shows it, by that edge's rules and that slot's owners
255
+ * (observedRowFor); elsewhere when none does, or the reader has no edge on
256
+ * the slot. A pure function of its arguments: it runs for a released agent,
257
+ * which has no live manager, too.
258
+ */
259
+ export function bearingOf(
260
+ row: Pick<StoredMessage, 'sequence' | 'participant' | 'metadata'>,
261
+ reader: ReaderFacts,
262
+ slot: RowSlot | undefined,
263
+ ): Bearing {
264
+ const metadata = row.metadata as Record<string, unknown> | undefined;
265
+ if (slot === undefined) return 'elsewhere';
266
+ if (suppressedRow(metadata)) return 'elsewhere';
267
+ if (slot !== 'own' && !sameSlot(slot, reader.ownSlot)) {
268
+ const shown = reader.observed.some((seen) => sameSlot(seen.slot, slot)
269
+ && observedRowFor(seen.edge, row, { observer: reader.name, owners: seen.owners }));
270
+ return shown ? 'arrival' : 'elsewhere';
271
+ }
272
+ const stamp = audienceOf(metadata);
273
+ if (stamp) {
274
+ if (stamp.ownRowOf !== undefined) {
275
+ if (stamp.ownRowOf === reader.name) return 'own';
276
+ return observesInOwnSlot(reader, stamp.ownRowOf) && !isAnotherAgentsInjection(metadata, reader.name) ? 'arrival' : 'elsewhere';
277
+ }
278
+ if (!stamp.audience.includes(reader.name)) return 'elsewhere';
279
+ if (isAnotherAgentsInjection(metadata, reader.name)) return 'elsewhere';
280
+ return reader.hidesHeld && heldFromResidents(metadata) ? 'elsewhere' : 'arrival';
281
+ }
282
+ if (reader.derivedAt !== undefined && row.sequence <= reader.derivedAt) return 'elsewhere';
283
+ if (reader.hidesHeld && heldFromResidents(metadata)) return 'elsewhere';
284
+ if (isAnotherAgentsInjection(metadata, reader.name)) return 'elsewhere';
285
+ return 'arrival';
286
+ }
287
+
288
+ /** Whether one of the reader's edges names `owner` and reads the reader's own slot: a co-resident it observes. */
289
+ function observesInOwnSlot(reader: ReaderFacts, owner: AgentName): boolean {
290
+ return reader.observed.some((seen) => seen.edge.agent === owner && sameSlot(seen.slot, reader.ownSlot));
291
+ }
292
+
293
+ /**
294
+ * Whether a reader is shown `owner`'s own rows through an observe edge, as
295
+ * bearingOf reads its edges: an edge on another slot that `owner` owns, or
296
+ * an edge that names `owner` and reads the reader's own slot (a resident
297
+ * observing a co-resident, AgentConfig.observes). An edge on the reader's
298
+ * own slot shows only the agent it names, though every resident owns that
299
+ * slot.
300
+ */
301
+ export function observesOwnRows(reader: ReaderFacts, owner: AgentName): boolean {
302
+ return reader.observed.some((seen) => (sameSlot(seen.slot, reader.ownSlot)
303
+ ? seen.edge.agent === owner
304
+ : seen.owners.includes(owner)));
305
+ }
306
+
307
+ /**
308
+ * The slots besides its own a reader's context merges into its record: the
309
+ * slots its edges read on its context's branch (no `branch` of their own),
310
+ * each once. The framework opens an observer's context with one auxiliary
311
+ * view per such slot (createSubconsciousAgent, reopenAgentContext); a slot
312
+ * on a branch of its own (a shared fork's) can't be merged so.
313
+ */
314
+ function mergedSlotsOf(reader: ReaderFacts): MessageSlotRef[] {
315
+ const slots: MessageSlotRef[] = [];
316
+ for (const { slot } of reader.observed) {
317
+ if (slot.branch !== undefined || sameSlot(slot, reader.ownSlot)) continue;
318
+ if (!slots.some((s) => sameSlot(s, slot))) slots.push(slot);
319
+ }
320
+ return slots;
321
+ }
322
+
323
+ /**
324
+ * Whether a row stamped for `audience` and stored in `slot` is meant only for
325
+ * agents that can't read it: its audience names someone, and none of them
326
+ * reads the slot, as an owner or through an observe edge (registry
327
+ * readersOf). Such a row is stored as named, never widened (no window
328
+ * presents it by its audience), and traced as a routing fault. A row whose
329
+ * audience names an observer of the slot is no fault: its edge shows it
330
+ * (observedRowFor), as one naming an owner is presented in that owner's
331
+ * window.
332
+ */
333
+ export function audienceFault(
334
+ audience: readonly AgentName[],
335
+ slot: MessageSlotRef | undefined,
336
+ registry: Pick<AgentRegistry, 'readersOf'>,
337
+ ): boolean {
338
+ if (audience.length === 0 || slot === undefined) return false;
339
+ const readers = registry.readersOf(slot);
340
+ return !audience.some((name) => readers.includes(name));
341
+ }
342
+
343
+ // ============================================================================
344
+ // The presentation module
345
+ // ============================================================================
346
+
347
+ /** Where one presentation into an agent's window happened. */
348
+ export type PresentationOccasion =
349
+ /** An agent's own row, presented as it was stored. */
350
+ | 'write'
351
+ /** A turn's start, before its compile: its own rows and its arrivals. */
352
+ | 'turn-start'
353
+ /** A start's assembly of a wake's own rows, before its compile. */
354
+ | 'assembly'
355
+ /** The backstop before every compile: its own rows only. */
356
+ | 'compile'
357
+ /** A tool boundary: the round's rows, then a prefix of its arrivals. */
358
+ | 'tool-boundary'
359
+ /** The check before a boundary hands the stream its rows. */
360
+ | 'hand-off'
361
+ /** A turn's end. */
362
+ | 'turn-end'
363
+ /** An agent with no turn alive, presented a row at its write, or at boot. */
364
+ | 'at-rest'
365
+ /** Rows handed a reader fork as framing. */
366
+ | 'framing'
367
+ /** An agent taken on: its window written down and its own rows repaired. */
368
+ | 'adopt'
369
+ /** The store's branch moved under a live agent (rebase): its window on the
370
+ * new branch written down, where that branch had none, and its own rows
371
+ * repaired. */
372
+ | 'rebase';
373
+
374
+ /** A context manager as the module uses it. */
375
+ export type WindowManager = Pick<ContextManager,
376
+ 'presentRows' | 'retractRows' | 'getUnpresentedMessages' | 'getPresentedMessages' | 'ordinalOf' | 'indexLength' | 'windowStatusOf'
377
+ | 'windowMode' | 'getMessage' | 'currentBranch' | 'isClosed' | 'retractRemoved' | 'retractAbsentRows' | 'getStore'>;
378
+
379
+ /** An agent as the module presents to it. The framework's Agent is one. */
380
+ export interface PresentedAgent {
381
+ readonly name: AgentName;
382
+ getContextManager(): WindowManager;
383
+ isOwnParticipant(participant: string): boolean;
384
+ /** Where the agent tells of its own rows once they are stored (Agent.setOwnRowSink). */
385
+ setOwnRowSink?(sink: ((ids: readonly MessageId[]) => void) | undefined): void;
386
+ }
387
+
388
+ /** The traces the module emits, as a host passes them on. */
389
+ export type PresentationTrace = Extract<TraceEventInput, { type: `presentation:${string}` }>;
390
+
391
+ /** What the module reads of its host (the framework). */
392
+ export interface PresentationHost {
393
+ /** Every agent registered now, a shared fork on its own branch included. */
394
+ liveAgents(): Iterable<PresentedAgent>;
395
+ readonly registry: Pick<AgentRegistry, 'get' | 'ownSlotOf' | 'observedSlotOf' | 'readersOf' | 'slotOwners'>;
396
+ /**
397
+ * Whether the agent's logical turn is alive: a turn token, a continuation
398
+ * or retry on its way, a live stream, or a tool cycle pending. Nothing but
399
+ * its own rows and its boundary's arrivals is presented to it then.
400
+ */
401
+ turnAlive(name: AgentName): boolean;
402
+ /**
403
+ * Whether others' rows are frozen out of every window: the host
404
+ * quiesced, or booting until create()'s pass over the windows. Own rows
405
+ * still present. A surgery's hold isn't asked here: its
406
+ * own refusals keep every point that reads this from being reached under
407
+ * it (the framework's `frozen`, where the host is built).
408
+ */
409
+ frozen(): boolean;
410
+ emitTrace(event: PresentationTrace): void;
411
+ }
412
+
413
+ /** A row a tool boundary presented for the live stream to carry: one per body, by the id that names it. */
414
+ export interface HeardRow {
415
+ readonly id: MessageId;
416
+ readonly participant: string;
417
+ /** The body as the store holds it, a sharded one's shards joined as compiles join them (asCompiled). */
418
+ readonly content: ContentBlock[];
419
+ readonly metadata?: MessageMetadata;
420
+ }
421
+
422
+ /** What a tool boundary presented beyond the round's own rows. */
423
+ export interface BoundaryPresentation {
424
+ /** The rows the stream carries next, in window order. */
425
+ readonly heard: readonly HeardRow[];
426
+ /** The first row the stream can't carry, where the rows presented stop. */
427
+ readonly cutAt?: MessageId;
428
+ }
429
+
430
+ /**
431
+ * An agent holding a row: in its window, at a place (`'window'`); in a
432
+ * window that is still the whole record (`'legacy'`), which holds every row
433
+ * its merged record does; or handed it as a reader fork's framing
434
+ * (`'framing'`).
435
+ */
436
+ export type Holder =
437
+ | { readonly agent: AgentName; readonly via: 'window'; readonly position: Position }
438
+ | { readonly agent: AgentName; readonly via: 'legacy' }
439
+ | { readonly agent: AgentName; readonly via: 'framing' };
440
+
441
+ /** What a presentation listener hears: the rows that entered one agent's window, in order, and where. */
442
+ export interface PresentedEvent {
443
+ readonly agentName: AgentName;
444
+ readonly occasion: PresentationOccasion;
445
+ readonly rows: readonly StoredMessage[];
446
+ }
447
+
448
+ /** One body of the agent's pending rows: its unpresented shards in record order, and what it is to the agent. */
449
+ interface PendingBody {
450
+ readonly shards: StoredMessage[];
451
+ readonly bearing: 'own' | 'arrival';
452
+ readonly unstamped: boolean;
453
+ }
454
+
455
+ /** Where a scan of one manager's unpresented rows may start: every one at or below `scanFrom` was elsewhere. */
456
+ interface ScanMemo {
457
+ generation: number;
458
+ branch: string;
459
+ length: number;
460
+ facts: string;
461
+ scanFrom: number;
462
+ /** The same for a scan at rest that leaves a rollback's held arrivals out (pending's `atRest`, a hold in force):
463
+ * every row at or below it was elsewhere or held. A held arrival doesn't hold it back, as one does `scanFrom`,
464
+ * so such a scan doesn't walk every row stored since the arrival until the agent's next start. */
465
+ heldScanFrom?: number;
466
+ }
467
+
468
+ /** What adopt left for one manager. */
469
+ interface Adopted {
470
+ /** Set when the window couldn't be written down: the agent stays in legacy mode for this process. */
471
+ pinnedLegacy?: string;
472
+ /** Set while taking out the rows a write-down took in that aren't the agent's (retractForeign) has failed:
473
+ * tried again at its next turn start or point at rest until it succeeds. */
474
+ retractPending?: true;
475
+ }
476
+
477
+ const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
478
+
479
+ /**
480
+ * The presentation index's decisions, over each live agent's context
481
+ * manager. The framework constructs it in create() and calls it at each
482
+ * presentation point.
483
+ */
484
+ export class AgentPresentation {
485
+ private readonly adopted = new WeakMap<WindowManager, Adopted>();
486
+ private readonly memos = new WeakMap<WindowManager, ScanMemo>();
487
+ /** Bumped when a registration may have changed what a row is to someone: every memo is then stale. */
488
+ private generation = 0;
489
+ /** Rows handed each reader fork as framing (noteFramed), in memory. */
490
+ private readonly framed = new Map<AgentName, Set<MessageId>>();
491
+ /** Reader forks whose framing may not all be in their window yet: framed before they were taken on, or whose framing's presentation failed. */
492
+ private readonly framedPending = new Set<AgentName>();
493
+ private readonly listeners = new Map<AgentName, Set<(event: PresentedEvent) => void>>();
494
+ /** Own rows whose presentation at their write failed, per manager (presentOwn), until they enter its window. */
495
+ private readonly failedOwn = new WeakMap<WindowManager, Set<MessageId>>();
496
+ /** Arrivals a rollback took out of each manager's window, kept out of it at rest until the agent's next turn start (holdUntilStart), on the branch the rollback left the store on. */
497
+ private readonly heldUntilStart = new WeakMap<WindowManager, { branch: string; ids: Set<MessageId> }>();
498
+ /** Agents the boot's pass at rest left out (repairAndRest's `restExcept`): no point at rest presents their arrivals until their next turn start. */
499
+ private readonly restWithheld = new Set<AgentName>();
500
+ /** Read-only handles on the slots a manager merges, by namespace (slotOfRow): made only for a reader whose context merges more than one. */
501
+ private readonly slotReaders = new WeakMap<WindowManager, Map<string | null, MessageStore>>();
502
+
503
+ constructor(private readonly host: PresentationHost) {}
504
+
505
+ // --------------------------------------------------------------------------
506
+ // Taking agents on
507
+ // --------------------------------------------------------------------------
508
+
509
+ /** Take on every live agent (adopt), then present what each is owed at rest (repairAndRest). */
510
+ boot(): void {
511
+ for (const agent of this.host.liveAgents()) this.adopt(agent);
512
+ this.repairAndRest();
513
+ }
514
+
515
+ /**
516
+ * Take an agent on. Once per manager object: a manager in legacy mode has
517
+ * its window written down (presentRows([]), which also finishes a
518
+ * write-down cut short), the stamped rows it took in that are elsewhere to
519
+ * the agent are taken out (retractForeign; where that fails, at the
520
+ * agent's next turn start or point at rest), and the agent's own rows
521
+ * stored and not in its window are presented to it, in record order (an
522
+ * undone turn's rows are not: getUnpresentedMessages leaves them out). A
523
+ * window that can't be
524
+ * written down (another version's index format, or a failed write; not a
525
+ * write-down that threw once its record was written, which reads as
526
+ * presented: writeDown) leaves the agent in legacy mode, traced once,
527
+ * until a move of the store's branch writes its window down on the new
528
+ * branch (rebase): its window is the whole record, as before the index.
529
+ * Then, every time, the agent's own-row sink is installed, one left in
530
+ * legacy mode's too, so the other readers of its slot hear of its rows
531
+ * (presentOwn), and every scan memo is dropped, since a registration can
532
+ * change who reads a slot.
533
+ */
534
+ adopt(agent: PresentedAgent): void {
535
+ const cm = agent.getContextManager();
536
+ this.generation++;
537
+ let state = this.adopted.get(cm);
538
+ if (!state) {
539
+ state = {};
540
+ this.adopted.set(cm, state);
541
+ this.writeDown(agent, state, 'adopt');
542
+ if (!state.pinnedLegacy) {
543
+ this.retractForeign(agent, 'adopt');
544
+ this.repair(agent);
545
+ // A reader fork is framed before it is taken on (noteFramed at its
546
+ // derivation, adopt at its run's registration): the held rows it was
547
+ // handed enter its window now, after its framing row.
548
+ this.presentFramed(agent);
549
+ }
550
+ }
551
+ // In legacy mode too: presentOwn presents nothing for it, and tells the
552
+ // other readers of its slot of its rows (afterStore).
553
+ agent.setOwnRowSink?.((ids) => this.presentOwn(agent, ids));
554
+ }
555
+
556
+ /**
557
+ * The store's branch moved under an agent taken on (a host's switchBranch,
558
+ * a rollback's or a suppression's switch, a failed surgery's restore).
559
+ * Its manager's window index is the new branch's: on a branch made before
560
+ * the agent's write-down (every branch an earlier release's store holds,
561
+ * or a rollback into rows the write-down presented, which branchAt cuts
562
+ * at their own sequence) there is none, and the window would be the
563
+ * whole record for the rest of the process. So, as at adopt, such a
564
+ * window is written down (presentRows([]), traced as presented at
565
+ * `'rebase'`), the stamped rows it took in that are elsewhere to the
566
+ * agent, a co-resident's own rows presented on the old branch among them,
567
+ * are taken out (retractForeign), and the agent's own rows stored and not
568
+ * in its window are presented to it (the own-row sweep). A window that is presented on the
569
+ * new branch is presented again for an agent left in legacy mode by an
570
+ * earlier branch, its own-row sink installed. A window that can't be
571
+ * written down, or a manager whose strategy couldn't follow the move
572
+ * (`failure`, from its re-initialization by the framework, #353), leaves
573
+ * the agent in legacy mode until the next move, traced as
574
+ * presentation:failed at `'rebase'`. Arrivals aren't presented here: the
575
+ * framework's surgery release presents what each agent is owed. Never
576
+ * throws.
577
+ */
578
+ rebase(agent: PresentedAgent, failure?: unknown): void {
579
+ const cm = agent.getContextManager();
580
+ const state = this.adopted.get(cm);
581
+ if (!state) return;
582
+ this.generation++;
583
+ this.memos.delete(cm);
584
+ try {
585
+ if (failure !== undefined) {
586
+ state.pinnedLegacy = describe(failure);
587
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion: 'rebase', error: state.pinnedLegacy, legacy: true });
588
+ return;
589
+ }
590
+ if (cm.isClosed()) return;
591
+ delete state.pinnedLegacy;
592
+ if (!this.writeDown(agent, state, 'rebase')) return;
593
+ agent.setOwnRowSink?.((ids) => this.presentOwn(agent, ids));
594
+ this.retractForeign(agent, 'rebase');
595
+ this.repair(agent, 'rebase');
596
+ // A reader fork's framing that its window doesn't hold on this branch.
597
+ this.presentFramed(agent);
598
+ } catch (error) {
599
+ state.pinnedLegacy = describe(error);
600
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion: 'rebase', error: state.pinnedLegacy, legacy: true });
601
+ }
602
+ }
603
+
604
+ /**
605
+ * Write `agent`'s window down where its manager is in legacy mode
606
+ * (presentRows([]), which also finishes a write-down cut short), and say
607
+ * whether the window is presented after it. A write-down that fails, or
608
+ * leaves the manager in legacy mode, pins the agent in legacy mode
609
+ * (`state.pinnedLegacy`), traced as presentation:failed at `occasion`
610
+ * with `legacy`, which the host logs and alerts. A
611
+ * write-down that throws once its record is written (the store's own work
612
+ * after a write, such as a snapshot, failing) has written the window
613
+ * down: the manager reads its index again after any throw, so a window
614
+ * that reads as presented then is taken as one, and the agent is
615
+ * presented for, with a log line. A write-down at a rebase is traced as
616
+ * presented, with the bodies the window holds; a read for that trace
617
+ * which throws is logged and the trace skipped, the window presented.
618
+ */
619
+ private writeDown(agent: PresentedAgent, state: Adopted, occasion: 'adopt' | 'rebase'): boolean {
620
+ const cm = agent.getContextManager();
621
+ let wrote = false;
622
+ if (cm.windowMode() === 'legacy') {
623
+ try {
624
+ cm.presentRows([]);
625
+ wrote = true;
626
+ } catch (error) {
627
+ if (!readsPresented(cm)) {
628
+ state.pinnedLegacy = describe(error);
629
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion, error: state.pinnedLegacy, legacy: true });
630
+ return false;
631
+ }
632
+ console.warn(`[presentation] ${agent.name}: writing its window down at ${occasion} threw after the window was written (${describe(error)}); its window is presented`);
633
+ wrote = true;
634
+ }
635
+ }
636
+ if (cm.windowMode() !== 'presented') {
637
+ state.pinnedLegacy = 'the window is not in presented mode after its write-down';
638
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion, error: state.pinnedLegacy, legacy: true });
639
+ return false;
640
+ }
641
+ if (wrote && occasion === 'rebase') {
642
+ // The trace's read is the trace's: a throw there leaves the window
643
+ // presented, as written down, and skips the trace.
644
+ let count = 0;
645
+ try {
646
+ count = bodyHeadCount(cm.getPresentedMessages());
647
+ } catch (error) {
648
+ console.error(`[presentation] ${agent.name}: its window was written down at ${occasion}, and reading it back for the trace failed (${describe(error)}); its window is presented, and the write-down isn't traced`);
649
+ }
650
+ if (count > 0) this.host.emitTrace({ type: 'presentation:presented', agentName: agent.name, occasion, count });
651
+ }
652
+ return true;
653
+ }
654
+
655
+ /**
656
+ * Take out of the agent's window the rows a write-down from the record
657
+ * took in that aren't its (decision 1): each row that carries an audience
658
+ * stamp and that bearingOf reads as elsewhere to the agent, such as
659
+ * another agent's own row, mail stamped for a co-resident, or a held row
660
+ * for a window that leaves held rows out. Each leaves its place as a plain
661
+ * retraction does, so it reads as arrived, and it stays elsewhere, so no
662
+ * later point presents it. Two kinds of row stay: an unstamped row, which
663
+ * a release before the stamp stored and the write-down migrates whole,
664
+ * and a shared derivation's inheritance (at or before its checkpoint),
665
+ * which is the child's history. Nothing is taken out for an agent the
666
+ * registry has no slot for. Run at every adopt and rebase, not only
667
+ * after a write-down this process made, so a window whose write-down
668
+ * landed and whose retraction didn't (a crash between the two records, a
669
+ * failed write) is repaired the next time it is taken on. Rows are
670
+ * weighed by the agent's relationships now, not by those they entered
671
+ * under, so a row the module presented is taken out too where it is
672
+ * elsewhere to the agent now: an observed agent's own row, presented
673
+ * through an observe edge the agent no longer has (a restart whose
674
+ * configuration dropped it). A reader fork's framing is passed over. Traced as
675
+ * presentation:retracted, reason `elsewhere`; a failure is traced as
676
+ * presentation:failed at `occasion`, and the rows stay in the window
677
+ * until the agent's next turn start or point at rest takes them out
678
+ * (`retractPending`, tried there until it succeeds), or the next adopt or
679
+ * rebase; a fresh turn start that can't take them out fails
680
+ * (presentAtStart). Never throws.
681
+ */
682
+ private retractForeign(agent: PresentedAgent, occasion: PresentationOccasion): void {
683
+ const cm = agent.getContextManager();
684
+ const state = this.adopted.get(cm);
685
+ try {
686
+ if (!this.presenting(agent)) return;
687
+ const foreign = this.foreignRows(agent);
688
+ if (foreign.length > 0) {
689
+ cm.retractRows(foreign);
690
+ this.memos.delete(cm);
691
+ this.host.emitTrace({ type: 'presentation:retracted', agentName: agent.name, messageIds: foreign, reason: 'elsewhere' });
692
+ }
693
+ if (state) delete state.retractPending;
694
+ } catch (error) {
695
+ if (state) state.retractPending = true;
696
+ console.error(`[presentation] ${agent.name}: taking the rows that aren't its out of its window at ${occasion} failed; they stay in it, and no turn of its starts, until its next turn start or point at rest takes them out:`, error);
697
+ this.host.emitTrace({ type: 'presentation:failed', agentName: agent.name, occasion, error: describe(error) });
698
+ }
699
+ }
700
+
701
+ /** The rows of the agent's window retractForeign takes out, each body by its first shard; none for an agent the registry has no slot for. */
702
+ private foreignRows(agent: PresentedAgent): MessageId[] {
703
+ const cm = agent.getContextManager();
704
+ const facts = readerFacts(this.host.registry, agent.name);
705
+ // An agent the registry doesn't know has no slot to weigh a row by.
706
+ if (facts.ownSlot === undefined) return [];
707
+ const framed = this.framed.get(agent.name);
708
+ const window = cm.getPresentedMessages();
709
+ const foreign: MessageId[] = [];
710
+ for (let i = 0; i < window.length; i++) {
711
+ const row = window[i]!;
712
+ // A body is taken out whole by its first shard.
713
+ if (i > 0 && continuesBody(window[i - 1], row)) continue;
714
+ if (audienceOf(row.metadata) === undefined || framed?.has(row.id)) continue;
715
+ if (facts.derivedAt !== undefined && row.sequence <= facts.derivedAt) continue;
716
+ if (bearingOf(row, facts, this.slotOfRow(cm, facts, row.id)) === 'elsewhere') foreign.push(row.id);
717
+ }
718
+ return foreign;
719
+ }
720
+
721
+ /** retractForeign again, where it failed before (`retractPending`). */
722
+ private retryRetraction(agent: PresentedAgent, occasion: PresentationOccasion): void {
723
+ if (this.adopted.get(agent.getContextManager())?.retractPending) this.retractForeign(agent, occasion);
724
+ }
725
+
726
+ /** Let an agent go: its sink off, and what the module kept for it (its memo, its framing, its held arrivals) dropped. */
727
+ forget(agent: PresentedAgent): void {
728
+ agent.setOwnRowSink?.(undefined);
729
+ const cm = agent.getContextManager();
730
+ this.adopted.delete(cm);
731
+ this.memos.delete(cm);
732
+ this.failedOwn.delete(cm);
733
+ this.heldUntilStart.delete(cm);
734
+ this.slotReaders.delete(cm);
735
+ this.framed.delete(agent.name);
736
+ this.framedPending.delete(agent.name);
737
+ this.restWithheld.delete(agent.name);
738
+ this.generation++;
739
+ }
740
+
741
+ /**
742
+ * For every live agent the module presents to and whose turn isn't alive:
743
+ * its own rows stored and not in its window (the own-row sweep, traced as
744
+ * presentation:repaired), then whatever it is owed at rest (presentAtEnd).
745
+ * Boot runs it once every agent is taken on and the stored rows are in,
746
+ * whether or not an adopt repaired anything. An agent in `restExcept` has
747
+ * its own rows swept and nothing else: the boot couldn't read what it is
748
+ * owed to ask the wakes its rows owe, so they stay out of its window until
749
+ * its next turn start, which no wake was asked for. Until then no point at
750
+ * rest presents its arrivals (a row stored for it while it is idle, a
751
+ * turn's end), only its own rows, so a later boot finds them out of its
752
+ * window and reads them again.
753
+ */
754
+ repairAndRest(options: { restExcept?: ReadonlySet<AgentName> } = {}): void {
755
+ for (const name of options.restExcept ?? []) this.restWithheld.add(name);
756
+ for (const agent of this.host.liveAgents()) {
757
+ if (!this.presenting(agent) || this.host.turnAlive(agent.name)) continue;
758
+ this.repair(agent);
759
+ if (!options.restExcept?.has(agent.name)) this.presentAtRest(agent, 'at-rest');
760
+ }
761
+ }
762
+
763
+ /** Whether the module presents for this agent: taken on, its manager open and in presented mode. */
764
+ presenting(agent: PresentedAgent): boolean {
765
+ const cm = agent.getContextManager();
766
+ const state = this.adopted.get(cm);
767
+ return !!state && !state.pinnedLegacy && !cm.isClosed() && cm.windowMode() === 'presented';
768
+ }
769
+
770
+ // --------------------------------------------------------------------------
771
+ // Presentation points
772
+ // --------------------------------------------------------------------------
773
+
774
+ /**
775
+ * Present the agent's own rows now, in the order given, those not in its
776
+ * window yet, even while the host is frozen; then tell the other readers
777
+ * of its slot (afterStore), whatever became of that: a presentation that
778
+ * threw, or an agent the module doesn't present for (a failed rebase
779
+ * leaves its sink on). The own-row sink calls it. It is for a row the
780
+ * agent's stream carries (its round, its results, a notice injected at its
781
+ * boundary), one written before its next compile or after its stream's
782
+ * last request, or one written while it has no turn alive: any other row
783
+ * would enter a live window its requests don't carry, so its writer holds
784
+ * it back (storeOwnRow's `present: false`) for the next point's sweep.
785
+ *
786
+ * An own row whose presentation here failed (a transient store error) is
787
+ * kept, and presented ahead of the rows given at the agent's next call,
788
+ * in record order, while it is still out of the window: its window's
789
+ * ordinals never move, so a row written after it and presented first
790
+ * would stay ahead of it for good (a round's results ahead of its reply,
791
+ * which every later compile would send so). It is kept until the agent's
792
+ * next turn start or tool boundary, whose own-row sweep presents it by
793
+ * that point's rule, or leaves it for the next point when that fails
794
+ * too: a request compiled, or a stream handed its rows, without it
795
+ * mustn't find it in the window ahead of a reply it didn't come before.
796
+ * A row its writer held back is never kept: it waits for the next point's
797
+ * sweep. Never throws.
798
+ */
799
+ presentOwn(agent: PresentedAgent, ids: ReadonlyArray<MessageId | undefined>): void {
800
+ const cm = agent.getContextManager();
801
+ // Every row this call tries, the ones an earlier failed write kept
802
+ // among them, from before the first read: a read that throws keeps them
803
+ // all (keepFailedOwn), so none of them is put behind the rows written
804
+ // after it.
805
+ let tried: readonly MessageId[] = unique([...(this.failedOwn.get(cm) ?? []), ...ids]);
806
+ try {
807
+ if (this.presenting(agent)) {
808
+ tried = unique([...this.failedOwnOf(agent), ...ids]).filter((id) => cm.ordinalOf(id) === undefined);
809
+ this.present(agent, tried, 'write');
810
+ this.keepFailedOwn(agent, tried);
811
+ }
812
+ } catch (error) {
813
+ this.failed(agent, 'write', error);
814
+ this.keepFailedOwn(agent, tried);
815
+ }
816
+ this.afterStore(agent, ids);
817
+ }
818
+
819
+ /**
820
+ * Rows `writer` just stored, in its own slot: each other reader of that
821
+ * slot (its owners and its observers) whose turn isn't alive, and the
822
+ * writer itself, is presented what it is owed at once, when one of the
823
+ * rows is its own or an arrival for it (present at rest). A reader with a
824
+ * turn alive takes them at its next point. Frozen, only own rows present.
825
+ * The module needn't present for the writer: one left in legacy mode
826
+ * tells the readers of its slot too. Each reader is weighed apart, so one
827
+ * whose window can't be read is traced and the others are still told.
828
+ * Never throws.
829
+ */
830
+ afterStore(writer: PresentedAgent, ids: ReadonlyArray<MessageId | undefined>): void {
831
+ try {
832
+ const stored = unique(ids);
833
+ if (stored.length === 0) return;
834
+ const writerCm = writer.getContextManager();
835
+ const rows = stored.map((id) => writerCm.getMessage(id)).filter((row): row is StoredMessage => row !== null);
836
+ const slot = this.host.registry.ownSlotOf(writer.name);
837
+ const readers = new Set<AgentName>([writer.name, ...(slot ? this.host.registry.readersOf(slot) : [])]);
838
+ for (const reader of [...this.host.liveAgents()]) {
839
+ if (!readers.has(reader.name)) continue;
840
+ try {
841
+ if (!this.presenting(reader) || this.host.turnAlive(reader.name)) continue;
842
+ const facts = readerFacts(this.host.registry, reader.name);
843
+ // The rows are in the writer's own slot: the reader's own when it
844
+ // is the writer or shares that slot (bearingOf compares the ref),
845
+ // else a slot it observes, weighed by its edges on that slot.
846
+ const from: RowSlot | undefined = reader === writer ? 'own' : slot;
847
+ // A row the writer's own slot doesn't hold (none found) can't be
848
+ // weighed here; the reader's own scan weighs it.
849
+ const owed = rows.length < stored.length || rows.some((row) => bearingOf(row, facts, from) !== 'elsewhere');
850
+ if (owed) this.presentAtRest(reader, 'at-rest');
851
+ } catch (error) {
852
+ this.failed(reader, 'at-rest', error);
853
+ }
854
+ }
855
+ } catch (error) {
856
+ this.failed(writer, 'at-rest', error);
857
+ }
858
+ }
859
+
860
+ /**
861
+ * A turn's start, before its compile. `'turn-start'` (a fresh start) and
862
+ * `'assembly'` (the rows a wake assembled for it) present, in one call and
863
+ * record order, the agent's own rows not in its window and its arrivals
864
+ * (none while frozen); `'compile'`, the backstop before every compile,
865
+ * fresh or resumed, its own rows only. Returns the arrivals presented, one
866
+ * per body, for the start to weigh. A fresh start ends a rollback's hold
867
+ * on the arrivals its cut returned (holdUntilStart): they enter with the
868
+ * rest, in record order, and the hold ends once they have, so a start
869
+ * that fails keeps it, and so does one while frozen, which presents no
870
+ * arrival; so does an agent the boot's pass at rest left out
871
+ * (repairAndRest's `restExcept`). A fresh start's presentation that fails (a read
872
+ * of the window or the record that throws, or a write of the window that
873
+ * leaves a row out) is traced, and then throws, so the start fails rather
874
+ * than compile without what it was started for, which waits outside the
875
+ * window for the next point. So does a fresh start where rows a
876
+ * write-down took in that aren't the agent's are still in its window
877
+ * (retractForeign failed again here), rather than compile with them. The
878
+ * backstop's is traced, and its compile goes on.
879
+ */
880
+ presentAtStart(agent: PresentedAgent, occasion: 'turn-start' | 'assembly' | 'compile'): StoredMessage[] {
881
+ if (!this.presenting(agent)) return [];
882
+ const cm = agent.getContextManager();
883
+ const fresh = occasion !== 'compile';
884
+ // The sweep below decides the own rows a failed write left (presentOwn):
885
+ // the backstop's at once, as its compile goes on whatever it presents; a
886
+ // fresh start's once it hasn't thrown, so the next own row's write still
887
+ // puts them first after a start that presented nothing. Only those kept
888
+ // before it: a listener of its presentation, which runs inside it, may
889
+ // store an own row whose presentation fails, kept by that nested write.
890
+ if (!fresh) this.failedOwn.delete(cm);
891
+ const keptBefore = fresh ? new Set(this.failedOwn.get(cm) ?? []) : undefined;
892
+ // A fresh start is where rows a write-down took in that aren't the
893
+ // agent's, whose retraction failed, leave before its compile, and a
894
+ // reader fork's framing whose presentation failed enters.
895
+ if (fresh) {
896
+ this.retryRetraction(agent, occasion);
897
+ if (this.adopted.get(cm)?.retractPending) {
898
+ throw new Error(`${agent.name}'s turn start could not take the rows that aren't its out of its window (at ${occasion}); they stay in it, and it doesn't compile, until a later point takes them out`);
899
+ }
900
+ }
901
+ if (fresh && this.framedPending.has(agent.name)) this.presentFramed(agent);
902
+ // A rollback's returned arrivals enter here (holdUntilStart): the hold
903
+ // is left out of this presentation, and ends once it hasn't failed, at a
904
+ // start that could present arrivals (none while frozen).
905
+ const withArrivals = fresh && !this.host.frozen();
906
+ const { arrivals, failure } = this.presentPending(agent, occasion, withArrivals, false,
907
+ fresh ? "the start fails, and what it didn't present waits for the next point" : undefined);
908
+ if (fresh && failure !== undefined) {
909
+ throw new Error(`${agent.name}'s turn start could not present what it is owed (at ${occasion}): ${describe(failure)}`, { cause: failure });
910
+ }
911
+ if (keptBefore) {
912
+ const keptMeanwhile = [...(this.failedOwn.get(cm) ?? [])].filter((id) => !keptBefore.has(id));
913
+ if (keptMeanwhile.length > 0) this.failedOwn.set(cm, new Set(keptMeanwhile));
914
+ else this.failedOwn.delete(cm);
915
+ }
916
+ if (withArrivals) {
917
+ this.heldUntilStart.delete(cm);
918
+ this.restWithheld.delete(agent.name);
919
+ }
920
+ return arrivals;
921
+ }
922
+
923
+ /**
924
+ * A tool boundary. First the round's own rows on the wire (`wire`: its
925
+ * reply, its results, a clock row due), those not in the window yet, in
926
+ * order; if that fails, nothing more. Then, unless the host is frozen or
927
+ * the stream can't carry injected rows (`injects` false), the agent's own
928
+ * rows not in its window and its arrivals, by bodies in record order, up
929
+ * to the first body the stream can't carry (isInjectableMidTurn: a tool
930
+ * block, or a row named as the agent), presented in one call: each body
931
+ * whole, named by its first shard not in the window. Those are what the
932
+ * stream carries next (`heard`); the cut body and those after it wait for
933
+ * the turn's end. A presentation cut short hears only the bodies wholly in
934
+ * the window. A read of the window or the record that throws is traced as
935
+ * presentation:failed, and the stream hears nothing: what wasn't presented
936
+ * waits for the next point, and the hand-off that follows checks the
937
+ * window as it then stands. Never throws, so the boundary goes on to hand
938
+ * the stream its results.
939
+ */
940
+ presentAtBoundary(agent: PresentedAgent, wire: ReadonlyArray<MessageId | undefined>, options: { injects: boolean }): BoundaryPresentation {
941
+ try {
942
+ if (!this.presenting(agent)) return { heard: [] };
943
+ const cm = agent.getContextManager();
944
+ const missing = unique(wire).filter((id) => cm.ordinalOf(id) === undefined);
945
+ // The round's rows are presented here, in order, and the own rows a
946
+ // failed write left (presentOwn) are this boundary's to sweep, or the
947
+ // next point's: none is put ahead of the next round's reply.
948
+ this.failedOwn.delete(cm);
949
+ if (missing.length > 0 && this.present(agent, missing, 'tool-boundary').error !== undefined) return { heard: [] };
950
+ if (this.host.frozen() || !options.injects) return { heard: [] };
951
+ const bodies = this.pending(agent, true);
952
+ const cut = bodies.findIndex((body) => body.shards.some((shard) => !isInjectableMidTurn(shard, agent)));
953
+ const prefix = cut === -1 ? bodies : bodies.slice(0, cut);
954
+ const cutAt = cut === -1 ? undefined : bodies[cut]!.shards[0]!.id;
955
+ const { entered } = this.present(agent, prefix.map((body) => body.shards[0]!.id), 'tool-boundary', {
956
+ unstamped: prefix.filter((body) => body.unstamped).length,
957
+ ...(cutAt !== undefined ? { cutAt } : {}),
958
+ }, prefix);
959
+ const heard = prefix
960
+ .filter((body) => entered.has(body.shards[0]!.id) && body.shards.every((shard) => cm.ordinalOf(shard.id) !== undefined))
961
+ .map((body): HeardRow => {
962
+ const head = body.shards[0]!;
963
+ return {
964
+ id: head.id,
965
+ participant: head.participant,
966
+ content: asCompiled(body.shards),
967
+ ...(head.metadata !== undefined ? { metadata: head.metadata } : {}),
968
+ };
969
+ });
970
+ return { heard, ...(cutAt !== undefined ? { cutAt } : {}) };
971
+ } catch (error) {
972
+ this.failed(agent, 'tool-boundary', error);
973
+ return { heard: [] };
974
+ }
975
+ }
976
+
977
+ /**
978
+ * A turn's end, and an agent at rest: when its logical turn isn't alive,
979
+ * its own rows not in its window and its arrivals (none while frozen), in
980
+ * one call and record order. Nothing while the turn is alive. Idempotent.
981
+ * Returns the arrivals presented, one per body.
982
+ */
983
+ presentAtEnd(agent: PresentedAgent): StoredMessage[] {
984
+ return this.presentAtRest(agent, 'turn-end');
985
+ }
986
+
987
+ /**
988
+ * The rows a rollback's branch cut took out of the agent's window and
989
+ * kept in the record (its `returnedToArrivals`, #291): they are arrivals
990
+ * again, and wait outside the window until the agent's next turn start
991
+ * (presentAtStart's `'turn-start'` or `'assembly'`), which presents them
992
+ * with whatever else it is owed, in record order (a start that fails
993
+ * keeps them held). Until then no point at
994
+ * rest presents them: not the surgery's release, a resume, a turn's end
995
+ * or a row stored for the agent while it is idle, so the cut the
996
+ * operator made is what the agent's window holds until it speaks again.
997
+ * A tool boundary isn't held back (a turn alive started since). An own
998
+ * row among them isn't held: own rows enter at every point, as ever. The
999
+ * hold is the branch's the store is on (the rollback's): on another
1000
+ * branch the same stored rows are arrivals as any, so a later move of the
1001
+ * store's branch, a suppression or rollback through another agent
1002
+ * included, ends it there, and back on this one they are held again until
1003
+ * the agent's next turn start. In memory: a restart presents them at its
1004
+ * pass at rest, or, where it boots quiesced, at the resume (a frozen pass
1005
+ * presents no arrival), and an agent let go (forget)
1006
+ * drops them. Rows given again on the same branch add to those held, and
1007
+ * on another replace them. Never throws.
1008
+ */
1009
+ holdUntilStart(agent: PresentedAgent, ids: readonly MessageId[]): void {
1010
+ const named = unique(ids);
1011
+ if (named.length === 0) return;
1012
+ const cm = agent.getContextManager();
1013
+ try {
1014
+ const branch = cm.currentBranch().name;
1015
+ const held = this.heldUntilStart.get(cm);
1016
+ const kept = held?.branch === branch ? held.ids : new Set<MessageId>();
1017
+ for (const id of named) kept.add(id);
1018
+ this.heldUntilStart.set(cm, { branch, ids: kept });
1019
+ // A scan at rest that left an earlier hold's rows out may have passed them.
1020
+ this.memos.delete(cm);
1021
+ } catch (error) {
1022
+ console.error(`[presentation] ${agent.name}: could not hold ${named.length} row(s) out of its window until its next turn start; they enter at its next presentation point:`, error);
1023
+ }
1024
+ }
1025
+
1026
+ /**
1027
+ * The check before a tool boundary hands the stream its rows: `sent` (the
1028
+ * round's reply, its results and the injected rows, in the order the
1029
+ * stream is given them) not yet in the window are presented, in order,
1030
+ * and the window's newest bodies must then be exactly those rows. On a
1031
+ * mismatch it traces presentation:hand-off-mismatch and the rows are not
1032
+ * vouched for, so the stream's later thinking is left out at the next
1033
+ * compile rather than sent under a prefix its window doesn't hold. An
1034
+ * agent the module doesn't present for is vouched for as before. A read
1035
+ * of the window that throws is traced as presentation:failed, and the
1036
+ * rows are not vouched for: the check couldn't be made. Never throws.
1037
+ */
1038
+ handOff(agent: PresentedAgent, sent: ReadonlyArray<MessageId | undefined>): { vouched: boolean } {
1039
+ try {
1040
+ if (!this.presenting(agent)) return { vouched: true };
1041
+ const cm = agent.getContextManager();
1042
+ const expected = unique(sent);
1043
+ if (expected.length === 0) return { vouched: true };
1044
+ const missing = expected.filter((id) => cm.ordinalOf(id) === undefined);
1045
+ if (missing.length > 0 && this.present(agent, missing, 'hand-off').error !== undefined) {
1046
+ this.host.emitTrace({ type: 'presentation:hand-off-mismatch', agentName: agent.name, expected, tail: lastBodyHeads(cm.getPresentedMessages(), expected.length) });
1047
+ return { vouched: false };
1048
+ }
1049
+ const tail = lastBodyHeads(cm.getPresentedMessages(), expected.length);
1050
+ if (tail.length !== expected.length || tail.some((id, i) => id !== expected[i])) {
1051
+ this.host.emitTrace({ type: 'presentation:hand-off-mismatch', agentName: agent.name, expected, tail });
1052
+ return { vouched: false };
1053
+ }
1054
+ return { vouched: true };
1055
+ } catch (error) {
1056
+ this.failed(agent, 'hand-off', error);
1057
+ return { vouched: false };
1058
+ }
1059
+ }
1060
+
1061
+ /** A read of the agent's arrivals not yet presented, one per body, in record order (for previews and a release). */
1062
+ arrivalsOf(agent: PresentedAgent): StoredMessage[] {
1063
+ if (!this.presenting(agent)) return [];
1064
+ return this.pending(agent, true).filter((body) => body.bearing === 'arrival').map((body) => body.shards[0]!);
1065
+ }
1066
+
1067
+ /**
1068
+ * A reader fork was handed held rows as framing (AF-5): those not in its
1069
+ * window yet are presented there, when the module presents for it, and
1070
+ * the fork counts as holding every one of them (holders, `'framing'`),
1071
+ * however its window filters held rows, until it is let go (forget). A
1072
+ * fork framed before it is taken on has them presented at its adopt. Its
1073
+ * window's filter (the residents', which a reader fork inherits) keeps
1074
+ * them out of its compiles, as it keeps all held traffic; its framing row
1075
+ * shows them where the framing puts them (the default's does); nothing
1076
+ * else of its window moves. Rows whose presentation fails enter at the
1077
+ * fork's next turn start, or after a move of the store's branch (rebase).
1078
+ */
1079
+ noteFramed(agent: PresentedAgent, rowIds: readonly MessageId[]): void {
1080
+ const set = this.framed.get(agent.name) ?? new Set<MessageId>();
1081
+ for (const id of rowIds) set.add(id);
1082
+ this.framed.set(agent.name, set);
1083
+ this.framedPending.add(agent.name);
1084
+ this.presentFramed(agent);
1085
+ }
1086
+
1087
+ /**
1088
+ * Drop the rows a reader fork was handed as framing (noteFramed) when the
1089
+ * fork is never taken on, so never let go (forget): one its run refused
1090
+ * before registering it (the host quiesced or stopping, a surgery holding
1091
+ * the store). Nothing for a name handed none.
1092
+ */
1093
+ forgetFramed(agent: AgentName): void {
1094
+ this.framed.delete(agent);
1095
+ this.framedPending.delete(agent);
1096
+ }
1097
+
1098
+ /**
1099
+ * The rows the agent is owed and its window doesn't hold yet, one per
1100
+ * body (its first shard not in the window), in record order: its own rows
1101
+ * and its arrivals, frozen or not, whatever its turn. None for an agent the
1102
+ * module doesn't present for. The subconscious's window start is fixed
1103
+ * once no row it is owed stored before the start is among them.
1104
+ */
1105
+ owedOf(agent: PresentedAgent): StoredMessage[] {
1106
+ if (!this.presenting(agent)) return [];
1107
+ return this.pending(agent, true).map((body) => body.shards[0]!);
1108
+ }
1109
+
1110
+ /**
1111
+ * Whether a row just stored in the agent's own slot, and presented at
1112
+ * rest by afterStore if at all, is out of its window though the agent is
1113
+ * owed it (its own row, or an arrival): a presentation that failed, or
1114
+ * the host's freeze, kept it out. A row that is nothing to the agent (held
1115
+ * from a resident, stamped for another) isn't. Yes where the window can't
1116
+ * be read to tell; no for an agent the module doesn't present for.
1117
+ */
1118
+ notPresented(agent: PresentedAgent, id: MessageId): boolean {
1119
+ try {
1120
+ if (!this.presenting(agent)) return false;
1121
+ const cm = agent.getContextManager();
1122
+ if (cm.windowStatusOf(id) !== 'out') return false;
1123
+ const row = cm.getMessage(id);
1124
+ return row === null || bearingOf(row, readerFacts(this.host.registry, agent.name), 'own') !== 'elsewhere';
1125
+ } catch {
1126
+ return true;
1127
+ }
1128
+ }
1129
+
1130
+ // --------------------------------------------------------------------------
1131
+ // Reads
1132
+ // --------------------------------------------------------------------------
1133
+
1134
+ /**
1135
+ * Every live agent holding a row: each whose window has it at a place,
1136
+ * leaving out one whose window leaves held rows out when the row is held
1137
+ * (a window written down from the record took in those an earlier release
1138
+ * stored, before the audience stamp; retractForeign takes out the rest),
1139
+ * and every one when a suppress rule hid the row, which no view renders;
1140
+ * each whose window
1141
+ * is still the whole record and whose record holds it; and each reader fork
1142
+ * handed it as framing.
1143
+ */
1144
+ holders(rowId: MessageId): Holder[] {
1145
+ const holders: Holder[] = [];
1146
+ const inWindow = new Set<AgentName>();
1147
+ for (const agent of this.host.liveAgents()) {
1148
+ const cm = agent.getContextManager();
1149
+ if (cm.isClosed()) continue;
1150
+ if (this.adopted.get(cm)?.pinnedLegacy || cm.windowMode() !== 'presented') {
1151
+ if (cm.getMessage(rowId) !== null || cm.getPresentedMessages().some((m) => m.id === rowId)) {
1152
+ holders.push({ agent: agent.name, via: 'legacy' });
1153
+ }
1154
+ continue;
1155
+ }
1156
+ const position = positionIn(cm, rowId);
1157
+ if (position === undefined) continue;
1158
+ const metadata = cm.getMessage(rowId)?.metadata as Record<string, unknown> | undefined;
1159
+ if (suppressedRow(metadata)) continue;
1160
+ if (readerFacts(this.host.registry, agent.name).hidesHeld && heldFromResidents(metadata)) continue;
1161
+ holders.push({ agent: agent.name, via: 'window', position });
1162
+ inWindow.add(agent.name);
1163
+ }
1164
+ for (const [agent, ids] of this.framed) {
1165
+ if (ids.has(rowId) && !inWindow.has(agent)) holders.push({ agent, via: 'framing' });
1166
+ }
1167
+ return holders;
1168
+ }
1169
+
1170
+ /**
1171
+ * Rows removed from the record through `remover` (a context manager of a
1172
+ * live agent's, or one opened apart from them), taken out of every other
1173
+ * live agent's window that still holds them: context-manager tombstones a
1174
+ * removal in the remover's own window only, and another window on the
1175
+ * same slot, or merging it, keeps the row's place (CM-T) while its listing
1176
+ * and its compile leave the row out. Each row leaves at its own place, so
1177
+ * no other row's place moves, and a cursor or watermark kept by place
1178
+ * stays good. A window on a branch whose record still holds the row (a
1179
+ * fork, a derived agent's view made before the removal) keeps it, as does
1180
+ * a window that is still the record, which is never written to here
1181
+ * (context-manager's retractRemoved passes over both). Each window's rows
1182
+ * taken out are traced (presentation:retracted, with `reason`), and a
1183
+ * window that couldn't be repaired is logged and passed by: the removal
1184
+ * stands. `ids` names every row removed, a body by each of its shards.
1185
+ * Returns what left each window. Never throws.
1186
+ */
1187
+ retractRemoved(remover: WindowManager | undefined, ids: readonly MessageId[], reason: PresentationRetractReason): Array<{ agent: AgentName; ids: MessageId[] }> {
1188
+ const named = unique(ids).filter((id) => id !== '');
1189
+ if (named.length === 0) return [];
1190
+ const visited = new Set<WindowManager>(remover ? [remover] : []);
1191
+ const out: Array<{ agent: AgentName; ids: MessageId[] }> = [];
1192
+ for (const agent of this.host.liveAgents()) {
1193
+ const cm = agent.getContextManager();
1194
+ if (visited.has(cm)) continue;
1195
+ visited.add(cm);
1196
+ try {
1197
+ // A window that is still the record holds no place for the row:
1198
+ // checked here as well as by the call, which writes nothing then.
1199
+ if (cm.isClosed() || cm.windowMode() !== 'presented') continue;
1200
+ const taken = cm.retractRemoved(named);
1201
+ if (taken.length === 0) continue;
1202
+ out.push({ agent: agent.name, ids: taken });
1203
+ this.host.emitTrace({ type: 'presentation:retracted', agentName: agent.name, messageIds: taken, reason });
1204
+ } catch (error) {
1205
+ console.error(`[presentation] could not take ${named.length} removed row(s) out of ${agent.name}'s window (${reason}); the removal stands: ${describe(error)}`);
1206
+ }
1207
+ }
1208
+ return out;
1209
+ }
1210
+
1211
+ /**
1212
+ * At boot, after every live agent is taken on: take out of each window
1213
+ * the module presents for every row it holds that its record no longer
1214
+ * does (context-manager's retractAbsentRows), as retractRemoved takes out
1215
+ * the rows a live removal named. These are rows removed where no live
1216
+ * context heard it: by an offline recovery's suppressions, with the host
1217
+ * stopped, through the one context it opened, and removals whose own
1218
+ * tombstone failed. Traced as presentation:retracted with `boot`; a
1219
+ * window that couldn't be repaired is logged and passed by. Each agent's
1220
+ * context is open with every slot it merges by then, so a row of a slot
1221
+ * it merges isn't taken for removed. Never throws.
1222
+ */
1223
+ retractAbsentRows(): Array<{ agent: AgentName; ids: MessageId[] }> {
1224
+ const out: Array<{ agent: AgentName; ids: MessageId[] }> = [];
1225
+ const visited = new Set<WindowManager>();
1226
+ for (const agent of this.host.liveAgents()) {
1227
+ const cm = agent.getContextManager();
1228
+ if (visited.has(cm)) continue;
1229
+ visited.add(cm);
1230
+ try {
1231
+ if (!this.presenting(agent)) continue;
1232
+ const taken = cm.retractAbsentRows();
1233
+ if (taken.length === 0) continue;
1234
+ out.push({ agent: agent.name, ids: taken });
1235
+ this.host.emitTrace({ type: 'presentation:retracted', agentName: agent.name, messageIds: taken, reason: 'boot' });
1236
+ } catch (error) {
1237
+ console.error(`[presentation] could not take removed rows out of ${agent.name}'s window at boot: ${describe(error)}`);
1238
+ }
1239
+ }
1240
+ return out;
1241
+ }
1242
+
1243
+ /** Whether a reader fork was handed the row as framing (noteFramed), and
1244
+ * hasn't been let go since, whether or not its window holds the row. */
1245
+ framedToAny(rowId: MessageId): boolean {
1246
+ for (const ids of this.framed.values()) if (ids.has(rowId)) return true;
1247
+ return false;
1248
+ }
1249
+
1250
+ /** Whether any live agent but `except` holds the row in a window or as framing: a window that is still the record doesn't count. */
1251
+ presentedToAnyone(rowId: MessageId, options: { except?: AgentName } = {}): boolean {
1252
+ return this.holders(rowId).some((h) => h.via !== 'legacy' && h.agent !== options.except);
1253
+ }
1254
+
1255
+ /** The rows of the agent's window at or after `mark`, in window order; none in legacy mode. */
1256
+ presentedSince(agent: PresentedAgent, mark: Position): StoredMessage[] {
1257
+ const cm = agent.getContextManager();
1258
+ if (cm.windowMode() !== 'presented') return [];
1259
+ return cm.getPresentedMessages().filter((m) => (cm.ordinalOf(m.id) ?? -1) >= mark);
1260
+ }
1261
+
1262
+ /** Hear each presentation into the named agent's window, after its rows entered. Returns the unsubscribe. */
1263
+ onPresented(agentName: AgentName, listener: (event: PresentedEvent) => void): () => void {
1264
+ const set = this.listeners.get(agentName) ?? new Set();
1265
+ set.add(listener);
1266
+ this.listeners.set(agentName, set);
1267
+ return () => {
1268
+ set.delete(listener);
1269
+ if (set.size === 0 && this.listeners.get(agentName) === set) this.listeners.delete(agentName);
1270
+ };
1271
+ }
1272
+
1273
+ /**
1274
+ * A write's stamp, checked as it is stored through `deliveredTo`'s
1275
+ * context: an audience none of whose agents reads that slot is traced
1276
+ * (presentation:unreadable-audience), once for the write. The row is
1277
+ * stored as named.
1278
+ */
1279
+ checkAudience(metadata: MessageMetadata | undefined, deliveredTo: AgentName): void {
1280
+ const stamp = audienceOf(metadata);
1281
+ if (!stamp) return;
1282
+ const slot = this.host.registry.ownSlotOf(deliveredTo);
1283
+ if (!slot || !audienceFault(stamp.audience, slot, this.host.registry)) return;
1284
+ this.host.emitTrace({ type: 'presentation:unreadable-audience', audience: stamp.audience, slot, deliveredTo });
1285
+ }
1286
+
1287
+ // --------------------------------------------------------------------------
1288
+ // Internals
1289
+ // --------------------------------------------------------------------------
1290
+
1291
+ /**
1292
+ * The own rows whose presentation at their write failed (presentOwn) and
1293
+ * that are still out of the agent's window, in record order. A row that
1294
+ * entered by another point since, was undone, or left the record (a
1295
+ * branch move, a removal) is dropped.
1296
+ */
1297
+ private failedOwnOf(agent: PresentedAgent): MessageId[] {
1298
+ const cm = agent.getContextManager();
1299
+ const kept = this.failedOwn.get(cm);
1300
+ if (!kept || kept.size === 0) return [];
1301
+ const owed: Array<{ id: MessageId; sequence: number }> = [];
1302
+ for (const id of kept) {
1303
+ const row = cm.windowStatusOf(id) === 'out' ? cm.getMessage(id) : null;
1304
+ if (row) owed.push({ id, sequence: row.sequence });
1305
+ }
1306
+ if (owed.length === 0) this.failedOwn.delete(cm);
1307
+ return owed.sort((a, b) => a.sequence - b.sequence).map((row) => row.id);
1308
+ }
1309
+
1310
+ /**
1311
+ * Keep, of the own rows presentOwn tried, those still out of the window,
1312
+ * for its next call; forget the rest. Rows kept meanwhile that this call
1313
+ * didn't try stay kept: a listener of its presentation, which runs
1314
+ * inside it, may have stored an own row whose presentation failed, kept
1315
+ * by that nested call.
1316
+ */
1317
+ private keepFailedOwn(agent: PresentedAgent, tried: readonly MessageId[]): void {
1318
+ const cm = agent.getContextManager();
1319
+ const triedHere = new Set(tried);
1320
+ const keptMeanwhile = [...(this.failedOwn.get(cm) ?? [])].filter((id) => !triedHere.has(id));
1321
+ let keep: MessageId[];
1322
+ try {
1323
+ keep = [...tried, ...keptMeanwhile].filter((id) => cm.ordinalOf(id) === undefined);
1324
+ } catch {
1325
+ // A window that can't be read now: keep every row tried.
1326
+ keep = [...tried, ...keptMeanwhile];
1327
+ }
1328
+ if (keep.length > 0) this.failedOwn.set(cm, new Set(keep));
1329
+ else this.failedOwn.delete(cm);
1330
+ }
1331
+
1332
+ /** presentAtEnd under a named occasion; a rollback's held arrivals wait (holdUntilStart), and so do all of an agent's the boot left out (restWithheld). */
1333
+ private presentAtRest(agent: PresentedAgent, occasion: 'turn-end' | 'at-rest'): StoredMessage[] {
1334
+ if (!this.presenting(agent) || this.host.turnAlive(agent.name)) return [];
1335
+ this.retryRetraction(agent, occasion);
1336
+ return this.presentPending(agent, occasion, !this.host.frozen() && !this.restWithheld.has(agent.name), true).arrivals;
1337
+ }
1338
+
1339
+ /** The rows the agent was handed as framing (noteFramed) that its window doesn't hold yet, presented in the order handed. */
1340
+ private presentFramed(agent: PresentedAgent): void {
1341
+ const framed = this.framed.get(agent.name);
1342
+ if (!framed || framed.size === 0) {
1343
+ this.framedPending.delete(agent.name);
1344
+ return;
1345
+ }
1346
+ try {
1347
+ if (!this.presenting(agent)) return;
1348
+ const cm = agent.getContextManager();
1349
+ // presentRows refuses a row the window holds already, and a reader
1350
+ // fork derived from a presented window holds those rows its parent's
1351
+ // window was written down with.
1352
+ const unpresented = new Set(cm.getUnpresentedMessages().map((m) => m.id));
1353
+ const { error } = this.present(agent, [...framed].filter((id) => unpresented.has(id)), 'framing');
1354
+ // Pending until a presentation of them doesn't fail: the fork's next
1355
+ // turn start tries again (presentAtStart).
1356
+ if (error === undefined) this.framedPending.delete(agent.name);
1357
+ } catch (error) {
1358
+ this.failed(agent, 'framing', error);
1359
+ }
1360
+ }
1361
+
1362
+ /** The own-row sweep: the agent's own rows not in its window, presented in record order, traced as a repair. */
1363
+ private repair(agent: PresentedAgent, occasion: 'adopt' | 'rebase' = 'adopt'): void {
1364
+ try {
1365
+ const own = this.pending(agent, false);
1366
+ if (own.length === 0) return;
1367
+ const { entered } = this.present(agent, own.map((body) => body.shards[0]!.id), occasion, undefined, own, true);
1368
+ if (entered.size > 0) this.host.emitTrace({ type: 'presentation:repaired', agentName: agent.name, count: entered.size });
1369
+ } catch (error) {
1370
+ this.failed(agent, occasion, error);
1371
+ }
1372
+ }
1373
+
1374
+ /**
1375
+ * Present the agent's own pending rows, and its arrivals when `arrivals`
1376
+ * (but those a rollback holds for its next start, with `atRest`), in one
1377
+ * call; return the arrivals that entered whole, and the error when the
1378
+ * presentation failed: a read that threw, or a write that left a row it
1379
+ * named out. `next` is what the failure's log says becomes of its rows.
1380
+ */
1381
+ private presentPending(
1382
+ agent: PresentedAgent,
1383
+ occasion: PresentationOccasion,
1384
+ arrivals: boolean,
1385
+ atRest = false,
1386
+ next?: string,
1387
+ ): { arrivals: StoredMessage[]; failure?: unknown } {
1388
+ try {
1389
+ const cm = agent.getContextManager();
1390
+ const bodies = this.pending(agent, arrivals, atRest);
1391
+ if (bodies.length === 0) return { arrivals: [] };
1392
+ const heads = bodies.map((body) => body.shards[0]!.id);
1393
+ const { entered, error } = this.present(agent, heads, occasion, {
1394
+ unstamped: bodies.filter((body) => body.unstamped).length,
1395
+ ...(next !== undefined ? { next } : {}),
1396
+ }, bodies);
1397
+ return {
1398
+ arrivals: bodies
1399
+ .filter((body) => body.bearing === 'arrival' && entered.has(body.shards[0]!.id)
1400
+ && body.shards.every((shard) => cm.ordinalOf(shard.id) !== undefined))
1401
+ .map((body) => body.shards[0]!),
1402
+ ...(error !== undefined && heads.some((id) => !entered.has(id)) ? { failure: error } : {}),
1403
+ };
1404
+ } catch (error) {
1405
+ this.failed(agent, occasion, error, undefined, next);
1406
+ return { arrivals: [], failure: error };
1407
+ }
1408
+ }
1409
+
1410
+ /**
1411
+ * The agent's pending bodies, in record order: its own rows not in its
1412
+ * window, and its arrivals when `arrivals`, leaving out, with `atRest`,
1413
+ * an arrival a rollback holds for the agent's next start (any shard of
1414
+ * its body held). A body is its run of unpresented shards
1415
+ * (continuesBody), weighed by its first.
1416
+ */
1417
+ private pending(agent: PresentedAgent, arrivals: boolean, atRest = false): PendingBody[] {
1418
+ const cm = agent.getContextManager();
1419
+ const facts = readerFacts(this.host.registry, agent.name);
1420
+ const factsKey = JSON.stringify(facts);
1421
+ const branch = cm.currentBranch().name;
1422
+ // A rollback's hold is its branch's: on another the rows are arrivals as any.
1423
+ const hold = atRest ? this.heldUntilStart.get(cm) : undefined;
1424
+ const held = hold?.branch === branch && hold.ids.size > 0 ? hold.ids : undefined;
1425
+ const length = cm.indexLength();
1426
+ let memo = this.memos.get(cm);
1427
+ if (!memo || memo.generation !== this.generation || memo.branch !== branch || memo.length !== length || memo.facts !== factsKey) {
1428
+ memo = { generation: this.generation, branch, length, facts: factsKey, scanFrom: -Infinity };
1429
+ this.memos.set(cm, memo);
1430
+ }
1431
+ // Every unpresented row at or below the memo's mark was elsewhere, so the
1432
+ // listing starts after it (context-manager finds the place by a search):
1433
+ // a scan walks the rows stored since, not every row of others' the
1434
+ // record holds. A scan that leaves held arrivals out may start at its own
1435
+ // mark too, which held rows don't hold back (heldScanFrom).
1436
+ const from = held ? Math.max(memo.scanFrom, memo.heldScanFrom ?? -Infinity) : memo.scanFrom;
1437
+ const unpresented = from === -Infinity
1438
+ ? cm.getUnpresentedMessages()
1439
+ : cm.getUnpresentedMessages({ afterSequence: from });
1440
+ const bodies: PendingBody[] = [];
1441
+ let firstOwed: number | undefined;
1442
+ let newest = from;
1443
+ let i = 0;
1444
+ while (i < unpresented.length) {
1445
+ const start = i;
1446
+ i++;
1447
+ while (i < unpresented.length && continuesBody(unpresented[i - 1], unpresented[i])) i++;
1448
+ const head = unpresented[start]!;
1449
+ newest = Math.max(newest, unpresented[i - 1]!.sequence);
1450
+ if (head.sequence <= from) continue;
1451
+ const bearing = bearingOf(head, facts, this.slotOfRow(cm, facts, head.id));
1452
+ if (bearing === 'elsewhere') continue;
1453
+ // A held arrival is still owed, and every scan but this one counts it
1454
+ // (firstOwed, in `scanFrom`), so a scan that presents it, or counts
1455
+ // what is owed, starts at or before it; this one passes it over.
1456
+ const isHeld = bearing === 'arrival' && held !== undefined
1457
+ && unpresented.slice(start, i).some((shard) => held.has(shard.id));
1458
+ if (!isHeld) firstOwed ??= head.sequence;
1459
+ if (isHeld || (bearing === 'arrival' && !arrivals)) continue;
1460
+ bodies.push({ shards: unpresented.slice(start, i), bearing, unstamped: audienceOf(head.metadata) === undefined });
1461
+ }
1462
+ const next = firstOwed !== undefined ? Math.max(from, firstOwed - 1) : newest;
1463
+ if (held) memo.heldScanFrom = next;
1464
+ else memo.scanFrom = next;
1465
+ return bodies;
1466
+ }
1467
+
1468
+ /**
1469
+ * The slot of `cm`'s record a row is stored in, for bearingOf: its own
1470
+ * (`'own'`, which getMessage reads), else the merged slot that holds it
1471
+ * (mergedSlotsOf). The record holds the context's own slot and one
1472
+ * auxiliary view per merged slot, so a row not in its own is in the one
1473
+ * merged slot when there is one; when there are more, each is asked, by
1474
+ * a read-only handle on it over the manager's store, which follows its
1475
+ * branch and its writes as the manager's own views do. undefined for a
1476
+ * row in none of them (a slot the reader has no edge on).
1477
+ */
1478
+ private slotOfRow(cm: WindowManager, facts: ReaderFacts, id: MessageId): RowSlot | undefined {
1479
+ if (cm.getMessage(id) !== null) return 'own';
1480
+ const merged = mergedSlotsOf(facts);
1481
+ if (merged.length <= 1) return merged[0];
1482
+ let readers = this.slotReaders.get(cm);
1483
+ if (!readers) {
1484
+ readers = new Map();
1485
+ this.slotReaders.set(cm, readers);
1486
+ }
1487
+ for (const slot of merged) {
1488
+ let reader = readers.get(slot.namespace);
1489
+ if (!reader) {
1490
+ reader = new MessageStore(cm.getStore(), slot.namespace === null ? {} : { namespace: slot.namespace });
1491
+ readers.set(slot.namespace, reader);
1492
+ }
1493
+ if (reader.sequenceOf(id) !== undefined) return slot;
1494
+ }
1495
+ return undefined;
1496
+ }
1497
+
1498
+ /**
1499
+ * One presentRows call for `ids` in the agent's window: every row named
1500
+ * counts once it returns (it refuses a row already in the window, and
1501
+ * returns one ordinal per row named); on a throw, the rows that entered
1502
+ * before it count, as far as the window can be read then, and the
1503
+ * failure is traced. Traces what entered and tells the listeners.
1504
+ */
1505
+ private present(
1506
+ agent: PresentedAgent,
1507
+ ids: readonly MessageId[],
1508
+ occasion: PresentationOccasion,
1509
+ extra?: { unstamped?: number; cutAt?: MessageId; next?: string },
1510
+ bodies?: readonly PendingBody[],
1511
+ quiet = false,
1512
+ ): { entered: Set<MessageId>; error?: unknown } {
1513
+ if (ids.length === 0) return { entered: new Set() };
1514
+ const cm = agent.getContextManager();
1515
+ const lengthBefore = cm.indexLength();
1516
+ let error: unknown;
1517
+ let entered: Set<MessageId>;
1518
+ try {
1519
+ cm.presentRows(ids);
1520
+ // Read from the write's return, not the window: a read that throws
1521
+ // now mustn't keep rows the store holds from being traced and told.
1522
+ entered = new Set(ids);
1523
+ } catch (thrown) {
1524
+ error = thrown;
1525
+ try {
1526
+ entered = new Set(ids.filter((id) => cm.ordinalOf(id) !== undefined));
1527
+ } catch (readError) {
1528
+ console.error(`[presentation] ${agent.name}'s window couldn't be read after a failed presentation, so none of it is counted as entered:`, readError);
1529
+ entered = new Set();
1530
+ }
1531
+ }
1532
+ const memo = this.memos.get(cm);
1533
+ if (memo && memo.length === lengthBefore) {
1534
+ try {
1535
+ memo.length = cm.indexLength();
1536
+ } catch {
1537
+ // The scan's memo can't be moved past the rows: the next scan reads them again.
1538
+ this.memos.delete(cm);
1539
+ }
1540
+ }
1541
+ if (error !== undefined) this.failed(agent, occasion, error, ids.filter((id) => !entered.has(id)), extra?.next);
1542
+ if (entered.size > 0) {
1543
+ if (!quiet) {
1544
+ const unstamped = extra?.unstamped !== undefined && bodies
1545
+ ? bodies.filter((body) => body.unstamped && entered.has(body.shards[0]!.id)).length
1546
+ : 0;
1547
+ this.host.emitTrace({
1548
+ type: 'presentation:presented',
1549
+ agentName: agent.name,
1550
+ occasion,
1551
+ count: entered.size,
1552
+ ...(extra?.cutAt !== undefined ? { cutAt: extra.cutAt } : {}),
1553
+ ...(unstamped > 0 ? { unstamped } : {}),
1554
+ });
1555
+ }
1556
+ this.tell(agent, occasion, ids, entered, bodies);
1557
+ }
1558
+ return { entered, ...(error !== undefined ? { error } : {}) };
1559
+ }
1560
+
1561
+ /**
1562
+ * Tell the agent's listeners of the rows that entered its window, in
1563
+ * order, each body as the window holds it. Where the window can't be
1564
+ * read for that, they are told of each entered row by its first shard
1565
+ * (a body's later shards left out), and that is logged: the rows are in
1566
+ * the window whatever the read, so the listeners (noteArrival, the
1567
+ * subconscious's anchor) still hear them.
1568
+ */
1569
+ private tell(
1570
+ agent: PresentedAgent,
1571
+ occasion: PresentationOccasion,
1572
+ ids: readonly MessageId[],
1573
+ entered: ReadonlySet<MessageId>,
1574
+ bodies?: readonly PendingBody[],
1575
+ ): void {
1576
+ const listeners = this.listeners.get(agent.name);
1577
+ if (!listeners || listeners.size === 0) return;
1578
+ const cm = agent.getContextManager();
1579
+ const byHead = new Map((bodies ?? []).map((body) => [body.shards[0]!.id, body.shards] as const));
1580
+ let window: StoredMessage[] | undefined;
1581
+ const named = ids.filter((id) => entered.has(id));
1582
+ let rows: StoredMessage[];
1583
+ try {
1584
+ rows = named.flatMap((id) => {
1585
+ const shards = byHead.get(id);
1586
+ if (shards) return shards.filter((shard) => cm.ordinalOf(shard.id) !== undefined);
1587
+ // A row named alone (an own row at its write): its body as the window now holds it.
1588
+ window ??= cm.getPresentedMessages();
1589
+ const at = window.findIndex((m) => m.id === id);
1590
+ if (at === -1) return [];
1591
+ let end = at + 1;
1592
+ while (end < window.length && continuesBody(window[end - 1], window[end])) end++;
1593
+ return window.slice(at, end);
1594
+ });
1595
+ } catch (error) {
1596
+ console.error(`[presentation] ${agent.name}'s window couldn't be read to tell its listeners which rows entered it, so they are told of each by its first shard:`, error);
1597
+ rows = named.flatMap((id) => {
1598
+ const head = byHead.get(id)?.[0];
1599
+ if (head) return [head];
1600
+ try {
1601
+ const row = cm.getMessage(id);
1602
+ return row ? [row] : [];
1603
+ } catch {
1604
+ return [];
1605
+ }
1606
+ });
1607
+ }
1608
+ for (const listener of [...listeners]) {
1609
+ try {
1610
+ listener({ agentName: agent.name, occasion, rows });
1611
+ } catch (error) {
1612
+ console.error(`[presentation] a listener of ${agent.name}'s window failed:`, error);
1613
+ }
1614
+ }
1615
+ }
1616
+
1617
+ /**
1618
+ * A presentation that failed, logged and traced (presentation:failed):
1619
+ * `ids` are the rows it named that didn't enter the window (a body by
1620
+ * the id that names it), where they are known, and `next` says what
1621
+ * becomes of them.
1622
+ */
1623
+ private failed(
1624
+ agent: PresentedAgent,
1625
+ occasion: PresentationOccasion,
1626
+ error: unknown,
1627
+ ids?: readonly MessageId[],
1628
+ next = "what it didn't present waits for the next point",
1629
+ ): void {
1630
+ const left = ids !== undefined && ids.length > 0 ? [...ids] : undefined;
1631
+ const named = left
1632
+ ? ` ${left.length} row${left.length === 1 ? '' : 's'} (${left.slice(0, 10).join(', ')}${left.length > 10 ? ', …' : ''})`
1633
+ : '';
1634
+ console.error(`[presentation] ${agent.name}: presenting${named} at ${occasion} failed; ${next}:`, error);
1635
+ this.host.emitTrace({
1636
+ type: 'presentation:failed', agentName: agent.name, occasion, error: describe(error), ...(left ? { messageIds: left } : {}),
1637
+ });
1638
+ }
1639
+ }
1640
+
1641
+ /** Whether `cm`'s window reads as presented; a mode that can't be read is not. */
1642
+ function readsPresented(cm: Pick<WindowManager, 'windowMode'>): boolean {
1643
+ try {
1644
+ return cm.windowMode() === 'presented';
1645
+ } catch {
1646
+ return false;
1647
+ }
1648
+ }
1649
+
1650
+ /** The defined ids, each once, in order. */
1651
+ function unique(ids: ReadonlyArray<MessageId | undefined>): MessageId[] {
1652
+ const seen = new Set<MessageId>();
1653
+ const out: MessageId[] = [];
1654
+ for (const id of ids) {
1655
+ if (id === undefined || seen.has(id)) continue;
1656
+ seen.add(id);
1657
+ out.push(id);
1658
+ }
1659
+ return out;
1660
+ }
1661
+
1662
+ /** How many bodies a window holds, a sharded one counted once. */
1663
+ function bodyHeadCount(window: readonly StoredMessage[]): number {
1664
+ let count = 0;
1665
+ for (let i = 0; i < window.length; i++) if (i === 0 || !continuesBody(window[i - 1], window[i])) count++;
1666
+ return count;
1667
+ }
1668
+
1669
+ /** The ids of the last `count` bodies of a window, by their first shards, in window order. */
1670
+ function lastBodyHeads(window: readonly StoredMessage[], count: number): MessageId[] {
1671
+ const heads: MessageId[] = [];
1672
+ for (let i = window.length - 1; i >= 0 && heads.length < count; i--) {
1673
+ if (i === 0 || !continuesBody(window[i - 1], window[i])) heads.unshift(window[i]!.id);
1674
+ }
1675
+ return heads;
1676
+ }