@memberjunction/server 6.2.0-edge.3 → 6.2.0-edge.4

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 (346) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/agentSessions/BridgeHostInstance.d.ts +25 -0
  3. package/dist/agentSessions/BridgeHostInstance.d.ts.map +1 -0
  4. package/dist/agentSessions/BridgeHostInstance.js +30 -0
  5. package/dist/agentSessions/BridgeHostInstance.js.map +1 -0
  6. package/dist/agentSessions/HostInstance.d.ts +75 -11
  7. package/dist/agentSessions/HostInstance.d.ts.map +1 -1
  8. package/dist/agentSessions/HostInstance.js +99 -28
  9. package/dist/agentSessions/HostInstance.js.map +1 -1
  10. package/dist/agentSessions/ReturningVisitorRecap.d.ts.map +1 -1
  11. package/dist/agentSessions/ReturningVisitorRecap.js +7 -3
  12. package/dist/agentSessions/ReturningVisitorRecap.js.map +1 -1
  13. package/dist/agentSessions/SessionJanitor.d.ts +173 -25
  14. package/dist/agentSessions/SessionJanitor.d.ts.map +1 -1
  15. package/dist/agentSessions/SessionJanitor.js +452 -54
  16. package/dist/agentSessions/SessionJanitor.js.map +1 -1
  17. package/dist/agentSessions/SessionManager.d.ts +43 -2
  18. package/dist/agentSessions/SessionManager.d.ts.map +1 -1
  19. package/dist/agentSessions/SessionManager.js +99 -8
  20. package/dist/agentSessions/SessionManager.js.map +1 -1
  21. package/dist/agentSessions/SessionRunIDVerifier.d.ts +63 -0
  22. package/dist/agentSessions/SessionRunIDVerifier.d.ts.map +1 -0
  23. package/dist/agentSessions/SessionRunIDVerifier.js +129 -0
  24. package/dist/agentSessions/SessionRunIDVerifier.js.map +1 -0
  25. package/dist/agentSessions/index.d.ts +2 -0
  26. package/dist/agentSessions/index.d.ts.map +1 -1
  27. package/dist/agentSessions/index.js +10 -3
  28. package/dist/agentSessions/index.js.map +1 -1
  29. package/dist/auth/actionAuthorization.d.ts +40 -0
  30. package/dist/auth/actionAuthorization.d.ts.map +1 -0
  31. package/dist/auth/actionAuthorization.js +94 -0
  32. package/dist/auth/actionAuthorization.js.map +1 -0
  33. package/dist/auth/index.d.ts.map +1 -1
  34. package/dist/auth/index.js +3 -10
  35. package/dist/auth/index.js.map +1 -1
  36. package/dist/auth/magicLink/MagicLinkService.d.ts.map +1 -1
  37. package/dist/auth/magicLink/MagicLinkService.js +6 -3
  38. package/dist/auth/magicLink/MagicLinkService.js.map +1 -1
  39. package/dist/auth/newUsers.d.ts +10 -0
  40. package/dist/auth/newUsers.d.ts.map +1 -1
  41. package/dist/auth/newUsers.js +80 -11
  42. package/dist/auth/newUsers.js.map +1 -1
  43. package/dist/config.d.ts +2378 -0
  44. package/dist/config.d.ts.map +1 -1
  45. package/dist/config.js +123 -0
  46. package/dist/config.js.map +1 -1
  47. package/dist/context.d.ts +8 -0
  48. package/dist/context.d.ts.map +1 -1
  49. package/dist/context.js +14 -11
  50. package/dist/context.js.map +1 -1
  51. package/dist/generated/graphql-schemas/__mj.d.ts +135 -0
  52. package/dist/generated/graphql-schemas/__mj.d.ts.map +1 -1
  53. package/dist/generated/graphql-schemas/__mj.js +706 -0
  54. package/dist/generated/graphql-schemas/__mj.js.map +1 -1
  55. package/dist/generic/OrphanedConversationDetailReconciler.js +3 -3
  56. package/dist/generic/OrphanedConversationDetailReconciler.js.map +1 -1
  57. package/dist/generic/ResolverBase.d.ts +20 -4
  58. package/dist/generic/ResolverBase.d.ts.map +1 -1
  59. package/dist/generic/ResolverBase.js +39 -10
  60. package/dist/generic/ResolverBase.js.map +1 -1
  61. package/dist/generic/RunViewResolver.d.ts.map +1 -1
  62. package/dist/generic/RunViewResolver.js +4 -0
  63. package/dist/generic/RunViewResolver.js.map +1 -1
  64. package/dist/index.d.ts +6 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +120 -131
  67. package/dist/index.js.map +1 -1
  68. package/dist/isolatedProvider.d.ts +20 -0
  69. package/dist/isolatedProvider.d.ts.map +1 -0
  70. package/dist/isolatedProvider.js +22 -0
  71. package/dist/isolatedProvider.js.map +1 -0
  72. package/dist/realtimeProxy/RealtimeProxyServer.d.ts +44 -4
  73. package/dist/realtimeProxy/RealtimeProxyServer.d.ts.map +1 -1
  74. package/dist/realtimeProxy/RealtimeProxyServer.js +121 -16
  75. package/dist/realtimeProxy/RealtimeProxyServer.js.map +1 -1
  76. package/dist/realtimeProxy/RealtimeRelayTunnel.d.ts +171 -0
  77. package/dist/realtimeProxy/RealtimeRelayTunnel.d.ts.map +1 -0
  78. package/dist/realtimeProxy/RealtimeRelayTunnel.js +532 -0
  79. package/dist/realtimeProxy/RealtimeRelayTunnel.js.map +1 -0
  80. package/dist/realtimeSessions/RealtimeSessionEventService.d.ts +148 -0
  81. package/dist/realtimeSessions/RealtimeSessionEventService.d.ts.map +1 -0
  82. package/dist/realtimeSessions/RealtimeSessionEventService.js +191 -0
  83. package/dist/realtimeSessions/RealtimeSessionEventService.js.map +1 -0
  84. package/dist/realtimeSessions/RealtimeSessionVerificationService.d.ts +66 -0
  85. package/dist/realtimeSessions/RealtimeSessionVerificationService.d.ts.map +1 -0
  86. package/dist/realtimeSessions/RealtimeSessionVerificationService.js +138 -0
  87. package/dist/realtimeSessions/RealtimeSessionVerificationService.js.map +1 -0
  88. package/dist/realtimeSessions/RealtimeVerifyRouter.d.ts +38 -0
  89. package/dist/realtimeSessions/RealtimeVerifyRouter.d.ts.map +1 -0
  90. package/dist/realtimeSessions/RealtimeVerifyRouter.js +98 -0
  91. package/dist/realtimeSessions/RealtimeVerifyRouter.js.map +1 -0
  92. package/dist/realtimeSessions/SessionVerificationPortsBase.d.ts +61 -0
  93. package/dist/realtimeSessions/SessionVerificationPortsBase.d.ts.map +1 -0
  94. package/dist/realtimeSessions/SessionVerificationPortsBase.js +149 -0
  95. package/dist/realtimeSessions/SessionVerificationPortsBase.js.map +1 -0
  96. package/dist/realtimeSessions/SlidingWindowRateLimiter.d.ts +57 -0
  97. package/dist/realtimeSessions/SlidingWindowRateLimiter.d.ts.map +1 -0
  98. package/dist/realtimeSessions/SlidingWindowRateLimiter.js +69 -0
  99. package/dist/realtimeSessions/SlidingWindowRateLimiter.js.map +1 -0
  100. package/dist/realtimeSessions/index.d.ts +17 -0
  101. package/dist/realtimeSessions/index.d.ts.map +1 -0
  102. package/dist/realtimeSessions/index.js +17 -0
  103. package/dist/realtimeSessions/index.js.map +1 -0
  104. package/dist/realtimeSessions/sessionAccess.d.ts +86 -0
  105. package/dist/realtimeSessions/sessionAccess.d.ts.map +1 -0
  106. package/dist/realtimeSessions/sessionAccess.js +90 -0
  107. package/dist/realtimeSessions/sessionAccess.js.map +1 -0
  108. package/dist/realtimeSessions/sessionConfigStamps.d.ts +70 -0
  109. package/dist/realtimeSessions/sessionConfigStamps.d.ts.map +1 -0
  110. package/dist/realtimeSessions/sessionConfigStamps.js +93 -0
  111. package/dist/realtimeSessions/sessionConfigStamps.js.map +1 -0
  112. package/dist/realtimeSessions/subscriptionAuthorization.d.ts +65 -0
  113. package/dist/realtimeSessions/subscriptionAuthorization.d.ts.map +1 -0
  114. package/dist/realtimeSessions/subscriptionAuthorization.js +71 -0
  115. package/dist/realtimeSessions/subscriptionAuthorization.js.map +1 -0
  116. package/dist/realtimeSessions/verificationCore.d.ts +243 -0
  117. package/dist/realtimeSessions/verificationCore.d.ts.map +1 -0
  118. package/dist/realtimeSessions/verificationCore.js +356 -0
  119. package/dist/realtimeSessions/verificationCore.js.map +1 -0
  120. package/dist/realtimeSessions/verificationPages.d.ts +66 -0
  121. package/dist/realtimeSessions/verificationPages.d.ts.map +1 -0
  122. package/dist/realtimeSessions/verificationPages.js +110 -0
  123. package/dist/realtimeSessions/verificationPages.js.map +1 -0
  124. package/dist/realtimeSessions/verificationPolicy.d.ts +147 -0
  125. package/dist/realtimeSessions/verificationPolicy.d.ts.map +1 -0
  126. package/dist/realtimeSessions/verificationPolicy.js +249 -0
  127. package/dist/realtimeSessions/verificationPolicy.js.map +1 -0
  128. package/dist/realtimeSessions/verificationWorkflow.d.ts +263 -0
  129. package/dist/realtimeSessions/verificationWorkflow.d.ts.map +1 -0
  130. package/dist/realtimeSessions/verificationWorkflow.js +435 -0
  131. package/dist/realtimeSessions/verificationWorkflow.js.map +1 -0
  132. package/dist/realtimeWidget/widgetGuestElevation.d.ts +20 -2
  133. package/dist/realtimeWidget/widgetGuestElevation.d.ts.map +1 -1
  134. package/dist/realtimeWidget/widgetGuestElevation.js +31 -2
  135. package/dist/realtimeWidget/widgetGuestElevation.js.map +1 -1
  136. package/dist/resolvers/ActionResolver.d.ts +31 -5
  137. package/dist/resolvers/ActionResolver.d.ts.map +1 -1
  138. package/dist/resolvers/ActionResolver.js +75 -14
  139. package/dist/resolvers/ActionResolver.js.map +1 -1
  140. package/dist/resolvers/AdhocQueryResolver.d.ts +14 -1
  141. package/dist/resolvers/AdhocQueryResolver.d.ts.map +1 -1
  142. package/dist/resolvers/AdhocQueryResolver.js +21 -5
  143. package/dist/resolvers/AdhocQueryResolver.js.map +1 -1
  144. package/dist/resolvers/CacheStatsResolver.d.ts +27 -0
  145. package/dist/resolvers/CacheStatsResolver.d.ts.map +1 -1
  146. package/dist/resolvers/CacheStatsResolver.js +113 -2
  147. package/dist/resolvers/CacheStatsResolver.js.map +1 -1
  148. package/dist/resolvers/ClientToolRequestResolver.d.ts +4 -2
  149. package/dist/resolvers/ClientToolRequestResolver.d.ts.map +1 -1
  150. package/dist/resolvers/ClientToolRequestResolver.js +28 -10
  151. package/dist/resolvers/ClientToolRequestResolver.js.map +1 -1
  152. package/dist/resolvers/FetchEntityVectorsResolver.d.ts +12 -1
  153. package/dist/resolvers/FetchEntityVectorsResolver.d.ts.map +1 -1
  154. package/dist/resolvers/FetchEntityVectorsResolver.js +83 -2
  155. package/dist/resolvers/FetchEntityVectorsResolver.js.map +1 -1
  156. package/dist/resolvers/HumanHandoffResolver.d.ts.map +1 -1
  157. package/dist/resolvers/HumanHandoffResolver.js +7 -1
  158. package/dist/resolvers/HumanHandoffResolver.js.map +1 -1
  159. package/dist/resolvers/MCPResolver.d.ts.map +1 -1
  160. package/dist/resolvers/MCPResolver.js +9 -4
  161. package/dist/resolvers/MCPResolver.js.map +1 -1
  162. package/dist/resolvers/RealtimeBridgeResolver.d.ts +54 -2
  163. package/dist/resolvers/RealtimeBridgeResolver.d.ts.map +1 -1
  164. package/dist/resolvers/RealtimeBridgeResolver.js +155 -10
  165. package/dist/resolvers/RealtimeBridgeResolver.js.map +1 -1
  166. package/dist/resolvers/RealtimeClientSessionResolver.d.ts +155 -25
  167. package/dist/resolvers/RealtimeClientSessionResolver.d.ts.map +1 -1
  168. package/dist/resolvers/RealtimeClientSessionResolver.js +394 -90
  169. package/dist/resolvers/RealtimeClientSessionResolver.js.map +1 -1
  170. package/dist/resolvers/RealtimeSessionEventsResolver.d.ts +61 -0
  171. package/dist/resolvers/RealtimeSessionEventsResolver.d.ts.map +1 -0
  172. package/dist/resolvers/RealtimeSessionEventsResolver.js +130 -0
  173. package/dist/resolvers/RealtimeSessionEventsResolver.js.map +1 -0
  174. package/dist/resolvers/RealtimeSessionVerificationResolver.d.ts +85 -0
  175. package/dist/resolvers/RealtimeSessionVerificationResolver.d.ts.map +1 -0
  176. package/dist/resolvers/RealtimeSessionVerificationResolver.js +188 -0
  177. package/dist/resolvers/RealtimeSessionVerificationResolver.js.map +1 -0
  178. package/dist/resolvers/RemoteBrowserActionResolver.d.ts +2 -0
  179. package/dist/resolvers/RemoteBrowserActionResolver.d.ts.map +1 -1
  180. package/dist/resolvers/RemoteBrowserActionResolver.js +5 -1
  181. package/dist/resolvers/RemoteBrowserActionResolver.js.map +1 -1
  182. package/dist/resolvers/RunAIAgentResolver.d.ts +10 -0
  183. package/dist/resolvers/RunAIAgentResolver.d.ts.map +1 -1
  184. package/dist/resolvers/RunAIAgentResolver.js +68 -11
  185. package/dist/resolvers/RunAIAgentResolver.js.map +1 -1
  186. package/dist/resolvers/RunTemplateResolver.d.ts.map +1 -1
  187. package/dist/resolvers/RunTemplateResolver.js +12 -11
  188. package/dist/resolvers/RunTemplateResolver.js.map +1 -1
  189. package/dist/resolvers/SyncDataResolver.d.ts.map +1 -1
  190. package/dist/resolvers/SyncDataResolver.js +6 -2
  191. package/dist/resolvers/SyncDataResolver.js.map +1 -1
  192. package/dist/resolvers/SyncRolesUsersResolver.d.ts +2 -0
  193. package/dist/resolvers/SyncRolesUsersResolver.d.ts.map +1 -1
  194. package/dist/resolvers/SyncRolesUsersResolver.js +23 -6
  195. package/dist/resolvers/SyncRolesUsersResolver.js.map +1 -1
  196. package/dist/resolvers/UserAvatarResolver.d.ts +16 -0
  197. package/dist/resolvers/UserAvatarResolver.d.ts.map +1 -0
  198. package/dist/resolvers/UserAvatarResolver.js +124 -0
  199. package/dist/resolvers/UserAvatarResolver.js.map +1 -0
  200. package/dist/resolvers/UserResolver.d.ts.map +1 -1
  201. package/dist/resolvers/UserResolver.js +2 -17
  202. package/dist/resolvers/UserResolver.js.map +1 -1
  203. package/dist/resolvers/agentVisionConsentAudit.d.ts +37 -0
  204. package/dist/resolvers/agentVisionConsentAudit.d.ts.map +1 -0
  205. package/dist/resolvers/agentVisionConsentAudit.js +63 -0
  206. package/dist/resolvers/agentVisionConsentAudit.js.map +1 -0
  207. package/dist/resolvers/avatarInputValidation.d.ts +40 -0
  208. package/dist/resolvers/avatarInputValidation.d.ts.map +1 -0
  209. package/dist/resolvers/avatarInputValidation.js +97 -0
  210. package/dist/resolvers/avatarInputValidation.js.map +1 -0
  211. package/dist/resolvers/currentUserRoles.d.ts +29 -0
  212. package/dist/resolvers/currentUserRoles.d.ts.map +1 -1
  213. package/dist/resolvers/currentUserRoles.js +30 -0
  214. package/dist/resolvers/currentUserRoles.js.map +1 -1
  215. package/dist/resolvers/meetings/meetingMutations.d.ts +6 -0
  216. package/dist/resolvers/meetings/meetingMutations.d.ts.map +1 -1
  217. package/dist/resolvers/meetings/meetingMutations.js +21 -0
  218. package/dist/resolvers/meetings/meetingMutations.js.map +1 -1
  219. package/dist/services/TaskGraphContinuationDeliverer.d.ts +4 -3
  220. package/dist/services/TaskGraphContinuationDeliverer.d.ts.map +1 -1
  221. package/dist/services/TaskGraphContinuationDeliverer.js +13 -7
  222. package/dist/services/TaskGraphContinuationDeliverer.js.map +1 -1
  223. package/dist/sharedCache.d.ts +105 -0
  224. package/dist/sharedCache.d.ts.map +1 -0
  225. package/dist/sharedCache.js +276 -0
  226. package/dist/sharedCache.js.map +1 -0
  227. package/dist/types.d.ts +6 -0
  228. package/dist/types.d.ts.map +1 -1
  229. package/dist/types.js.map +1 -1
  230. package/package.json +97 -95
  231. package/src/__tests__/ActionResolver.authorization.test.ts +353 -0
  232. package/src/__tests__/AdhocQueryResolver.sqlAuthorizer.test.ts +104 -0
  233. package/src/__tests__/BridgeHostInstance.test.ts +232 -0
  234. package/src/__tests__/ClientToolRequestResolver.test.ts +116 -0
  235. package/src/__tests__/FetchEntityVectorsResolver.test.ts +285 -0
  236. package/src/__tests__/HostInstance.test.ts +84 -0
  237. package/src/__tests__/HumanHandoffResolver.test.ts +17 -0
  238. package/src/__tests__/MeetingResolver.test.ts +75 -1
  239. package/src/__tests__/RealtimeBridgeResolver.test.ts +415 -6
  240. package/src/__tests__/RealtimeClientSessionResolver.configTamper.test.ts +383 -0
  241. package/src/__tests__/RealtimeClientSessionResolver.test.ts +682 -58
  242. package/src/__tests__/RealtimeProxyServer.test.ts +16 -1
  243. package/src/__tests__/RealtimeRelay.test.ts +876 -0
  244. package/src/__tests__/RemoteBrowserActionResolver.goalRunLink.test.ts +129 -0
  245. package/src/__tests__/ResolverBase.aggregateScreen.test.ts +174 -0
  246. package/src/__tests__/ResolverBase.clientOldValues.test.ts +6 -3
  247. package/src/__tests__/ReturningVisitorRecap.test.ts +115 -0
  248. package/src/__tests__/RunAIAgentResolver.branch.test.ts +169 -0
  249. package/src/__tests__/RunAIAgentResolver.historyFrom.test.ts +4 -4
  250. package/src/__tests__/RunAIAgentResolver.stoppedPredecessor.test.ts +166 -0
  251. package/src/__tests__/RunTemplateResolver.test.ts +132 -0
  252. package/src/__tests__/RunViewResolver.cacheCheckForwarding.test.ts +63 -0
  253. package/src/__tests__/SessionJanitor.test.ts +845 -18
  254. package/src/__tests__/SessionManager.test.ts +213 -17
  255. package/src/__tests__/SessionRunIDVerifier.test.ts +251 -0
  256. package/src/__tests__/SyncRolesUsersResolver.userRoles.test.ts +97 -0
  257. package/src/__tests__/TaskGraphContinuationDeliverer.test.ts +50 -3
  258. package/src/__tests__/UserAvatarResolver.test.ts +255 -0
  259. package/src/__tests__/UserResolver.currentUser.test.ts +16 -1
  260. package/src/__tests__/actionAuthorization.test.ts +130 -0
  261. package/src/__tests__/agentVisionConsentAudit.test.ts +118 -0
  262. package/src/__tests__/avatarInputValidation.test.ts +160 -0
  263. package/src/__tests__/isolatedProviderTransactions.test.ts +169 -0
  264. package/src/__tests__/magicLinkService.consume.test.ts +6 -0
  265. package/src/__tests__/magicLinkService.provisionLog.test.ts +5 -0
  266. package/src/__tests__/newUsers.template.test.ts +151 -0
  267. package/src/__tests__/newUsers.test.ts +74 -5
  268. package/src/__tests__/orphanedConversationDetailReconciler.test.ts +17 -2
  269. package/src/__tests__/realtimeSessions/RealtimeSessionEventService.test.ts +201 -0
  270. package/src/__tests__/realtimeSessions/RealtimeSessionEventsResolver.test.ts +215 -0
  271. package/src/__tests__/realtimeSessions/RealtimeSessionVerificationResolver.test.ts +102 -0
  272. package/src/__tests__/realtimeSessions/RealtimeSessionVerificationService.test.ts +349 -0
  273. package/src/__tests__/realtimeSessions/RealtimeVerifyRouter.test.ts +131 -0
  274. package/src/__tests__/realtimeSessions/SlidingWindowRateLimiter.test.ts +56 -0
  275. package/src/__tests__/realtimeSessions/helpers.ts +4 -0
  276. package/src/__tests__/realtimeSessions/sessionAccess.test.ts +129 -0
  277. package/src/__tests__/realtimeSessions/sessionConfigStamps.test.ts +124 -0
  278. package/src/__tests__/realtimeSessions/verificationCore.test.ts +355 -0
  279. package/src/__tests__/realtimeSessions/verificationPages.test.ts +84 -0
  280. package/src/__tests__/realtimeSessions/verificationPolicy.test.ts +226 -0
  281. package/src/__tests__/realtimeSessions/verificationWorkflow.test.ts +633 -0
  282. package/src/__tests__/resolverBase.fls.test.ts +87 -4
  283. package/src/__tests__/serverExtensionReservedRoots.test.ts +2 -0
  284. package/src/__tests__/sharedCache.test.ts +310 -0
  285. package/src/__tests__/widgetGuestElevation.test.ts +44 -0
  286. package/src/agentSessions/BridgeHostInstance.ts +32 -0
  287. package/src/agentSessions/HostInstance.ts +124 -28
  288. package/src/agentSessions/ReturningVisitorRecap.ts +7 -3
  289. package/src/agentSessions/SessionJanitor.ts +543 -57
  290. package/src/agentSessions/SessionManager.ts +125 -25
  291. package/src/agentSessions/SessionRunIDVerifier.ts +171 -0
  292. package/src/agentSessions/index.ts +10 -3
  293. package/src/auth/actionAuthorization.ts +116 -0
  294. package/src/auth/index.ts +3 -8
  295. package/src/auth/magicLink/MagicLinkService.ts +6 -3
  296. package/src/auth/newUsers.ts +99 -11
  297. package/src/config.ts +125 -0
  298. package/src/context.ts +15 -10
  299. package/src/generated/graphql-schemas/__mj.ts +496 -1
  300. package/src/generic/OrphanedConversationDetailReconciler.ts +3 -3
  301. package/src/generic/ResolverBase.ts +39 -9
  302. package/src/generic/RunViewResolver.ts +4 -0
  303. package/src/index.ts +132 -143
  304. package/src/isolatedProvider.ts +22 -0
  305. package/src/realtimeProxy/RealtimeProxyServer.ts +148 -16
  306. package/src/realtimeProxy/RealtimeRelayTunnel.ts +645 -0
  307. package/src/realtimeSessions/README.md +179 -0
  308. package/src/realtimeSessions/RealtimeSessionEventService.ts +274 -0
  309. package/src/realtimeSessions/RealtimeSessionVerificationService.ts +167 -0
  310. package/src/realtimeSessions/RealtimeVerifyRouter.ts +108 -0
  311. package/src/realtimeSessions/SessionVerificationPortsBase.ts +189 -0
  312. package/src/realtimeSessions/SlidingWindowRateLimiter.ts +92 -0
  313. package/src/realtimeSessions/index.ts +16 -0
  314. package/src/realtimeSessions/sessionAccess.ts +141 -0
  315. package/src/realtimeSessions/sessionConfigStamps.ts +123 -0
  316. package/src/realtimeSessions/subscriptionAuthorization.ts +116 -0
  317. package/src/realtimeSessions/verificationCore.ts +502 -0
  318. package/src/realtimeSessions/verificationPages.ts +149 -0
  319. package/src/realtimeSessions/verificationPolicy.ts +321 -0
  320. package/src/realtimeSessions/verificationWorkflow.ts +702 -0
  321. package/src/realtimeWidget/widgetGuestElevation.ts +34 -2
  322. package/src/resolvers/ActionResolver.ts +84 -21
  323. package/src/resolvers/AdhocQueryResolver.ts +24 -6
  324. package/src/resolvers/CacheStatsResolver.ts +89 -2
  325. package/src/resolvers/ClientToolRequestResolver.ts +25 -7
  326. package/src/resolvers/FetchEntityVectorsResolver.ts +97 -2
  327. package/src/resolvers/HumanHandoffResolver.ts +8 -0
  328. package/src/resolvers/MCPResolver.ts +8 -5
  329. package/src/resolvers/RealtimeBridgeResolver.ts +163 -11
  330. package/src/resolvers/RealtimeClientSessionResolver.ts +501 -96
  331. package/src/resolvers/RealtimeSessionEventsResolver.ts +133 -0
  332. package/src/resolvers/RealtimeSessionVerificationResolver.ts +174 -0
  333. package/src/resolvers/RemoteBrowserActionResolver.ts +11 -1
  334. package/src/resolvers/RunAIAgentResolver.ts +78 -11
  335. package/src/resolvers/RunTemplateResolver.ts +13 -12
  336. package/src/resolvers/SyncDataResolver.ts +6 -2
  337. package/src/resolvers/SyncRolesUsersResolver.ts +24 -6
  338. package/src/resolvers/UserAvatarResolver.ts +111 -0
  339. package/src/resolvers/UserResolver.ts +2 -16
  340. package/src/resolvers/agentVisionConsentAudit.ts +82 -0
  341. package/src/resolvers/avatarInputValidation.ts +123 -0
  342. package/src/resolvers/currentUserRoles.ts +32 -1
  343. package/src/resolvers/meetings/meetingMutations.ts +21 -0
  344. package/src/services/TaskGraphContinuationDeliverer.ts +13 -7
  345. package/src/sharedCache.ts +302 -0
  346. package/src/types.ts +7 -0
