@memberjunction/ng-conversations 6.2.0-edge.3 → 6.2.0-edge.5

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 (318) hide show
  1. package/README.md +33 -7
  2. package/dist/lib/components/collection/collection-view.component.d.ts.map +1 -1
  3. package/dist/lib/components/collection/collection-view.component.js +1 -0
  4. package/dist/lib/components/collection/collection-view.component.js.map +1 -1
  5. package/dist/lib/components/composer/ai-composer.component.d.ts +14 -2
  6. package/dist/lib/components/composer/ai-composer.component.d.ts.map +1 -1
  7. package/dist/lib/components/composer/ai-composer.component.js +35 -4
  8. package/dist/lib/components/composer/ai-composer.component.js.map +1 -1
  9. package/dist/lib/components/conversation/conversation-agent-picker.component.d.ts +1 -1
  10. package/dist/lib/components/conversation/conversation-agent-picker.component.js +3 -3
  11. package/dist/lib/components/conversation/conversation-agent-picker.component.js.map +1 -1
  12. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +651 -53
  13. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
  14. package/dist/lib/components/conversation/conversation-chat-area.component.js +3002 -661
  15. package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
  16. package/dist/lib/components/conversation/forks-popover.component.d.ts +37 -0
  17. package/dist/lib/components/conversation/forks-popover.component.d.ts.map +1 -0
  18. package/dist/lib/components/conversation/forks-popover.component.js +164 -0
  19. package/dist/lib/components/conversation/forks-popover.component.js.map +1 -0
  20. package/dist/lib/components/export/export-modal.component.d.ts +7 -2
  21. package/dist/lib/components/export/export-modal.component.d.ts.map +1 -1
  22. package/dist/lib/components/export/export-modal.component.js +16 -3
  23. package/dist/lib/components/export/export-modal.component.js.map +1 -1
  24. package/dist/lib/components/message/conversation-message-rating.component.d.ts.map +1 -1
  25. package/dist/lib/components/message/conversation-message-rating.component.js +11 -9
  26. package/dist/lib/components/message/conversation-message-rating.component.js.map +1 -1
  27. package/dist/lib/components/message/message-input.component.d.ts +96 -11
  28. package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
  29. package/dist/lib/components/message/message-input.component.js +253 -112
  30. package/dist/lib/components/message/message-input.component.js.map +1 -1
  31. package/dist/lib/components/message/message-item.component.d.ts +304 -16
  32. package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
  33. package/dist/lib/components/message/message-item.component.js +2029 -363
  34. package/dist/lib/components/message/message-item.component.js.map +1 -1
  35. package/dist/lib/components/message/message-list.component.d.ts +101 -22
  36. package/dist/lib/components/message/message-list.component.d.ts.map +1 -1
  37. package/dist/lib/components/message/message-list.component.js +326 -55
  38. package/dist/lib/components/message/message-list.component.js.map +1 -1
  39. package/dist/lib/components/realtime/avatar/realtime-avatar-channel.d.ts +34 -0
  40. package/dist/lib/components/realtime/avatar/realtime-avatar-channel.d.ts.map +1 -0
  41. package/dist/lib/components/realtime/avatar/realtime-avatar-channel.js +75 -0
  42. package/dist/lib/components/realtime/avatar/realtime-avatar-channel.js.map +1 -0
  43. package/dist/lib/components/realtime/avatar/realtime-avatar-surface.component.d.ts +80 -0
  44. package/dist/lib/components/realtime/avatar/realtime-avatar-surface.component.d.ts.map +1 -0
  45. package/dist/lib/components/realtime/avatar/realtime-avatar-surface.component.js +202 -0
  46. package/dist/lib/components/realtime/avatar/realtime-avatar-surface.component.js.map +1 -0
  47. package/dist/lib/components/realtime/capture/realtime-camera-check-card.component.d.ts +45 -0
  48. package/dist/lib/components/realtime/capture/realtime-camera-check-card.component.d.ts.map +1 -0
  49. package/dist/lib/components/realtime/capture/realtime-camera-check-card.component.js +123 -0
  50. package/dist/lib/components/realtime/capture/realtime-camera-check-card.component.js.map +1 -0
  51. package/dist/lib/components/realtime/capture/realtime-capture-channel.d.ts +90 -0
  52. package/dist/lib/components/realtime/capture/realtime-capture-channel.d.ts.map +1 -0
  53. package/dist/lib/components/realtime/capture/realtime-capture-channel.js +223 -0
  54. package/dist/lib/components/realtime/capture/realtime-capture-channel.js.map +1 -0
  55. package/dist/lib/components/realtime/capture/realtime-capture-model.d.ts +98 -0
  56. package/dist/lib/components/realtime/capture/realtime-capture-model.d.ts.map +1 -0
  57. package/dist/lib/components/realtime/capture/realtime-capture-model.js +161 -0
  58. package/dist/lib/components/realtime/capture/realtime-capture-model.js.map +1 -0
  59. package/dist/lib/components/realtime/capture/realtime-capture-surface.component.d.ts +48 -0
  60. package/dist/lib/components/realtime/capture/realtime-capture-surface.component.d.ts.map +1 -0
  61. package/dist/lib/components/realtime/capture/realtime-capture-surface.component.js +205 -0
  62. package/dist/lib/components/realtime/capture/realtime-capture-surface.component.js.map +1 -0
  63. package/dist/lib/components/realtime/channels/client-context-channel.d.ts +19 -2
  64. package/dist/lib/components/realtime/channels/client-context-channel.d.ts.map +1 -1
  65. package/dist/lib/components/realtime/channels/client-context-channel.js +83 -9
  66. package/dist/lib/components/realtime/channels/client-context-channel.js.map +1 -1
  67. package/dist/lib/components/realtime/channels/realtime-channel-pane.component.d.ts +30 -9
  68. package/dist/lib/components/realtime/channels/realtime-channel-pane.component.d.ts.map +1 -1
  69. package/dist/lib/components/realtime/channels/realtime-channel-pane.component.js +78 -14
  70. package/dist/lib/components/realtime/channels/realtime-channel-pane.component.js.map +1 -1
  71. package/dist/lib/components/realtime/identity-verification/identity-verification-channel.d.ts +71 -0
  72. package/dist/lib/components/realtime/identity-verification/identity-verification-channel.d.ts.map +1 -0
  73. package/dist/lib/components/realtime/identity-verification/identity-verification-channel.js +259 -0
  74. package/dist/lib/components/realtime/identity-verification/identity-verification-channel.js.map +1 -0
  75. package/dist/lib/components/realtime/identity-verification/identity-verification-model.d.ts +129 -0
  76. package/dist/lib/components/realtime/identity-verification/identity-verification-model.d.ts.map +1 -0
  77. package/dist/lib/components/realtime/identity-verification/identity-verification-model.js +373 -0
  78. package/dist/lib/components/realtime/identity-verification/identity-verification-model.js.map +1 -0
  79. package/dist/lib/components/realtime/identity-verification/identity-verification-surface.component.d.ts +77 -0
  80. package/dist/lib/components/realtime/identity-verification/identity-verification-surface.component.d.ts.map +1 -0
  81. package/dist/lib/components/realtime/identity-verification/identity-verification-surface.component.js +420 -0
  82. package/dist/lib/components/realtime/identity-verification/identity-verification-surface.component.js.map +1 -0
  83. package/dist/lib/components/realtime/interactive-component/component-contract.d.ts +83 -0
  84. package/dist/lib/components/realtime/interactive-component/component-contract.d.ts.map +1 -0
  85. package/dist/lib/components/realtime/interactive-component/component-contract.js +292 -0
  86. package/dist/lib/components/realtime/interactive-component/component-contract.js.map +1 -0
  87. package/dist/lib/components/realtime/interactive-component/component-data-state.d.ts +39 -0
  88. package/dist/lib/components/realtime/interactive-component/component-data-state.d.ts.map +1 -0
  89. package/dist/lib/components/realtime/interactive-component/component-data-state.js +152 -0
  90. package/dist/lib/components/realtime/interactive-component/component-data-state.js.map +1 -0
  91. package/dist/lib/components/realtime/interactive-component/component-instance-engine.d.ts +109 -0
  92. package/dist/lib/components/realtime/interactive-component/component-instance-engine.d.ts.map +1 -0
  93. package/dist/lib/components/realtime/interactive-component/component-instance-engine.js +146 -0
  94. package/dist/lib/components/realtime/interactive-component/component-instance-engine.js.map +1 -0
  95. package/dist/lib/components/realtime/interactive-component/component-spec-content.d.ts +19 -0
  96. package/dist/lib/components/realtime/interactive-component/component-spec-content.d.ts.map +1 -0
  97. package/dist/lib/components/realtime/interactive-component/component-spec-content.js +39 -0
  98. package/dist/lib/components/realtime/interactive-component/component-spec-content.js.map +1 -0
  99. package/dist/lib/components/realtime/interactive-component/interactive-component-channel.d.ts +183 -0
  100. package/dist/lib/components/realtime/interactive-component/interactive-component-channel.d.ts.map +1 -0
  101. package/dist/lib/components/realtime/interactive-component/interactive-component-channel.js +761 -0
  102. package/dist/lib/components/realtime/interactive-component/interactive-component-channel.js.map +1 -0
  103. package/dist/lib/components/realtime/interactive-component/interactive-component-config.d.ts +25 -0
  104. package/dist/lib/components/realtime/interactive-component/interactive-component-config.d.ts.map +1 -0
  105. package/dist/lib/components/realtime/interactive-component/interactive-component-config.js +57 -0
  106. package/dist/lib/components/realtime/interactive-component/interactive-component-config.js.map +1 -0
  107. package/dist/lib/components/realtime/interactive-component/interactive-component-host.component.d.ts +40 -0
  108. package/dist/lib/components/realtime/interactive-component/interactive-component-host.component.d.ts.map +1 -0
  109. package/dist/lib/components/realtime/interactive-component/interactive-component-host.component.js +97 -0
  110. package/dist/lib/components/realtime/interactive-component/interactive-component-host.component.js.map +1 -0
  111. package/dist/lib/components/realtime/interactive-component/interactive-component-types.d.ts +144 -0
  112. package/dist/lib/components/realtime/interactive-component/interactive-component-types.d.ts.map +1 -0
  113. package/dist/lib/components/realtime/interactive-component/interactive-component-types.js +57 -0
  114. package/dist/lib/components/realtime/interactive-component/interactive-component-types.js.map +1 -0
  115. package/dist/lib/components/realtime/interactive-component/react-component-handle.d.ts +36 -0
  116. package/dist/lib/components/realtime/interactive-component/react-component-handle.d.ts.map +1 -0
  117. package/dist/lib/components/realtime/interactive-component/react-component-handle.js +55 -0
  118. package/dist/lib/components/realtime/interactive-component/react-component-handle.js.map +1 -0
  119. package/dist/lib/components/realtime/interactive-component/realtime-interactive-component-surface.component.d.ts +55 -0
  120. package/dist/lib/components/realtime/interactive-component/realtime-interactive-component-surface.component.d.ts.map +1 -0
  121. package/dist/lib/components/realtime/interactive-component/realtime-interactive-component-surface.component.js +210 -0
  122. package/dist/lib/components/realtime/interactive-component/realtime-interactive-component-surface.component.js.map +1 -0
  123. package/dist/lib/components/realtime/interactive-component/run-view-component-artifact-source.d.ts +32 -0
  124. package/dist/lib/components/realtime/interactive-component/run-view-component-artifact-source.d.ts.map +1 -0
  125. package/dist/lib/components/realtime/interactive-component/run-view-component-artifact-source.js +90 -0
  126. package/dist/lib/components/realtime/interactive-component/run-view-component-artifact-source.js.map +1 -0
  127. package/dist/lib/components/realtime/media/media-channel.d.ts +7 -0
  128. package/dist/lib/components/realtime/media/media-channel.d.ts.map +1 -1
  129. package/dist/lib/components/realtime/media/media-channel.js +28 -1
  130. package/dist/lib/components/realtime/media/media-channel.js.map +1 -1
  131. package/dist/lib/components/realtime/realtime-agent-banner.component.d.ts +8 -1
  132. package/dist/lib/components/realtime/realtime-agent-banner.component.d.ts.map +1 -1
  133. package/dist/lib/components/realtime/realtime-agent-banner.component.js +89 -71
  134. package/dist/lib/components/realtime/realtime-agent-banner.component.js.map +1 -1
  135. package/dist/lib/components/realtime/realtime-agent-orb.component.d.ts +21 -0
  136. package/dist/lib/components/realtime/realtime-agent-orb.component.d.ts.map +1 -0
  137. package/dist/lib/components/realtime/realtime-agent-orb.component.js +49 -0
  138. package/dist/lib/components/realtime/realtime-agent-orb.component.js.map +1 -0
  139. package/dist/lib/components/realtime/realtime-agent-picker.component.d.ts +44 -11
  140. package/dist/lib/components/realtime/realtime-agent-picker.component.d.ts.map +1 -1
  141. package/dist/lib/components/realtime/realtime-agent-picker.component.js +162 -50
  142. package/dist/lib/components/realtime/realtime-agent-picker.component.js.map +1 -1
  143. package/dist/lib/components/realtime/realtime-audio-visuals.d.ts +8 -2
  144. package/dist/lib/components/realtime/realtime-audio-visuals.d.ts.map +1 -1
  145. package/dist/lib/components/realtime/realtime-audio-visuals.js +14 -18
  146. package/dist/lib/components/realtime/realtime-audio-visuals.js.map +1 -1
  147. package/dist/lib/components/realtime/realtime-composer.component.d.ts +42 -2
  148. package/dist/lib/components/realtime/realtime-composer.component.d.ts.map +1 -1
  149. package/dist/lib/components/realtime/realtime-composer.component.js +137 -102
  150. package/dist/lib/components/realtime/realtime-composer.component.js.map +1 -1
  151. package/dist/lib/components/realtime/realtime-perception-chip.component.d.ts +71 -0
  152. package/dist/lib/components/realtime/realtime-perception-chip.component.d.ts.map +1 -0
  153. package/dist/lib/components/realtime/realtime-perception-chip.component.js +221 -0
  154. package/dist/lib/components/realtime/realtime-perception-chip.component.js.map +1 -0
  155. package/dist/lib/components/realtime/realtime-session-overlay.component.d.ts +264 -22
  156. package/dist/lib/components/realtime/realtime-session-overlay.component.d.ts.map +1 -1
  157. package/dist/lib/components/realtime/realtime-session-overlay.component.js +851 -135
  158. package/dist/lib/components/realtime/realtime-session-overlay.component.js.map +1 -1
  159. package/dist/lib/components/realtime/realtime-surface-placement-prefs.d.ts +14 -0
  160. package/dist/lib/components/realtime/realtime-surface-placement-prefs.d.ts.map +1 -0
  161. package/dist/lib/components/realtime/realtime-surface-placement-prefs.js +14 -0
  162. package/dist/lib/components/realtime/realtime-surface-placement-prefs.js.map +1 -0
  163. package/dist/lib/components/realtime/realtime-surface-stage.model.d.ts +74 -0
  164. package/dist/lib/components/realtime/realtime-surface-stage.model.d.ts.map +1 -0
  165. package/dist/lib/components/realtime/realtime-surface-stage.model.js +171 -0
  166. package/dist/lib/components/realtime/realtime-surface-stage.model.js.map +1 -0
  167. package/dist/lib/components/realtime/realtime-surface-tabs.component.d.ts +71 -13
  168. package/dist/lib/components/realtime/realtime-surface-tabs.component.d.ts.map +1 -1
  169. package/dist/lib/components/realtime/realtime-surface-tabs.component.js +232 -73
  170. package/dist/lib/components/realtime/realtime-surface-tabs.component.js.map +1 -1
  171. package/dist/lib/components/realtime/realtime-surface-tabs.model.d.ts +5 -0
  172. package/dist/lib/components/realtime/realtime-surface-tabs.model.d.ts.map +1 -1
  173. package/dist/lib/components/realtime/realtime-surface-tabs.model.js +8 -0
  174. package/dist/lib/components/realtime/realtime-surface-tabs.model.js.map +1 -1
  175. package/dist/lib/components/realtime/realtime-ui-config.d.ts +12 -2
  176. package/dist/lib/components/realtime/realtime-ui-config.d.ts.map +1 -1
  177. package/dist/lib/components/realtime/realtime-ui-config.js +5 -1
  178. package/dist/lib/components/realtime/realtime-ui-config.js.map +1 -1
  179. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts +10 -1
  180. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts.map +1 -1
  181. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js +42 -2
  182. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js.map +1 -1
  183. package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.d.ts +20 -3
  184. package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.d.ts.map +1 -1
  185. package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.js +44 -10
  186. package/dist/lib/components/realtime/remote-browser/remote-browser-surface.component.js.map +1 -1
  187. package/dist/lib/components/realtime/whiteboard/whiteboard-channel.d.ts +28 -44
  188. package/dist/lib/components/realtime/whiteboard/whiteboard-channel.d.ts.map +1 -1
  189. package/dist/lib/components/realtime/whiteboard/whiteboard-channel.js +76 -162
  190. package/dist/lib/components/realtime/whiteboard/whiteboard-channel.js.map +1 -1
  191. package/dist/lib/components/search/search-panel.component.d.ts +2 -0
  192. package/dist/lib/components/search/search-panel.component.d.ts.map +1 -1
  193. package/dist/lib/components/search/search-panel.component.js +25 -12
  194. package/dist/lib/components/search/search-panel.component.js.map +1 -1
  195. package/dist/lib/components/sidebar/routines-section.component.js +1 -1
  196. package/dist/lib/components/sidebar/routines-section.component.js.map +1 -1
  197. package/dist/lib/components/task/tasks-full-view.component.d.ts +152 -31
  198. package/dist/lib/components/task/tasks-full-view.component.d.ts.map +1 -1
  199. package/dist/lib/components/task/tasks-full-view.component.js +2227 -214
  200. package/dist/lib/components/task/tasks-full-view.component.js.map +1 -1
  201. package/dist/lib/components/tasks/tasks-dropdown.component.js +4 -4
  202. package/dist/lib/components/tasks/tasks-dropdown.component.js.map +1 -1
  203. package/dist/lib/components/workspace/conversation-workspace.component.d.ts +33 -32
  204. package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
  205. package/dist/lib/components/workspace/conversation-workspace.component.js +72 -88
  206. package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
  207. package/dist/lib/conversations.module.d.ts +30 -29
  208. package/dist/lib/conversations.module.d.ts.map +1 -1
  209. package/dist/lib/conversations.module.js +27 -5
  210. package/dist/lib/conversations.module.js.map +1 -1
  211. package/dist/lib/events/chat-events.d.ts +25 -0
  212. package/dist/lib/events/chat-events.d.ts.map +1 -1
  213. package/dist/lib/events/chat-events.js +36 -0
  214. package/dist/lib/events/chat-events.js.map +1 -1
  215. package/dist/lib/models/agent-turn.model.d.ts +5 -0
  216. package/dist/lib/models/agent-turn.model.d.ts.map +1 -1
  217. package/dist/lib/models/agent-turn.model.js.map +1 -1
  218. package/dist/lib/services/agent-state.service.d.ts +34 -8
  219. package/dist/lib/services/agent-state.service.d.ts.map +1 -1
  220. package/dist/lib/services/agent-state.service.js +90 -37
  221. package/dist/lib/services/agent-state.service.js.map +1 -1
  222. package/dist/lib/services/artifact-state.service.d.ts +0 -9
  223. package/dist/lib/services/artifact-state.service.d.ts.map +1 -1
  224. package/dist/lib/services/artifact-state.service.js +1 -32
  225. package/dist/lib/services/artifact-state.service.js.map +1 -1
  226. package/dist/lib/services/browser-realtime-media-host.d.ts +19 -7
  227. package/dist/lib/services/browser-realtime-media-host.d.ts.map +1 -1
  228. package/dist/lib/services/browser-realtime-media-host.js +21 -72
  229. package/dist/lib/services/browser-realtime-media-host.js.map +1 -1
  230. package/dist/lib/services/conversation-agent.service.d.ts +48 -16
  231. package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
  232. package/dist/lib/services/conversation-agent.service.js +110 -35
  233. package/dist/lib/services/conversation-agent.service.js.map +1 -1
  234. package/dist/lib/services/conversation-detail-window.store.d.ts +22 -4
  235. package/dist/lib/services/conversation-detail-window.store.d.ts.map +1 -1
  236. package/dist/lib/services/conversation-detail-window.store.js +50 -9
  237. package/dist/lib/services/conversation-detail-window.store.js.map +1 -1
  238. package/dist/lib/services/conversation-naming.d.ts +72 -22
  239. package/dist/lib/services/conversation-naming.d.ts.map +1 -1
  240. package/dist/lib/services/conversation-naming.js +93 -12
  241. package/dist/lib/services/conversation-naming.js.map +1 -1
  242. package/dist/lib/services/conversation-tasks-filter.d.ts +15 -0
  243. package/dist/lib/services/conversation-tasks-filter.d.ts.map +1 -0
  244. package/dist/lib/services/conversation-tasks-filter.js +69 -0
  245. package/dist/lib/services/conversation-tasks-filter.js.map +1 -0
  246. package/dist/lib/services/data-cache.service.d.ts +13 -5
  247. package/dist/lib/services/data-cache.service.d.ts.map +1 -1
  248. package/dist/lib/services/data-cache.service.js +39 -19
  249. package/dist/lib/services/data-cache.service.js.map +1 -1
  250. package/dist/lib/services/export.service.d.ts +26 -9
  251. package/dist/lib/services/export.service.d.ts.map +1 -1
  252. package/dist/lib/services/export.service.js +61 -18
  253. package/dist/lib/services/export.service.js.map +1 -1
  254. package/dist/lib/services/realtime-audio-recorder.d.ts +115 -79
  255. package/dist/lib/services/realtime-audio-recorder.d.ts.map +1 -1
  256. package/dist/lib/services/realtime-audio-recorder.js +273 -186
  257. package/dist/lib/services/realtime-audio-recorder.js.map +1 -1
  258. package/dist/lib/services/realtime-pairing.d.ts +10 -5
  259. package/dist/lib/services/realtime-pairing.d.ts.map +1 -1
  260. package/dist/lib/services/realtime-pairing.js +15 -6
  261. package/dist/lib/services/realtime-pairing.js.map +1 -1
  262. package/dist/lib/services/realtime-session.service.d.ts +31 -2
  263. package/dist/lib/services/realtime-session.service.d.ts.map +1 -1
  264. package/dist/lib/services/realtime-session.service.js +34 -2
  265. package/dist/lib/services/realtime-session.service.js.map +1 -1
  266. package/dist/lib/services/recording/libopus-wasm-binary.d.ts +3 -0
  267. package/dist/lib/services/recording/libopus-wasm-binary.d.ts.map +1 -0
  268. package/dist/lib/services/recording/libopus-wasm-binary.js +489 -0
  269. package/dist/lib/services/recording/libopus-wasm-binary.js.map +1 -0
  270. package/dist/lib/services/recording/libopus-worker-source.d.ts +48 -0
  271. package/dist/lib/services/recording/libopus-worker-source.d.ts.map +1 -0
  272. package/dist/lib/services/recording/libopus-worker-source.js +170 -0
  273. package/dist/lib/services/recording/libopus-worker-source.js.map +1 -0
  274. package/dist/lib/services/recording/linear-resampler.d.ts +45 -0
  275. package/dist/lib/services/recording/linear-resampler.d.ts.map +1 -0
  276. package/dist/lib/services/recording/linear-resampler.js +85 -0
  277. package/dist/lib/services/recording/linear-resampler.js.map +1 -0
  278. package/dist/lib/services/recording/opus-packet-encoder.d.ts +50 -0
  279. package/dist/lib/services/recording/opus-packet-encoder.d.ts.map +1 -0
  280. package/dist/lib/services/recording/opus-packet-encoder.js +41 -0
  281. package/dist/lib/services/recording/opus-packet-encoder.js.map +1 -0
  282. package/dist/lib/services/recording/wasm-opus-encoder.d.ts +86 -0
  283. package/dist/lib/services/recording/wasm-opus-encoder.d.ts.map +1 -0
  284. package/dist/lib/services/recording/wasm-opus-encoder.js +232 -0
  285. package/dist/lib/services/recording/wasm-opus-encoder.js.map +1 -0
  286. package/dist/lib/services/recording/webcodecs-opus-encoder.d.ts +39 -0
  287. package/dist/lib/services/recording/webcodecs-opus-encoder.d.ts.map +1 -0
  288. package/dist/lib/services/recording/webcodecs-opus-encoder.js +101 -0
  289. package/dist/lib/services/recording/webcodecs-opus-encoder.js.map +1 -0
  290. package/dist/lib/services/search.service.d.ts +7 -2
  291. package/dist/lib/services/search.service.d.ts.map +1 -1
  292. package/dist/lib/services/search.service.js +16 -20
  293. package/dist/lib/services/search.service.js.map +1 -1
  294. package/dist/lib/utils/conversation-branching.d.ts +4 -0
  295. package/dist/lib/utils/conversation-branching.d.ts.map +1 -0
  296. package/dist/lib/utils/conversation-branching.js +5 -0
  297. package/dist/lib/utils/conversation-branching.js.map +1 -0
  298. package/dist/lib/utils/conversation-forks.d.ts +315 -0
  299. package/dist/lib/utils/conversation-forks.d.ts.map +1 -0
  300. package/dist/lib/utils/conversation-forks.js +456 -0
  301. package/dist/lib/utils/conversation-forks.js.map +1 -0
  302. package/dist/lib/utils/distinct-artifacts.d.ts +9 -3
  303. package/dist/lib/utils/distinct-artifacts.d.ts.map +1 -1
  304. package/dist/lib/utils/distinct-artifacts.js +24 -5
  305. package/dist/lib/utils/distinct-artifacts.js.map +1 -1
  306. package/dist/public-api.d.ts +23 -1
  307. package/dist/public-api.d.ts.map +1 -1
  308. package/dist/public-api.js +30 -1
  309. package/dist/public-api.js.map +1 -1
  310. package/package.json +37 -33
  311. package/dist/lib/components/thread/thread-panel.component.d.ts +0 -126
  312. package/dist/lib/components/thread/thread-panel.component.d.ts.map +0 -1
  313. package/dist/lib/components/thread/thread-panel.component.js +0 -440
  314. package/dist/lib/components/thread/thread-panel.component.js.map +0 -1
  315. package/dist/lib/services/realtime-pcm-wav.d.ts +0 -79
  316. package/dist/lib/services/realtime-pcm-wav.d.ts.map +0 -1
  317. package/dist/lib/services/realtime-pcm-wav.js +0 -213
  318. package/dist/lib/services/realtime-pcm-wav.js.map +0 -1