@@ -1,36 +1,81 @@
1
1
  import { BaseSingleton, ShutdownRegistry } from '@memberjunction/global';
2
2
  import { CompositeKey, RunView, LogError, LogStatus, } from '@memberjunction/core';
3
- import { GetHostInstanceID, GetHostNamePrefix } from './HostInstance.js';
3
+ import { RecoverRealtimeRecordingFromSegments, ResolveRecordingStorageAccountID, } from '@memberjunction/ai-agents';
4
+ import { GetCurrentHostInstance, GetHostInstanceID } from './HostInstance.js';
4
5
  import { SessionManager } from './SessionManager.js';
5
6
  /** Entity name for session rows (kept in sync with {@link SessionManager}). */
6
7
  const SESSION_ENTITY = 'MJ: AI Agent Sessions';
7
8
  /** Rows fetched per keyset page during a sweep. Small enough to bound memory on a large backlog. */
8
9
  const SWEEP_PAGE_SIZE = 200;
10
+ /** Entity name for agent rows (the recording storage account is configured on the agent). */
11
+ const AGENT_ENTITY = 'MJ: AI Agents';
12
+ /** A session whose recording recovery has failed this many times is given up on for the life of the process. */
13
+ const MAX_RECOVERY_ATTEMPTS = 8;
14
+ /** Recovery attempts (calls into the recovery routine) per sweep; bounds the I/O one tick can trigger. */
15
+ const MAX_RECOVERIES_PER_SWEEP = 5;
16
+ /**
17
+ * Abandoned (timed-out, still running) recovery attempts allowed at once. Each keeps its socket and any
18
+ * shard buffers it had read (up to the 384 MiB recovery cap) until it settles, so recovery pauses at this
19
+ * many instead of adding one more every timeout while storage keeps hanging.
20
+ */
21
+ const MAX_ABANDONED_RECOVERIES = 2;
22
+ /** Backoff after the k-th failed recovery is `2^k * base`, capped at the max. */
23
+ const RECOVERY_BACKOFF_BASE_MS = 5 * 60_000;
24
+ const RECOVERY_BACKOFF_MAX_MS = 6 * 60 * 60_000;
25
+ /**
26
+ * How long {@link SessionJanitor.Shutdown} waits for an in-flight recording recovery pass. A pass can
27
+ * spend minutes on large downloads/uploads, and graceful shutdown must not hang on it indefinitely.
28
+ */
29
+ const RECOVERY_SHUTDOWN_WAIT_MS = 10_000;
9
30
  const DEFAULT_CONFIG = {
10
31
  closeThresholdMinutes: 15,
11
32
  sweepIntervalMs: 60_000,
33
+ recordingRecoveryGraceMinutes: 10,
34
+ recordingRecoveryLookbackHours: 168,
35
+ recordingRecoveryAttemptTimeoutMinutes: 10,
12
36
  };
37
+ /** Every knob {@link SessionJanitor.Configure} accepts; each must be a finite number greater than zero. */
38
+ const CONFIG_KEYS = [
39
+ 'closeThresholdMinutes',
40
+ 'sweepIntervalMs',
41
+ 'recordingRecoveryGraceMinutes',
42
+ 'recordingRecoveryLookbackHours',
43
+ 'recordingRecoveryAttemptTimeoutMinutes',
44
+ ];
13
45
  /**
14
46
  * `BaseSingleton` background reconciler that keeps the durable `AIAgentSession` state from drifting
15
47
  * away from volatile process reality. A crash/redeploy vaporizes a host's in-memory sockets but
16
48
  * leaves its session rows reading `Active`/`Idle` forever; the janitor force-closes those orphans.
17
49
  *
18
- * Two sweeps, both writing through {@link SessionManager.CloseSession} so Record Changes captures
50
+ * Three close sweeps, all writing through {@link SessionManager.CloseSession} so Record Changes captures
19
51
  * each transition and channel rows are disconnected consistently:
20
52
  *
21
- * 1. **Own-host recovery ({@link RunStartupRecovery})** — run once at boot. Closes any `Active`/`Idle`
22
- * session whose `HostInstanceID` belongs to a *previous* boot of *this* host (same hostname prefix,
23
- * different `bootId`). Primary defense against the "Active forever" leak after a restart.
24
- * 2. **Global staleness sweep ({@link RunStalenessSweep})** — run periodically on every instance.
25
- * Closes any `Active`/`Idle` session whose `LastActiveAt` is older than `closeThresholdMinutes`,
26
- * regardless of host. Catches sessions whose owner died without a clean reboot (OOM, scaled-down pod).
53
+ * 1. **Own-instance recovery ({@link RunStartupRecovery})** — run once at boot. Closes any `Active`/`Idle`
54
+ * session whose `HostInstanceID` belongs to an *earlier* boot of *this* MJAPI instance (same host and port,
55
+ * different boot; see {@link HostInstanceIdentity}). Another MJAPI on the same host serves on another port,
56
+ * so its live sessions are left alone. Primary defense against the "Active forever" leak after a restart.
57
+ * 2. **Global staleness sweep ({@link RunStalenessSweep})** — run on every periodic tick, on every
58
+ * instance. Closes any `Active`/`Idle` session whose `LastActiveAt` is older than
59
+ * `closeThresholdMinutes`, regardless of host. Catches sessions whose owner died without a clean
60
+ * reboot (OOM, scaled-down pod).
61
+ * 3. **Max-duration sweep ({@link RunMaxDurationSweep})** — run on every periodic tick after the
62
+ * staleness sweep. Closes any session past its stored hard deadline (the public voice cost cap).
63
+ *
64
+ * The close sweeps stamp `CloseReason = 'Janitor'`. A shutdown-time path — {@link RunShutdownDrain},
65
+ * invoked from {@link Shutdown} during the graceful ShutdownRegistry drain — closes this exact host
66
+ * instance's own live sessions with `CloseReason = 'Shutdown'`.
27
67
  *
28
- * Both sweeps stamp `CloseReason = 'Janitor'`. A third, shutdown-time path —
29
- * {@link RunShutdownDrain}, invoked from {@link Shutdown} during the graceful ShutdownRegistry
30
- * drain — closes this exact host instance's own live sessions with `CloseReason = 'Shutdown'`.
68
+ * Separately from closing, {@link RunRecordingRecoverySweep} runs after the close sweeps on every
69
+ * periodic tick, without blocking them, and rebuilds the recording of already-`Closed` sessions whose
70
+ * end-of-call upload never arrived (it closes nothing).
31
71
  *
32
- * Both sweeps are **idempotent and safe to run concurrently** on every instance: closing an
33
- * already-`Closed` session is a no-op, and the close path is last-writer-wins. Both page with keyset
72
+ * The close sweeps are **idempotent and safe to run concurrently** on every instance: closing an
73
+ * already-`Closed` session is a no-op, and the close path is last-writer-wins. Recording recovery is not
74
+ * strictly so: two instances can recover the same session at once (there is no claim column). Each
75
+ * attempt uploads its own file and defers to an already-stamped recording on a best-effort basis, so
76
+ * the cost is duplicate work and an extra file, not a lost recording. The extra file is an orphan when the
77
+ * second attempt's re-check sees the first stamp; when both re-checks pass first, both files are stamped in
78
+ * turn and both are linked to the session (the later stamp wins `RecordingFileID`). Every sweep pages with keyset
34
79
  * (`AfterKey`) pagination per the deep-pagination guide so a large backlog can't blow up memory.
35
80
  */