@@ -6,7 +6,7 @@ import { AIEngineBase } from '@memberjunction/ai-engine-base';
6
6
  import { ConversationEngine } from '@memberjunction/core-entities';
7
7
  import { MJNotificationService } from '@memberjunction/ng-notifications';
8
8
  import { ConversationsRuntime } from '@memberjunction/conversations-runtime';
9
- import { UUIDsEqual } from '@memberjunction/global';
9
+ import { EscapeSQLString, UUIDsEqual } from '@memberjunction/global';
10
10
  import { GroupVersionsByArtifact } from '../utils/agent-artifact-summary';
11
11
  import * as i0 from "@angular/core";
12
12
  import * as i1 from "./conversations-runtime-bootstrap.service";
@@ -115,6 +115,11 @@ export class ConversationAgentService {
115
115
  if (this._conversationManagerAgent) {
116
116
  return this._conversationManagerAgent;
117
117
  }
118
+ // A user who may not read the agents has no manager agent to resolve: say nothing, rather than an error for a state
119
+ // that is theirs by design (MJ#5240)
120
+ if (AIEngineBase.Instance.IsPermissionConstrained && AIEngineBase.Instance.ReadableAgents.length === 0) {
121
+ return null;
122
+ }
118
123
  try {
119
124
  const provider = this.Provider;
120
125
  const agent = await ConversationsRuntime.Instance.DefaultAgent.resolve({
@@ -204,12 +209,19 @@ export class ConversationAgentService {
204
209
  * mention blob (`@{"type":"agent","id":"…","configId":"…"}`). So SQL narrows and the parser
205
210
  * decides — both `configId` and the agent id appear verbatim in that blob, which makes the
206
211
  * two LIKEs a tight prefilter, and `parseMentions` is what actually confirms a match.
212
+ *
213
+ * @param branchId The active branch. Only messages on its path count; null or omitted reads
214
+ * the trunk.
207
215
  */
208
- async FindConfigurationPresetForAgent(conversationId, agentId) {
216
+ async FindConfigurationPresetForAgent(conversationId, agentId, branchId) {
217
+ const pathFilter = await this.branchPathFilter(conversationId, branchId);
218
+ if (pathFilter == null) {
219
+ return undefined;
220
+ }
209
221
  const rv = RunView.FromMetadataProvider(this.Provider);
210
222
  const result = await rv.RunView({
211
223
  EntityName: 'MJ: Conversation Details',
212
- ExtraFilter: `ConversationID='${conversationId}' AND Role='User'`
224
+ ExtraFilter: `${pathFilter} AND Role='User'`
213
225
  + ` AND Message LIKE '%"configId"%' AND Message LIKE '%${agentId}%'`,
214
226
  OrderBy: 'Sequence DESC',
215
227
  // >1 because LIKE cannot tell a mention blob from the same id appearing elsewhere in
@@ -236,7 +248,7 @@ export class ConversationAgentService {
236
248
  if (!message) {
237
249
  return null;
238
250
  }
239
- const parsed = this.mentionParser.parseMentions(message, AIEngineBase.Instance.Agents, []);
251
+ const parsed = this.mentionParser.parseMentions(message, AIEngineBase.Instance.ReadableAgents, []);
240
252
  const mention = parsed.agentMention;
241
253
  return mention?.id === agentId && mention.configurationId ? mention.configurationId : null;
242
254
  }
@@ -281,7 +293,7 @@ export class ConversationAgentService {
281
293
  // Ensure AIEngineBase is configured
282
294
  await AIEngineBase.Instance.Config(false);
283
295
  // Find the agent by name
284
- const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);
296
+ const agent = AIEngineBase.Instance.ReadableAgents.find(a => a.Name === agentName);
285
297
  if (!agent || !agent.ID) {
286
298
  const errorMsg = `Sub-agent "${agentName}" not found`;
287
299
  console.warn(`${errorMsg}`);
@@ -360,8 +372,11 @@ export class ConversationAgentService {
360
372
  *
361
373
  * Stays on the Angular shim because it directly uses GraphQLAIClient.
362
374
  * Could move to the runtime in a follow-up.
375
+ *
376
+ * @param branchId The active branch. Only the agent's artifacts on its path are listed for the
377
+ * classifier; null or omitted reads the trunk.
363
378
  */
364
- async CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory) {
379
+ async CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory, branchId) {
365
380
  if (!this._aiClient) {
366
381
  console.warn('AI Client not initialized, defaulting to UNSURE for intent check');
367
382
  return { decision: 'UNSURE', reasoning: 'AI Client not initialized' };
@@ -373,7 +388,7 @@ export class ConversationAgentService {
373
388
  console.warn('⚠️ Check Sage Intent prompt not found, defaulting to UNSURE');
374
389
  return { decision: 'UNSURE', reasoning: 'Check Sage Intent prompt not found' };
375
390
  }
376
- const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, agentId));
391
+ const agent = AIEngineBase.Instance.ReadableAgents.find(a => UUIDsEqual(a.ID, agentId));
377
392
  if (!agent) {
378
393
  console.warn('⚠️ Previous agent not found, defaulting to UNSURE');
379
394
  return { decision: 'UNSURE', reasoning: 'Previous agent not found' };
@@ -381,7 +396,7 @@ export class ConversationAgentService {
381
396
  // Queried, not read off the caller's window-scoped maps — see findAllAgentArtifacts.
382
397
  // `conversationHistory` below is still the window on purpose: the `.slice(-10)` wants
383
398
  // the most recent exchange, which the loaded tail always contains.
384
- const agentArtifacts = await this.findAllAgentArtifacts(conversationId, agentId);
399
+ const agentArtifacts = await this.findAllAgentArtifacts(conversationId, agentId, undefined, branchId);
385
400
  const recentHistory = conversationHistory.slice(-10);
386
401
  const compactHistory = recentHistory.map((msg, idx) => {
387
402
  const role = msg.Role === 'User' ? 'User' : agent.Name || 'Agent';
@@ -455,8 +470,8 @@ ${compactHistory}${artifactContext}
455
470
  }
456
471
  }
457
472
  /** @deprecated Use {@link CheckAgentContinuityIntent}. */
458
- async checkAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory) {
459
- return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory);
473
+ async checkAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory, branchId) {
474
+ return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory, branchId);
460
475
  }
461
476
  /**
462
477
  * Runs a typed decision on the server in one round trip, through
@@ -473,18 +488,20 @@ ${compactHistory}${artifactContext}
473
488
  return this._aiClient.RunDecision(params);
474
489
  }
475
490
  /**
476
- * Every artifact this agent produced in this conversation, newest version first, for decision
477
- * routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.
491
+ * Every artifact this agent produced on the active branch path, newest version first, for
492
+ * decision routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.
478
493
  *
479
494
  * @param historyFrom The chat's history floor. When set, only artifacts on replies written at or
480
495
  * after it count, as with {@link FindLatestAgentOutputVersion}.
496
+ * @param branchId The active branch. Only artifacts on its path count, as with
497
+ * {@link FindLatestAgentOutputVersion}; null or omitted reads the trunk.
481
498
  */
482
- async FindAgentArtifacts(conversationId, agentId, historyFrom) {
483
- return this.findAllAgentArtifacts(conversationId, agentId, historyFrom);
499
+ async FindAgentArtifacts(conversationId, agentId, historyFrom, branchId) {
500
+ return this.findAllAgentArtifacts(conversationId, agentId, historyFrom, branchId);
484
501
  }
485
502
  /**
486
- * Every artifact this agent produced in this conversation, newest version first — resolved
487
- * by QUERY, not by scanning the display array.
503
+ * Every artifact this agent produced on the active branch path, newest version first —
504
+ * resolved by QUERY, not by scanning the display array.
488
505
  *
489
506
  * The scan this replaces walked `conversationDetails` and looked each row up in the
490
507
  * caller's `artifactsByDetailId` / `agentRunsByDetailId` maps. Both are scoped to the
@@ -498,16 +515,21 @@ ${compactHistory}${artifactContext}
498
515
  * plausible, and wrong: the same failure class as {@link FindLatestAgentOutputVersion},
499
516
  * closed the same way.
500
517
  *
501
- * Two reads, not the four the old shape would have needed — see
518
+ * Three reads: the agent's replies, their Output versions, and the artifacts' names. See
502
519
  * {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.
503
520
  *
504
521
  * @param historyFrom The chat's history floor, when set (see {@link FindAgentArtifacts}).
522
+ * @param branchId The branch whose path to read; null or omitted reads the trunk.
505
523
  */
506
- async findAllAgentArtifacts(conversationId, agentId, historyFrom) {
524
+ async findAllAgentArtifacts(conversationId, agentId, historyFrom, branchId) {
525
+ const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId, historyFrom, branchId);
526
+ if (!versionFilter) {
527
+ return []; // the classifier degrades to no artifact context
528
+ }
507
529
  const rv = RunView.FromMetadataProvider(this.Provider);
508
530
  const versionResult = await rv.RunView({
509
531
  EntityName: 'MJ: Artifact Versions',
510
- ExtraFilter: this.agentOutputVersionFilter(conversationId, agentId, historyFrom),
532
+ ExtraFilter: versionFilter,
511
533
  OrderBy: '__mj_CreatedAt DESC',
512
534
  MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,
513
535
  Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],
@@ -549,37 +571,90 @@ ${compactHistory}${artifactContext}
549
571
  * again" exchanges where payload continuity matters most. A null payload is a LEGAL agent
550
572
  * input, so the failure is silent: the agent regenerates from scratch instead of modifying.
551
573
  *
552
- * One round trip. The subquery walks details -> Output junctions, and versions carry
574
+ * Two reads: the agent's replies, then their newest Output version. Versions carry
553
575
  * `__mj_CreatedAt`, so "newest" is expressible without joining back for `Sequence`.
554
576
  *
555
577
  * @param historyFrom The chat's history floor. When set, only artifacts on replies written at
556
578
  * or after it count: a run that may not read earlier messages must not pick up their work
557
579
  * as its payload either.
580
+ * @param branchId The active branch. Only replies on its path count, so an artifact made on
581
+ * another branch is never the latest here; null or omitted reads the trunk.
558
582
  */
559
- async FindLatestAgentOutputVersion(conversationId, agentId, historyFrom) {
560
- return this.runPayloadSourceQuery(this.agentOutputVersionFilter(conversationId, agentId, historyFrom), '__mj_CreatedAt DESC');
583
+ async FindLatestAgentOutputVersion(conversationId, agentId, historyFrom, branchId) {
584
+ const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId, historyFrom, branchId);
585
+ return versionFilter ? this.runPayloadSourceQuery(versionFilter, '__mj_CreatedAt DESC') : null;
561
586
  }
562
587
  /**
563
- * `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced in one
564
- * conversation. Shared by {@link FindLatestAgentOutputVersion} and
565
- * {@link findAllAgentArtifacts} so the two can never disagree about what "this agent's
566
- * artifacts" means.
588
+ * `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced on one
589
+ * conversation path, in messages no rerun replaced, or null when the agent has no such reply
590
+ * there. Shared by {@link FindLatestAgentOutputVersion} and {@link findAllAgentArtifacts} so
591
+ * the two can never disagree about what "this agent's artifacts" means.
592
+ *
593
+ * The replies are read with their own RunView ({@link agentReplyIds}), so the row-level
594
+ * security on conversation messages applies. A subquery over their view would skip it, and the
595
+ * server refuses one for a user whose read of messages is row-filtered.
596
+ */
597
+ async agentOutputVersionFilter(conversationId, agentId, historyFrom, branchId) {
598
+ const replyIds = await this.agentReplyIds(conversationId, agentId, historyFrom, branchId);
599
+ if (replyIds.length === 0) {
600
+ return null;
601
+ }
602
+ const inReplies = replyIds.map(id => `'${EscapeSQLString(id)}'`).join(',');
603
+ return `ID IN (
604
+ SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]
605
+ WHERE Direction='Output' AND ConversationDetailID IN (${inReplies})
606
+ )`;
607
+ }
608
+ /**
609
+ * IDs of the agent's replies on one conversation path, in messages no rerun replaced, written
610
+ * at or after the history floor when one is set. Empty when the path cannot be built
611
+ * ({@link branchPathFilter}) or the read fails.
567
612
  *
568
613
  * Filters on the DETAIL's `Status <> 'Error'` rather than the agent run's
569
614
  * `Status = 'Completed'` (which is what the array scan this replaced used). Doing it on the
570
615
  * run would mean joining back to `MJ: AI Agent Runs` purely to restate a condition the
571
616
  * detail already carries.
572
617
  */
573
- agentOutputVersionFilter(conversationId, agentId, historyFrom) {
618
+ async agentReplyIds(conversationId, agentId, historyFrom, branchId) {
619
+ const pathFilter = await this.branchPathFilter(conversationId, branchId);
620
+ if (pathFilter == null) {
621
+ return [];
622
+ }
574
623
  const floor = historyFrom ? ` AND ${ConversationEngine.HistoryFromFilter(historyFrom)}` : '';
575
- return `ID IN (
576
- SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]
577
- WHERE Direction='Output' AND ConversationDetailID IN (
578
- SELECT ID FROM [__mj].[vwConversationDetails]
579
- WHERE ConversationID='${conversationId}' AND AgentID='${agentId}'
580
- AND Role='AI' AND Status <> 'Error'${floor}
581
- )
582
- )`;
624
+ const rv = RunView.FromMetadataProvider(this.Provider);
625
+ const result = await rv.RunView({
626
+ EntityName: 'MJ: Conversation Details',
627
+ ExtraFilter: `${ConversationEngine.LiveRowsFilter(pathFilter)} AND AgentID='${EscapeSQLString(agentId)}'` +
628
+ ` AND Role='AI' AND Status <> 'Error'${floor}`,
629
+ Fields: ['ID'],
630
+ ResultType: 'simple',
631
+ IgnoreMaxRows: true
632
+ }, this.Provider.CurrentUser ?? undefined);
633
+ if (!result.Success) {
634
+ console.error('Failed to load agent replies:', result.ErrorMessage);
635
+ return [];
636
+ }
637
+ return (result.Results || []).map(reply => reply.ID);
638
+ }
639
+ /**
640
+ * The SQL predicate for one branch's path in a conversation, from
641
+ * `ConversationEngine.BranchPathFilterFresh`. A null or omitted branch is the trunk and costs
642
+ * no query.
643
+ *
644
+ * Never throws. When the path cannot be built (the branch rows fail to load, or the branch is
645
+ * not among them), it logs the error and returns null. Each lookup then returns its own
646
+ * failure value, as it does when its main query fails. A caller must not fall back to the
647
+ * trunk predicate: on a branch, that reads trunk rows past the fork point.
648
+ */
649
+ async branchPathFilter(conversationId, branchId) {
650
+ try {
651
+ const user = this.Provider.CurrentUser ?? undefined;
652
+ return await ConversationEngine.BranchPathFilterFresh(conversationId, branchId, user, this.Provider);
653
+ }
654
+ catch (error) {
655
+ console.error(`Failed to build the path of branch ${branchId} in conversation ${conversationId}:`, error);
656
+ return null;
657
+ }
583
658
  }
584
659
  /**
585
660
  * One artifact version by ID, as a payload source.
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-agent.service.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,Q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AM;;iFAEP,wBAAwB;cAHpC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB;;AAguBD;;;;;;;;GAQG;AACH,SAAS,oBAAoB,CAAC,OAAkC;IAC9D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC;QACH,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC5C,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IACjD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACvE,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,yFAAyF;AACzF,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Metadata, IMetadataProvider, RunView } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient, type RunDecisionParams, type RunDecisionResult } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, coerceFailedExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport {\n ConversationEngine,\n MJConversationDetailEntity,\n MJArtifactVersionEntity,\n MJArtifactEntity\n} from '@memberjunction/core-entities';\nimport { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended } from '@memberjunction/ai-core-plus';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { AgentClientService } from '@memberjunction/ng-agent-client';\nimport { RunAgentFromConversationDetailParams } from '@memberjunction/ai-agent-client';\nimport { ConversationsRuntime } from '@memberjunction/conversations-runtime';\nimport { LazyArtifactInfo } from '../models/lazy-artifact-info';\nimport { MentionParserService } from './mention-parser.service';\nimport { UUIDsEqual } from '@memberjunction/global';\n\nimport { ConversationsRuntimeBootstrap } from './conversations-runtime-bootstrap.service';\nimport {\n GroupVersionsByArtifact,\n type AgentArtifactSummary\n} from '../utils/agent-artifact-summary';\n\n/**\n * Rows the configuration-preset lookup parses before giving up. The SQL prefilter is a LIKE,\n * so a few candidates may not be real mention blobs; this bounds how many we inspect.\n */\nconst CONFIG_PRESET_CANDIDATE_ROWS = 5;\n\n/**\n * Cap on artifact versions listed for the intent classifier.\n *\n * The block is a hint, not a record: the prompt prints a name, a type, a version count and\n * the latest version per artifact. Newest-first ordering means the cap only ever trims the\n * oldest versions of the busiest artifacts, which are the least useful lines in it.\n */\nconst MAX_AGENT_ARTIFACT_VERSIONS = 40;\n\n/**\n * Context for artifact lookups — pre-loaded conversation data.\n *\n * NO LONGER CONSUMED by this service. Both readers were converted to queries when transcript\n * windowing made these maps a partial view: they are keyed to the loaded window, so any\n * lookup for an older row silently missed. Retained as an exported type for API\n * compatibility; new code should not build one.\n */\nexport interface ArtifactLookupContext {\n agentRunsByDetailId: Map<string, MJAIAgentRunEntityExtended>;\n artifactsByDetailId: Map<string, LazyArtifactInfo[]>;\n}\n\n/**\n * An agent's prior OUTPUT artifact, resolved for payload continuity.\n *\n * `payload` is the parsed `ArtifactVersion.Content`, typed to match what actually consumes it\n * — `executeAgentContinuation` and `invokeSubAgent` both take `Record<string, unknown> | null`.\n * It is null when the version carried no content, the content did not parse, or the content\n * parsed to something that is not a JSON object; callers treat all three the same as \"no prior\n * artifact\", which is already a legal agent input.\n */\nexport interface AgentPayloadSource {\n artifactId: string;\n versionId: string;\n versionNumber: number;\n payload: Record<string, unknown> | null;\n}\n\n/**\n * Result from intent check - indicates whether to continue with agent\n * and which artifact version to use as payload\n */\nexport interface IntentCheckResult {\n decision: 'YES' | 'NO' | 'UNSURE';\n reasoning: string;\n targetArtifactVersionId?: string;\n}\n\n/**\n * Angular DI service for conversation-level agent orchestration.\n *\n * After PR 2 of the conversations-runtime extraction, the core\n * `processMessage` flow and the conversation-manager-agent resolution are\n * delegated to `@memberjunction/conversations-runtime`. This service is\n * primarily a shim for those operations PLUS the holder of the helpers\n * that haven't been ported yet:\n *\n * - `invokeSubAgent(...)` — used by Sage's routing decisions in\n * `message-input.component`.\n * - `checkAgentContinuityIntent(...)` — fast intent classification when the\n * user replies to a previous-agent thread.\n * - `FindConfigurationPresetForAgent(...)` — locates an agent's preset\n * from prior @mentions in the conversation.\n * - `clearSession(...)` — per-conversation session-id bookkeeping.\n *\n * These can move to the runtime in a follow-up; they aren't strictly needed\n * to invoke an agent end-to-end and stay here so the shim has zero behavior\n * difference vs. the original.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ConversationAgentService {\n /** GraphQL AI client - retained for RunAIPrompt (intent checking) which AgentClientService doesn't wrap */\n private _aiClient: GraphQLAIClient | null = null;\n /** Cached resolution of the conversation manager agent (default agent). */\n private _conversationManagerAgent: MJAIAgentEntityExtended | null = null;\n private _sessionIds: Map<string, string> = new Map();\n\n /** Observable indicating if the ambient agent is currently processing — delegated to the runtime's AgentRunner. */\n public readonly IsProcessing$: Observable<boolean>;\n\n /** @deprecated Use {@link IsProcessing$}. */\n public get isProcessing$(): Observable<boolean> {\n return this.IsProcessing$;\n }\n\n private _provider: IMetadataProvider | null = null;\n\n constructor(\n _bootstrap: ConversationsRuntimeBootstrap,\n private mentionParser: MentionParserService,\n private agentClientService: AgentClientService\n ) {\n // Injecting `_bootstrap` forces the runtime's INotificationAdapter +\n // IActiveTaskTracker adapters to register before any shim method runs.\n this.IsProcessing$ = ConversationsRuntime.Instance.AgentRunner.isProcessing$;\n this.initializeAIClient();\n }\n\n /**\n * The metadata provider this service uses. When unset, falls back to Metadata.Provider.\n * Setting it re-initializes the AI client and forwards the provider to the runtime's runner.\n */\n public get Provider(): IMetadataProvider {\n return this._provider ?? Metadata.Provider;\n }\n public set Provider(value: IMetadataProvider | null) {\n this._provider = value;\n this.initializeAIClient();\n ConversationsRuntime.Instance.AgentRunner.Provider = value;\n }\n\n /**\n * Initialize the GraphQL AI Client.\n * Retained for RunAIPrompt calls (intent checking) which the AgentClientService doesn't wrap.\n * Agent execution (RunAIAgentFromConversationDetail) now goes through ConversationsRuntime.AgentRunner.\n */\n private initializeAIClient(): void {\n try {\n const provider = this.Provider as GraphQLDataProvider;\n if (provider) {\n this._aiClient = new GraphQLAIClient(provider);\n } else {\n console.warn('GraphQLDataProvider not available, agent functionality will be limited');\n }\n } catch (error) {\n console.error('Failed to initialize GraphQL AI Client:', error);\n }\n }\n\n /**\n * Resolve the conversation manager agent via the runtime's 4-step\n * DefaultAgentResolver chain (explicit input → app-scoped Application\n * Setting → global Application Setting → code-const Sage fallback). The\n * result is cached on this service for use by the synchronous\n * {@link ConversationManagerAgentName} getter.\n *\n * Existing callers expect a Promise<MJAIAgentEntityExtended | null> — we\n * preserve that shape (returning null on failure rather than throwing)\n * so the call sites don't need to change.\n */\n public async GetConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n if (this._conversationManagerAgent) {\n return this._conversationManagerAgent;\n }\n\n try {\n const provider = this.Provider;\n const agent = await ConversationsRuntime.Instance.DefaultAgent.resolve({\n contextUser: provider.CurrentUser ?? undefined,\n provider,\n });\n this._conversationManagerAgent = agent;\n return agent;\n } catch (error) {\n const errorMsg = 'Error resolving conversation manager agent: ' + (error instanceof Error ? error.message : String(error));\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n /** @deprecated Use {@link GetConversationManagerAgent}. */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n return this.GetConversationManagerAgent();\n }\n\n /**\n * Synchronous read of the cached conversation-manager-agent name. Returns\n * `null` until {@link getConversationManagerAgent} has been called at least\n * once and resolved successfully. Used by `MessageItemComponent.isConversationManager`\n * to flag messages from the routing agent without hardcoding `'Sage'`.\n */\n public get ConversationManagerAgentName(): string | null {\n return this._conversationManagerAgent?.Name ?? null;\n }\n\n /**\n * Returns `true` if the supplied agent identifier (UUID or name) matches the\n * currently cached conversation manager agent. Robust to either input.\n */\n public IsConversationManagerAgent(agentIdOrName: string | null | undefined): boolean {\n if (!agentIdOrName || !this._conversationManagerAgent) return false;\n return (\n UUIDsEqual(this._conversationManagerAgent.ID, agentIdOrName) ||\n this._conversationManagerAgent.Name === agentIdOrName\n );\n }\n\n /**\n * Process a message through the conversation manager agent. Delegates to\n * `ConversationsRuntime.Instance.AgentRunner.processMessage(...)`.\n *\n * Signature is preserved verbatim from the original service so existing\n * call sites continue to compile. The unused `conversationHistory`\n * parameter is kept for backwards compatibility (it was already\n * documented as \"kept for backwards compatibility but not used\" in the\n * original).\n */\n async ProcessMessage(\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n conversationDetailId: string,\n onProgress?: AgentExecutionProgressCallback,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n /** The agents the conversation manager may delegate to. Null or omitted allows every agent. */\n allowedAgentIDs?: readonly string[] | null,\n /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n // Warm the cached default-agent name for any synchronous consumers\n // before the runtime resolves on its own.\n if (!this._conversationManagerAgent) {\n await this.GetConversationManagerAgent();\n }\n return ConversationsRuntime.Instance.AgentRunner.processMessage({\n conversationId,\n message,\n conversationDetailId,\n appContext,\n onProgress,\n ...(planMode ? { planMode: true } : {}),\n ...(requestedSkillIDs?.length ? { requestedSkillIDs } : {}),\n ...(allowedAgentIDs != null ? { AllowedAgentIDs: allowedAgentIDs } : {}),\n ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\n });\n }\n\n /** @deprecated Use {@link ProcessMessage}. */\n async processMessage(\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n conversationDetailId: string,\n onProgress?: AgentExecutionProgressCallback,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n allowedAgentIDs?: readonly string[] | null,\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.ProcessMessage(conversationId, message, conversationHistory, conversationDetailId, onProgress, appContext, planMode, requestedSkillIDs, allowedAgentIDs, agentHistoryFrom);\n }\n\n /**\n * Configuration preset an agent was pinned to by a previous `@mention` in this conversation.\n *\n * Resolved by QUERY, not by scanning the display array. The pinning `@mention` is normally\n * the FIRST message of an exchange and everything after it is follow-up, so it is the\n * message most likely to fall below the loaded transcript window — and `undefined` is a\n * legal value for `configurationPresetId`, so the miss is silent. The visible consequence\n * is a run executed under the default configuration (a different model tier) instead of the\n * one the user explicitly chose, with a plausible-looking result and no error.\n *\n * There is no column to filter on: the preset lives inside the message body as a JSON\n * mention blob (`@{\"type\":\"agent\",\"id\":\"…\",\"configId\":\"…\"}`). So SQL narrows and the parser\n * decides — both `configId` and the agent id appear verbatim in that blob, which makes the\n * two LIKEs a tight prefilter, and `parseMentions` is what actually confirms a match.\n */\n public async FindConfigurationPresetForAgent(\n conversationId: string,\n agentId: string\n ): Promise<string | undefined> {\n type MentionRow = Pick<MJConversationDetailEntity, 'ID' | 'Message'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<MentionRow>({\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: `ConversationID='${conversationId}' AND Role='User'`\n + ` AND Message LIKE '%\"configId\"%' AND Message LIKE '%${agentId}%'`,\n OrderBy: 'Sequence DESC',\n // >1 because LIKE cannot tell a mention blob from the same id appearing elsewhere in\n // the prose; the parse below is authoritative and picks the newest genuine match.\n MaxRows: CONFIG_PRESET_CANDIDATE_ROWS,\n Fields: ['ID', 'Message'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve configuration preset:', result.ErrorMessage);\n return undefined;\n }\n\n for (const row of result.Results || []) {\n const configurationId = this.readAgentConfigFromMention(row.Message, agentId);\n if (configurationId) {\n console.log(`\\u{1F3AF} Found configuration preset from @mention: ${configurationId}`);\n return configurationId;\n }\n }\n return undefined;\n }\n\n /** Returns the configId this message pins for `agentId`, or null when it pins none. */\n private readAgentConfigFromMention(message: string | null, agentId: string): string | null {\n if (!message) {\n return null;\n }\n const parsed = this.mentionParser.parseMentions(message, AIEngineBase.Instance.Agents, []);\n const mention = parsed.agentMention;\n return mention?.id === agentId && mention.configurationId ? mention.configurationId : null;\n }\n\n\n /**\n * Clear the session for a conversation (useful when starting a new topic)\n */\n ClearSession(conversationId: string): void {\n this._sessionIds.delete(conversationId);\n }\n\n /** @deprecated Use {@link ClearSession}. */\n clearSession(conversationId: string): void {\n return this.ClearSession(conversationId);\n }\n\n /**\n * Surfaces a warning toast when the user requested skills (via /skill mentions) that the\n * target agent cannot activate — the server drops such requests, and without this the\n * refusal is invisible to the user. Client-side check uses the agent gate only (the server\n * additionally intersects with the user's Run permission).\n */\n private warnOnUnacceptedSkills(agent: MJAIAgentEntityExtended, requestedSkillIDs: string[]): void {\n const allowed = AIEngineBase.Instance.GetSkillsForAgent(agent);\n const dropped = requestedSkillIDs.filter(id => !allowed.some(s => UUIDsEqual(s.ID, id)));\n if (dropped.length === 0) return;\n const names = dropped.map(\n id => AIEngineBase.Instance.Skills.find(s => UUIDsEqual(s.ID, id))?.Name ?? 'requested skill'\n );\n const reason = agent.AcceptsSkills === 'None'\n ? `${agent.Name} doesn't accept skills`\n : `${agent.Name} can't activate ${names.length === 1 ? 'this skill' : 'these skills'}`;\n MJNotificationService.Instance?.CreateSimpleNotification(\n `${reason} — ${names.join(', ')} won't be used for this run.`,\n 'warning',\n 6000\n );\n }\n\n /**\n * Invoke a sub-agent based on Sage Agent's payload.\n * This is called when Sage decides to delegate to a specialist agent.\n *\n * Stays on the Angular shim because it directly uses AgentClientService.\n * Could move to the runtime in a follow-up if needed.\n */\n async InvokeSubAgent(\n agentName: string,\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n reasoning: string,\n conversationDetailId: string,\n payload?: Record<string, unknown> | null,\n onProgress?: AgentExecutionProgressCallback,\n sourceArtifactId?: string,\n sourceArtifactVersionId?: string,\n agentConfigurationPresetId?: string,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n try {\n // Ensure AIEngineBase is configured\n await AIEngineBase.Instance.Config(false);\n\n // Find the agent by name\n const agent = AIEngineBase.Instance.Agents.find(a => a.Name === agentName);\n\n if (!agent || !agent.ID) {\n const errorMsg = `Sub-agent \"${agentName}\" not found`;\n console.warn(`${errorMsg}`);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n if (requestedSkillIDs?.length) {\n this.warnOnUnacceptedSkills(agent, requestedSkillIDs);\n }\n\n console.log(`Invoking sub-agent: ${agentName}`, { reasoning, hasPayload: !!payload, hasConfigPreset: !!agentConfigurationPresetId });\n\n // Map AIAgentConfiguration preset ID to actual AIConfiguration ID\n let aiConfigurationId: string | undefined = undefined;\n if (agentConfigurationPresetId) {\n const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agent.ID, false);\n const preset = presets.find(p => UUIDsEqual(p.ID, agentConfigurationPresetId) || UUIDsEqual(p.AIConfigurationID, agentConfigurationPresetId));\n\n if (preset) {\n aiConfigurationId = preset.AIConfigurationID || undefined;\n console.log(`Mapped agent configuration preset \"${preset.Name}\" to AIConfigurationID: ${aiConfigurationId || 'default'}`);\n } else {\n console.warn(`Agent configuration preset ${agentConfigurationPresetId} not found for agent ${agent.ID}`);\n }\n }\n\n const agentParams: RunAgentFromConversationDetailParams = {\n ConversationDetailId: conversationDetailId,\n AgentId: agent.ID,\n MaxHistoryMessages: 20,\n Data: {\n conversationId: conversationId,\n latestMessageId: message.ID,\n invocationReason: reasoning,\n ...(appContext ? { appContext } : {}),\n },\n ...(payload ? { Payload: payload } : {}),\n ...(aiConfigurationId ? { ConfigurationId: aiConfigurationId } : {}),\n ...(planMode ? { PlanMode: true } : {}),\n ...(requestedSkillIDs?.length ? { RequestedSkillIDs: requestedSkillIDs } : {}),\n ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\n CreateArtifacts: true,\n CreateNotification: true,\n SourceArtifactId: sourceArtifactId,\n SourceArtifactVersionId: sourceArtifactVersionId,\n OnProgress: onProgress ? (progress) => {\n onProgress({\n step: progress.CurrentStep as 'initialization' | 'validation' | 'prompt_execution' | 'action_execution' | 'subagent_execution' | 'decision_processing' | 'finalization',\n percentage: progress.Percentage,\n message: progress.Message,\n metadata: progress.Metadata\n });\n } : undefined\n };\n\n const runResult = await this.agentClientService.RunAgentFromConversationDetail(agentParams);\n\n if (runResult.Success && runResult.Result) {\n return runResult.Result as ExecuteAgentResult;\n }\n\n const failed = coerceFailedExecuteAgentResult(\n runResult.Result as ExecuteAgentResult | null | undefined,\n runResult.ErrorMessage || `Sub-agent \"${agentName}\" failed`,\n );\n const errorMsg = `Sub-agent \"${agentName}\" failed: ${failed.errorMessage}`;\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return failed;\n } catch (error) {\n const errorMsg = `Error invoking sub-agent \"${agentName}\": ` + (error instanceof Error ? error.message : String(error));\n console.error(`Error invoking sub-agent \"${agentName}\":`, error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return coerceFailedExecuteAgentResult<ExecuteAgentResult>(undefined, errorMsg);\n }\n }\n\n /** @deprecated Use {@link InvokeSubAgent}. */\n async invokeSubAgent(\n agentName: string,\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n reasoning: string,\n conversationDetailId: string,\n payload?: Record<string, unknown> | null,\n onProgress?: AgentExecutionProgressCallback,\n sourceArtifactId?: string,\n sourceArtifactVersionId?: string,\n agentConfigurationPresetId?: string,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.InvokeSubAgent(agentName, conversationId, message, conversationHistory, reasoning, conversationDetailId, payload, onProgress, sourceArtifactId, sourceArtifactVersionId, agentConfigurationPresetId, appContext, planMode, requestedSkillIDs, agentHistoryFrom);\n }\n\n /**\n * Check if user's latest message should continue with the previous agent or route through Sage.\n * Uses fast inference (<500ms) to determine intent and avoid unnecessary Sage overhead.\n *\n * Stays on the Angular shim because it directly uses GraphQLAIClient.\n * Could move to the runtime in a follow-up.\n */\n async CheckAgentContinuityIntent(\n conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[]\n ): Promise<IntentCheckResult> {\n if (!this._aiClient) {\n console.warn('AI Client not initialized, defaulting to UNSURE for intent check');\n return { decision: 'UNSURE', reasoning: 'AI Client not initialized' };\n }\n\n try {\n await AIEngineBase.Instance.Config(false);\n const prompt = AIEngineBase.Instance.Prompts.find(p => p.Name === 'Check Sage Intent');\n if (!prompt) {\n console.warn('⚠️ Check Sage Intent prompt not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Check Sage Intent prompt not found' };\n }\n\n const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, agentId));\n if (!agent) {\n console.warn('⚠️ Previous agent not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Previous agent not found' };\n }\n\n // Queried, not read off the caller's window-scoped maps — see findAllAgentArtifacts.\n // `conversationHistory` below is still the window on purpose: the `.slice(-10)` wants\n // the most recent exchange, which the loaded tail always contains.\n const agentArtifacts = await this.findAllAgentArtifacts(conversationId, agentId);\n\n const recentHistory = conversationHistory.slice(-10);\n const compactHistory = recentHistory.map((msg, idx) => {\n const role = msg.Role === 'User' ? 'User' : agent.Name || 'Agent';\n const content = msg.Message || '';\n return `${idx + 1}. ${role}: ${content.substring(0, 150)}${content.length > 150 ? '...' : ''}`;\n }).join('\\n');\n\n let artifactContext = '';\n if (agentArtifacts.length > 0) {\n artifactContext = '\\n\\n**Prior Artifacts Created by This Agent**:\\n';\n agentArtifacts.forEach((artifact, idx) => {\n artifactContext += `${idx + 1}. ${artifact.artifactName} (${artifact.ArtifactType})\\n`;\n artifactContext += ` - Versions: ${artifact.Versions.length}\\n`;\n if (artifact.Versions.length > 0) {\n artifactContext += ` - Latest: v${artifact.Versions[0].versionNumber}`;\n if (artifact.Versions[0].versionName) {\n artifactContext += ` - ${artifact.Versions[0].versionName}`;\n }\n artifactContext += '\\n';\n }\n });\n }\n\n const userMessage = `**Previous Agent**: ${agent.Name} - ${agent.Description || 'No description'}\n\n**Conversation History** (last ${recentHistory.length} messages):\n${compactHistory}${artifactContext}\n\n**Latest User Message**: \"${latestMessage}\"`;\n\n console.log('🔍 Checking agent continuity intent...', {\n agentName: agent.Name,\n messagePreview: latestMessage.substring(0, 50),\n artifactCount: agentArtifacts.length\n });\n\n const result = await this._aiClient.RunAIPrompt({\n promptId: prompt.ID,\n messages: [{ role: 'user', content: userMessage }],\n data: {\n hasPriorArtifact: agentArtifacts.length > 0,\n priorArtifacts: agentArtifacts\n }\n });\n\n if (result && result.success && (result.parsedResult || result.output)) {\n const parsed = result.parsedResult ||\n (result.output ? JSON.parse(result.output) : null);\n\n if (parsed && parsed.continuesWith) {\n const decision = parsed.continuesWith.toUpperCase();\n const reasoning = parsed.reasoning || 'No reasoning provided';\n const targetArtifactVersionId = parsed.targetArtifactVersionId || undefined;\n\n console.log(`✅ Intent check result: ${decision}`, {\n reasoning,\n targetArtifactVersionId,\n latency: result.executionTimeMs || 'unknown'\n });\n\n if (decision === 'YES' || decision === 'NO' || decision === 'UNSURE') {\n return {\n decision: decision as 'YES' | 'NO' | 'UNSURE',\n reasoning,\n targetArtifactVersionId\n };\n }\n }\n }\n\n console.warn('⚠️ Intent check failed or returned invalid format, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Invalid format from intent check prompt' };\n } catch (error) {\n console.error('❌ Error checking agent continuity intent:', error);\n return {\n decision: 'UNSURE',\n reasoning: `Error during intent check: ${error instanceof Error ? error.message : String(error)}`\n };\n }\n }\n\n /** @deprecated Use {@link CheckAgentContinuityIntent}. */\n async checkAgentContinuityIntent(\n conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[]\n ): Promise<IntentCheckResult> {\n return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory);\n }\n\n /**\n * Runs a typed decision on the server in one round trip, through\n * {@link GraphQLAIClient.RunDecision}. Decision routing (`EnableDecisionRouting`) asks its\n * routing questions here.\n *\n * Never throws: without an AI client, or on any failure, it resolves with `Success: false` and\n * no answers.\n */\n public async RunDecision(params: RunDecisionParams): Promise<RunDecisionResult> {\n if (!this._aiClient) {\n return { Success: false, ErrorMessage: 'AI Client not initialized', Answers: {} };\n }\n return this._aiClient.RunDecision(params);\n }\n\n /**\n * Every artifact this agent produced in this conversation, newest version first, for decision\n * routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.\n *\n * @param historyFrom The chat's history floor. When set, only artifacts on replies written at or\n * after it count, as with {@link FindLatestAgentOutputVersion}.\n */\n public async FindAgentArtifacts(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\n ): Promise<AgentArtifactSummary[]> {\n return this.findAllAgentArtifacts(conversationId, agentId, historyFrom);\n }\n\n /**\n * Every artifact this agent produced in this conversation, newest version first — resolved\n * by QUERY, not by scanning the display array.\n *\n * The scan this replaces walked `conversationDetails` and looked each row up in the\n * caller's `artifactsByDetailId` / `agentRunsByDetailId` maps. Both are scoped to the\n * LOADED WINDOW, so under transcript windowing it saw only the artifacts attached to the\n * page currently on screen.\n *\n * That matters because this list is the \"Prior Artifacts Created by This Agent\" block fed\n * to the Check Sage Intent prompt, which is what produces `targetArtifactVersionId`. A\n * truncated list does not make the classifier fail — it makes it reason over a partial\n * history and confidently name the wrong version, or miss continuity altogether. Silent,\n * plausible, and wrong: the same failure class as {@link FindLatestAgentOutputVersion},\n * closed the same way.\n *\n * Two reads, not the four the old shape would have needed — see\n * {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.\n *\n * @param historyFrom The chat's history floor, when set (see {@link FindAgentArtifacts}).\n */\n private async findAllAgentArtifacts(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\n ): Promise<AgentArtifactSummary[]> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Name'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const versionResult = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: this.agentOutputVersionFilter(conversationId, agentId, historyFrom),\n OrderBy: '__mj_CreatedAt DESC',\n MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!versionResult.Success) {\n console.error('Failed to load agent artifact versions:', versionResult.ErrorMessage);\n return []; // the classifier degrades to no artifact context\n }\n const versions = versionResult.Results || [];\n if (versions.length === 0) {\n return [];\n }\n\n const artifactsById = await this.loadArtifactNames(\n [...new Set(versions.map(v => v.ArtifactID))]\n );\n return GroupVersionsByArtifact(versions, artifactsById);\n }\n\n /** Names and types for the artifacts behind a set of versions. */\n private async loadArtifactNames(\n artifactIds: string[]\n ): Promise<Map<string, Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>>> {\n type ArtifactRow = Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<ArtifactRow>({\n EntityName: 'MJ: Artifacts',\n ExtraFilter: `ID IN (${artifactIds.map(id => `'${id}'`).join(',')})`,\n Fields: ['ID', 'Name', 'Type'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to load agent artifacts:', result.ErrorMessage);\n return new Map<string, ArtifactRow>();\n }\n return new Map((result.Results || []).map(a => [a.ID, a]));\n }\n\n /**\n * Newest OUTPUT artifact version an agent produced in this conversation — resolved by\n * QUERY, not by scanning the display array.\n *\n * The array scan this replaces was correct only while `conversationHistory` held the whole\n * conversation. Under transcript windowing it holds one page, so the scan silently returns\n * null for any artifact below the window's oldest row — exactly the long \"modify this\n * again\" exchanges where payload continuity matters most. A null payload is a LEGAL agent\n * input, so the failure is silent: the agent regenerates from scratch instead of modifying.\n *\n * One round trip. The subquery walks details -> Output junctions, and versions carry\n * `__mj_CreatedAt`, so \"newest\" is expressible without joining back for `Sequence`.\n *\n * @param historyFrom The chat's history floor. When set, only artifacts on replies written at\n * or after it count: a run that may not read earlier messages must not pick up their work\n * as its payload either.\n */\n public async FindLatestAgentOutputVersion(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null\n ): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(\n this.agentOutputVersionFilter(conversationId, agentId, historyFrom), '__mj_CreatedAt DESC'\n );\n }\n\n /**\n * `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced in one\n * conversation. Shared by {@link FindLatestAgentOutputVersion} and\n * {@link findAllAgentArtifacts} so the two can never disagree about what \"this agent's\n * artifacts\" means.\n *\n * Filters on the DETAIL's `Status <> 'Error'` rather than the agent run's\n * `Status = 'Completed'` (which is what the array scan this replaced used). Doing it on the\n * run would mean joining back to `MJ: AI Agent Runs` purely to restate a condition the\n * detail already carries.\n */\n private agentOutputVersionFilter(conversationId: string, agentId: string, historyFrom?: Date | null): string {\n const floor = historyFrom ? ` AND ${ConversationEngine.HistoryFromFilter(historyFrom)}` : '';\n return `ID IN (\n SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]\n WHERE Direction='Output' AND ConversationDetailID IN (\n SELECT ID FROM [__mj].[vwConversationDetails]\n WHERE ConversationID='${conversationId}' AND AgentID='${agentId}'\n AND Role='AI' AND Status <> 'Error'${floor}\n )\n )`;\n }\n\n /**\n * One artifact version by ID, as a payload source.\n *\n * Used by the continuity path after the intent check names a specific version: that ID may\n * belong to a message below the loaded window, so it cannot be resolved from the window's\n * artifact maps.\n */\n public async FindArtifactVersionById(versionId: string): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(`ID='${versionId}'`, undefined);\n }\n\n /**\n * Shared read behind {@link FindLatestAgentOutputVersion} and {@link FindArtifactVersionById}.\n *\n * `ResultType: 'simple'` with an explicit `Fields` list: nothing here is mutated, and under\n * `entity_object` the `Fields` narrowing would be silently discarded by `PreRunView`.\n */\n private async runPayloadSourceQuery(\n extraFilter: string,\n orderBy: string | undefined\n ): Promise<AgentPayloadSource | null> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Content'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: extraFilter,\n OrderBy: orderBy,\n MaxRows: 1,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Content'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve agent payload source:', result.ErrorMessage);\n return null;\n }\n const row = result.Results?.[0];\n if (!row) {\n return null;\n }\n return {\n artifactId: row.ArtifactID,\n versionId: row.ID,\n versionNumber: row.VersionNumber,\n payload: parseArtifactContent(row.Content)\n };\n }\n\n}\n\n/**\n * Parses an artifact version's `Content` into an agent payload. Returns null rather than\n * throwing — a malformed artifact must not take down the send path, and \"no payload\" is\n * already a legal agent input.\n *\n * A payload must be a JSON OBJECT. Valid JSON that parses to an array, string, or number is\n * rejected for the same reason a parse failure is: every consumer spreads it or reads named\n * keys off it, so a non-object would satisfy the type at the boundary and misbehave deeper in.\n */\nfunction parseArtifactContent(content: string | null | undefined): Record<string, unknown> | null {\n if (!content) {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(content);\n return isPayloadObject(parsed) ? parsed : null;\n } catch (error) {\n console.warn('Artifact version content did not parse as JSON:', error);\n return null;\n }\n}\n\n/** Narrows a parsed JSON value to a plain object — the only shape a payload may take. */\nfunction isPayloadObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"conversation-agent.service.js","sourceRoot":"","sources":["../../../src/lib/services/conversation-agent.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,QAAQ,EAAqB,OAAO,EAAY,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAuB,eAAe,EAAkD,MAAM,sCAAsC,CAAC;AAC5I,OAAO,EAAsD,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAClI,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EACL,kBAAkB,EAInB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAG7E,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAGrE,OAAO,EACL,uBAAuB,EAExB,MAAM,iCAAiC,CAAC;;;;;AAEzC;;;GAGG;AACH,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAEvC;;;;;;GAMG;AACH,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAyCvC;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,MAAM,OAAO,wBAAwB;IAmBzB;IACA;IAnBV,2G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KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { Metadata, IMetadataProvider, RunView, UserInfo } from '@memberjunction/core';\nimport { GraphQLDataProvider, GraphQLAIClient, type RunDecisionParams, type RunDecisionResult } from '@memberjunction/graphql-dataprovider';\nimport { ExecuteAgentResult, AgentExecutionProgressCallback, coerceFailedExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport { AIEngineBase } from '@memberjunction/ai-engine-base';\nimport {\n ConversationEngine,\n MJConversationDetailEntity,\n MJArtifactVersionEntity,\n MJArtifactEntity\n} from '@memberjunction/core-entities';\nimport { MJAIAgentEntityExtended, MJAIAgentRunEntityExtended } from '@memberjunction/ai-core-plus';\nimport { MJNotificationService } from '@memberjunction/ng-notifications';\nimport { AgentClientService } from '@memberjunction/ng-agent-client';\nimport { RunAgentFromConversationDetailParams } from '@memberjunction/ai-agent-client';\nimport { ConversationsRuntime } from '@memberjunction/conversations-runtime';\nimport { LazyArtifactInfo } from '../models/lazy-artifact-info';\nimport { MentionParserService } from './mention-parser.service';\nimport { EscapeSQLString, UUIDsEqual } from '@memberjunction/global';\n\nimport { ConversationsRuntimeBootstrap } from './conversations-runtime-bootstrap.service';\nimport {\n GroupVersionsByArtifact,\n type AgentArtifactSummary\n} from '../utils/agent-artifact-summary';\n\n/**\n * Rows the configuration-preset lookup parses before giving up. The SQL prefilter is a LIKE,\n * so a few candidates may not be real mention blobs; this bounds how many we inspect.\n */\nconst CONFIG_PRESET_CANDIDATE_ROWS = 5;\n\n/**\n * Cap on artifact versions listed for the intent classifier.\n *\n * The block is a hint, not a record: the prompt prints a name, a type, a version count and\n * the latest version per artifact. Newest-first ordering means the cap only ever trims the\n * oldest versions of the busiest artifacts, which are the least useful lines in it.\n */\nconst MAX_AGENT_ARTIFACT_VERSIONS = 40;\n\n/**\n * Context for artifact lookups — pre-loaded conversation data.\n *\n * NO LONGER CONSUMED by this service. Both readers were converted to queries when transcript\n * windowing made these maps a partial view: they are keyed to the loaded window, so any\n * lookup for an older row silently missed. Retained as an exported type for API\n * compatibility; new code should not build one.\n */\nexport interface ArtifactLookupContext {\n agentRunsByDetailId: Map<string, MJAIAgentRunEntityExtended>;\n artifactsByDetailId: Map<string, LazyArtifactInfo[]>;\n}\n\n/**\n * An agent's prior OUTPUT artifact, resolved for payload continuity.\n *\n * `payload` is the parsed `ArtifactVersion.Content`, typed to match what actually consumes it\n * — `executeAgentContinuation` and `invokeSubAgent` both take `Record<string, unknown> | null`.\n * It is null when the version carried no content, the content did not parse, or the content\n * parsed to something that is not a JSON object; callers treat all three the same as \"no prior\n * artifact\", which is already a legal agent input.\n */\nexport interface AgentPayloadSource {\n artifactId: string;\n versionId: string;\n versionNumber: number;\n payload: Record<string, unknown> | null;\n}\n\n/**\n * Result from intent check - indicates whether to continue with agent\n * and which artifact version to use as payload\n */\nexport interface IntentCheckResult {\n decision: 'YES' | 'NO' | 'UNSURE';\n reasoning: string;\n targetArtifactVersionId?: string;\n}\n\n/**\n * Angular DI service for conversation-level agent orchestration.\n *\n * After PR 2 of the conversations-runtime extraction, the core\n * `processMessage` flow and the conversation-manager-agent resolution are\n * delegated to `@memberjunction/conversations-runtime`. This service is\n * primarily a shim for those operations PLUS the holder of the helpers\n * that haven't been ported yet:\n *\n * - `invokeSubAgent(...)` — used by Sage's routing decisions in\n * `message-input.component`.\n * - `checkAgentContinuityIntent(...)` — fast intent classification when the\n * user replies to a previous-agent thread.\n * - `FindConfigurationPresetForAgent(...)` — locates an agent's preset\n * from prior @mentions in the conversation.\n * - `clearSession(...)` — per-conversation session-id bookkeeping.\n *\n * These can move to the runtime in a follow-up; they aren't strictly needed\n * to invoke an agent end-to-end and stay here so the shim has zero behavior\n * difference vs. the original.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class ConversationAgentService {\n /** GraphQL AI client - retained for RunAIPrompt (intent checking) which AgentClientService doesn't wrap */\n private _aiClient: GraphQLAIClient | null = null;\n /** Cached resolution of the conversation manager agent (default agent). */\n private _conversationManagerAgent: MJAIAgentEntityExtended | null = null;\n private _sessionIds: Map<string, string> = new Map();\n\n /** Observable indicating if the ambient agent is currently processing — delegated to the runtime's AgentRunner. */\n public readonly IsProcessing$: Observable<boolean>;\n\n /** @deprecated Use {@link IsProcessing$}. */\n public get isProcessing$(): Observable<boolean> {\n return this.IsProcessing$;\n }\n\n private _provider: IMetadataProvider | null = null;\n\n constructor(\n _bootstrap: ConversationsRuntimeBootstrap,\n private mentionParser: MentionParserService,\n private agentClientService: AgentClientService\n ) {\n // Injecting `_bootstrap` forces the runtime's INotificationAdapter +\n // IActiveTaskTracker adapters to register before any shim method runs.\n this.IsProcessing$ = ConversationsRuntime.Instance.AgentRunner.isProcessing$;\n this.initializeAIClient();\n }\n\n /**\n * The metadata provider this service uses. When unset, falls back to Metadata.Provider.\n * Setting it re-initializes the AI client and forwards the provider to the runtime's runner.\n */\n public get Provider(): IMetadataProvider {\n return this._provider ?? Metadata.Provider;\n }\n public set Provider(value: IMetadataProvider | null) {\n this._provider = value;\n this.initializeAIClient();\n ConversationsRuntime.Instance.AgentRunner.Provider = value;\n }\n\n /**\n * Initialize the GraphQL AI Client.\n * Retained for RunAIPrompt calls (intent checking) which the AgentClientService doesn't wrap.\n * Agent execution (RunAIAgentFromConversationDetail) now goes through ConversationsRuntime.AgentRunner.\n */\n private initializeAIClient(): void {\n try {\n const provider = this.Provider as GraphQLDataProvider;\n if (provider) {\n this._aiClient = new GraphQLAIClient(provider);\n } else {\n console.warn('GraphQLDataProvider not available, agent functionality will be limited');\n }\n } catch (error) {\n console.error('Failed to initialize GraphQL AI Client:', error);\n }\n }\n\n /**\n * Resolve the conversation manager agent via the runtime's 4-step\n * DefaultAgentResolver chain (explicit input → app-scoped Application\n * Setting → global Application Setting → code-const Sage fallback). The\n * result is cached on this service for use by the synchronous\n * {@link ConversationManagerAgentName} getter.\n *\n * Existing callers expect a Promise<MJAIAgentEntityExtended | null> — we\n * preserve that shape (returning null on failure rather than throwing)\n * so the call sites don't need to change.\n */\n public async GetConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n if (this._conversationManagerAgent) {\n return this._conversationManagerAgent;\n }\n // A user who may not read the agents has no manager agent to resolve: say nothing, rather than an error for a state\n // that is theirs by design (MJ#5240)\n if (AIEngineBase.Instance.IsPermissionConstrained && AIEngineBase.Instance.ReadableAgents.length === 0) {\n return null;\n }\n\n try {\n const provider = this.Provider;\n const agent = await ConversationsRuntime.Instance.DefaultAgent.resolve({\n contextUser: provider.CurrentUser ?? undefined,\n provider,\n });\n this._conversationManagerAgent = agent;\n return agent;\n } catch (error) {\n const errorMsg = 'Error resolving conversation manager agent: ' + (error instanceof Error ? error.message : String(error));\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n }\n\n /** @deprecated Use {@link GetConversationManagerAgent}. */\n public async getConversationManagerAgent(): Promise<MJAIAgentEntityExtended | null> {\n return this.GetConversationManagerAgent();\n }\n\n /**\n * Synchronous read of the cached conversation-manager-agent name. Returns\n * `null` until {@link getConversationManagerAgent} has been called at least\n * once and resolved successfully. Used by `MessageItemComponent.isConversationManager`\n * to flag messages from the routing agent without hardcoding `'Sage'`.\n */\n public get ConversationManagerAgentName(): string | null {\n return this._conversationManagerAgent?.Name ?? null;\n }\n\n /**\n * Returns `true` if the supplied agent identifier (UUID or name) matches the\n * currently cached conversation manager agent. Robust to either input.\n */\n public IsConversationManagerAgent(agentIdOrName: string | null | undefined): boolean {\n if (!agentIdOrName || !this._conversationManagerAgent) return false;\n return (\n UUIDsEqual(this._conversationManagerAgent.ID, agentIdOrName) ||\n this._conversationManagerAgent.Name === agentIdOrName\n );\n }\n\n /**\n * Process a message through the conversation manager agent. Delegates to\n * `ConversationsRuntime.Instance.AgentRunner.processMessage(...)`.\n *\n * Signature is preserved verbatim from the original service so existing\n * call sites continue to compile. The unused `conversationHistory`\n * parameter is kept for backwards compatibility (it was already\n * documented as \"kept for backwards compatibility but not used\" in the\n * original).\n */\n async ProcessMessage(\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n conversationDetailId: string,\n onProgress?: AgentExecutionProgressCallback,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n /** The agents the conversation manager may delegate to. Null or omitted allows every agent. */\n allowedAgentIDs?: readonly string[] | null,\n /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n // Warm the cached default-agent name for any synchronous consumers\n // before the runtime resolves on its own.\n if (!this._conversationManagerAgent) {\n await this.GetConversationManagerAgent();\n }\n return ConversationsRuntime.Instance.AgentRunner.processMessage({\n conversationId,\n message,\n conversationDetailId,\n appContext,\n onProgress,\n ...(planMode ? { planMode: true } : {}),\n ...(requestedSkillIDs?.length ? { requestedSkillIDs } : {}),\n ...(allowedAgentIDs != null ? { AllowedAgentIDs: allowedAgentIDs } : {}),\n ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\n });\n }\n\n /** @deprecated Use {@link ProcessMessage}. */\n async processMessage(\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n conversationDetailId: string,\n onProgress?: AgentExecutionProgressCallback,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n allowedAgentIDs?: readonly string[] | null,\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.ProcessMessage(conversationId, message, conversationHistory, conversationDetailId, onProgress, appContext, planMode, requestedSkillIDs, allowedAgentIDs, agentHistoryFrom);\n }\n\n /**\n * Configuration preset an agent was pinned to by a previous `@mention` in this conversation.\n *\n * Resolved by QUERY, not by scanning the display array. The pinning `@mention` is normally\n * the FIRST message of an exchange and everything after it is follow-up, so it is the\n * message most likely to fall below the loaded transcript window — and `undefined` is a\n * legal value for `configurationPresetId`, so the miss is silent. The visible consequence\n * is a run executed under the default configuration (a different model tier) instead of the\n * one the user explicitly chose, with a plausible-looking result and no error.\n *\n * There is no column to filter on: the preset lives inside the message body as a JSON\n * mention blob (`@{\"type\":\"agent\",\"id\":\"…\",\"configId\":\"…\"}`). So SQL narrows and the parser\n * decides — both `configId` and the agent id appear verbatim in that blob, which makes the\n * two LIKEs a tight prefilter, and `parseMentions` is what actually confirms a match.\n *\n * @param branchId The active branch. Only messages on its path count; null or omitted reads\n * the trunk.\n */\n public async FindConfigurationPresetForAgent(\n conversationId: string,\n agentId: string,\n branchId?: string | null\n ): Promise<string | undefined> {\n type MentionRow = Pick<MJConversationDetailEntity, 'ID' | 'Message'>;\n const pathFilter = await this.branchPathFilter(conversationId, branchId);\n if (pathFilter == null) {\n return undefined;\n }\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<MentionRow>({\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: `${pathFilter} AND Role='User'`\n + ` AND Message LIKE '%\"configId\"%' AND Message LIKE '%${agentId}%'`,\n OrderBy: 'Sequence DESC',\n // >1 because LIKE cannot tell a mention blob from the same id appearing elsewhere in\n // the prose; the parse below is authoritative and picks the newest genuine match.\n MaxRows: CONFIG_PRESET_CANDIDATE_ROWS,\n Fields: ['ID', 'Message'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve configuration preset:', result.ErrorMessage);\n return undefined;\n }\n\n for (const row of result.Results || []) {\n const configurationId = this.readAgentConfigFromMention(row.Message, agentId);\n if (configurationId) {\n console.log(`\\u{1F3AF} Found configuration preset from @mention: ${configurationId}`);\n return configurationId;\n }\n }\n return undefined;\n }\n\n /** Returns the configId this message pins for `agentId`, or null when it pins none. */\n private readAgentConfigFromMention(message: string | null, agentId: string): string | null {\n if (!message) {\n return null;\n }\n const parsed = this.mentionParser.parseMentions(message, AIEngineBase.Instance.ReadableAgents, []);\n const mention = parsed.agentMention;\n return mention?.id === agentId && mention.configurationId ? mention.configurationId : null;\n }\n\n\n /**\n * Clear the session for a conversation (useful when starting a new topic)\n */\n ClearSession(conversationId: string): void {\n this._sessionIds.delete(conversationId);\n }\n\n /** @deprecated Use {@link ClearSession}. */\n clearSession(conversationId: string): void {\n return this.ClearSession(conversationId);\n }\n\n /**\n * Surfaces a warning toast when the user requested skills (via /skill mentions) that the\n * target agent cannot activate — the server drops such requests, and without this the\n * refusal is invisible to the user. Client-side check uses the agent gate only (the server\n * additionally intersects with the user's Run permission).\n */\n private warnOnUnacceptedSkills(agent: MJAIAgentEntityExtended, requestedSkillIDs: string[]): void {\n const allowed = AIEngineBase.Instance.GetSkillsForAgent(agent);\n const dropped = requestedSkillIDs.filter(id => !allowed.some(s => UUIDsEqual(s.ID, id)));\n if (dropped.length === 0) return;\n const names = dropped.map(\n id => AIEngineBase.Instance.Skills.find(s => UUIDsEqual(s.ID, id))?.Name ?? 'requested skill'\n );\n const reason = agent.AcceptsSkills === 'None'\n ? `${agent.Name} doesn't accept skills`\n : `${agent.Name} can't activate ${names.length === 1 ? 'this skill' : 'these skills'}`;\n MJNotificationService.Instance?.CreateSimpleNotification(\n `${reason} — ${names.join(', ')} won't be used for this run.`,\n 'warning',\n 6000\n );\n }\n\n /**\n * Invoke a sub-agent based on Sage Agent's payload.\n * This is called when Sage decides to delegate to a specialist agent.\n *\n * Stays on the Angular shim because it directly uses AgentClientService.\n * Could move to the runtime in a follow-up if needed.\n */\n async InvokeSubAgent(\n agentName: string,\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n reasoning: string,\n conversationDetailId: string,\n payload?: Record<string, unknown> | null,\n onProgress?: AgentExecutionProgressCallback,\n sourceArtifactId?: string,\n sourceArtifactVersionId?: string,\n agentConfigurationPresetId?: string,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n /** The first moment of the conversation the run may read. Null or omitted reads all of it. */\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n try {\n // Ensure AIEngineBase is configured\n await AIEngineBase.Instance.Config(false);\n\n // Find the agent by name\n const agent = AIEngineBase.Instance.ReadableAgents.find(a => a.Name === agentName);\n\n if (!agent || !agent.ID) {\n const errorMsg = `Sub-agent \"${agentName}\" not found`;\n console.warn(`${errorMsg}`);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return null;\n }\n\n if (requestedSkillIDs?.length) {\n this.warnOnUnacceptedSkills(agent, requestedSkillIDs);\n }\n\n console.log(`Invoking sub-agent: ${agentName}`, { reasoning, hasPayload: !!payload, hasConfigPreset: !!agentConfigurationPresetId });\n\n // Map AIAgentConfiguration preset ID to actual AIConfiguration ID\n let aiConfigurationId: string | undefined = undefined;\n if (agentConfigurationPresetId) {\n const presets = AIEngineBase.Instance.GetAgentConfigurationPresets(agent.ID, false);\n const preset = presets.find(p => UUIDsEqual(p.ID, agentConfigurationPresetId) || UUIDsEqual(p.AIConfigurationID, agentConfigurationPresetId));\n\n if (preset) {\n aiConfigurationId = preset.AIConfigurationID || undefined;\n console.log(`Mapped agent configuration preset \"${preset.Name}\" to AIConfigurationID: ${aiConfigurationId || 'default'}`);\n } else {\n console.warn(`Agent configuration preset ${agentConfigurationPresetId} not found for agent ${agent.ID}`);\n }\n }\n\n const agentParams: RunAgentFromConversationDetailParams = {\n ConversationDetailId: conversationDetailId,\n AgentId: agent.ID,\n MaxHistoryMessages: 20,\n Data: {\n conversationId: conversationId,\n latestMessageId: message.ID,\n invocationReason: reasoning,\n ...(appContext ? { appContext } : {}),\n },\n ...(payload ? { Payload: payload } : {}),\n ...(aiConfigurationId ? { ConfigurationId: aiConfigurationId } : {}),\n ...(planMode ? { PlanMode: true } : {}),\n ...(requestedSkillIDs?.length ? { RequestedSkillIDs: requestedSkillIDs } : {}),\n ...(agentHistoryFrom ? { AgentHistoryFrom: agentHistoryFrom } : {}),\n CreateArtifacts: true,\n CreateNotification: true,\n SourceArtifactId: sourceArtifactId,\n SourceArtifactVersionId: sourceArtifactVersionId,\n OnProgress: onProgress ? (progress) => {\n onProgress({\n step: progress.CurrentStep as 'initialization' | 'validation' | 'prompt_execution' | 'action_execution' | 'subagent_execution' | 'decision_processing' | 'finalization',\n percentage: progress.Percentage,\n message: progress.Message,\n metadata: progress.Metadata\n });\n } : undefined\n };\n\n const runResult = await this.agentClientService.RunAgentFromConversationDetail(agentParams);\n\n if (runResult.Success && runResult.Result) {\n return runResult.Result as ExecuteAgentResult;\n }\n\n const failed = coerceFailedExecuteAgentResult(\n runResult.Result as ExecuteAgentResult | null | undefined,\n runResult.ErrorMessage || `Sub-agent \"${agentName}\" failed`,\n );\n const errorMsg = `Sub-agent \"${agentName}\" failed: ${failed.errorMessage}`;\n console.error(errorMsg);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return failed;\n } catch (error) {\n const errorMsg = `Error invoking sub-agent \"${agentName}\": ` + (error instanceof Error ? error.message : String(error));\n console.error(`Error invoking sub-agent \"${agentName}\":`, error);\n MJNotificationService.Instance?.CreateSimpleNotification(errorMsg, 'error', 5000);\n return coerceFailedExecuteAgentResult<ExecuteAgentResult>(undefined, errorMsg);\n }\n }\n\n /** @deprecated Use {@link InvokeSubAgent}. */\n async invokeSubAgent(\n agentName: string,\n conversationId: string,\n message: MJConversationDetailEntity,\n conversationHistory: MJConversationDetailEntity[],\n reasoning: string,\n conversationDetailId: string,\n payload?: Record<string, unknown> | null,\n onProgress?: AgentExecutionProgressCallback,\n sourceArtifactId?: string,\n sourceArtifactVersionId?: string,\n agentConfigurationPresetId?: string,\n appContext?: Record<string, unknown> | null,\n planMode?: boolean,\n requestedSkillIDs?: string[],\n agentHistoryFrom?: Date | null\n ): Promise<ExecuteAgentResult | null> {\n return this.InvokeSubAgent(agentName, conversationId, message, conversationHistory, reasoning, conversationDetailId, payload, onProgress, sourceArtifactId, sourceArtifactVersionId, agentConfigurationPresetId, appContext, planMode, requestedSkillIDs, agentHistoryFrom);\n }\n\n /**\n * Check if user's latest message should continue with the previous agent or route through Sage.\n * Uses fast inference (<500ms) to determine intent and avoid unnecessary Sage overhead.\n *\n * Stays on the Angular shim because it directly uses GraphQLAIClient.\n * Could move to the runtime in a follow-up.\n *\n * @param branchId The active branch. Only the agent's artifacts on its path are listed for the\n * classifier; null or omitted reads the trunk.\n */\n async CheckAgentContinuityIntent(\n conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[],\n branchId?: string | null\n ): Promise<IntentCheckResult> {\n if (!this._aiClient) {\n console.warn('AI Client not initialized, defaulting to UNSURE for intent check');\n return { decision: 'UNSURE', reasoning: 'AI Client not initialized' };\n }\n\n try {\n await AIEngineBase.Instance.Config(false);\n const prompt = AIEngineBase.Instance.Prompts.find(p => p.Name === 'Check Sage Intent');\n if (!prompt) {\n console.warn('⚠️ Check Sage Intent prompt not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Check Sage Intent prompt not found' };\n }\n\n const agent = AIEngineBase.Instance.ReadableAgents.find(a => UUIDsEqual(a.ID, agentId));\n if (!agent) {\n console.warn('⚠️ Previous agent not found, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Previous agent not found' };\n }\n\n // Queried, not read off the caller's window-scoped maps — see findAllAgentArtifacts.\n // `conversationHistory` below is still the window on purpose: the `.slice(-10)` wants\n // the most recent exchange, which the loaded tail always contains.\n const agentArtifacts = await this.findAllAgentArtifacts(conversationId, agentId, undefined, branchId);\n\n const recentHistory = conversationHistory.slice(-10);\n const compactHistory = recentHistory.map((msg, idx) => {\n const role = msg.Role === 'User' ? 'User' : agent.Name || 'Agent';\n const content = msg.Message || '';\n return `${idx + 1}. ${role}: ${content.substring(0, 150)}${content.length > 150 ? '...' : ''}`;\n }).join('\\n');\n\n let artifactContext = '';\n if (agentArtifacts.length > 0) {\n artifactContext = '\\n\\n**Prior Artifacts Created by This Agent**:\\n';\n agentArtifacts.forEach((artifact, idx) => {\n artifactContext += `${idx + 1}. ${artifact.artifactName} (${artifact.ArtifactType})\\n`;\n artifactContext += ` - Versions: ${artifact.Versions.length}\\n`;\n if (artifact.Versions.length > 0) {\n artifactContext += ` - Latest: v${artifact.Versions[0].versionNumber}`;\n if (artifact.Versions[0].versionName) {\n artifactContext += ` - ${artifact.Versions[0].versionName}`;\n }\n artifactContext += '\\n';\n }\n });\n }\n\n const userMessage = `**Previous Agent**: ${agent.Name} - ${agent.Description || 'No description'}\n\n**Conversation History** (last ${recentHistory.length} messages):\n${compactHistory}${artifactContext}\n\n**Latest User Message**: \"${latestMessage}\"`;\n\n console.log('🔍 Checking agent continuity intent...', {\n agentName: agent.Name,\n messagePreview: latestMessage.substring(0, 50),\n artifactCount: agentArtifacts.length\n });\n\n const result = await this._aiClient.RunAIPrompt({\n promptId: prompt.ID,\n messages: [{ role: 'user', content: userMessage }],\n data: {\n hasPriorArtifact: agentArtifacts.length > 0,\n priorArtifacts: agentArtifacts\n }\n });\n\n if (result && result.success && (result.parsedResult || result.output)) {\n const parsed = result.parsedResult ||\n (result.output ? JSON.parse(result.output) : null);\n\n if (parsed && parsed.continuesWith) {\n const decision = parsed.continuesWith.toUpperCase();\n const reasoning = parsed.reasoning || 'No reasoning provided';\n const targetArtifactVersionId = parsed.targetArtifactVersionId || undefined;\n\n console.log(`✅ Intent check result: ${decision}`, {\n reasoning,\n targetArtifactVersionId,\n latency: result.executionTimeMs || 'unknown'\n });\n\n if (decision === 'YES' || decision === 'NO' || decision === 'UNSURE') {\n return {\n decision: decision as 'YES' | 'NO' | 'UNSURE',\n reasoning,\n targetArtifactVersionId\n };\n }\n }\n }\n\n console.warn('⚠️ Intent check failed or returned invalid format, defaulting to UNSURE');\n return { decision: 'UNSURE', reasoning: 'Invalid format from intent check prompt' };\n } catch (error) {\n console.error('❌ Error checking agent continuity intent:', error);\n return {\n decision: 'UNSURE',\n reasoning: `Error during intent check: ${error instanceof Error ? error.message : String(error)}`\n };\n }\n }\n\n /** @deprecated Use {@link CheckAgentContinuityIntent}. */\n async checkAgentContinuityIntent(\n conversationId: string,\n agentId: string,\n latestMessage: string,\n conversationHistory: MJConversationDetailEntity[],\n branchId?: string | null\n ): Promise<IntentCheckResult> {\n return this.CheckAgentContinuityIntent(conversationId, agentId, latestMessage, conversationHistory, branchId);\n }\n\n /**\n * Runs a typed decision on the server in one round trip, through\n * {@link GraphQLAIClient.RunDecision}. Decision routing (`EnableDecisionRouting`) asks its\n * routing questions here.\n *\n * Never throws: without an AI client, or on any failure, it resolves with `Success: false` and\n * no answers.\n */\n public async RunDecision(params: RunDecisionParams): Promise<RunDecisionResult> {\n if (!this._aiClient) {\n return { Success: false, ErrorMessage: 'AI Client not initialized', Answers: {} };\n }\n return this._aiClient.RunDecision(params);\n }\n\n /**\n * Every artifact this agent produced on the active branch path, newest version first, for\n * decision routing's artifact question. Resolved by query, as {@link findAllAgentArtifacts} explains.\n *\n * @param historyFrom The chat's history floor. When set, only artifacts on replies written at or\n * after it count, as with {@link FindLatestAgentOutputVersion}.\n * @param branchId The active branch. Only artifacts on its path count, as with\n * {@link FindLatestAgentOutputVersion}; null or omitted reads the trunk.\n */\n public async FindAgentArtifacts(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null,\n branchId?: string | null\n ): Promise<AgentArtifactSummary[]> {\n return this.findAllAgentArtifacts(conversationId, agentId, historyFrom, branchId);\n }\n\n /**\n * Every artifact this agent produced on the active branch path, newest version first —\n * resolved by QUERY, not by scanning the display array.\n *\n * The scan this replaces walked `conversationDetails` and looked each row up in the\n * caller's `artifactsByDetailId` / `agentRunsByDetailId` maps. Both are scoped to the\n * LOADED WINDOW, so under transcript windowing it saw only the artifacts attached to the\n * page currently on screen.\n *\n * That matters because this list is the \"Prior Artifacts Created by This Agent\" block fed\n * to the Check Sage Intent prompt, which is what produces `targetArtifactVersionId`. A\n * truncated list does not make the classifier fail — it makes it reason over a partial\n * history and confidently name the wrong version, or miss continuity altogether. Silent,\n * plausible, and wrong: the same failure class as {@link FindLatestAgentOutputVersion},\n * closed the same way.\n *\n * Three reads: the agent's replies, their Output versions, and the artifacts' names. See\n * {@link AgentArtifactSummary} for why dropping `runId` removes the join back to agent runs.\n *\n * @param historyFrom The chat's history floor, when set (see {@link FindAgentArtifacts}).\n * @param branchId The branch whose path to read; null or omitted reads the trunk.\n */\n private async findAllAgentArtifacts(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null,\n branchId?: string | null\n ): Promise<AgentArtifactSummary[]> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Name'>;\n const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId, historyFrom, branchId);\n if (!versionFilter) {\n return []; // the classifier degrades to no artifact context\n }\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const versionResult = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: versionFilter,\n OrderBy: '__mj_CreatedAt DESC',\n MaxRows: MAX_AGENT_ARTIFACT_VERSIONS,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!versionResult.Success) {\n console.error('Failed to load agent artifact versions:', versionResult.ErrorMessage);\n return []; // the classifier degrades to no artifact context\n }\n const versions = versionResult.Results || [];\n if (versions.length === 0) {\n return [];\n }\n\n const artifactsById = await this.loadArtifactNames(\n [...new Set(versions.map(v => v.ArtifactID))]\n );\n return GroupVersionsByArtifact(versions, artifactsById);\n }\n\n /** Names and types for the artifacts behind a set of versions. */\n private async loadArtifactNames(\n artifactIds: string[]\n ): Promise<Map<string, Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>>> {\n type ArtifactRow = Pick<MJArtifactEntity, 'ID' | 'Name' | 'Type'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<ArtifactRow>({\n EntityName: 'MJ: Artifacts',\n ExtraFilter: `ID IN (${artifactIds.map(id => `'${id}'`).join(',')})`,\n Fields: ['ID', 'Name', 'Type'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to load agent artifacts:', result.ErrorMessage);\n return new Map<string, ArtifactRow>();\n }\n return new Map((result.Results || []).map(a => [a.ID, a]));\n }\n\n /**\n * Newest OUTPUT artifact version an agent produced in this conversation — resolved by\n * QUERY, not by scanning the display array.\n *\n * The array scan this replaces was correct only while `conversationHistory` held the whole\n * conversation. Under transcript windowing it holds one page, so the scan silently returns\n * null for any artifact below the window's oldest row — exactly the long \"modify this\n * again\" exchanges where payload continuity matters most. A null payload is a LEGAL agent\n * input, so the failure is silent: the agent regenerates from scratch instead of modifying.\n *\n * Two reads: the agent's replies, then their newest Output version. Versions carry\n * `__mj_CreatedAt`, so \"newest\" is expressible without joining back for `Sequence`.\n *\n * @param historyFrom The chat's history floor. When set, only artifacts on replies written at\n * or after it count: a run that may not read earlier messages must not pick up their work\n * as its payload either.\n * @param branchId The active branch. Only replies on its path count, so an artifact made on\n * another branch is never the latest here; null or omitted reads the trunk.\n */\n public async FindLatestAgentOutputVersion(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null,\n branchId?: string | null\n ): Promise<AgentPayloadSource | null> {\n const versionFilter = await this.agentOutputVersionFilter(conversationId, agentId, historyFrom, branchId);\n return versionFilter ? this.runPayloadSourceQuery(versionFilter, '__mj_CreatedAt DESC') : null;\n }\n\n /**\n * `ArtifactVersion.ID IN (...)` for every OUTPUT artifact an agent produced on one\n * conversation path, in messages no rerun replaced, or null when the agent has no such reply\n * there. Shared by {@link FindLatestAgentOutputVersion} and {@link findAllAgentArtifacts} so\n * the two can never disagree about what \"this agent's artifacts\" means.\n *\n * The replies are read with their own RunView ({@link agentReplyIds}), so the row-level\n * security on conversation messages applies. A subquery over their view would skip it, and the\n * server refuses one for a user whose read of messages is row-filtered.\n */\n private async agentOutputVersionFilter(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null,\n branchId?: string | null\n ): Promise<string | null> {\n const replyIds = await this.agentReplyIds(conversationId, agentId, historyFrom, branchId);\n if (replyIds.length === 0) {\n return null;\n }\n const inReplies = replyIds.map(id => `'${EscapeSQLString(id)}'`).join(',');\n return `ID IN (\n SELECT ArtifactVersionID FROM [__mj].[vwConversationDetailArtifacts]\n WHERE Direction='Output' AND ConversationDetailID IN (${inReplies})\n )`;\n }\n\n /**\n * IDs of the agent's replies on one conversation path, in messages no rerun replaced, written\n * at or after the history floor when one is set. Empty when the path cannot be built\n * ({@link branchPathFilter}) or the read fails.\n *\n * Filters on the DETAIL's `Status <> 'Error'` rather than the agent run's\n * `Status = 'Completed'` (which is what the array scan this replaced used). Doing it on the\n * run would mean joining back to `MJ: AI Agent Runs` purely to restate a condition the\n * detail already carries.\n */\n private async agentReplyIds(\n conversationId: string,\n agentId: string,\n historyFrom?: Date | null,\n branchId?: string | null\n ): Promise<string[]> {\n const pathFilter = await this.branchPathFilter(conversationId, branchId);\n if (pathFilter == null) {\n return [];\n }\n const floor = historyFrom ? ` AND ${ConversationEngine.HistoryFromFilter(historyFrom)}` : '';\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<Pick<MJConversationDetailEntity, 'ID'>>({\n EntityName: 'MJ: Conversation Details',\n ExtraFilter: `${ConversationEngine.LiveRowsFilter(pathFilter)} AND AgentID='${EscapeSQLString(agentId)}'` +\n ` AND Role='AI' AND Status <> 'Error'${floor}`,\n Fields: ['ID'],\n ResultType: 'simple',\n IgnoreMaxRows: true\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to load agent replies:', result.ErrorMessage);\n return [];\n }\n return (result.Results || []).map(reply => reply.ID);\n }\n\n /**\n * The SQL predicate for one branch's path in a conversation, from\n * `ConversationEngine.BranchPathFilterFresh`. A null or omitted branch is the trunk and costs\n * no query.\n *\n * Never throws. When the path cannot be built (the branch rows fail to load, or the branch is\n * not among them), it logs the error and returns null. Each lookup then returns its own\n * failure value, as it does when its main query fails. A caller must not fall back to the\n * trunk predicate: on a branch, that reads trunk rows past the fork point.\n */\n private async branchPathFilter(conversationId: string, branchId: string | null | undefined): Promise<string | null> {\n try {\n const user = this.Provider.CurrentUser ?? undefined;\n return await ConversationEngine.BranchPathFilterFresh(conversationId, branchId, user as UserInfo, this.Provider);\n } catch (error) {\n console.error(`Failed to build the path of branch ${branchId} in conversation ${conversationId}:`, error);\n return null;\n }\n }\n\n /**\n * One artifact version by ID, as a payload source.\n *\n * Used by the continuity path after the intent check names a specific version: that ID may\n * belong to a message below the loaded window, so it cannot be resolved from the window's\n * artifact maps.\n */\n public async FindArtifactVersionById(versionId: string): Promise<AgentPayloadSource | null> {\n return this.runPayloadSourceQuery(`ID='${versionId}'`, undefined);\n }\n\n /**\n * Shared read behind {@link FindLatestAgentOutputVersion} and {@link FindArtifactVersionById}.\n *\n * `ResultType: 'simple'` with an explicit `Fields` list: nothing here is mutated, and under\n * `entity_object` the `Fields` narrowing would be silently discarded by `PreRunView`.\n */\n private async runPayloadSourceQuery(\n extraFilter: string,\n orderBy: string | undefined\n ): Promise<AgentPayloadSource | null> {\n type VersionRow = Pick<MJArtifactVersionEntity, 'ID' | 'ArtifactID' | 'VersionNumber' | 'Content'>;\n\n const rv = RunView.FromMetadataProvider(this.Provider);\n const result = await rv.RunView<VersionRow>({\n EntityName: 'MJ: Artifact Versions',\n ExtraFilter: extraFilter,\n OrderBy: orderBy,\n MaxRows: 1,\n Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Content'],\n ResultType: 'simple'\n }, this.Provider.CurrentUser ?? undefined);\n\n if (!result.Success) {\n console.error('Failed to resolve agent payload source:', result.ErrorMessage);\n return null;\n }\n const row = result.Results?.[0];\n if (!row) {\n return null;\n }\n return {\n artifactId: row.ArtifactID,\n versionId: row.ID,\n versionNumber: row.VersionNumber,\n payload: parseArtifactContent(row.Content)\n };\n }\n\n}\n\n/**\n * Parses an artifact version's `Content` into an agent payload. Returns null rather than\n * throwing — a malformed artifact must not take down the send path, and \"no payload\" is\n * already a legal agent input.\n *\n * A payload must be a JSON OBJECT. Valid JSON that parses to an array, string, or number is\n * rejected for the same reason a parse failure is: every consumer spreads it or reads named\n * keys off it, so a non-object would satisfy the type at the boundary and misbehave deeper in.\n */\nfunction parseArtifactContent(content: string | null | undefined): Record<string, unknown> | null {\n if (!content) {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(content);\n return isPayloadObject(parsed) ? parsed : null;\n } catch (error) {\n console.warn('Artifact version content did not parse as JSON:', error);\n return null;\n }\n}\n\n/** Narrows a parsed JSON value to a plain object — the only shape a payload may take. */\nfunction isPayloadObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"]}
@@ -50,6 +50,8 @@ export interface ConversationDetailWindowSnapshot extends ConversationDetailWind
50
50
  * - {@link Reset} bumps a generation counter; every in-flight load checks it after each
51
51
  * await and discards its result if the conversation changed underneath.
52
52
  * - {@link LoadOlder} is a no-op while a load is in flight or when nothing is above.
53
+ * - A window loaded with an `upToSequence` ({@link LoadLatest}) holds only rows at or below it;
54
+ * every later read keeps that bound.
53
55
  * - Merges dedupe by normalized ID and re-sort by `Sequence` — session expansion can
54
56
  * return rows an earlier page already had.
55
57
  * - {@link ApplyLocalDetail} never hits the network; it is the send/stream/edit path.
@@ -59,6 +61,7 @@ export interface ConversationDetailWindowSnapshot extends ConversationDetailWind
59
61
  export declare class ConversationDetailWindowStore {
60
62
  private loader;
61
63
  private conversationId;
64
+ private branchId;
62
65
  private loadedDetails;
63
66
  private pinnedDetails;
64
67
  private pinnedTotalCount;
@@ -68,9 +71,19 @@ export declare class ConversationDetailWindowStore {
68
71
  private isLoadingLatest;
69
72
  private isLoadingOlder;
70
73
  private loadFailed;
74
+ /** The newest `Sequence` the window may hold; null for no bound. */
75
+ private upToSequence;
71
76
  constructor(loader: DetailWindowLoader);
72
- /** Drops all state and invalidates in-flight loads. Call on every conversation switch. */
73
- Reset(conversationId: string | null): void;
77
+ /**
78
+ * Drops all state and invalidates in-flight loads. Call on every conversation switch.
79
+ * `branchId` is the branch whose path every later load pages; null is the trunk.
80
+ */
81
+ Reset(conversationId: string | null, branchId?: string | null): void;
82
+ /**
83
+ * The exclusive `BeforeSequence` that keeps a newest-rows read at or below {@link upToSequence};
84
+ * undefined when the window has no bound. `Sequence` is an int column, so `< n + 1` is `<= n`.
85
+ */
86
+ private newestReadBound;
74
87
  /**
75
88
  * Fetches a page, WIDENING the raw over-read until it yields a full page of timeline
76
89
  * items (or the conversation runs out).
@@ -85,13 +98,16 @@ export declare class ConversationDetailWindowStore {
85
98
  */
86
99
  private fetchPageFillingTimeline;
87
100
  /**
88
- * First paint: the newest page of a conversation.
101
+ * First paint: the newest page of a conversation's path.
102
+ *
103
+ * With `upToSequence`, the window holds only rows at or below that `Sequence`: the first page
104
+ * ends there, and every later read of the window keeps the bound. Older pages load as usual.
89
105
  *
90
106
  * The loader is not expected to throw — `LoadDetailWindow` logs and returns an empty
91
107
  * window on a failed read — but a transport-layer rejection would otherwise strand
92
108
  * `isLoadingLatest` at true and wedge the store, so the flag is cleared in `finally`.
93
109
  */
94
- LoadLatest(conversationId: string, contextUser: UserInfo): Promise<void>;
110
+ LoadLatest(conversationId: string, contextUser: UserInfo, branchId?: string | null, upToSequence?: number | null): Promise<void>;
95
111
  /**
96
112
  * Prepends the next older page. No-op when nothing is above or a load is running.
97
113
  *
@@ -155,6 +171,8 @@ export declare class ConversationDetailWindowStore {
155
171
  get PinnedDetails(): readonly MJConversationDetailEntity[];
156
172
  /** True when the most recent load failed — an empty transcript vs. a broken one. */
157
173
  get LoadFailed(): boolean;
174
+ /** The branch whose path the window pages; null is the trunk. */
175
+ get BranchId(): string | null;
158
176
  /** True when a `LoadOlder` would actually do work. Drives the sentinel's observer. */
159
177
  CanLoadOlder(): boolean;
160
178
  /**