36
81
  export class SessionJanitor extends BaseSingleton {
@@ -39,10 +84,26 @@ export class SessionJanitor extends BaseSingleton {
39
84
  this._config = DEFAULT_CONFIG;
40
85
  this._sweepTimer = null;
41
86
  this._sweepRunning = false;
87
+ /**
88
+ * The in-flight recording recovery pass, or null. Separate from {@link _sweepRunning}: slow recovery
89
+ * must never block the close sweeps. Kept as a promise so {@link Shutdown} can wait for it.
90
+ */
91
+ this._recoveryPass = null;
92
+ /** Set by {@link Stop}, cleared by {@link Start}: no new recovery pass starts while stopped. */
93
+ this._stopped = false;
42
94
  this._registered = false;
43
95
  this._provider = null;
44
96
  this._systemUser = null;
45
97
  this.sessionManager = new SessionManager();
98
+ /** Recovery retry state keyed by lowercase session id. Process-local: a restart gets fresh attempts. */
99
+ this.recoveryBackoff = new Map();
100
+ /**
101
+ * Lowercase ids of sessions whose recovery attempt timed out but has not settled. Skipped by later
102
+ * sweeps so a second attempt never runs alongside the abandoned one; removed when it settles.
103
+ */
104
+ this.abandonedRecoveries = new Set();
105
+ /** True once the "recovery paused" error has been logged for the current pause; reset when it lifts. */
106
+ this._recoveryPauseLogged = false;
46
107
  /** Identifier surfaced in graceful-shutdown logs. */
47
108
  this.ShutdownName = 'SessionJanitor';
48
109
  }
@@ -50,35 +111,60 @@ export class SessionJanitor extends BaseSingleton {
50
111
  static get Instance() {
51
112
  return super.getInstance();
52
113
  }
53
- /** Overrides default tuning. Safe to call before or after {@link Start}. */
114
+ /**
115
+ * Overrides default tuning. Safe to call before or after {@link Start}. Every value given must be a
116
+ * finite number greater than zero: a NaN or non-positive duration would otherwise build an invalid
117
+ * cutoff date and make every later sweep throw. All-or-nothing: on an invalid value it throws, naming
118
+ * the field and value, and applies nothing. `undefined` values are ignored.
119
+ */
54
120
  Configure(config) {
55
- this._config = { ...this._config, ...config };
121
+ const next = { ...this._config };
122
+ for (const key of CONFIG_KEYS) {
123
+ const value = config[key];
124
+ if (value === undefined) {
125
+ continue;
126
+ }
127
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
128
+ throw new Error(`SessionJanitor.Configure: ${key} must be a finite number greater than 0, got ${String(value)}`);
129
+ }
130
+ next[key] = value;
131
+ }
132
+ this._config = next;
56
133
  }
57
134
  /**
58
- * Run own-host startup recovery once, then schedule the periodic staleness sweep. Idempotent:
59
- * a second call does not stack a second timer. Captures the provider + system user so the timer
60
- * callback can run without re-supplying them.
135
+ * Run own-host startup recovery once, then schedule the periodic tick (staleness and max-duration
136
+ * close sweeps, then recording recovery). Idempotent: a second call does not stack a second timer.
137
+ * Captures the provider + system user so the timer callback can run without re-supplying them, and
138
+ * re-enables recording recovery after a {@link Stop}. Throws, before doing any work, when
139
+ * `intervalMs` is invalid (see {@link Configure}).
61
140
  */
62
141
  async Start(provider, systemUser, intervalMs) {
63
- this._provider = provider;
64
- this._systemUser = systemUser;
65
142
  if (intervalMs != null) {
66
- this._config = { ...this._config, sweepIntervalMs: intervalMs };
143
+ this.Configure({ sweepIntervalMs: intervalMs });
67
144
  }
145
+ this._provider = provider;
146
+ this._systemUser = systemUser;
147
+ this._stopped = false;
68
148
  this.ensureRegistered();
69
149
  await this.RunStartupRecovery(provider, systemUser);
70
150
  this.scheduleSweep();
71
151
  }
72
- /** Stops the periodic sweep timer. Idempotent. Part of {@link IShutdownable}. */
152
+ /**
153
+ * Stops the periodic tick and keeps any new recording recovery pass from starting until the next
154
+ * {@link Start}, including one a tick already in progress would have started. A pass that is already
155
+ * running is not interrupted ({@link Shutdown} waits for it). Idempotent. Part of {@link IShutdownable}.
156
+ */
73
157
  Stop() {
158
+ this._stopped = true;
74
159
  if (this._sweepTimer) {
75
160
  clearInterval(this._sweepTimer);
76
161
  this._sweepTimer = null;
77
162
  }
78
163
  }
79
164
  /**
80
- * {@link IShutdownable}: clear the timer, then drain this host's own live sessions so a
81
- * graceful stop never strands `Active`/`Idle` rows for the next boot's janitor to mop up.
165
+ * {@link IShutdownable}: stop the timer, then drain this host's own live sessions so a
166
+ * graceful stop never strands `Active`/`Idle` rows for the next boot's janitor to mop up, then wait
167
+ * (at most {@link RECOVERY_SHUTDOWN_WAIT_MS}) for an in-flight recording recovery pass.
82
168
  * Drained sessions are stamped `CloseReason = 'Shutdown'` (vs. `'Janitor'` for crash orphans),
83
169
  * so the dashboards can tell a clean redeploy from a reconciled crash. Never throws; the drain
84
170
  * is skipped when {@link Start} was never called (no captured provider/user).
@@ -93,6 +179,7 @@ export class SessionJanitor extends BaseSingleton {
93
179
  LogError(`SessionJanitor shutdown drain failed: ${err instanceof Error ? err.message : String(err)}`);
94
180
  }
95
181
  }
182
+ await this.waitForRecoveryPass();
96
183
  }
97
184
  /**
98
185
  * Close every `Active`/`Idle` session owned by **this exact host instance** (current boot),
@@ -110,18 +197,27 @@ export class SessionJanitor extends BaseSingleton {
110
197
  return closed;
111
198
  }
112
199
  /**
113
- * Force-close any `Active`/`Idle` session left behind by a *previous boot of this host*
114
- * (matching hostname prefix, differing `bootId`). Returns the number of sessions closed.
200
+ * Force-close any `Active`/`Idle` session left behind by an earlier boot of this MJAPI instance: its
201
+ * `HostInstanceID` has this instance's prefix (`hostname:port:`) and another boot. The sessions of another
202
+ * MJAPI on the same host carry another port and stay open. Returns the number of sessions closed.
203
+ *
204
+ * @param provider The metadata provider for the reads and writes.
205
+ * @param systemUser The user the closes run as.
206
+ * @param hostInstance The instance whose earlier boots to close. Defaults to this process's
207
+ * ({@link GetCurrentHostInstance}).
115
208
  */
116
- async RunStartupRecovery(provider, systemUser) {
117
- const prefix = GetHostNamePrefix().replace(/'/g, "''");
118
- const current = GetHostInstanceID().replace(/'/g, "''");
209
+ async RunStartupRecovery(provider, systemUser, hostInstance = GetCurrentHostInstance()) {
210
+ const prefix = hostInstance.GetInstancePrefix().replace(/'/g, "''");
211
+ const current = hostInstance.GetHostInstanceID().replace(/'/g, "''");
119
212
  const filter = `Status IN ('Active','Idle') ` +
120
213
  `AND HostInstanceID LIKE '${prefix}%' ` +
121
214
  `AND HostInstanceID <> '${current}'`;
122
- const closed = await this.sweepAndClose(filter, provider, systemUser, 'Janitor');
215
+ // The LIKE narrows the read; the exact check decides, since LIKE reads a `_` in a host name as any character.
216
+ const isPriorBoot = (session) => hostInstance.IsPriorBoot(session.HostInstanceID);
217
+ const closed = await this.sweepAndClose(filter, provider, systemUser, 'Janitor', isPriorBoot);
123
218
  if (closed > 0) {
124
- LogStatus(`[SessionJanitor] Startup recovery closed ${closed} orphaned session(s) from a prior boot of this host`);
219
+ LogStatus(`[SessionJanitor] Startup recovery closed ${closed} orphaned session(s) from an earlier boot of this instance ` +
220
+ `(${hostInstance.GetInstancePrefix()})`);
125
221
  }
126
222
  return closed;
127
223
  }
@@ -163,6 +259,57 @@ export class SessionJanitor extends BaseSingleton {
163
259
  }
164
260
  return closed;
165
261
  }
262
+ /**
263
+ * Rebuilds the recording of sessions whose end-of-call upload never arrived (browser died, tab
264
+ * closed). A session is a candidate when it is `Closed`, has `RecordingStartedAt` (consent is implied:
265
+ * recording only starts after the guest agreed), still has no `RecordingFileID`, and closed between
266
+ * the lookback window and the grace period (see {@link SessionJanitorConfig.recordingRecoveryGraceMinutes}).
267
+ *
268
+ * Work is bounded: candidates are handled sequentially, at most {@link MAX_RECOVERIES_PER_SWEEP}
269
+ * recovery attempts per call, and a failing session backs off exponentially (`min(2^k * 5 min, 6 h)`)
270
+ * and is abandoned after {@link MAX_RECOVERY_ATTEMPTS} failures with one `LogError`. Backoff entries of
271
+ * sessions that left the candidate set are pruned, but only after a pass that saw every candidate, so
272
+ * a capped pass never forgets sessions it did not reach.
273
+ *
274
+ * Never throws for a single bad session. Returns the number of recordings recovered.
275
+ */
276
+ async RunRecordingRecoverySweep(provider, systemUser) {
277
+ if (this.isRecoveryPausedForAbandonedAttempts()) {
278
+ return 0;
279
+ }
280
+ const nowMs = Date.now();
281
+ const graceCutoff = new Date(nowMs - this._config.recordingRecoveryGraceMinutes * 60_000).toISOString();
282
+ const lookbackCutoff = new Date(nowMs - this._config.recordingRecoveryLookbackHours * 3_600_000).toISOString();
283
+ const filter = `Status = 'Closed' AND RecordingStartedAt IS NOT NULL AND RecordingFileID IS NULL ` +
284
+ `AND ClosedAt < '${graceCutoff}' AND ClosedAt >= '${lookbackCutoff}'`;
285
+ const context = { provider, systemUser, storage: new Map() };
286
+ const seen = new Set();
287
+ let attempts = 0;
288
+ let recovered = 0;
289
+ const walk = await this.forEachSessionPage(filter, provider, systemUser, async (page) => {
290
+ for (const session of page) {
291
+ seen.add(session.ID.toLowerCase());
292
+ if (this.isRecoveryBackedOff(session.ID) || this.abandonedRecoveries.has(session.ID.toLowerCase())) {
293
+ continue;
294
+ }
295
+ if (attempts >= MAX_RECOVERIES_PER_SWEEP || this.abandonedRecoveries.size >= MAX_ABANDONED_RECOVERIES) {
296
+ return false; // per-sweep cap, or too many abandoned attempts still running: stop paging
297
+ }
298
+ const visit = await this.recoverSessionRecording(session, context);
299
+ attempts += visit.Attempted ? 1 : 0;
300
+ recovered += visit.Recovered ? 1 : 0;
301
+ }
302
+ });
303
+ // Only a walk that reached the end saw every candidate. A capped or failed-load walk has an
304
+ // incomplete `seen`; pruning on it would wipe backoff and give-up state for unseen sessions.
305
+ if (walk === 'complete') {
306
+ this.pruneRecoveryBackoff(seen);
307
+ }
308
+ if (recovered > 0) {
309
+ LogStatus(`[SessionJanitor] Recording recovery rebuilt ${recovered} recording(s)`);
310
+ }
311
+ return recovered;
312
+ }
166
313
  /** Parses the absolute deadline (ms) from a session's `Config_` JSON, or null when absent/malformed. */
167
314
  parseSessionDeadlineMs(configJson) {
168
315
  if (!configJson) {
@@ -188,7 +335,7 @@ export class SessionJanitor extends BaseSingleton {
188
335
  this._registered = true;
189
336
  }
190
337
  }
191
- /** Schedule the periodic staleness sweep, exactly once. Timer is unref'd so it never blocks exit. */
338
+ /** Schedule the periodic sweep tick (close sweeps + recording recovery), exactly once. Timer is unref'd so it never blocks exit. */
192
339
  scheduleSweep() {
193
340
  if (this._sweepTimer) {
194
341
  return;
@@ -196,7 +343,16 @@ export class SessionJanitor extends BaseSingleton {
196
343
  this._sweepTimer = setInterval(() => void this.periodicSweep(), this._config.sweepIntervalMs);
197
344
  this._sweepTimer.unref?.();
198
345
  }
199
- /** Timer tick: run the staleness sweep under the captured provider/user, guarding overlap. */
346
+ /**
347
+ * Timer tick: run the close sweeps (staleness, then max-duration) under the captured
348
+ * provider/user, guarding overlap, then kick off recording recovery.
349
+ *
350
+ * Recovery is started WITHOUT awaiting and has its own overlap guard: it can spend minutes on
351
+ * large downloads/uploads, and awaiting it under the close sweeps' guard would delay the
352
+ * max-duration cost cap and make every later tick return early. Each tick skips recovery while a pass
353
+ * is still running; because every session's attempt is bounded by
354
+ * `recordingRecoveryAttemptTimeoutMinutes`, a hung storage call delays later passes, never stops them.
355
+ */
200
356
  async periodicSweep() {
201
357
  if (this._sweepRunning || !this._provider || !this._systemUser) {
202
358
  return;
@@ -214,6 +370,233 @@ export class SessionJanitor extends BaseSingleton {
214
370
  finally {
215
371
  this._sweepRunning = false;
216
372
  }
373
+ this.startRecoveryPass(this._provider, this._systemUser);
374
+ }
375
+ /**
376
+ * Fire-and-forget recording recovery, skipped when the previous pass is still running or the janitor
377
+ * has been stopped (a tick that was mid-close-sweep when {@link Stop} ran must not start one).
378
+ */
379
+ startRecoveryPass(provider, systemUser) {
380
+ if (this._stopped || this._recoveryPass) {
381
+ return;
382
+ }
383
+ this._recoveryPass = this.RunRecordingRecoverySweep(provider, systemUser)
384
+ .then(() => undefined, err => {
385
+ LogError(`SessionJanitor recording recovery sweep failed: ${err instanceof Error ? err.message : String(err)}`);
386
+ })
387
+ .finally(() => {
388
+ this._recoveryPass = null;
389
+ });
390
+ }
391
+ /**
392
+ * Waits for the in-flight recovery pass, if any, for at most {@link RECOVERY_SHUTDOWN_WAIT_MS}; logs
393
+ * once when it gives up. Never throws: the pass promise already logs and absorbs its own errors.
394
+ */
395
+ async waitForRecoveryPass() {
396
+ const pass = this._recoveryPass;
397
+ if (!pass) {
398
+ return;
399
+ }
400
+ let timer;
401
+ const timedOut = new Promise(resolve => {
402
+ timer = setTimeout(() => resolve('timeout'), RECOVERY_SHUTDOWN_WAIT_MS);
403
+ });
404
+ try {
405
+ const outcome = await Promise.race([pass.then(() => 'finished'), timedOut]);
406
+ if (outcome === 'timeout') {
407
+ LogError(`SessionJanitor shutdown (host instance ${GetHostInstanceID()}): recording recovery pass still running after ` +
408
+ `${RECOVERY_SHUTDOWN_WAIT_MS} ms; shutting down without it. A session it had not yet stamped is retried by a later sweep.`);
409
+ }
410
+ }
411
+ finally {
412
+ clearTimeout(timer);
413
+ }
414
+ }
415
+ /**
416
+ * Recovers one candidate's recording and updates its backoff. Never throws: any exception is logged
417
+ * with the session id and counted as a failure.
418
+ */
419
+ async recoverSessionRecording(candidate, context) {
420
+ let attempted = false;
421
+ // The sweep filter requires RecordingStartedAt, so this only fires on drifted data; recovery would
422
+ // otherwise stamp a recording with no t0. Counted as a failure so it backs off rather than logging every tick.
423
+ const startedAt = candidate.RecordingStartedAt;
424
+ if (!startedAt) {
425
+ LogError(`[SessionJanitor] Recording recovery skipped for session ${candidate.ID}: RecordingStartedAt is empty`);
426
+ return this.recordRecoveryFailure(candidate.ID, false);
427
+ }
428
+ try {
429
+ // Re-read: the late upload may have landed since the candidate page was fetched.
430
+ const session = await context.provider.GetEntityObject(SESSION_ENTITY, context.systemUser);
431
+ if (!(await session.Load(candidate.ID))) {
432
+ LogError(`[SessionJanitor] Recording recovery could not reload session ${candidate.ID}`);
433
+ return this.recordRecoveryFailure(candidate.ID, false);
434
+ }
435
+ if (session.RecordingFileID) {
436
+ return { Attempted: false, Recovered: false };
437
+ }
438
+ const storage = await this.resolveRecoveryStorage(candidate.AgentID, context);
439
+ if (storage.Kind === 'NoAccount') {
440
+ return this.deferRecovery(candidate.ID, `no recording storage account for agent ${candidate.AgentID}`);
441
+ }
442
+ if (storage.Kind === 'AgentUnavailable') {
443
+ LogStatus(`[SessionJanitor] Recording recovery skipped for session ${candidate.ID}: agent ${candidate.AgentID} could not be loaded`);
444
+ return this.recordRecoveryFailure(candidate.ID, false);
445
+ }
446
+ const accountID = storage.AccountID;
447
+ attempted = true;
448
+ const result = await this.recoverWithinTimeout({
449
+ SessionID: candidate.ID,
450
+ StorageAccountID: accountID,
451
+ StartedAt: startedAt,
452
+ ContextUser: context.systemUser,
453
+ Provider: context.provider,
454
+ });
455
+ if (result === 'TimedOut') {
456
+ LogError(`[SessionJanitor] Recording recovery for session ${candidate.ID} did not finish within ` +
457
+ `${this._config.recordingRecoveryAttemptTimeoutMinutes} minutes; abandoning this attempt (its storage call may ` +
458
+ `still complete) and continuing the sweep. The session is not retried until that call settles.`);
459
+ return this.recordRecoveryFailure(candidate.ID, true);
460
+ }
461
+ switch (result.Outcome) {
462
+ case 'Recovered':
463
+ this.recoveryBackoff.delete(candidate.ID.toLowerCase());
464
+ LogStatus(`[SessionJanitor] Recovered recording for session ${candidate.ID} from ${result.SegmentCount} segment(s) (file ${result.FileID})`);
465
+ return { Attempted: true, Recovered: true };
466
+ case 'Superseded':
467
+ this.recoveryBackoff.delete(candidate.ID.toLowerCase());
468
+ LogStatus(`[SessionJanitor] Session ${candidate.ID} was given a recording by another writer; recovery left it alone`);
469
+ return { Attempted: true, Recovered: false };
470
+ case 'NoSegments':
471
+ LogStatus(`[SessionJanitor] No recoverable segments for session ${candidate.ID} (agent ${candidate.AgentID}, storage account ${accountID})`);
472
+ // Retried with backoff: a storage outage can also read as an empty folder (drivers that swallow
473
+ // list errors), but a session that never has shards is not an error when checking stops.
474
+ return this.recordRecoveryFailure(candidate.ID, true, 'NoSegments');
475
+ default:
476
+ LogError(`[SessionJanitor] Recording recovery failed for session ${candidate.ID}: ${result.ErrorMessage ?? 'unknown error'}`);
477
+ return this.recordRecoveryFailure(candidate.ID, true);
478
+ }
479
+ }
480
+ catch (err) {
481
+ LogError(`[SessionJanitor] Recording recovery threw for session ${candidate.ID}: ${err instanceof Error ? err.message : String(err)}`);
482
+ return this.recordRecoveryFailure(candidate.ID, attempted);
483
+ }
484
+ }
485
+ /**
486
+ * Runs one session's recovery, giving up on waiting after `recordingRecoveryAttemptTimeoutMinutes`.
487
+ * A call cannot be cancelled, so a timed-out one keeps running: the session is marked abandoned until
488
+ * it settles (later sweeps skip it), and its late outcome is logged then.
489
+ */
490
+ async recoverWithinTimeout(input) {
491
+ const key = input.SessionID.toLowerCase();
492
+ const attempt = RecoverRealtimeRecordingFromSegments(input);
493
+ let timer;
494
+ const timedOut = new Promise(resolve => {
495
+ timer = setTimeout(() => resolve('TimedOut'), this._config.recordingRecoveryAttemptTimeoutMinutes * 60_000);
496
+ timer.unref?.();
497
+ });
498
+ try {
499
+ const outcome = await Promise.race([attempt, timedOut]);
500
+ if (outcome === 'TimedOut') {
501
+ this.abandonedRecoveries.add(key);
502
+ attempt.then(late => LogStatus(`[SessionJanitor] Abandoned recording recovery for session ${input.SessionID} finished late: ${late.Outcome}`), err => LogError(`[SessionJanitor] Abandoned recording recovery for session ${input.SessionID} failed late: ${err instanceof Error ? err.message : String(err)}`)).finally(() => this.abandonedRecoveries.delete(key));
503
+ }
504
+ return outcome;
505
+ }
506
+ finally {
507
+ clearTimeout(timer);
508
+ }
509
+ }
510
+ /**
511
+ * True while {@link MAX_ABANDONED_RECOVERIES} timed-out attempts are still running: no new attempt
512
+ * starts until one settles. Logs one `LogError` per pause.
513
+ */
514
+ isRecoveryPausedForAbandonedAttempts() {
515
+ if (this.abandonedRecoveries.size < MAX_ABANDONED_RECOVERIES) {
516
+ this._recoveryPauseLogged = false;
517
+ return false;
518
+ }
519
+ if (!this._recoveryPauseLogged) {
520
+ LogError(`[SessionJanitor] Recording recovery paused: ${this.abandonedRecoveries.size} abandoned attempts are still waiting on storage ` +
521
+ `(sessions ${[...this.abandonedRecoveries].join(', ')}); no new attempt starts until one of them settles`);
522
+ this._recoveryPauseLogged = true;
523
+ }
524
+ return true;
525
+ }
526
+ /**
527
+ * Defers a session that cannot be recovered until configuration changes (its agent has no recording
528
+ * storage account). That is not a failed attempt, so it never counts toward the give-up: the session
529
+ * is re-checked every {@link RECOVERY_BACKOFF_MAX_MS} and logged only the first time.
530
+ */
531
+ deferRecovery(sessionID, reason) {
532
+ const key = sessionID.toLowerCase();
533
+ const state = this.recoveryBackoff.get(key);
534
+ if (!state?.Deferred) {
535
+ LogStatus(`[SessionJanitor] Recording recovery skipped for session ${sessionID}: ${reason}; re-checked every ${RECOVERY_BACKOFF_MAX_MS / 3_600_000} h`);
536
+ }
537
+ this.recoveryBackoff.set(key, { Failures: state?.Failures ?? 0, NextAttemptAt: Date.now() + RECOVERY_BACKOFF_MAX_MS, Deferred: true });
538
+ return { Attempted: false, Recovered: false };
539
+ }
540
+ /**
541
+ * Loads the agent carrying a session's recording storage config and resolves its storage account,
542
+ * memoized per agent for the sweep: the resolve may force a storage-engine reload, so it must not
543
+ * repeat for every session of the same agent.
544
+ */
545
+ async resolveRecoveryStorage(agentID, context) {
546
+ const key = agentID.toLowerCase();
547
+ const cached = context.storage.get(key);
548
+ if (cached) {
549
+ return cached;
550
+ }
551
+ const agent = await context.provider.GetEntityObject(AGENT_ENTITY, context.systemUser);
552
+ let storage;
553
+ if (!(await agent.Load(agentID))) {
554
+ LogError(`[SessionJanitor] Recording recovery could not load agent ${agentID}`);
555
+ storage = { Kind: 'AgentUnavailable' };
556
+ }
557
+ else {
558
+ const accountID = await ResolveRecordingStorageAccountID(agent, context.systemUser, context.provider);
559
+ storage = accountID ? { Kind: 'Resolved', AccountID: accountID } : { Kind: 'NoAccount' };
560
+ }
561
+ context.storage.set(key, storage);
562
+ return storage;
563
+ }
564
+ /** True while a session's backoff (or give-up) window has not elapsed. */
565
+ isRecoveryBackedOff(sessionID) {
566
+ const state = this.recoveryBackoff.get(sessionID.toLowerCase());
567
+ return state != null && Date.now() < state.NextAttemptAt;
568
+ }
569
+ /**
570
+ * Counts one more unsuccessful recovery for a session and schedules its next attempt
571
+ * (`min(2^k * 5 min, 6 h)`); at {@link MAX_RECOVERY_ATTEMPTS} it stops checking the session for this
572
+ * process with a single log line: a `LogError` when the last attempt failed, a `LogStatus` when it
573
+ * simply found no shards (nothing to recover is not an error).
574
+ */
575
+ recordRecoveryFailure(sessionID, attempted, kind = 'Failed') {
576
+ const key = sessionID.toLowerCase();
577
+ const failures = (this.recoveryBackoff.get(key)?.Failures ?? 0) + 1;
578
+ if (failures >= MAX_RECOVERY_ATTEMPTS) {
579
+ this.recoveryBackoff.set(key, { Failures: failures, NextAttemptAt: Infinity, Deferred: false });
580
+ if (kind === 'NoSegments') {
581
+ LogStatus(`[SessionJanitor] Session ${sessionID} had no recoverable segments in ${failures} checks; not checking it again until restart`);
582
+ }
583
+ else {
584
+ LogError(`[SessionJanitor] Giving up on recording recovery for session ${sessionID} after ${failures} failed attempts`);
585
+ }
586
+ }
587
+ else {
588
+ const waitMs = Math.min(2 ** failures * RECOVERY_BACKOFF_BASE_MS, RECOVERY_BACKOFF_MAX_MS);
589
+ this.recoveryBackoff.set(key, { Failures: failures, NextAttemptAt: Date.now() + waitMs, Deferred: false });
590
+ }
591
+ return { Attempted: attempted, Recovered: false };
592
+ }
593
+ /** Drops backoff state for sessions that were not in the latest complete candidate set. */
594
+ pruneRecoveryBackoff(candidateKeys) {
595
+ for (const key of this.recoveryBackoff.keys()) {
596
+ if (!candidateKeys.has(key)) {
597
+ this.recoveryBackoff.delete(key);
598
+ }
599
+ }
217
600
  }
218
601
  /**
219
602
  * Page through every session matching `filter` with keyset (`AfterKey`) pagination and close each
@@ -223,28 +606,11 @@ export class SessionJanitor extends BaseSingleton {
223
606
  */
224
607
  async sweepAndClose(filter, provider, systemUser, closeReason, shouldClose) {
225
608
  let closedCount = 0;
226
- let afterKey;
227
- // eslint-disable-next-line no-constant-condition
228
- while (true) {
229
- const fetched = await this.fetchPage(filter, afterKey, provider, systemUser);
230
- if (fetched == null) {
231
- break; // load failure already logged
232
- }
233
- if (fetched.length === 0) {
234
- break;
235
- }
236
- // Advance the keyset BEFORE the optional JS predicate narrows the page (we must page by the
237
- // SQL-matched set, not the post-filtered subset, or pagination would stall/skip).
238
- const lastFetchedId = fetched[fetched.length - 1].ID;
239
- const fetchedCount = fetched.length;
609
+ await this.forEachSessionPage(filter, provider, systemUser, async (fetched) => {
240
610
  // Optional in-JS narrowing (e.g. exact deadline check the SQL pre-filter can't express).
241
611
  const page = shouldClose ? fetched.filter(shouldClose) : fetched;
242
612
  if (page.length === 0) {
243
- if (fetchedCount < SWEEP_PAGE_SIZE) {
244
- break;
245
- }
246
- afterKey = CompositeKey.FromID(lastFetchedId); // first-pk-ok: keyset AfterKey on SESSION_ENTITY = MJ: AI Agent Sessions, a core entity keyed by ID
247
- continue;
613
+ return;
248
614
  }
249
615
  // Batch-load every channel for this whole page of sessions in ONE query, then hand each
250
616
  // session its own slice to CloseSession — avoids the N+1 channel read (one RunView per
@@ -256,12 +622,44 @@ export class SessionJanitor extends BaseSingleton {
256
622
  closedCount++;
257
623
  }
258
624
  }
625
+ });
626
+ return closedCount;
627
+ }
628
+ /**
629
+ * Keyset-page (`AfterKey`) through every session matching `filter`, handing each full fetched page
630
+ * to `visit`. Stops on a load failure (already logged), an empty page, a partial page, or when
631
+ * `visit` returns `false`.
632
+ *
633
+ * `visit` receives the page exactly as the SQL filter matched it. The keyset advances from the
634
+ * LAST FETCHED row, so any narrowing `visit` does in JS can never stall or skip pagination.
635
+ *
636
+ * Returns how the walk ended: `'complete'` (reached the end of the matching set), `'stopped'`
637
+ * (`visit` returned `false`) or `'failed'` (a page failed to load). Callers that reason about the
638
+ * WHOLE set (e.g. pruning state for absent rows) must act only on `'complete'`.
639
+ */
640
+ async forEachSessionPage(filter, provider, systemUser, visit) {
641
+ let afterKey;
642
+ // eslint-disable-next-line no-constant-condition
643
+ while (true) {
644
+ const fetched = await this.fetchPage(filter, afterKey, provider, systemUser);
645
+ if (fetched == null) {
646
+ return 'failed'; // load failure already logged
647
+ }
648
+ if (fetched.length === 0) {
649
+ return 'complete';
650
+ }
651
+ // Advance from the last FETCHED row (before `visit` narrows anything): we must page by the
652
+ // SQL-matched set, not a post-filtered subset, or pagination would stall/skip.
653
+ const lastFetchedId = fetched[fetched.length - 1].ID;
654
+ const fetchedCount = fetched.length;
655
+ if ((await visit(fetched)) === false) {
656
+ return 'stopped';
657
+ }
259
658
  if (fetchedCount < SWEEP_PAGE_SIZE) {
260
- break; // partial page (by the SQL-matched set) => end of data
659
+ return 'complete'; // partial page (by the SQL-matched set) => end of data
261
660
  }
262
661
  afterKey = CompositeKey.FromID(lastFetchedId); // first-pk-ok: keyset AfterKey on SESSION_ENTITY = MJ: AI Agent Sessions, a core entity keyed by ID
263
662
  }
264
- return closedCount;
265
663
  }
266
664
  /** Fetch one keyset page of matching sessions, or null on a load failure (logged). */
267
665
  async fetchPage(filter, afterKey, provider, systemUser) {