@sentry/junior 0.313.0 → 0.315.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (652) hide show
  1. package/dist/{channel-access-mt7K6dPh.js → adapter-context-BlSGE44V.js} +46 -7
  2. package/dist/{admin-Cyhb4TwZ.js → admin-5jUYY46p.js} +1 -1
  3. package/dist/agent-runner-C7GNLRB6.js +23438 -0
  4. package/dist/agent-update-delivery-BNEYQsAf.js +149 -0
  5. package/dist/api/schema.d.ts +9500 -2
  6. package/dist/api/schema.js +5 -7
  7. package/dist/api.d.ts +2 -3
  8. package/dist/api.js +1172 -371
  9. package/dist/{app-DA8-hCMj.d.ts → app-D_bAXRDe.d.ts} +312 -48
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +305 -184
  12. package/dist/change-record-Bqsa5ZXE.d.ts +175 -0
  13. package/dist/chat-core-engine-CxkwRpn9.js +123 -0
  14. package/dist/child-message--2G3Ft26.js +19 -0
  15. package/dist/cli/chat.d.ts +4 -1
  16. package/dist/cli/chat.js +40 -25
  17. package/dist/cli/check.js +4 -4
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.js +4 -5
  20. package/dist/cli/run.d.ts +1 -1
  21. package/dist/cli/run.js +1 -1
  22. package/dist/cli/snapshot-create.js +2 -5
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +68 -97
  25. package/dist/{continue-in-slack-CxyFzdlF.js → continue-in-slack-BGKjIdFp.js} +3 -7
  26. package/dist/{conversation-feed-BEXLD3Me.js → conversation-feed-Sl8lKKmR.js} +22 -2
  27. package/dist/{conversation-turn-B35eu0uz.js → conversation-turn-BoLK9i6g.js} +514 -83
  28. package/dist/create-BOycVH9h.js +213 -0
  29. package/dist/{credential-sync-DWTOEQrm.js → credential-sync-Mn4OdkEh.js} +10 -18
  30. package/dist/db-BpxcYXfD.d.ts +2 -0
  31. package/dist/{credentialed-Dyv8b-lu.js → db-DXTOYRzR.js} +22220 -9334
  32. package/dist/deployment-CG3TchWh.js +51 -0
  33. package/dist/direct-url-BYgYfuIy.js +22 -0
  34. package/dist/engine-context-dyWlfNdD.js +1817 -0
  35. package/dist/{html-DidUcRhI.js → html-CfXEwl_h.js} +2 -7
  36. package/dist/instrumentation.js +3 -3
  37. package/dist/job-runner-CySgpi9v.js +1131 -0
  38. package/dist/{lineage-BXplQAVH.js → lineage-tRTOcrsL.js} +1 -2
  39. package/dist/{list-DyIyReSV.js → list-DXBz8SYL.js} +610 -173
  40. package/dist/local-server-CpnGhYml.js +276 -0
  41. package/dist/{logging-DNt-qOIO.js → logging-czs0nqLC.js} +2 -45
  42. package/dist/{turn-membership-DTR3SaKD.js → mailbox-turn-79Nv1JXv.js} +4153 -559
  43. package/dist/markers-CE0HMXWT.js +67 -0
  44. package/dist/{media-B0pZJ0bG.js → media-Cr9pGkzr.js} +701 -41
  45. package/dist/{message-Z5YKC-Af.js → message-BTox2Cmb.js} +25 -36
  46. package/dist/{model-input-BhPJYdSV.js → model-input-IRGa98V7.js} +3 -3
  47. package/dist/nitro.d.ts +8 -4
  48. package/dist/nitro.js +106 -24
  49. package/dist/{oauth-callback-server-ByvDdcdY.js → oauth-callback-server-NXK7AlBp.js} +2 -2
  50. package/dist/{oauth-relay-D-kK0yoN.js → oauth-relay-6NBPSpFE.js} +1 -1
  51. package/dist/{package-discovery-DD9vencX.js → package-discovery-BI6T_RkD.js} +50 -1
  52. package/dist/parent-result-Dg6P6roR.js +323 -0
  53. package/dist/people-Cegp1Iwq.js +81 -0
  54. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  55. package/dist/{conversation-privacy-BrMiDN61.js → proxy-path-Dc-0jXGi.js} +16 -2
  56. package/dist/{resolve-CWtBNSKP.js → resolve-BUFkmxkT.js} +229 -4
  57. package/dist/result-DfATzX77.js +337 -0
  58. package/dist/{runner-CsZ_VRxp.js → runner-CmKP3inb.js} +7 -8
  59. package/dist/{sandbox-egress-signals-FbCk1FkN.js → sandbox-egress-signals-DYo5BsM7.js} +1 -1
  60. package/dist/{schema-DojR2uCL.js → schema-DrBMdPmv.js} +197 -20
  61. package/dist/{service-account-CDYb9hfX.js → service-account-CxTX7nnR.js} +4 -5
  62. package/dist/{skills-B0jP4whm.js → skills-BlHUDj7k.js} +4 -4
  63. package/dist/{slack-conversation-unfurl-D26t9kBC.js → slack-conversation-unfurl-Dhe3lB1U.js} +6 -10
  64. package/dist/{spawn-BjljgExZ.js → spawn-CfvlFdfz.js} +8 -17
  65. package/dist/start-conversation-Uh8Sk1EF.js +162 -0
  66. package/dist/system-prompt-table-CDCYVwqN.js +1169 -0
  67. package/dist/{task-runner--Ke8KSMf.js → task-runner-DcdQJd9e.js} +163 -55
  68. package/dist/{thread-context-B8exINEe.js → thread-context-DF5uDcWN.js} +7 -9
  69. package/dist/topic-CRYYBYp-.js +7 -0
  70. package/dist/transcript-BHhJVY0P.js +410 -0
  71. package/dist/turn-session-routing-GtetHsdO.js +1309 -0
  72. package/dist/turn-wake-um5Ubd4m.js +152 -0
  73. package/dist/user-customization-B27StpVQ.js +9 -0
  74. package/dist/{validation-Ce0qbMlT.js → validation-CJyuOPD2.js} +1 -1
  75. package/dist/{version-DFh4n9nr.js → version-Bhe7RPIe.js} +1 -1
  76. package/dist/version.js +1 -1
  77. package/dist/virtual-module-BeKA_EII.js +12 -0
  78. package/dist/{worker-CDg9Lbpg.js → worker-D8PRgUqr.js} +3 -6
  79. package/migrations/20260711145847_initial/snapshot.json +2103 -0
  80. package/migrations/20260711145900_conversation_metrics/snapshot.json +135 -0
  81. package/migrations/20260712153649_conversation_message_search/snapshot.json +50 -0
  82. package/migrations/20260713040256_peaceful_scalphunter/snapshot.json +42 -0
  83. package/migrations/20260715174202_useful_magus/snapshot.json +42 -0
  84. package/migrations/20260715174203_conversation_events/snapshot.json +539 -0
  85. package/migrations/20260723042835_drop_legacy_conversation_messages/snapshot.json +9 -0
  86. package/migrations/20260723050612_thick_sugar_man/snapshot.json +120 -0
  87. package/migrations/20260727223822_sticky_rage/snapshot.json +274 -0
  88. package/migrations/20260728033158_slippery_harrier/snapshot.json +191 -0
  89. package/migrations/20260728040836_native_conversation_history/snapshot.json +9 -0
  90. package/migrations/20260728204900_sour_golden_guardian/snapshot.json +124 -0
  91. package/migrations/20260730233332_structured_conversation_events/snapshot.json +9 -0
  92. package/migrations/20260731164038_conversation_session_source/snapshot.json +42 -0
  93. package/migrations/20260801230336_source_visibility/snapshot.json +9 -0
  94. package/migrations/20260802023731_magical_ezekiel_stane/snapshot.json +266 -0
  95. package/migrations/20260804015843_neat_the_anarchist/snapshot.json +714 -0
  96. package/migrations/20260804165952_drop_paused_scheduled_tasks/snapshot.json +9 -0
  97. package/migrations/20260804225613_curvy_excalibur/snapshot.json +223 -0
  98. package/migrations/20260805174033_lowly_valkyrie/snapshot.json +344 -0
  99. package/migrations/20260805200301_restrict_task_execution_kinds/snapshot.json +36 -0
  100. package/migrations/20260806030729_first_warhawk/snapshot.json +690 -0
  101. package/migrations/20260807185200_task_execution_status/snapshot.json +92 -0
  102. package/migrations/20260808014743_task_title_columns/snapshot.json +68 -0
  103. package/migrations/20260809220421_misty_typhoid_mary/snapshot.json +191 -0
  104. package/migrations/20260811193709_mcp_credential_subject/snapshot.json +9 -0
  105. package/migrations/20260812032924_conversation_event_actor_and_participants/snapshot.json +393 -0
  106. package/migrations/20260812172418_attachment_storage/snapshot.json +341 -0
  107. package/migrations/20260813230732_artifacts/snapshot.json +349 -0
  108. package/migrations/20260814062905_dizzy_barracuda/snapshot.json +342 -0
  109. package/migrations/20260814231353_drop_workspace_repo_primary/snapshot.json +55 -0
  110. package/migrations/20260815030100_wild_phantom_reporter/snapshot.json +135 -0
  111. package/migrations/20260817082233_workspace_snapshots_table/snapshot.json +625 -0
  112. package/migrations/20260818160339_workspace_snapshot_active_build/snapshot.json +62 -0
  113. package/migrations/20260821180755_strong_randall/snapshot.json +42 -0
  114. package/migrations/20260823030308_workspace_snapshot_size_bytes/snapshot.json +62 -0
  115. package/migrations/20260824190313_complex_rage/snapshot.json +690 -0
  116. package/migrations/20260827233711_conversation_location/snapshot.json +42 -0
  117. package/migrations/20260901224306_event_task_status/snapshot.json +100 -0
  118. package/migrations/20260904153232_attachment_provider/snapshot.json +234 -0
  119. package/migrations/20260909111415_conversation_briefs/snapshot.json +364 -0
  120. package/migrations/20260910144928_automation_outcomes_backfill/snapshot.json +9 -0
  121. package/migrations/20260911184346_conversation_metrics/snapshot.json +226 -0
  122. package/migrations/20260921140842_scheduled_automation_channel_destinations/snapshot.json +9 -0
  123. package/migrations/20260922221709_event_automation_channel_destinations/snapshot.json +9 -0
  124. package/migrations/20261001113455_conversation_forks/snapshot.json +120 -0
  125. package/migrations/20261005161844_automation_versions/snapshot.json +150 -0
  126. package/migrations/20261006152043_user_timezone/snapshot.json +37 -0
  127. package/migrations/20261008200858_user_admin/snapshot.json +37 -0
  128. package/migrations/20261009145407_event_automation_status_reason/snapshot.json +42 -0
  129. package/migrations/20261013160816_agent_invocation_parent_mailbox/snapshot.json +93 -0
  130. package/migrations/20261013215020_agent_invocation_parent_tool_call/snapshot.json +42 -0
  131. package/migrations/20261014011138_agent_invocation_title/snapshot.json +42 -0
  132. package/migrations/20261014211942_conversation_stopped_at/snapshot.json +42 -0
  133. package/migrations/20261015012820_flowery_rage/snapshot.json +42 -0
  134. package/migrations/20261017000924_automations/snapshot.json +790 -0
  135. package/migrations/20261017134736_automation_runs/snapshot.json +474 -0
  136. package/migrations/20261017170250_drop_legacy_automation_tables/snapshot.json +397 -0
  137. package/migrations/20261018134754_automation_creator_identity/snapshot.json +130 -0
  138. package/migrations/20261023071954_automation_run_version/snapshot.json +79 -0
  139. package/migrations/20261025233137_identity_signed_in_at/snapshot.json +42 -0
  140. package/migrations/20261027234315_workspace_vcpus/snapshot.json +37 -0
  141. package/migrations/20261028124242_plugin_report_index/snapshot.json +68 -0
  142. package/migrations/20261028154230_agent_invocation_type/snapshot.json +42 -0
  143. package/migrations/20261030021803_any_resource_event_triggers/snapshot.json +42 -0
  144. package/migrations/20261030234309_user_customization/snapshot.json +37 -0
  145. package/migrations/20261031020656_review_items/snapshot.json +1078 -0
  146. package/migrations/20261031024151_review_item_dedupe_tenant/snapshot.json +62 -0
  147. package/migrations/20261031024246_review_item_slack_cards/snapshot.json +159 -0
  148. package/migrations/20261031155308_system_identity/snapshot.json +9 -0
  149. package/migrations/20261101193952_review_item_foreign_keys/snapshot.json +108 -0
  150. package/migrations/20261102172751_review_item_turn/snapshot.json +42 -0
  151. package/migrations/20261102221411_conversation_read_positions/snapshot.json +190 -0
  152. package/migrations/20261104085028_conversation_quick_question/snapshot.json +42 -0
  153. package/migrations/20261104145136_conversation_participant_pins/snapshot.json +42 -0
  154. package/migrations/20261104164429_conversation_detail_version/snapshot.json +42 -0
  155. package/migrations/20261104172055_conversation_auto_archive/snapshot.json +206 -0
  156. package/migrations/20261105005443_drop_agent_invocation_model_profile/snapshot.json +30 -0
  157. package/migrations/20261105043807_plugin_conversation_index/snapshot.json +76 -0
  158. package/migrations/20261105051837_conversation_event_author_index/snapshot.json +70 -0
  159. package/migrations/20261105182854_conversation_event_latest_message_indexes/snapshot.json +136 -0
  160. package/migrations/20261106011443_conversation_pin_position/snapshot.json +42 -0
  161. package/migrations/20261106095004_push_notifications/snapshot.json +308 -0
  162. package/migrations/20261106162740_conversation_kind/snapshot.json +88 -0
  163. package/migrations/20261107002001_read_position_backfill/snapshot.json +9 -0
  164. package/migrations/20261107025209_child_archived_at/snapshot.json +42 -0
  165. package/migrations/20261107035735_shared_archive/snapshot.json +67 -0
  166. package/migrations/20261107215055_child_location/snapshot.json +9 -0
  167. package/migrations/20261108191927_conversation_unsubscribe/snapshot.json +42 -0
  168. package/migrations/20261109021618_conversation_paused_status/snapshot.json +9 -0
  169. package/migrations/20261109111553_guardian_review_time_index/snapshot.json +54 -0
  170. package/migrations/20261109173130_conversation_participant_unsubscribed_index/snapshot.json +62 -0
  171. package/migrations/20261109182006_turn_metric_actor/snapshot.json +128 -0
  172. package/migrations/20261109202836_participant_root_actor_backfill/snapshot.json +9 -0
  173. package/migrations/20261109232640_conversation_delivery_paused_at/snapshot.json +42 -0
  174. package/migrations/20261110120937_web_linked_slack_identity_repair/snapshot.json +9 -0
  175. package/migrations/20261110175824_automation_task_kind/snapshot.json +145 -0
  176. package/migrations/20261110210242_conversation_kind_automation/snapshot.json +55 -0
  177. package/migrations/20261110222632_review_item_plugin_actions/snapshot.json +37 -0
  178. package/migrations/20261110225157_conversation_last_message_at/snapshot.json +42 -0
  179. package/migrations/20261111013351_automation_task_kind_repair/snapshot.json +9 -0
  180. package/migrations/20261111163126_drop_legacy_columns/snapshot.json +9 -0
  181. package/migrations/20261111170150_code_change_last_activity/snapshot.json +42 -0
  182. package/migrations/20261111191441_agent_invocation_fork/snapshot.json +42 -0
  183. package/migrations/20261112142841_code_change_draft/snapshot.json +37 -0
  184. package/migrations/20261112202901_attachment_uploads/snapshot.json +255 -0
  185. package/migrations/20261112220407_conversation_agent_config/snapshot.json +42 -0
  186. package/migrations/20261113081247_attachment_deferred_download/snapshot.json +52 -0
  187. package/migrations/20261113225551_conversation_embeddings/snapshot.json +203 -0
  188. package/migrations/20261114213238_user_preferences/snapshot.json +37 -0
  189. package/migrations/20261114222527_code_change_repository_state_index/snapshot.json +70 -0
  190. package/migrations/20261115172605_attachment_kinds/snapshot.json +244 -0
  191. package/migrations/20261115173004_attachment_url_fill/snapshot.json +9 -0
  192. package/migrations/20261115180216_attachment_url_index/snapshot.json +62 -0
  193. package/migrations/20261116103700_plan_items/snapshot.json +420 -0
  194. package/migrations/20261117100100_automation_creator_slack_index/snapshot.json +62 -0
  195. package/migrations/20261117132522_conversation_event_search/snapshot.json +396 -0
  196. package/migrations/20261117164007_automation_last_run/snapshot.json +108 -0
  197. package/migrations/20261117164047_automation_last_run_index/snapshot.json +54 -0
  198. package/migrations/20261117210444_money_micro_usd/snapshot.json +68 -0
  199. package/migrations/20261117210505_conversation_cost_micro_usd/snapshot.json +9 -0
  200. package/migrations/20261118081416_people_list_metric_index/snapshot.json +86 -0
  201. package/migrations/20261118095216_automation_rollout_repair/snapshot.json +9 -0
  202. package/migrations/20261118143948_cache_warming_history_reset/snapshot.json +9 -0
  203. package/migrations/20261119040651_artifact_visibility/snapshot.json +132 -0
  204. package/migrations/20261119040715_artifact_public_sha_index/snapshot.json +9 -0
  205. package/migrations/20261119052706_artifact_drop_public/snapshot.json +71 -0
  206. package/migrations/20261119053831_artifact_path/snapshot.json +114 -0
  207. package/migrations/20261119053844_artifact_path_index/snapshot.json +9 -0
  208. package/migrations/20261119091949_review_item_answered_index/snapshot.json +70 -0
  209. package/migrations/20261119100029_review_item_status_index/snapshot.json +54 -0
  210. package/migrations/20261119165607_brief_outcome_status/snapshot.json +42 -0
  211. package/migrations/20261119165622_brief_outcome_status_backfill/snapshot.json +9 -0
  212. package/migrations/20261119213716_brief_created_at_index/snapshot.json +62 -0
  213. package/migrations/20261119222456_slack_person_search_index/snapshot.json +50 -0
  214. package/migrations/20261119225522_code_change_size/snapshot.json +104 -0
  215. package/migrations/20261119232253_merge_conflict_notice_dismiss/snapshot.json +9 -0
  216. package/migrations/20261119235649_inbox_snoozes/snapshot.json +605 -0
  217. package/migrations/20261120093118_code_change_search_index/snapshot.json +89 -0
  218. package/migrations/20261120093452_review_item_owner/snapshot.json +314 -0
  219. package/migrations/20261120185654_review_item_owner_index/snapshot.json +62 -0
  220. package/migrations/20261120185754_memory_core_adoption/snapshot.json +1184 -0
  221. package/migrations/20261120185854_memory_core_indexes/snapshot.json +70 -0
  222. package/migrations/20261120235226_todos/snapshot.json +473 -0
  223. package/migrations/20261121082316_inbox_items/snapshot.json +2026 -0
  224. package/migrations/20261121175651_todo_changed_by_agent/snapshot.json +42 -0
  225. package/migrations/20261121183527_inbox_item_subject_title_parts/snapshot.json +42 -0
  226. package/migrations/20261121194143_inbox_snooze_wake_reason/snapshot.json +42 -0
  227. package/migrations/20261121222400_authorization_request_index/snapshot.json +62 -0
  228. package/migrations/20261121225908_conversation_metadata/snapshot.json +184 -0
  229. package/migrations/20261121225910_conversation_metadata_fill/snapshot.json +9 -0
  230. package/migrations/20261121225913_conversation_search_index/snapshot.json +50 -0
  231. package/migrations/20261122022900_inbox_item_legacy_automation_keys/snapshot.json +9 -0
  232. package/migrations/20261122024454_artifact_expiry/snapshot.json +37 -0
  233. package/migrations/20261122024455_artifact_permanent_sha_index/snapshot.json +62 -0
  234. package/migrations/20261122024457_artifact_drop_public_sha_index/snapshot.json +37 -0
  235. package/migrations/20261122024458_conversation_kind_lead/snapshot.json +55 -0
  236. package/migrations/20261122024459_conversation_lead_actor_index/snapshot.json +54 -0
  237. package/migrations/20261122071549_keep_legacy_archive_columns/snapshot.json +49 -0
  238. package/migrations/20261122191400_conversation_embeddings_fk_validate/snapshot.json +9 -0
  239. package/migrations/20261122204325_money_micro_usd_repair/migration.sql +99 -0
  240. package/migrations/20261122204325_money_micro_usd_repair/snapshot.json +9 -0
  241. package/migrations/20261122204326_agent_config_backfill/migration.sql +34 -0
  242. package/migrations/20261122204326_agent_config_backfill/snapshot.json +143 -0
  243. package/migrations/20261122221456_inbox_item_deliveries/migration.sql +15 -0
  244. package/migrations/20261122221456_inbox_item_deliveries/snapshot.json +301 -0
  245. package/migrations/20261123155735_pg_trgm/migration.sql +2 -0
  246. package/migrations/20261123155735_pg_trgm/snapshot.json +9 -0
  247. package/migrations/20261123155739_search_indexes/migration.sql +4 -0
  248. package/migrations/20261123155739_search_indexes/snapshot.json +167 -0
  249. package/migrations/20261123172647_drop_legacy_archive_columns/migration.sql +4 -0
  250. package/migrations/20261123172647_drop_legacy_archive_columns/snapshot.json +9 -0
  251. package/migrations/20261123192506_memory_prefix_index/migration.sql +1 -0
  252. package/migrations/20261123192506_memory_prefix_index/snapshot.json +69 -0
  253. package/migrations/20261123201740_todo_search_indexes/migration.sql +2 -0
  254. package/migrations/20261123201740_todo_search_indexes/snapshot.json +89 -0
  255. package/migrations/20261123211505_todo_inbox_items/migration.sql +4 -0
  256. package/migrations/20261123211505_todo_inbox_items/snapshot.json +38 -0
  257. package/migrations/20261123214917_drop_code_urls/migration.sql +2 -0
  258. package/migrations/20261123214917_drop_code_urls/snapshot.json +44 -0
  259. package/migrations/20261123224000_code_change_conversations_index/migration.sql +1 -0
  260. package/migrations/20261123224000_code_change_conversations_index/snapshot.json +54 -0
  261. package/migrations/20261124122023_drop_code_change_sizes/migration.sql +4 -0
  262. package/migrations/20261124122023_drop_code_change_sizes/snapshot.json +82 -0
  263. package/migrations/20261124142958_conversation_root_lookup_index/migration.sql +1 -0
  264. package/migrations/20261124142958_conversation_root_lookup_index/snapshot.json +62 -0
  265. package/migrations/20261124183352_legacy_brief_metadata_fill/migration.sql +26 -0
  266. package/migrations/20261124183352_legacy_brief_metadata_fill/snapshot.json +114 -0
  267. package/migrations/20261124202143_drizzle_v1_baseline/migration.sql +5 -0
  268. package/migrations/20261124202143_drizzle_v1_baseline/snapshot.json +2012 -0
  269. package/migrations/20261124221751_spaces/migration.sql +22 -0
  270. package/migrations/20261124221751_spaces/snapshot.json +436 -0
  271. package/migrations/20261124230319_conversation_metrics_utc_day_stats/migration.sql +11 -0
  272. package/migrations/20261124230319_conversation_metrics_utc_day_stats/snapshot.json +9 -0
  273. package/migrations/20261124234024_space_conversations/migration.sql +5 -0
  274. package/migrations/20261124234024_space_conversations/snapshot.json +103 -0
  275. package/migrations/20261124234026_space_conversations_index/migration.sql +1 -0
  276. package/migrations/20261124234026_space_conversations_index/snapshot.json +62 -0
  277. package/migrations/20261125012448_drop_lead_actor_index/migration.sql +3 -0
  278. package/migrations/20261125012448_drop_lead_actor_index/snapshot.json +36 -0
  279. package/migrations/20261125012452_space_lead_index/migration.sql +1 -0
  280. package/migrations/20261125012452_space_lead_index/snapshot.json +54 -0
  281. package/migrations/20261125043821_space_configurations/migration.sql +11 -0
  282. package/migrations/20261125043821_space_configurations/snapshot.json +194 -0
  283. package/migrations/20261125064854_agent_update_done_status/migration.sql +9 -0
  284. package/migrations/20261125064854_agent_update_done_status/snapshot.json +9 -0
  285. package/migrations/20261125073321_turn_engine_tables/migration.sql +75 -0
  286. package/migrations/20261125073321_turn_engine_tables/snapshot.json +1497 -0
  287. package/migrations/20261125073339_turn_inbox_one_source/migration.sql +5 -0
  288. package/migrations/20261125073339_turn_inbox_one_source/snapshot.json +9 -0
  289. package/migrations/20261125124506_versions_notify/migration.sql +27 -0
  290. package/migrations/20261125124506_versions_notify/snapshot.json +9 -0
  291. package/migrations/20261125140339_turn_group_key/migration.sql +14 -0
  292. package/migrations/20261125140339_turn_group_key/snapshot.json +75 -0
  293. package/migrations/20261125140343_turn_group_key_not_null/migration.sql +4 -0
  294. package/migrations/20261125140343_turn_group_key_not_null/snapshot.json +29 -0
  295. package/migrations/20261125142845_code_change_requesters/migration.sql +1 -0
  296. package/migrations/20261125142845_code_change_requesters/snapshot.json +42 -0
  297. package/migrations/20261125142846_code_change_requesters_index/migration.sql +1 -0
  298. package/migrations/20261125142846_code_change_requesters_index/snapshot.json +54 -0
  299. package/migrations/20261125143903_space_visibility/migration.sql +1 -0
  300. package/migrations/20261125143903_space_visibility/snapshot.json +37 -0
  301. package/migrations/20261125154848_merge_leaves/migration.sql +2 -0
  302. package/migrations/20261125154848_merge_leaves/snapshot.json +14 -0
  303. package/package.json +17 -25
  304. package/skills/design-automation-skill/SKILL.md +3 -4
  305. package/dist/actor-BsBdxDXQ.js +0 -208
  306. package/dist/adapter-CYAvJzZS.js +0 -259
  307. package/dist/adapter-context-CVsHoVSf.js +0 -43
  308. package/dist/agent-runner-B5y9MsT-.js +0 -11295
  309. package/dist/background-compaction-queue-iZXadLV3.js +0 -206
  310. package/dist/catalog-runtime-kkE3hvCX.js +0 -6
  311. package/dist/config-CWbwKj0j.js +0 -2331
  312. package/dist/db-DYGcXYl3.d.ts +0 -274
  313. package/dist/db-PwSRzWWn.js +0 -3607
  314. package/dist/executor-CgWyWfYz.js +0 -1858
  315. package/dist/fan-out-Cod-yEHG.js +0 -10
  316. package/dist/history-CYstOMKX.js +0 -577
  317. package/dist/ingest-B0AggUEC.js +0 -7931
  318. package/dist/install-2urLLXNt.js +0 -228
  319. package/dist/proxy-path-BHYoKZdq.js +0 -15
  320. package/dist/registry-POH4bZC4.js +0 -1686
  321. package/dist/request-deadline-BUiRYQYj.js +0 -24
  322. package/dist/rule-DAxQY-1h.js +0 -20
  323. package/dist/schema-DBf18QPS.d.ts +0 -9339
  324. package/dist/service-account-o15pZWcJ.js +0 -931
  325. package/dist/start-conversation-DbVujrwO.js +0 -755
  326. package/dist/state-BTawTCme.js +0 -161
  327. package/dist/statuses-BKwqCPhj.js +0 -69
  328. package/dist/store-CjXrp-Up.js +0 -492
  329. package/dist/task-queue-Cwlatjz3.js +0 -90
  330. package/dist/vercel-queue-q4z8w5QO.js +0 -349
  331. package/dist/warmup-D5hzqTcp.js +0 -12257
  332. package/migrations/meta/0000_snapshot.json +0 -946
  333. package/migrations/meta/0001_snapshot.json +0 -972
  334. package/migrations/meta/0002_snapshot.json +0 -987
  335. package/migrations/meta/0003_snapshot.json +0 -1035
  336. package/migrations/meta/0004_snapshot.json +0 -1041
  337. package/migrations/meta/0005_snapshot.json +0 -948
  338. package/migrations/meta/0006_snapshot.json +0 -948
  339. package/migrations/meta/0007_snapshot.json +0 -1013
  340. package/migrations/meta/0008_snapshot.json +0 -1076
  341. package/migrations/meta/0009_snapshot.json +0 -1146
  342. package/migrations/meta/0010_snapshot.json +0 -1190
  343. package/migrations/meta/0011_snapshot.json +0 -1195
  344. package/migrations/meta/0012_snapshot.json +0 -1244
  345. package/migrations/meta/0013_snapshot.json +0 -1250
  346. package/migrations/meta/0014_snapshot.json +0 -1201
  347. package/migrations/meta/0015_snapshot.json +0 -1360
  348. package/migrations/meta/0016_snapshot.json +0 -1617
  349. package/migrations/meta/0017_snapshot.json +0 -1666
  350. package/migrations/meta/0018_snapshot.json +0 -1756
  351. package/migrations/meta/0019_snapshot.json +0 -1904
  352. package/migrations/meta/0020_snapshot.json +0 -1848
  353. package/migrations/meta/0021_snapshot.json +0 -2176
  354. package/migrations/meta/0022_snapshot.json +0 -2186
  355. package/migrations/meta/0023_snapshot.json +0 -2198
  356. package/migrations/meta/0024_snapshot.json +0 -2275
  357. package/migrations/meta/0025_snapshot.json +0 -2275
  358. package/migrations/meta/0026_snapshot.json +0 -2424
  359. package/migrations/meta/0027_snapshot.json +0 -2554
  360. package/migrations/meta/0028_snapshot.json +0 -2685
  361. package/migrations/meta/0029_snapshot.json +0 -2709
  362. package/migrations/meta/0030_snapshot.json +0 -2799
  363. package/migrations/meta/0031_snapshot.json +0 -2823
  364. package/migrations/meta/0032_snapshot.json +0 -2892
  365. package/migrations/meta/0033_snapshot.json +0 -2914
  366. package/migrations/meta/0034_snapshot.json +0 -3038
  367. package/migrations/meta/0035_snapshot.json +0 -3048
  368. package/migrations/meta/0036_snapshot.json +0 -3186
  369. package/migrations/meta/0037_snapshot.json +0 -3192
  370. package/migrations/meta/0038_snapshot.json +0 -3323
  371. package/migrations/meta/0039_snapshot.json +0 -3368
  372. package/migrations/meta/0040_snapshot.json +0 -3516
  373. package/migrations/meta/0041_snapshot.json +0 -3516
  374. package/migrations/meta/0042_snapshot.json +0 -3610
  375. package/migrations/meta/0043_snapshot.json +0 -3610
  376. package/migrations/meta/0044_snapshot.json +0 -3473
  377. package/migrations/meta/0045_snapshot.json +0 -3503
  378. package/migrations/meta/0046_snapshot.json +0 -3707
  379. package/migrations/meta/0047_snapshot.json +0 -3713
  380. package/migrations/meta/0048_snapshot.json +0 -3720
  381. package/migrations/meta/0049_snapshot.json +0 -3581
  382. package/migrations/meta/0050_snapshot.json +0 -3753
  383. package/migrations/meta/0051_snapshot.json +0 -3759
  384. package/migrations/meta/0052_snapshot.json +0 -3765
  385. package/migrations/meta/0053_snapshot.json +0 -3771
  386. package/migrations/meta/0054_snapshot.json +0 -3777
  387. package/migrations/meta/0055_snapshot.json +0 -3948
  388. package/migrations/meta/0056_snapshot.json +0 -4280
  389. package/migrations/meta/0057_snapshot.json +0 -3618
  390. package/migrations/meta/0058_snapshot.json +0 -3598
  391. package/migrations/meta/0059_snapshot.json +0 -3619
  392. package/migrations/meta/0060_snapshot.json +0 -3465
  393. package/migrations/meta/0061_snapshot.json +0 -3471
  394. package/migrations/meta/0062_snapshot.json +0 -3499
  395. package/migrations/meta/0063_snapshot.json +0 -3505
  396. package/migrations/meta/0064_snapshot.json +0 -3505
  397. package/migrations/meta/0065_snapshot.json +0 -3511
  398. package/migrations/meta/0066_snapshot.json +0 -4099
  399. package/migrations/meta/0067_snapshot.json +0 -3921
  400. package/migrations/meta/0068_snapshot.json +0 -4176
  401. package/migrations/meta/0069_snapshot.json +0 -3979
  402. package/migrations/meta/0070_snapshot.json +0 -3997
  403. package/migrations/meta/0071_snapshot.json +0 -4003
  404. package/migrations/meta/0072_snapshot.json +0 -4064
  405. package/migrations/meta/0073_snapshot.json +0 -4070
  406. package/migrations/meta/0074_snapshot.json +0 -4076
  407. package/migrations/meta/0075_snapshot.json +0 -4083
  408. package/migrations/meta/0076_snapshot.json +0 -4147
  409. package/migrations/meta/0077_snapshot.json +0 -4141
  410. package/migrations/meta/0078_snapshot.json +0 -4175
  411. package/migrations/meta/0079_snapshot.json +0 -4203
  412. package/migrations/meta/0080_snapshot.json +0 -4265
  413. package/migrations/meta/0081_snapshot.json +0 -4271
  414. package/migrations/meta/0082_snapshot.json +0 -4373
  415. package/migrations/meta/0083_snapshot.json +0 -4388
  416. package/migrations/meta/0084_snapshot.json +0 -4388
  417. package/migrations/meta/0085_snapshot.json +0 -4394
  418. package/migrations/meta/0086_snapshot.json +0 -4366
  419. package/migrations/meta/0087_snapshot.json +0 -4366
  420. package/migrations/meta/0088_snapshot.json +0 -4372
  421. package/migrations/meta/0089_snapshot.json +0 -4372
  422. package/migrations/meta/0090_snapshot.json +0 -4388
  423. package/migrations/meta/0091_snapshot.json +0 -4410
  424. package/migrations/meta/0092_snapshot.json +0 -4446
  425. package/migrations/meta/0093_snapshot.json +0 -4446
  426. package/migrations/meta/0094_snapshot.json +0 -4452
  427. package/migrations/meta/0095_snapshot.json +0 -4452
  428. package/migrations/meta/0096_snapshot.json +0 -4490
  429. package/migrations/meta/0097_snapshot.json +0 -4490
  430. package/migrations/meta/0098_snapshot.json +0 -4490
  431. package/migrations/meta/0099_snapshot.json +0 -4496
  432. package/migrations/meta/0100_snapshot.json +0 -4496
  433. package/migrations/meta/0101_snapshot.json +0 -4496
  434. package/migrations/meta/0102_snapshot.json +0 -4502
  435. package/migrations/meta/0103_snapshot.json +0 -4509
  436. package/migrations/meta/0104_snapshot.json +0 -4516
  437. package/migrations/meta/0105_snapshot.json +0 -4611
  438. package/migrations/meta/0106_snapshot.json +0 -4617
  439. package/migrations/meta/0107_snapshot.json +0 -4617
  440. package/migrations/meta/0108_snapshot.json +0 -4688
  441. package/migrations/meta/0109_snapshot.json +0 -4925
  442. package/migrations/meta/0110_snapshot.json +0 -4952
  443. package/migrations/meta/0111_snapshot.json +0 -5011
  444. package/migrations/meta/0112_snapshot.json +0 -5011
  445. package/migrations/meta/0113_snapshot.json +0 -5033
  446. package/migrations/meta/0114_snapshot.json +0 -5203
  447. package/migrations/meta/0115_snapshot.json +0 -5225
  448. package/migrations/meta/0116_snapshot.json +0 -5388
  449. package/migrations/meta/0117_snapshot.json +0 -5413
  450. package/migrations/meta/0118_snapshot.json +0 -5428
  451. package/migrations/meta/0119_snapshot.json +0 -5441
  452. package/migrations/meta/0120_snapshot.json +0 -5441
  453. package/migrations/meta/0121_snapshot.json +0 -5481
  454. package/migrations/meta/0122_snapshot.json +0 -5481
  455. package/migrations/meta/0123_snapshot.json +0 -5481
  456. package/migrations/meta/0124_snapshot.json +0 -5516
  457. package/migrations/meta/0125_snapshot.json +0 -5516
  458. package/migrations/meta/0126_snapshot.json +0 -5488
  459. package/migrations/meta/0127_snapshot.json +0 -5519
  460. package/migrations/meta/0128_snapshot.json +0 -5519
  461. package/migrations/meta/0129_snapshot.json +0 -5547
  462. package/migrations/meta/0130_snapshot.json +0 -5563
  463. package/migrations/meta/0131_snapshot.json +0 -5569
  464. package/migrations/meta/0132_snapshot.json +0 -5569
  465. package/migrations/meta/0133_snapshot.json +0 -5590
  466. package/migrations/meta/0134_snapshot.json +0 -5606
  467. package/migrations/meta/0135_snapshot.json +0 -5624
  468. package/migrations/meta/0136_snapshot.json +0 -5624
  469. package/migrations/meta/0137_snapshot.json +0 -5864
  470. package/migrations/meta/0138_snapshot.json +0 -5894
  471. package/migrations/meta/0139_snapshot.json +0 -5898
  472. package/migrations/meta/0140_snapshot.json +0 -5919
  473. package/migrations/meta/0141_snapshot.json +0 -6429
  474. package/migrations/meta/0142_snapshot.json +0 -6457
  475. package/migrations/meta/0143_snapshot.json +0 -6434
  476. package/migrations/meta/0144_snapshot.json +0 -6434
  477. package/migrations/meta/0145_snapshot.json +0 -6440
  478. package/migrations/meta/0146_snapshot.json +0 -6446
  479. package/migrations/meta/0147_snapshot.json +0 -6452
  480. package/migrations/meta/0148_snapshot.json +0 -6474
  481. package/migrations/meta/0149_snapshot.json +0 -6490
  482. package/migrations/meta/0150_snapshot.json +0 -6490
  483. package/migrations/meta/0151_snapshot.json +0 -6505
  484. package/migrations/meta/0152_snapshot.json +0 -6505
  485. package/migrations/meta/0153_snapshot.json +0 -6511
  486. package/migrations/meta/0154_snapshot.json +0 -6533
  487. package/migrations/meta/0155_snapshot.json +0 -6511
  488. package/migrations/meta/0156_snapshot.json +0 -6511
  489. package/migrations/meta/0157_snapshot.json +0 -6527
  490. package/migrations/meta/0158_snapshot.json +0 -6515
  491. package/migrations/meta/0159_snapshot.json +0 -6515
  492. package/migrations/meta/_journal.json +0 -1126
  493. /package/migrations/{0000_initial.sql → 20260711145847_initial/migration.sql} +0 -0
  494. /package/migrations/{0001_conversation_metrics.sql → 20260711145900_conversation_metrics/migration.sql} +0 -0
  495. /package/migrations/{0002_conversation_message_search.sql → 20260712153649_conversation_message_search/migration.sql} +0 -0
  496. /package/migrations/{0003_peaceful_scalphunter.sql → 20260713040256_peaceful_scalphunter/migration.sql} +0 -0
  497. /package/migrations/{0004_useful_magus.sql → 20260715174202_useful_magus/migration.sql} +0 -0
  498. /package/migrations/{0005_conversation_events.sql → 20260715174203_conversation_events/migration.sql} +0 -0
  499. /package/migrations/{0006_drop_legacy_conversation_messages.sql → 20260723042835_drop_legacy_conversation_messages/migration.sql} +0 -0
  500. /package/migrations/{0007_thick_sugar_man.sql → 20260723050612_thick_sugar_man/migration.sql} +0 -0
  501. /package/migrations/{0008_sticky_rage.sql → 20260727223822_sticky_rage/migration.sql} +0 -0
  502. /package/migrations/{0009_slippery_harrier.sql → 20260728033158_slippery_harrier/migration.sql} +0 -0
  503. /package/migrations/{0010_native_conversation_history.sql → 20260728040836_native_conversation_history/migration.sql} +0 -0
  504. /package/migrations/{0011_sour_golden_guardian.sql → 20260728204900_sour_golden_guardian/migration.sql} +0 -0
  505. /package/migrations/{0012_structured_conversation_events.sql → 20260730233332_structured_conversation_events/migration.sql} +0 -0
  506. /package/migrations/{0013_conversation_session_source.sql → 20260731164038_conversation_session_source/migration.sql} +0 -0
  507. /package/migrations/{0014_source_visibility.sql → 20260801230336_source_visibility/migration.sql} +0 -0
  508. /package/migrations/{0015_magical_ezekiel_stane.sql → 20260802023731_magical_ezekiel_stane/migration.sql} +0 -0
  509. /package/migrations/{0016_neat_the_anarchist.sql → 20260804015843_neat_the_anarchist/migration.sql} +0 -0
  510. /package/migrations/{0017_drop_paused_scheduled_tasks.sql → 20260804165952_drop_paused_scheduled_tasks/migration.sql} +0 -0
  511. /package/migrations/{0018_curvy_excalibur.sql → 20260804225613_curvy_excalibur/migration.sql} +0 -0
  512. /package/migrations/{0019_lowly_valkyrie.sql → 20260805174033_lowly_valkyrie/migration.sql} +0 -0
  513. /package/migrations/{0020_restrict_task_execution_kinds.sql → 20260805200301_restrict_task_execution_kinds/migration.sql} +0 -0
  514. /package/migrations/{0021_first_warhawk.sql → 20260806030729_first_warhawk/migration.sql} +0 -0
  515. /package/migrations/{0022_task_execution_status.sql → 20260807185200_task_execution_status/migration.sql} +0 -0
  516. /package/migrations/{0023_task_title_columns.sql → 20260808014743_task_title_columns/migration.sql} +0 -0
  517. /package/migrations/{0024_misty_typhoid_mary.sql → 20260809220421_misty_typhoid_mary/migration.sql} +0 -0
  518. /package/migrations/{0025_mcp_credential_subject.sql → 20260811193709_mcp_credential_subject/migration.sql} +0 -0
  519. /package/migrations/{0026_conversation_event_actor_and_participants.sql → 20260812032924_conversation_event_actor_and_participants/migration.sql} +0 -0
  520. /package/migrations/{0027_attachment_storage.sql → 20260812172418_attachment_storage/migration.sql} +0 -0
  521. /package/migrations/{0028_artifacts.sql → 20260813230732_artifacts/migration.sql} +0 -0
  522. /package/migrations/{0029_dizzy_barracuda.sql → 20260814062905_dizzy_barracuda/migration.sql} +0 -0
  523. /package/migrations/{0030_drop_workspace_repo_primary.sql → 20260814231353_drop_workspace_repo_primary/migration.sql} +0 -0
  524. /package/migrations/{0031_wild_phantom_reporter.sql → 20260815030100_wild_phantom_reporter/migration.sql} +0 -0
  525. /package/migrations/{0032_workspace_snapshots_table.sql → 20260817082233_workspace_snapshots_table/migration.sql} +0 -0
  526. /package/migrations/{0033_workspace_snapshot_active_build.sql → 20260818160339_workspace_snapshot_active_build/migration.sql} +0 -0
  527. /package/migrations/{0034_strong_randall.sql → 20260821180755_strong_randall/migration.sql} +0 -0
  528. /package/migrations/{0035_workspace_snapshot_size_bytes.sql → 20260823030308_workspace_snapshot_size_bytes/migration.sql} +0 -0
  529. /package/migrations/{0036_complex_rage.sql → 20260824190313_complex_rage/migration.sql} +0 -0
  530. /package/migrations/{0037_conversation_location.sql → 20260827233711_conversation_location/migration.sql} +0 -0
  531. /package/migrations/{0038_event_task_status.sql → 20260901224306_event_task_status/migration.sql} +0 -0
  532. /package/migrations/{0039_attachment_provider.sql → 20260904153232_attachment_provider/migration.sql} +0 -0
  533. /package/migrations/{0040_conversation_briefs.sql → 20260909111415_conversation_briefs/migration.sql} +0 -0
  534. /package/migrations/{0041_automation_outcomes_backfill.sql → 20260910144928_automation_outcomes_backfill/migration.sql} +0 -0
  535. /package/migrations/{0042_conversation_metrics.sql → 20260911184346_conversation_metrics/migration.sql} +0 -0
  536. /package/migrations/{0043_scheduled_automation_channel_destinations.sql → 20260921140842_scheduled_automation_channel_destinations/migration.sql} +0 -0
  537. /package/migrations/{0044_event_automation_channel_destinations.sql → 20260922221709_event_automation_channel_destinations/migration.sql} +0 -0
  538. /package/migrations/{0045_conversation_forks.sql → 20261001113455_conversation_forks/migration.sql} +0 -0
  539. /package/migrations/{0046_automation_versions.sql → 20261005161844_automation_versions/migration.sql} +0 -0
  540. /package/migrations/{0047_user_timezone.sql → 20261006152043_user_timezone/migration.sql} +0 -0
  541. /package/migrations/{0048_user_admin.sql → 20261008200858_user_admin/migration.sql} +0 -0
  542. /package/migrations/{0049_event_automation_status_reason.sql → 20261009145407_event_automation_status_reason/migration.sql} +0 -0
  543. /package/migrations/{0050_agent_invocation_parent_mailbox.sql → 20261013160816_agent_invocation_parent_mailbox/migration.sql} +0 -0
  544. /package/migrations/{0051_agent_invocation_parent_tool_call.sql → 20261013215020_agent_invocation_parent_tool_call/migration.sql} +0 -0
  545. /package/migrations/{0052_agent_invocation_title.sql → 20261014011138_agent_invocation_title/migration.sql} +0 -0
  546. /package/migrations/{0053_conversation_stopped_at.sql → 20261014211942_conversation_stopped_at/migration.sql} +0 -0
  547. /package/migrations/{0054_flowery_rage.sql → 20261015012820_flowery_rage/migration.sql} +0 -0
  548. /package/migrations/{0055_automations.sql → 20261017000924_automations/migration.sql} +0 -0
  549. /package/migrations/{0056_automation_runs.sql → 20261017134736_automation_runs/migration.sql} +0 -0
  550. /package/migrations/{0057_drop_legacy_automation_tables.sql → 20261017170250_drop_legacy_automation_tables/migration.sql} +0 -0
  551. /package/migrations/{0058_automation_creator_identity.sql → 20261018134754_automation_creator_identity/migration.sql} +0 -0
  552. /package/migrations/{0059_automation_run_version.sql → 20261023071954_automation_run_version/migration.sql} +0 -0
  553. /package/migrations/{0060_identity_signed_in_at.sql → 20261025233137_identity_signed_in_at/migration.sql} +0 -0
  554. /package/migrations/{0061_workspace_vcpus.sql → 20261027234315_workspace_vcpus/migration.sql} +0 -0
  555. /package/migrations/{0062_plugin_report_index.sql → 20261028124242_plugin_report_index/migration.sql} +0 -0
  556. /package/migrations/{0063_agent_invocation_type.sql → 20261028154230_agent_invocation_type/migration.sql} +0 -0
  557. /package/migrations/{0064_any_resource_event_triggers.sql → 20261030021803_any_resource_event_triggers/migration.sql} +0 -0
  558. /package/migrations/{0065_user_customization.sql → 20261030234309_user_customization/migration.sql} +0 -0
  559. /package/migrations/{0066_review_items.sql → 20261031020656_review_items/migration.sql} +0 -0
  560. /package/migrations/{0067_review_item_dedupe_tenant.sql → 20261031024151_review_item_dedupe_tenant/migration.sql} +0 -0
  561. /package/migrations/{0068_review_item_slack_cards.sql → 20261031024246_review_item_slack_cards/migration.sql} +0 -0
  562. /package/migrations/{0069_system_identity.sql → 20261031155308_system_identity/migration.sql} +0 -0
  563. /package/migrations/{0070_review_item_foreign_keys.sql → 20261101193952_review_item_foreign_keys/migration.sql} +0 -0
  564. /package/migrations/{0071_review_item_turn.sql → 20261102172751_review_item_turn/migration.sql} +0 -0
  565. /package/migrations/{0072_conversation_read_positions.sql → 20261102221411_conversation_read_positions/migration.sql} +0 -0
  566. /package/migrations/{0073_conversation_quick_question.sql → 20261104085028_conversation_quick_question/migration.sql} +0 -0
  567. /package/migrations/{0074_conversation_participant_pins.sql → 20261104145136_conversation_participant_pins/migration.sql} +0 -0
  568. /package/migrations/{0075_conversation_detail_version.sql → 20261104164429_conversation_detail_version/migration.sql} +0 -0
  569. /package/migrations/{0076_conversation_auto_archive.sql → 20261104172055_conversation_auto_archive/migration.sql} +0 -0
  570. /package/migrations/{0077_drop_agent_invocation_model_profile.sql → 20261105005443_drop_agent_invocation_model_profile/migration.sql} +0 -0
  571. /package/migrations/{0078_plugin_conversation_index.sql → 20261105043807_plugin_conversation_index/migration.sql} +0 -0
  572. /package/migrations/{0079_conversation_event_author_index.sql → 20261105051837_conversation_event_author_index/migration.sql} +0 -0
  573. /package/migrations/{0080_conversation_event_latest_message_indexes.sql → 20261105182854_conversation_event_latest_message_indexes/migration.sql} +0 -0
  574. /package/migrations/{0081_conversation_pin_position.sql → 20261106011443_conversation_pin_position/migration.sql} +0 -0
  575. /package/migrations/{0082_push_notifications.sql → 20261106095004_push_notifications/migration.sql} +0 -0
  576. /package/migrations/{0083_conversation_kind.sql → 20261106162740_conversation_kind/migration.sql} +0 -0
  577. /package/migrations/{0084_read_position_backfill.sql → 20261107002001_read_position_backfill/migration.sql} +0 -0
  578. /package/migrations/{0085_child_archived_at.sql → 20261107025209_child_archived_at/migration.sql} +0 -0
  579. /package/migrations/{0086_shared_archive.sql → 20261107035735_shared_archive/migration.sql} +0 -0
  580. /package/migrations/{0087_child_location.sql → 20261107215055_child_location/migration.sql} +0 -0
  581. /package/migrations/{0088_conversation_unsubscribe.sql → 20261108191927_conversation_unsubscribe/migration.sql} +0 -0
  582. /package/migrations/{0089_conversation_paused_status.sql → 20261109021618_conversation_paused_status/migration.sql} +0 -0
  583. /package/migrations/{0090_guardian_review_time_index.sql → 20261109111553_guardian_review_time_index/migration.sql} +0 -0
  584. /package/migrations/{0091_conversation_participant_unsubscribed_index.sql → 20261109173130_conversation_participant_unsubscribed_index/migration.sql} +0 -0
  585. /package/migrations/{0092_turn_metric_actor.sql → 20261109182006_turn_metric_actor/migration.sql} +0 -0
  586. /package/migrations/{0093_participant_root_actor_backfill.sql → 20261109202836_participant_root_actor_backfill/migration.sql} +0 -0
  587. /package/migrations/{0094_conversation_delivery_paused_at.sql → 20261109232640_conversation_delivery_paused_at/migration.sql} +0 -0
  588. /package/migrations/{0095_web_linked_slack_identity_repair.sql → 20261110120937_web_linked_slack_identity_repair/migration.sql} +0 -0
  589. /package/migrations/{0096_automation_task_kind.sql → 20261110175824_automation_task_kind/migration.sql} +0 -0
  590. /package/migrations/{0097_conversation_kind_automation.sql → 20261110210242_conversation_kind_automation/migration.sql} +0 -0
  591. /package/migrations/{0098_review_item_plugin_actions.sql → 20261110222632_review_item_plugin_actions/migration.sql} +0 -0
  592. /package/migrations/{0099_conversation_last_message_at.sql → 20261110225157_conversation_last_message_at/migration.sql} +0 -0
  593. /package/migrations/{0100_automation_task_kind_repair.sql → 20261111013351_automation_task_kind_repair/migration.sql} +0 -0
  594. /package/migrations/{0101_drop_legacy_columns.sql → 20261111163126_drop_legacy_columns/migration.sql} +0 -0
  595. /package/migrations/{0102_code_change_last_activity.sql → 20261111170150_code_change_last_activity/migration.sql} +0 -0
  596. /package/migrations/{0103_agent_invocation_fork.sql → 20261111191441_agent_invocation_fork/migration.sql} +0 -0
  597. /package/migrations/{0104_code_change_draft.sql → 20261112142841_code_change_draft/migration.sql} +0 -0
  598. /package/migrations/{0105_attachment_uploads.sql → 20261112202901_attachment_uploads/migration.sql} +0 -0
  599. /package/migrations/{0106_conversation_agent_config.sql → 20261112220407_conversation_agent_config/migration.sql} +0 -0
  600. /package/migrations/{0107_attachment_deferred_download.sql → 20261113081247_attachment_deferred_download/migration.sql} +0 -0
  601. /package/migrations/{0108_conversation_embeddings.sql → 20261113225551_conversation_embeddings/migration.sql} +0 -0
  602. /package/migrations/{0109_user_preferences.sql → 20261114213238_user_preferences/migration.sql} +0 -0
  603. /package/migrations/{0110_code_change_repository_state_index.sql → 20261114222527_code_change_repository_state_index/migration.sql} +0 -0
  604. /package/migrations/{0111_attachment_kinds.sql → 20261115172605_attachment_kinds/migration.sql} +0 -0
  605. /package/migrations/{0112_attachment_url_fill.sql → 20261115173004_attachment_url_fill/migration.sql} +0 -0
  606. /package/migrations/{0113_attachment_url_index.sql → 20261115180216_attachment_url_index/migration.sql} +0 -0
  607. /package/migrations/{0114_plan_items.sql → 20261116103700_plan_items/migration.sql} +0 -0
  608. /package/migrations/{0115_automation_creator_slack_index.sql → 20261117100100_automation_creator_slack_index/migration.sql} +0 -0
  609. /package/migrations/{0116_conversation_event_search.sql → 20261117132522_conversation_event_search/migration.sql} +0 -0
  610. /package/migrations/{0117_automation_last_run.sql → 20261117164007_automation_last_run/migration.sql} +0 -0
  611. /package/migrations/{0118_automation_last_run_index.sql → 20261117164047_automation_last_run_index/migration.sql} +0 -0
  612. /package/migrations/{0119_money_micro_usd.sql → 20261117210444_money_micro_usd/migration.sql} +0 -0
  613. /package/migrations/{0120_conversation_cost_micro_usd.sql → 20261117210505_conversation_cost_micro_usd/migration.sql} +0 -0
  614. /package/migrations/{0121_people_list_metric_index.sql → 20261118081416_people_list_metric_index/migration.sql} +0 -0
  615. /package/migrations/{0122_automation_rollout_repair.sql → 20261118095216_automation_rollout_repair/migration.sql} +0 -0
  616. /package/migrations/{0123_cache_warming_history_reset.sql → 20261118143948_cache_warming_history_reset/migration.sql} +0 -0
  617. /package/migrations/{0124_artifact_visibility.sql → 20261119040651_artifact_visibility/migration.sql} +0 -0
  618. /package/migrations/{0125_artifact_public_sha_index.sql → 20261119040715_artifact_public_sha_index/migration.sql} +0 -0
  619. /package/migrations/{0126_artifact_drop_public.sql → 20261119052706_artifact_drop_public/migration.sql} +0 -0
  620. /package/migrations/{0127_artifact_path.sql → 20261119053831_artifact_path/migration.sql} +0 -0
  621. /package/migrations/{0128_artifact_path_index.sql → 20261119053844_artifact_path_index/migration.sql} +0 -0
  622. /package/migrations/{0129_review_item_answered_index.sql → 20261119091949_review_item_answered_index/migration.sql} +0 -0
  623. /package/migrations/{0130_review_item_status_index.sql → 20261119100029_review_item_status_index/migration.sql} +0 -0
  624. /package/migrations/{0131_brief_outcome_status.sql → 20261119165607_brief_outcome_status/migration.sql} +0 -0
  625. /package/migrations/{0132_brief_outcome_status_backfill.sql → 20261119165622_brief_outcome_status_backfill/migration.sql} +0 -0
  626. /package/migrations/{0133_brief_created_at_index.sql → 20261119213716_brief_created_at_index/migration.sql} +0 -0
  627. /package/migrations/{0134_slack_person_search_index.sql → 20261119222456_slack_person_search_index/migration.sql} +0 -0
  628. /package/migrations/{0135_code_change_size.sql → 20261119225522_code_change_size/migration.sql} +0 -0
  629. /package/migrations/{0136_merge_conflict_notice_dismiss.sql → 20261119232253_merge_conflict_notice_dismiss/migration.sql} +0 -0
  630. /package/migrations/{0137_inbox_snoozes.sql → 20261119235649_inbox_snoozes/migration.sql} +0 -0
  631. /package/migrations/{0138_code_change_search_index.sql → 20261120093118_code_change_search_index/migration.sql} +0 -0
  632. /package/migrations/{0139_review_item_owner.sql → 20261120093452_review_item_owner/migration.sql} +0 -0
  633. /package/migrations/{0140_review_item_owner_index.sql → 20261120185654_review_item_owner_index/migration.sql} +0 -0
  634. /package/migrations/{0141_memory_core_adoption.sql → 20261120185754_memory_core_adoption/migration.sql} +0 -0
  635. /package/migrations/{0142_memory_core_indexes.sql → 20261120185854_memory_core_indexes/migration.sql} +0 -0
  636. /package/migrations/{0143_todos.sql → 20261120235226_todos/migration.sql} +0 -0
  637. /package/migrations/{0144_inbox_items.sql → 20261121082316_inbox_items/migration.sql} +0 -0
  638. /package/migrations/{0145_todo_changed_by_agent.sql → 20261121175651_todo_changed_by_agent/migration.sql} +0 -0
  639. /package/migrations/{0146_inbox_item_subject_title_parts.sql → 20261121183527_inbox_item_subject_title_parts/migration.sql} +0 -0
  640. /package/migrations/{0147_inbox_snooze_wake_reason.sql → 20261121194143_inbox_snooze_wake_reason/migration.sql} +0 -0
  641. /package/migrations/{0148_authorization_request_index.sql → 20261121222400_authorization_request_index/migration.sql} +0 -0
  642. /package/migrations/{0149_conversation_metadata.sql → 20261121225908_conversation_metadata/migration.sql} +0 -0
  643. /package/migrations/{0150_conversation_metadata_fill.sql → 20261121225910_conversation_metadata_fill/migration.sql} +0 -0
  644. /package/migrations/{0151_conversation_search_index.sql → 20261121225913_conversation_search_index/migration.sql} +0 -0
  645. /package/migrations/{0152_inbox_item_legacy_automation_keys.sql → 20261122022900_inbox_item_legacy_automation_keys/migration.sql} +0 -0
  646. /package/migrations/{0153_artifact_expiry.sql → 20261122024454_artifact_expiry/migration.sql} +0 -0
  647. /package/migrations/{0154_artifact_permanent_sha_index.sql → 20261122024455_artifact_permanent_sha_index/migration.sql} +0 -0
  648. /package/migrations/{0155_artifact_drop_public_sha_index.sql → 20261122024457_artifact_drop_public_sha_index/migration.sql} +0 -0
  649. /package/migrations/{0156_conversation_kind_lead.sql → 20261122024458_conversation_kind_lead/migration.sql} +0 -0
  650. /package/migrations/{0157_conversation_lead_actor_index.sql → 20261122024459_conversation_lead_actor_index/migration.sql} +0 -0
  651. /package/migrations/{0158_keep_legacy_archive_columns.sql → 20261122071549_keep_legacy_archive_columns/migration.sql} +0 -0
  652. /package/migrations/{0159_conversation_embeddings_fk_validate.sql → 20261122191400_conversation_embeddings_fk_validate/migration.sql} +0 -0
@@ -1,3607 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { N as cacheKeyPrefix, P as createCache, r as getChatConfig } from "./config-CWbwKj0j.js";
3
- import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-BsBdxDXQ.js";
4
- import { A as juniorConversationMetrics, B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, P as juniorConversationAnnotations, S as juniorConversationReadPositions, T as juniorConversationBriefs, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, f as juniorInboxItemAssignees, g as juniorAutomations, h as juniorInboxItems, j as isUserInstruction, k as CONVERSATION_METRICS, p as juniorInboxItemConversations, q as juniorDestinations, t as createJuniorSqlExecutor, w as juniorConversationBindings } from "./executor-CgWyWfYz.js";
5
- import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-CYstOMKX.js";
6
- import { t as canExposeConversationPayload } from "./conversation-privacy-BrMiDN61.js";
7
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
8
- import { J as normalizeIdentityEmail, K as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-DNt-qOIO.js";
9
- import { i as getStateAdapter } from "./adapter-CYAvJzZS.js";
10
- import * as z from "zod";
11
- import { createHash, randomUUID } from "node:crypto";
12
- import { PluginToolInputError, destinationSchema, identitySchema, locationSchema, sourceSchema, userSchema } from "@sentry/junior-plugin-api";
13
- import { SQL, and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, or, sql } from "drizzle-orm";
14
- import { alias } from "drizzle-orm/pg-core";
15
- // src/chat/destination.ts
16
- /** Build Junior's canonical destination from Slack workspace and channel ids. */
17
- function createSlackDestination(input) {
18
- const channelId = parseSlackChannelReferenceId(input.channelId);
19
- const teamId = parseSlackTeamId(input.teamId);
20
- if (!channelId || !teamId) return;
21
- return {
22
- platform: "slack",
23
- teamId,
24
- channelId
25
- };
26
- }
27
- /** Parse and validate a serialized destination that crossed a runtime boundary. */
28
- function parseDestination(value) {
29
- const parsed = destinationSchema.safeParse(value);
30
- return parsed.success ? parsed.data : void 0;
31
- }
32
- /** Require a Slack destination at a Slack-only runtime boundary. */
33
- function requireSlackDestination(destination, action) {
34
- if (destination?.platform === "slack") return destination;
35
- throw new Error(`${action} requires a Slack destination`);
36
- }
37
- /** Compare two destinations without relying on object identity. */
38
- function sameDestination(left, right) {
39
- if (left.platform !== right.platform) return false;
40
- if (left.platform === "local" && right.platform === "local") return left.conversationId === right.conversationId;
41
- if (left.platform === "slack" && right.platform === "slack") return left.teamId === right.teamId && left.channelId === right.channelId;
42
- return false;
43
- }
44
- // src/chat/conversations/sql/detail-version.ts
45
- /** SQL that advances `detail_version` inside a `juniorConversations` set. */
46
- const nextDetailVersion = sql`${juniorConversations.detailVersion} + 1`;
47
- function bumpDetailVersion(db, conversationIds) {
48
- return db.update(juniorConversations).set({ detailVersion: nextDetailVersion }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
49
- }
50
- /**
51
- * Return a CTE that marks the detail report of each Conversation as changed,
52
- * in the same statement as the write that it covers:
53
- * `db.with(conversationDetailTouch(db, ids)).insert(table)`.
54
- * Postgres runs a data-modifying CTE even when the statement does not read it,
55
- * and both changes commit together.
56
- */
57
- function conversationDetailTouch(db, conversationIds) {
58
- return db.$with("conversation_detail_touch").as(bumpDetailVersion(db, conversationIds).returning({ conversationId: juniorConversations.conversationId }));
59
- }
60
- /**
61
- * Mark the detail report of each Conversation as changed, for a write that
62
- * cannot carry `conversationDetailTouch`. Call it after that write, in the same
63
- * transaction when there is one. A bump before the write lets a detail read
64
- * store old content under the new version.
65
- */
66
- async function touchConversationDetail(db, conversationIds) {
67
- if (conversationIds.length === 0) return;
68
- await bumpDetailVersion(db, conversationIds);
69
- }
70
- // src/chat/conversations/sql/participants.ts
71
- /** Resolve the root conversation id that owns personal-feed membership. */
72
- async function resolveRootConversationId(executor, conversationId) {
73
- const [row] = await executor.db().select({ rootConversationId: juniorConversations.rootConversationId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
74
- return row?.rootConversationId ?? conversationId;
75
- }
76
- /** True when the root of this conversation is archived. */
77
- async function rootConversationIsArchived(executor, conversationId) {
78
- const rootConversationId = await resolveRootConversationId(executor, conversationId);
79
- const [row] = await executor.db().select({ archivedAt: juniorConversations.archivedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, rootConversationId)).limit(1);
80
- return Boolean(row?.archivedAt);
81
- }
82
- /**
83
- * Upsert one linked user as a participant on a root conversation.
84
- * No-ops and returns false when the identity is missing, unlinked, or not a
85
- * user. `resubscribe` ends an unsubscribe: the user addressed Junior again.
86
- */
87
- async function recordConversationParticipant(executor, args) {
88
- const [identity] = await executor.db().select({
89
- kind: juniorIdentities.kind,
90
- userId: juniorIdentities.userId
91
- }).from(juniorIdentities).where(eq(juniorIdentities.id, args.actorIdentityId)).limit(1);
92
- if (!identity?.userId || identity.kind !== "user") return false;
93
- const rootConversationId = await resolveRootConversationId(executor, args.conversationId);
94
- const at = new Date(args.atMs);
95
- await executor.db().insert(juniorConversationParticipants).values({
96
- userId: identity.userId,
97
- rootConversationId,
98
- lastMessageAt: at
99
- }).onConflictDoUpdate({
100
- target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
101
- set: {
102
- lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`,
103
- ...args.resubscribe ? { unsubscribedAt: null } : void 0
104
- }
105
- });
106
- return true;
107
- }
108
- /**
109
- * Add a User as a Participant of each root that their Identity started,
110
- * when that Identity gets its User after the roots exist. The root write
111
- * adds a Participant only for an Identity that already has a User.
112
- */
113
- async function recordStartedConversationParticipants(executor, args) {
114
- const roots = await executor.db().select({
115
- conversationId: juniorConversations.conversationId,
116
- lastActivityAt: juniorConversations.lastActivityAt
117
- }).from(juniorConversations).where(and(eq(juniorConversations.actorIdentityId, args.identityId), isNull(juniorConversations.parentConversationId)));
118
- if (roots.length === 0) return;
119
- const added = await executor.db().insert(juniorConversationParticipants).values(roots.map((root) => ({
120
- userId: args.userId,
121
- rootConversationId: root.conversationId,
122
- lastMessageAt: root.lastActivityAt
123
- }))).onConflictDoNothing().returning({ rootConversationId: juniorConversationParticipants.rootConversationId });
124
- await touchConversationDetail(executor.db(), added.map((row) => row.rootConversationId));
125
- }
126
- // src/chat/usage.ts
127
- const agentTurnUsageSchema = usageSchema;
128
- const COMPONENT_USAGE_FIELDS = [
129
- "inputTokens",
130
- "outputTokens",
131
- "cachedInputTokens",
132
- "cacheCreationTokens"
133
- ];
134
- const COST_COMPONENT_FIELDS = [
135
- "input",
136
- "output",
137
- "cacheRead",
138
- "cacheWrite"
139
- ];
140
- /** Return whether any token counter is present on a usage record. */
141
- function hasAgentTurnUsage(usage) {
142
- return Boolean(usage && (Object.entries(usage).some(([field, value]) => field !== "cost" && typeof value === "number" && Number.isFinite(value)) || Object.values(usage.cost ?? {}).some((value) => typeof value === "number" && Number.isFinite(value))));
143
- }
144
- function getFiniteCount(value) {
145
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : void 0;
146
- }
147
- function getFiniteCost(value) {
148
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
149
- }
150
- function addCost(left, right) {
151
- return Math.round(((left ?? 0) + right) * 0xe8d4a51000) / 0xe8d4a51000;
152
- }
153
- function getComponentTotal(usage) {
154
- let total;
155
- for (const field of COMPONENT_USAGE_FIELDS) {
156
- const value = getFiniteCount(usage[field]);
157
- if (value === void 0) continue;
158
- total = (total ?? 0) + value;
159
- }
160
- return total;
161
- }
162
- /** Estimated total USD cost from one usage record, when any cost field is present. */
163
- function agentTurnCostUsd(usage) {
164
- if (!usage?.cost) return void 0;
165
- const total = getFiniteCost(usage.cost.total);
166
- if (total !== void 0) return total;
167
- let componentTotal = 0;
168
- let hasComponent = false;
169
- for (const field of COST_COMPONENT_FIELDS) {
170
- const value = getFiniteCost(usage.cost[field]);
171
- if (value === void 0) continue;
172
- hasComponent = true;
173
- componentTotal = addCost(componentTotal, value);
174
- }
175
- return hasComponent ? componentTotal : void 0;
176
- }
177
- /** Total token count from one usage record, preferring component counters. */
178
- function agentTurnTotalTokens(usage) {
179
- if (!usage) return void 0;
180
- const componentTotal = getComponentTotal(usage);
181
- if (componentTotal !== void 0) return componentTotal;
182
- return getFiniteCount(usage.totalTokens);
183
- }
184
- /** Aggregate token usage across slices without double-counting provider totals. */
185
- function addAgentTurnUsage(...usages) {
186
- const components = {};
187
- let componentTotal;
188
- let totalOnlyTokens;
189
- let reasoningTokens;
190
- const cost = {};
191
- for (const usage of usages) {
192
- if (!usage) continue;
193
- const reasoning = getFiniteCount(usage.reasoningTokens);
194
- if (reasoning !== void 0) reasoningTokens = (reasoningTokens ?? 0) + reasoning;
195
- if (usage.cost) for (const field of [...COST_COMPONENT_FIELDS, "total"]) {
196
- const value = getFiniteCost(usage.cost[field]);
197
- if (value === void 0) continue;
198
- cost[field] = addCost(cost[field], value);
199
- }
200
- const usageComponentTotal = getComponentTotal(usage);
201
- if (usageComponentTotal !== void 0) {
202
- componentTotal = (componentTotal ?? 0) + usageComponentTotal;
203
- for (const field of COMPONENT_USAGE_FIELDS) {
204
- const value = getFiniteCount(usage[field]);
205
- if (value === void 0) continue;
206
- components[field] = (components[field] ?? 0) + value;
207
- }
208
- continue;
209
- }
210
- const totalTokens = getFiniteCount(usage.totalTokens);
211
- if (totalTokens !== void 0) totalOnlyTokens = (totalOnlyTokens ?? 0) + totalTokens;
212
- }
213
- if (totalOnlyTokens !== void 0) return {
214
- totalTokens: totalOnlyTokens + (componentTotal ?? 0),
215
- ...reasoningTokens !== void 0 ? { reasoningTokens } : void 0,
216
- ...Object.keys(cost).length > 0 ? { cost } : void 0
217
- };
218
- const result = {
219
- ...components,
220
- ...reasoningTokens !== void 0 ? { reasoningTokens } : void 0,
221
- ...Object.keys(cost).length > 0 ? { cost } : void 0
222
- };
223
- return hasAgentTurnUsage(result) ? result : void 0;
224
- }
225
- // src/api/conversations/membership.ts
226
- /**
227
- * Select the person's participant row on the outer `juniorConversations`
228
- * root, with an optional extra condition.
229
- */
230
- function memberParticipantRow(member, condition) {
231
- const rows = getDb().select({ rootConversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
232
- const onRoot = eq(juniorConversationParticipants.rootConversationId, juniorConversations.conversationId);
233
- return "userId" in member ? rows.where(and(onRoot, eq(juniorConversationParticipants.userId, member.userId), condition)) : rows.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(onRoot, eq(juniorUsers.primaryEmailNormalized, member.email), condition));
234
- }
235
- /** True when the viewer is a materialized participant on this root conversation. */
236
- function conversationHasParticipantUser(userId) {
237
- return exists(memberParticipantRow({ userId }));
238
- }
239
- /**
240
- * True when the viewer may find the outer root conversation by a link to
241
- * it: its Destination, joined as `juniorDestinations`, is public, or the
242
- * viewer is a Participant.
243
- */
244
- function rootVisibleToViewer(viewerUserId) {
245
- return or(eq(juniorDestinations.visibility, "public"), viewerUserId ? conversationHasParticipantUser(viewerUserId) : void 0);
246
- }
247
- /**
248
- * True when the person is a Participant of the conversation. Feeds filter
249
- * with this id set instead of a per-row membership check, so Postgres reads
250
- * only that person's conversations, not every root.
251
- */
252
- function conversationIsMemberRoot(member) {
253
- const participating = getDb().select({ conversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
254
- const memberRoots = "userId" in member ? participating.where(eq(juniorConversationParticipants.userId, member.userId)) : participating.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email));
255
- return inArray(juniorConversations.conversationId, memberRoots);
256
- }
257
- /**
258
- * True when the person has not unsubscribed from the conversation. The
259
- * active feed uses it, so a conversation that someone else carries on
260
- * leaves the feed of a person who left it.
261
- */
262
- function conversationIsNotUnsubscribedRoot(member) {
263
- return not(exists(memberParticipantRow(member, isNotNull(juniorConversationParticipants.unsubscribedAt))));
264
- }
265
- /**
266
- * Read the roots among a bounded set where one person is a Participant, each
267
- * with their pin marks. An unpinned root maps to empty marks.
268
- */
269
- async function readMemberParticipants(db, conversationIds, member) {
270
- if (!member || conversationIds.length === 0) return /* @__PURE__ */ new Map();
271
- const listed = inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]);
272
- const query = db.select({
273
- pinnedAt: juniorConversationParticipants.pinnedAt,
274
- pinPosition: juniorConversationParticipants.pinPosition,
275
- rootConversationId: juniorConversationParticipants.rootConversationId
276
- }).from(juniorConversationParticipants);
277
- const rows = "userId" in member ? await query.where(and(eq(juniorConversationParticipants.userId, member.userId), listed)) : await query.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorUsers.primaryEmailNormalized, member.email), listed));
278
- return new Map(rows.map((row) => [row.rootConversationId, viewerMarksFromParticipant(row) ?? {}]));
279
- }
280
- /** Project one participant row into marks, or undefined when it has none. */
281
- function viewerMarksFromParticipant(row) {
282
- if (!row.pinnedAt) return void 0;
283
- return {
284
- pinnedAtMs: row.pinnedAt.getTime(),
285
- ...row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
286
- };
287
- }
288
- /** True when one user pinned this root. Feeds sort these rows first. */
289
- function conversationPinnedForUser(userId) {
290
- return exists(memberParticipantRow({ userId }, isNotNull(juniorConversationParticipants.pinnedAt)));
291
- }
292
- /** Find which of the supplied roots include the linked viewer as a participant. */
293
- async function conversationIdsWithParticipantUser(db, conversationIds, userId) {
294
- if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
295
- const rows = await db.select({ rootConversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, userId), inArray(juniorConversationParticipants.rootConversationId, [...conversationIds])));
296
- return new Set(rows.map((row) => row.rootConversationId));
297
- }
298
- // src/api/conversations/access.ts
299
- const rootConversation = alias(juniorConversations, "access_root_conversation");
300
- const rootDestination = alias(juniorDestinations, "access_root_destination");
301
- /** Resolve viewer access for a bounded set of persisted conversations. */
302
- async function readConversationAccessFromSql(db, conversationIds, viewer) {
303
- const rows = await readConversationAccessRows(db, conversationIds);
304
- const membershipConversationIds = /* @__PURE__ */ new Set();
305
- for (const row of rows) {
306
- membershipConversationIds.add(row.conversationId);
307
- if (row.storedRootConversationId) membershipConversationIds.add(row.storedRootConversationId);
308
- }
309
- return conversationAccessFromRows(rows, viewer !== void 0 ? await conversationIdsWithParticipantUser(db, [...membershipConversationIds], viewer.id) : /* @__PURE__ */ new Set());
310
- }
311
- /**
312
- * Read the stored tree and root Destination of each conversation. A caller
313
- * that reads the viewer's participant rows itself passes these rows to
314
- * `conversationAccessFromRows`.
315
- */
316
- async function readConversationAccessRows(db, conversationIds) {
317
- if (conversationIds.length === 0) return [];
318
- return await db.select({
319
- conversationId: juniorConversations.conversationId,
320
- parentConversationId: juniorConversations.parentConversationId,
321
- storedRootConversationId: juniorConversations.rootConversationId,
322
- rootConversationId: rootConversation.conversationId,
323
- rootParentConversationId: rootConversation.parentConversationId,
324
- rootRootConversationId: rootConversation.rootConversationId,
325
- destinationId: rootDestination.id,
326
- visibility: rootDestination.visibility,
327
- provider: rootDestination.provider,
328
- providerTenantId: rootDestination.providerTenantId
329
- }).from(juniorConversations).leftJoin(rootConversation, eq(rootConversation.conversationId, juniorConversations.rootConversationId)).leftJoin(rootDestination, eq(rootDestination.id, rootConversation.destinationId)).where(inArray(juniorConversations.conversationId, [...conversationIds]));
330
- }
331
- /**
332
- * Resolve access from `readConversationAccessRows`. `participantRootIds`
333
- * holds the viewer's participant roots among the conversations and their
334
- * stored roots, and is empty without a viewer.
335
- */
336
- function conversationAccessFromRows(rows, participantRootIds) {
337
- return new Map(rows.map((row) => {
338
- const validRootConversationId = row.rootConversationId !== null && row.rootConversationId === row.storedRootConversationId && row.rootRootConversationId === row.rootConversationId && row.rootParentConversationId === null && (row.parentConversationId !== null || row.storedRootConversationId === row.conversationId) ? row.rootConversationId ?? void 0 : void 0;
339
- const visibility = validRootConversationId === void 0 ? null : row.visibility;
340
- const isParticipant = row.parentConversationId === null && participantRootIds.has(row.conversationId) || validRootConversationId !== void 0 && participantRootIds.has(validRootConversationId);
341
- const canViewPrivateContent = isParticipant || validRootConversationId !== void 0 && canExposeConversationPayload({ visibility: visibility ?? void 0 });
342
- return [row.conversationId, {
343
- canViewPrivateContent,
344
- ...validRootConversationId !== void 0 && row.destinationId ? { destinationId: row.destinationId } : void 0,
345
- isParticipant,
346
- ...validRootConversationId !== void 0 ? { rootConversationId: validRootConversationId } : void 0,
347
- visibility,
348
- ...validRootConversationId !== void 0 && row.provider !== null && row.providerTenantId ? { tenant: {
349
- provider: row.provider,
350
- providerTenantId: row.providerTenantId
351
- } } : void 0
352
- }];
353
- }));
354
- }
355
- /**
356
- * Whether the viewer may add a Message to a Conversation. A signed-in person
357
- * joins a public Conversation by posting in it, the same as a public Slack
358
- * thread: their first Turn adds their Participant row. A private one takes
359
- * Messages only from its Participants.
360
- */
361
- function canAddConversationMessages(access) {
362
- return Boolean(access?.isParticipant || access?.visibility === "public");
363
- }
364
- /**
365
- * The Slack workspace of a Conversation that the viewer can read. A mention
366
- * in it must name a Slack user of that workspace.
367
- */
368
- function readableSlackTeamId(access) {
369
- return access?.canViewPrivateContent && access.tenant?.provider === "slack" ? access.tenant.providerTenantId : void 0;
370
- }
371
- /**
372
- * Read access for one request. Each id is read at most once, so the parts of
373
- * one response that need the same Conversation share a query.
374
- */
375
- function createConversationAccessReader(db, viewer) {
376
- const byId = /* @__PURE__ */ new Map();
377
- return async (conversationIds) => {
378
- const missing = [...new Set(conversationIds)].filter((id) => !byId.has(id));
379
- if (missing.length > 0) {
380
- const read = readConversationAccessFromSql(db, missing, viewer);
381
- for (const id of missing) byId.set(id, read.then((access) => access.get(id)));
382
- }
383
- const entries = await Promise.all(conversationIds.map(async (id) => [id, await byId.get(id)]));
384
- return new Map(entries.flatMap(([id, access]) => access ? [[id, access]] : []));
385
- };
386
- }
387
- /**
388
- * Apply `policies/conversation-access.md`: whether work in the `requester`
389
- * Conversation may read or find the data of the `target` Conversation. The
390
- * person of the Turn does not change the result. A public Conversation is
391
- * reachable from any Conversation, on any surface and in any provider tenant.
392
- * A private Conversation is reachable only from its own tree and from
393
- * Conversations at the same Destination, which have the same audience.
394
- */
395
- function canAccessConversation(args) {
396
- const { requester, target } = args;
397
- if (requester.rootConversationId !== void 0 && requester.rootConversationId === target.rootConversationId) return true;
398
- if (requester.destinationId !== void 0 && requester.destinationId === target.destinationId) return true;
399
- return target.visibility === "public";
400
- }
401
- /**
402
- * Whether work in `requesterConversationId` may read `conversationId`, by
403
- * `canAccessConversation`. A missing target is not readable. A requester that
404
- * is not stored yet reaches only public targets.
405
- */
406
- async function canReadConversation(db, requesterConversationId, conversationId) {
407
- const access = await readConversationAccessFromSql(db, [requesterConversationId, conversationId]);
408
- const target = access.get(conversationId);
409
- return target !== void 0 && canAccessConversation({
410
- requester: access.get(requesterConversationId) ?? { visibility: null },
411
- target
412
- });
413
- }
414
- // src/chat/tool-support/tool-input-error.ts
415
- /** Thrown when a tool fails due to invalid model/user input, not a system error. */
416
- var ToolInputError = class extends Error {
417
- constructor(message, options) {
418
- super(message, options);
419
- this.name = "ToolInputError";
420
- }
421
- };
422
- /** Whether an error is an expected tool input failure that is not a Sentry exception. */
423
- function isToolInputError(error) {
424
- return error instanceof ToolInputError || error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
425
- }
426
- // src/chat/identities/user-cache.ts
427
- /**
428
- * Cache of each User and their user Identities. Every signed-in request
429
- * resolves its viewer, and person cards read the people that a message
430
- * links to, so these reads go to the state cache instead of the database.
431
- *
432
- * Every write to a cached column or to a user Identity must call
433
- * `clearCachedUser`. The other columns of a User, such as the timezone or
434
- * the customization, are not in the cache.
435
- */
436
- const USER_TTL_MS = 864e5;
437
- const MISSING_TTL_MS = 6e4;
438
- const SETTLE_MS = 1e4;
439
- /** The cache namespace of every key in this cache. */
440
- const USER_CACHE_NAMESPACE = "identities";
441
- const cachedUserSchema = z.object({
442
- identities: z.array(z.object({
443
- avatarUrl: z.string().nullable(),
444
- displayName: z.string().nullable(),
445
- handle: z.string().nullable(),
446
- id: z.string(),
447
- provider: z.string(),
448
- providerSubjectId: z.string(),
449
- providerTenantId: z.string(),
450
- updatedAt: z.coerce.date()
451
- })),
452
- user: z.object({
453
- displayName: z.string().nullable(),
454
- id: z.string(),
455
- isAdmin: z.boolean(),
456
- primaryEmail: z.string()
457
- })
458
- });
459
- const versionSchema = z.object({
460
- token: z.string(),
461
- writtenAtMs: z.number()
462
- });
463
- function versionKey(userId) {
464
- return `${cacheKeyPrefix(USER_CACHE_NAMESPACE)}version:${userId}`;
465
- }
466
- function cache() {
467
- return createCache(getStateAdapter(), USER_CACHE_NAMESPACE);
468
- }
469
- async function readVersion(userId) {
470
- const state = getStateAdapter();
471
- const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
472
- if (stored.success) return stored.data;
473
- const created = {
474
- token: randomUUID(),
475
- writtenAtMs: 0
476
- };
477
- if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
478
- return versionSchema.parse(await state.get(versionKey(userId)));
479
- }
480
- async function loadUser(db, userId) {
481
- const rows = await db.select({
482
- avatarUrl: juniorIdentities.avatarUrl,
483
- displayName: juniorIdentities.displayName,
484
- handle: juniorIdentities.handle,
485
- identityId: juniorIdentities.id,
486
- provider: juniorIdentities.provider,
487
- providerSubjectId: juniorIdentities.providerSubjectId,
488
- providerTenantId: juniorIdentities.providerTenantId,
489
- updatedAt: juniorIdentities.updatedAt,
490
- userDisplayName: juniorUsers.displayName,
491
- userId: juniorUsers.id,
492
- userIsAdmin: juniorUsers.isAdmin,
493
- userPrimaryEmail: juniorUsers.primaryEmail
494
- }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.id, userId)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
495
- const first = rows[0];
496
- if (!first) return null;
497
- return {
498
- identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
499
- avatarUrl: row.avatarUrl,
500
- displayName: row.displayName,
501
- handle: row.handle,
502
- id: row.identityId,
503
- provider: row.provider,
504
- providerSubjectId: row.providerSubjectId,
505
- providerTenantId: row.providerTenantId,
506
- updatedAt: row.updatedAt
507
- }] : []),
508
- user: {
509
- displayName: first.userDisplayName,
510
- id: first.userId,
511
- isAdmin: first.userIsAdmin,
512
- primaryEmail: first.userPrimaryEmail
513
- }
514
- };
515
- }
516
- /** Read one User and their user Identities by User id. */
517
- async function readCachedUser(db, userId) {
518
- const version = await readVersion(userId);
519
- const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
520
- const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
521
- const value = await loadUser(db, userId);
522
- if (!settled) return { value };
523
- return {
524
- value,
525
- ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
526
- };
527
- });
528
- return cached ? cachedUserSchema.parse(cached) : void 0;
529
- }
530
- /**
531
- * Read one User and their user Identities by normalized primary email. A
532
- * primary email never changes, so the email to User id entry stays valid.
533
- * A missing User is not cached: a first sign-in can create it at any time.
534
- */
535
- async function readCachedUserByEmail(db, normalizedEmail) {
536
- const userId = await cache().getOrLoad(emailKey(normalizedEmail), async () => {
537
- const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
538
- return id ? {
539
- value: id,
540
- ttlMs: USER_TTL_MS
541
- } : { value: null };
542
- });
543
- return userId ? await readCachedUser(db, userId) : void 0;
544
- }
545
- function emailKey(normalizedEmail) {
546
- return `email:${normalizedEmail}`;
547
- }
548
- /** Clear the cached User after a write to their row or user Identities. */
549
- async function clearCachedUser(userId) {
550
- await getStateAdapter().set(versionKey(userId), {
551
- token: randomUUID(),
552
- writtenAtMs: Date.now()
553
- }, 2 * USER_TTL_MS);
554
- }
555
- // src/chat/identities/sql.ts
556
- function dateFromMs$1(ms) {
557
- return new Date(ms);
558
- }
559
- function tenantId$1(value) {
560
- return value ?? "";
561
- }
562
- async function upsertUser(executor, args) {
563
- const id = (await executor.db().insert(juniorUsers).values({
564
- id: randomUUID(),
565
- primaryEmail: args.email,
566
- primaryEmailNormalized: args.emailNormalized,
567
- displayName: args.displayName ?? null,
568
- createdAt: dateFromMs$1(args.nowMs),
569
- updatedAt: dateFromMs$1(args.nowMs)
570
- }).onConflictDoUpdate({
571
- target: juniorUsers.primaryEmailNormalized,
572
- set: {
573
- displayName: sql`coalesce(${juniorUsers.displayName}, excluded.display_name)`,
574
- updatedAt: sql`excluded.updated_at`
575
- }
576
- }).returning({ id: juniorUsers.id }))[0]?.id;
577
- if (!id) throw new Error("User identity upsert returned no row");
578
- return id;
579
- }
580
- async function existingIdentity(executor, identity) {
581
- return (await executor.db().select().from(juniorIdentities).where(and(eq(juniorIdentities.provider, identity.provider), eq(juniorIdentities.providerTenantId, tenantId$1(identity.providerTenantId)), eq(juniorIdentities.providerSubjectId, identity.providerSubjectId))))[0];
582
- }
583
- async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
584
- const emailNormalized = normalizeIdentityEmail(identity.email);
585
- const email = emailNormalized ? identity.email?.trim() || emailNormalized : void 0;
586
- const existing = await existingIdentity(executor, identity);
587
- const userEmailNormalized = existing?.emailVerified && existing.emailNormalized ? existing.emailNormalized : identity.emailVerified ? emailNormalized : void 0;
588
- const userEmail = existing?.emailVerified && existing.email ? existing.email : email ?? userEmailNormalized;
589
- const verifiedUserId = identity.kind === "user" && userEmailNormalized ? await upsertUser(executor, {
590
- email: userEmail ?? userEmailNormalized,
591
- emailNormalized: userEmailNormalized,
592
- nowMs,
593
- ...existing?.displayName || identity.displayName ? { displayName: existing?.displayName ?? identity.displayName } : void 0
594
- }) : void 0;
595
- if (existing?.userId && verifiedUserId && existing.userId !== verifiedUserId) throw new Error("Identity verified email conflicts with linked user");
596
- if (linkedUserId && verifiedUserId && linkedUserId !== verifiedUserId) throw new Error("Linked identity conflicts with verified email user");
597
- if (existing?.userId && linkedUserId && existing.userId !== linkedUserId) throw new Error("Identity conflicts with linked user");
598
- const userId = existing?.userId ?? linkedUserId ?? verifiedUserId;
599
- const row = (await executor.db().insert(juniorIdentities).values({
600
- id: randomUUID(),
601
- userId: userId ?? null,
602
- kind: identity.kind,
603
- provider: identity.provider,
604
- providerTenantId: tenantId$1(identity.providerTenantId),
605
- providerSubjectId: identity.providerSubjectId,
606
- displayName: identity.displayName ?? null,
607
- handle: identity.handle ?? null,
608
- email: email ?? null,
609
- emailNormalized: emailNormalized ?? null,
610
- emailVerified: Boolean(identity.emailVerified && emailNormalized),
611
- avatarUrl: identity.avatarUrl ?? null,
612
- metadata: identity.metadata ?? null,
613
- createdAt: dateFromMs$1(nowMs),
614
- updatedAt: dateFromMs$1(nowMs)
615
- }).onConflictDoUpdate({
616
- target: [
617
- juniorIdentities.provider,
618
- juniorIdentities.providerTenantId,
619
- juniorIdentities.providerSubjectId
620
- ],
621
- set: {
622
- kind: sql`excluded.kind`,
623
- userId: sql`coalesce(${juniorIdentities.userId}, excluded.user_id)`,
624
- displayName: linkedUserId ? sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})` : sql`coalesce(${juniorIdentities.displayName}, excluded.display_name)`,
625
- handle: linkedUserId ? sql`coalesce(excluded.handle, ${juniorIdentities.handle})` : sql`coalesce(${juniorIdentities.handle}, excluded.handle)`,
626
- email: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.email}, excluded.email) when excluded.email_verified then excluded.email else coalesce(${juniorIdentities.email}, excluded.email) end`,
627
- emailNormalized: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) when excluded.email_verified then excluded.email_normalized else coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) end`,
628
- emailVerified: sql`${juniorIdentities.emailVerified} OR excluded.email_verified`,
629
- avatarUrl: identity.avatarUrl === void 0 ? sql`${juniorIdentities.avatarUrl}` : sql`excluded.avatar_url`,
630
- metadata: sql`coalesce(${juniorIdentities.metadata}, excluded.metadata_json)`,
631
- updatedAt: sql`excluded.updated_at`
632
- },
633
- ...linkedUserId ? { setWhere: sql`${juniorIdentities.userId} IS NULL OR ${juniorIdentities.userId} = excluded.user_id` } : void 0
634
- }).returning({
635
- id: juniorIdentities.id,
636
- userId: juniorIdentities.userId
637
- }))[0];
638
- if (!row) {
639
- if (linkedUserId) throw new Error("Identity conflicts with linked user");
640
- throw new Error("Identity upsert returned no row");
641
- }
642
- const previousUserId = existing?.userId;
643
- await Promise.all([row.userId ? clearCachedUser(row.userId) : void 0, previousUserId && previousUserId !== row.userId ? clearCachedUser(previousUserId) : void 0]);
644
- if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
645
- identityId: row.id,
646
- userId: row.userId
647
- });
648
- return {
649
- id: row.id,
650
- ...row.userId ? { userId: row.userId } : void 0
651
- };
652
- }
653
- /** Read the saved timezone for one user. */
654
- async function readUserTimezone(db, userId) {
655
- return (await db.select({ timezone: juniorUsers.timezone }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1))[0]?.timezone ?? void 0;
656
- }
657
- /** Save the IANA timezone for one user. */
658
- async function saveUserTimezone(db, userId, timezone, nowMs) {
659
- await db.update(juniorUsers).set({
660
- timezone,
661
- updatedAt: dateFromMs$1(nowMs)
662
- }).where(and(eq(juniorUsers.id, userId), sql`${juniorUsers.timezone} is distinct from ${timezone}`));
663
- }
664
- /** Return the Slack user most recently linked to a Junior user. */
665
- async function linkedSlackUser(db, userId) {
666
- const row = (await db.select({
667
- teamId: juniorIdentities.providerTenantId,
668
- slackUserId: juniorIdentities.providerSubjectId
669
- }).from(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"))).orderBy(desc(juniorIdentities.updatedAt)).limit(1))[0];
670
- return row?.teamId ? {
671
- teamId: row.teamId,
672
- userId: row.slackUserId
673
- } : void 0;
674
- }
675
- /** Persist one provider identity observation and link verified emails to users. */
676
- async function upsertIdentity(executor, identity, nowMs = Date.now()) {
677
- return await upsertIdentityRecord(executor, identity, void 0, nowMs);
678
- }
679
- /**
680
- * Persist one provider identity after a trusted account-linking flow.
681
- * Callers must use provider-verified account data, such as GitHub's authenticated
682
- * user response, never identity claims inferred from content such as Git commits.
683
- */
684
- async function upsertLinkedIdentity(executor, userId, identity, nowMs = Date.now()) {
685
- return await upsertIdentityRecord(executor, identity, userId, nowMs);
686
- }
687
- /**
688
- * Find the one user whose primary email is in a provider-verified email list.
689
- * Return undefined when no user or more than one user matches.
690
- */
691
- async function findUserByVerifiedEmails(executor, emails) {
692
- const normalized = new Set(emails.map((email) => normalizeIdentityEmail(email) ?? ""));
693
- normalized.delete("");
694
- if (normalized.size === 0) return void 0;
695
- const rows = await executor.db().select({
696
- email: juniorUsers.primaryEmail,
697
- userId: juniorUsers.id
698
- }).from(juniorUsers).where(inArray(juniorUsers.primaryEmailNormalized, Array.from(normalized))).limit(2);
699
- return rows.length === 1 ? rows[0] : void 0;
700
- }
701
- const linkedSlackIdentity = alias(juniorIdentities, "linked_slack_identity");
702
- const linkedSlackUserColumns = {
703
- displayName: juniorUsers.displayName,
704
- email: juniorUsers.primaryEmail,
705
- slackUserId: linkedSlackIdentity.providerSubjectId,
706
- userId: juniorUsers.id
707
- };
708
- function singleLinkedSlackUser(rows) {
709
- const [row] = rows;
710
- if (rows.length !== 1 || !row) return void 0;
711
- return {
712
- slackUserId: row.slackUserId,
713
- user: {
714
- id: row.userId,
715
- email: row.email,
716
- ...row.displayName ? { displayName: row.displayName } : void 0
717
- }
718
- };
719
- }
720
- /**
721
- * Find the one Slack user in a workspace who is linked to an exact provider
722
- * Identity, and the User behind both.
723
- *
724
- * Only the provider account id from an account-linking flow matches. Handles,
725
- * emails, and display names never match. Return undefined when no Slack user
726
- * or more than one Slack user matches.
727
- */
728
- async function findLinkedSlackUser(executor, args) {
729
- return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorIdentities).innerJoin(linkedSlackIdentity, and(eq(linkedSlackIdentity.userId, juniorIdentities.userId), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, args.providerSubjectId))).limit(2));
730
- }
731
- /**
732
- * Find the one Slack user in a workspace whose User has this primary email.
733
- *
734
- * The caller must have verified that the person sent from this address.
735
- * Return undefined when no Slack user or more than one Slack user matches.
736
- */
737
- async function findSlackUserByPrimaryEmail(executor, args) {
738
- return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorUsers).innerJoin(linkedSlackIdentity, eq(linkedSlackIdentity.userId, juniorUsers.id)).where(and(eq(juniorUsers.primaryEmailNormalized, args.normalizedEmail), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).limit(2));
739
- }
740
- /** Remove one exact provider identity owned by a workspace Slack user. */
741
- async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUserId, provider, providerSubjectId) {
742
- const userId = (await executor.db().select({ userId: juniorIdentities.userId }).from(juniorIdentities).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"), eq(juniorIdentities.providerTenantId, slackTeamId), eq(juniorIdentities.providerSubjectId, slackUserId))).limit(1))[0]?.userId;
743
- if (!userId) return;
744
- await deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId);
745
- }
746
- /** Remove one exact provider identity owned by a user. */
747
- async function deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId) {
748
- await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
749
- await clearCachedUser(userId);
750
- }
751
- /**
752
- * Save one Google sign-in. Link the Google identity to the user of its
753
- * verified email, and set its sign-in time. Return the previous sign-in
754
- * time, if any.
755
- */
756
- async function recordGoogleSignIn(executor, account, nowMs = Date.now()) {
757
- const stored = await upsertIdentity(executor, {
758
- kind: "user",
759
- provider: GOOGLE_IDENTITY_PROVIDER,
760
- providerSubjectId: account.subject,
761
- email: account.email,
762
- emailVerified: true,
763
- displayName: account.displayName,
764
- avatarUrl: account.avatarUrl ?? null
765
- }, nowMs);
766
- const [previous] = await executor.db().select({ signedInAt: juniorIdentities.signedInAt }).from(juniorIdentities).where(eq(juniorIdentities.id, stored.id)).limit(1);
767
- await executor.db().update(juniorIdentities).set({ signedInAt: dateFromMs$1(nowMs) }).where(eq(juniorIdentities.id, stored.id));
768
- return previous?.signedInAt?.getTime();
769
- }
770
- // src/chat/identities/actor.ts
771
- /**
772
- * Resolve runtime Actors to the Identity rows that Junior stores for them.
773
- *
774
- * The Conversation store, OAuth, the viewer, and message events use this
775
- * module, so they agree on one Identity per person. The key for each Actor
776
- * stays private here, so it can change without changing callers.
777
- */
778
- /**
779
- * The fixed id of the one system Identity: kind `system`, provider `junior`,
780
- * an empty tenant, and subject `system`. A migration creates the row, so
781
- * callers use this id without a database read.
782
- */
783
- const SYSTEM_IDENTITY_ID = "system";
784
- /**
785
- * Return whether an Actor uses the system Identity.
786
- *
787
- * `SystemActor.name` is provenance, not part of the Identity. A LocalActor
788
- * uses the system Identity because the local runner has no per-person user id.
789
- */
790
- function usesSystemIdentity(actor) {
791
- return actor.platform === "local" || actor.platform === "system";
792
- }
793
- /** Return the Identity key for one Slack or web Actor. */
794
- function identityKey(actor) {
795
- switch (actor.platform) {
796
- case "slack": return {
797
- kind: "user",
798
- provider: "slack",
799
- providerTenantId: actor.teamId,
800
- providerSubjectId: actor.userId,
801
- ...actor.fullName ? { displayName: actor.fullName } : void 0,
802
- ...actor.userName ? { handle: actor.userName } : void 0,
803
- ...actor.email ? {
804
- email: actor.email,
805
- emailVerified: true
806
- } : void 0,
807
- metadata: { platform: "slack" }
808
- };
809
- case "web": {
810
- const email = normalizeIdentityEmail(actor.email);
811
- if (!email) return;
812
- return {
813
- kind: "user",
814
- provider: "junior",
815
- providerSubjectId: email,
816
- email,
817
- emailVerified: true,
818
- ...actor.fullName ? { displayName: actor.fullName } : void 0,
819
- metadata: { platform: "web" }
820
- };
821
- }
822
- }
823
- }
824
- /**
825
- * Return the Identity id for one Actor. Save a Slack or web Identity first.
826
- * Return undefined only for a web Actor without a verified email.
827
- */
828
- async function resolveActorIdentityId(executor, actor, nowMs = Date.now()) {
829
- if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
830
- const key = identityKey(actor);
831
- return key ? (await upsertIdentity(executor, key, nowMs)).id : void 0;
832
- }
833
- /** Save the profile photo on the Identity of one Slack Actor. Null clears it. */
834
- async function saveActorAvatar(executor, actor, avatarUrl, nowMs = Date.now()) {
835
- const key = identityKey(actor);
836
- if (key) await upsertIdentity(executor, {
837
- ...key,
838
- avatarUrl
839
- }, nowMs);
840
- }
841
- /** Find the stored Identity id for one Actor without writing. */
842
- async function findActorIdentityId(db, actor) {
843
- if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
844
- const key = identityKey(actor);
845
- if (!key) return;
846
- return (await db.select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, key.provider), eq(juniorIdentities.providerTenantId, key.providerTenantId ?? ""), eq(juniorIdentities.providerSubjectId, key.providerSubjectId))).limit(1))[0]?.id;
847
- }
848
- // src/chat/identities/avatar.ts
849
- /**
850
- * Profile photos of people, saved on their native Slack and Google
851
- * identities. `/api/people/avatars/:identityId` serves each photo through
852
- * the shared image route code, so browsers never load a photo from Slack or
853
- * Google.
854
- */
855
- const AVATAR_HOSTS = {
856
- slack: ["avatars.slack-edge.com"],
857
- [GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
858
- };
859
- const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
860
- /**
861
- * Return the URL when it is HTTPS on a photo host of the provider or a
862
- * subdomain. Junior fetches only these URLs.
863
- */
864
- function parseAvatarUrl(value, provider) {
865
- const hosts = AVATAR_HOSTS[provider];
866
- if (!hosts || !value || !URL.canParse(value)) return void 0;
867
- const url = new URL(value);
868
- if (url.protocol !== "https:" || url.username || url.password) return;
869
- const host = url.hostname.toLowerCase();
870
- return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
871
- }
872
- function avatarVersion(url) {
873
- return createHash("sha256").update(url).digest("hex").slice(0, 16);
874
- }
875
- function avatarPath(identityId, avatarUrl) {
876
- return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
877
- }
878
- /**
879
- * Match the user Identities that hold a photo, for a read that joins them to
880
- * the Identities of other rows.
881
- */
882
- function hasUserPhoto(identities) {
883
- return and(eq(identities.kind, "user"), inArray(identities.provider, AVATAR_PROVIDERS), isNotNull(identities.avatarUrl));
884
- }
885
- /**
886
- * Read the photo path of each user: the Slack photo, then the Google photo.
887
- * Users without a photo are not in the map.
888
- */
889
- async function readUserAvatarUrls(db, userIds) {
890
- if (userIds.length === 0) return /* @__PURE__ */ new Map();
891
- return userAvatarUrlsFromIdentities(await db.select({
892
- avatarUrl: juniorIdentities.avatarUrl,
893
- identityId: juniorIdentities.id,
894
- provider: juniorIdentities.provider,
895
- updatedAt: juniorIdentities.updatedAt,
896
- userId: juniorIdentities.userId
897
- }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), hasUserPhoto(juniorIdentities))));
898
- }
899
- /**
900
- * Pick the photo path of each user from their user Identities, for a caller
901
- * that already read them: the Slack photo, then the Google photo.
902
- */
903
- function userAvatarUrlsFromIdentities(rows) {
904
- const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
905
- const ranked = rows.filter((row) => rank(row) >= 0).sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
906
- const avatars = /* @__PURE__ */ new Map();
907
- for (const row of ranked) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
908
- return avatars;
909
- }
910
- /**
911
- * Pick the photo path of each user from rows that joined their photo
912
- * Identities with `hasUserPhoto`: the Slack photo, then the Google photo.
913
- */
914
- function userAvatarUrlsFromJoinedPhotos(rows) {
915
- return userAvatarUrlsFromIdentities(rows.flatMap(({ photo, userId }) => photo?.identityId && photo.provider && photo.updatedAt ? [{
916
- avatarUrl: photo.avatarUrl,
917
- identityId: photo.identityId,
918
- provider: photo.provider,
919
- updatedAt: photo.updatedAt,
920
- userId
921
- }] : []));
922
- }
923
- /**
924
- * Return the photo path for one Identity row. A linked Identity uses the
925
- * photo of its user. An Identity without a user uses its own photo.
926
- */
927
- function identityAvatarUrl(row, userAvatarUrls) {
928
- if (row.userId) return userAvatarUrls.get(row.userId);
929
- return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
930
- }
931
- /**
932
- * Return how to fetch the photo of one user Identity, or nothing when it has
933
- * no photo on a photo host of its provider. A redirect cannot leave the
934
- * photo hosts of the provider.
935
- */
936
- async function readAvatarFetch(db, identityId) {
937
- const [row] = await db.select({
938
- avatarUrl: juniorIdentities.avatarUrl,
939
- provider: juniorIdentities.provider
940
- }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
941
- const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
942
- const hosts = row && AVATAR_HOSTS[row.provider];
943
- return url && hosts ? {
944
- hosts,
945
- url
946
- } : void 0;
947
- }
948
- // src/chat/plugins/viewer.ts
949
- function identityFromRow(row) {
950
- return identitySchema.parse({
951
- id: row.id,
952
- provider: row.provider,
953
- providerSubjectId: row.providerSubjectId,
954
- ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
955
- ...row.displayName ? { displayName: row.displayName } : void 0,
956
- ...row.handle ? { handle: row.handle } : void 0
957
- });
958
- }
959
- async function readUserById(db, userRow) {
960
- return userFromRows(userRow, await db.select().from(juniorIdentities).where(and(eq(juniorIdentities.userId, userRow.id), eq(juniorIdentities.kind, "user"))).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId)));
961
- }
962
- function userFromRows(userRow, identityRows) {
963
- return userSchema.parse({
964
- email: userRow.primaryEmail,
965
- id: userRow.id,
966
- identities: identityRows.map(identityFromRow),
967
- ...userRow.displayName ? { displayName: userRow.displayName } : void 0,
968
- ...userRow.isAdmin ? { isAdmin: true } : void 0
969
- });
970
- }
971
- async function readUserByNormalizedEmail(db, normalizedEmail) {
972
- const cached = await readCachedUserByEmail(db, normalizedEmail);
973
- return cached ? userFromRows(cached.user, cached.identities) : void 0;
974
- }
975
- /** Resolve or create the canonical user for one verified viewer email. */
976
- async function resolveViewerUserFromSql(db, email) {
977
- const normalizedEmail = normalizeIdentityEmail(email);
978
- if (!normalizedEmail) return void 0;
979
- const existing = await readUserByNormalizedEmail(db, normalizedEmail);
980
- if (existing) return existing;
981
- const now = /* @__PURE__ */ new Date();
982
- const userRow = (await db.insert(juniorUsers).values({
983
- id: randomUUID(),
984
- primaryEmail: email.trim(),
985
- primaryEmailNormalized: normalizedEmail,
986
- displayName: null,
987
- createdAt: now,
988
- updatedAt: now
989
- }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
990
- return userRow ? await readUserById(db, userRow) : void 0;
991
- }
992
- /** Resolve or create the canonical user for one authenticated viewer. */
993
- async function resolveViewerUser(email) {
994
- return await resolveViewerUserFromSql(getDb(), email);
995
- }
996
- /** Read one existing canonical user by verified email without creating a row. */
997
- async function findUserByEmailFromSql(db, email) {
998
- const normalizedEmail = normalizeIdentityEmail(email);
999
- if (!normalizedEmail) return void 0;
1000
- return await readUserByNormalizedEmail(db, normalizedEmail);
1001
- }
1002
- /** Read one existing canonical user by verified email without creating a row. */
1003
- async function findUserByEmail(email) {
1004
- return await findUserByEmailFromSql(getDb(), email);
1005
- }
1006
- /** Update one canonical user's display name in SQL. */
1007
- async function updateViewerDisplayNameFromSql(db, userId, displayName) {
1008
- const rows = await db.update(juniorUsers).set({
1009
- displayName,
1010
- updatedAt: /* @__PURE__ */ new Date()
1011
- }).where(eq(juniorUsers.id, userId)).returning();
1012
- await clearCachedUser(userId);
1013
- const userRow = rows[0];
1014
- return userRow ? await readUserById(db, userRow) : void 0;
1015
- }
1016
- /** Read the photo path of one canonical user: Slack, then Google. */
1017
- async function readViewerAvatarUrl(userId) {
1018
- return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
1019
- }
1020
- /** Update one canonical user's display name. */
1021
- async function updateViewerDisplayName(userId, displayName) {
1022
- return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
1023
- }
1024
- /**
1025
- * Grant or revoke the Junior-wide admin role for one email.
1026
- *
1027
- * Granting creates the canonical user when needed, so an operator can grant
1028
- * admin before that person first signs in. Revoking never creates a user.
1029
- */
1030
- async function setUserAdminFromSql(db, email, isAdmin) {
1031
- const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
1032
- if (!user) return void 0;
1033
- const rows = await db.update(juniorUsers).set({
1034
- isAdmin,
1035
- updatedAt: /* @__PURE__ */ new Date()
1036
- }).where(eq(juniorUsers.id, user.id)).returning();
1037
- await clearCachedUser(user.id);
1038
- const userRow = rows[0];
1039
- return userRow ? await readUserById(db, userRow) : void 0;
1040
- }
1041
- /** List every Junior admin by primary email. */
1042
- async function listAdminUsersFromSql(db) {
1043
- const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
1044
- if (rows.length === 0) return [];
1045
- const identityRows = await db.select().from(juniorIdentities).where(and(inArray(juniorIdentities.userId, rows.map((row) => row.id)), eq(juniorIdentities.kind, "user"))).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
1046
- return rows.map((row) => userFromRows(row, identityRows.filter((identity) => identity.userId === row.id)));
1047
- }
1048
- /** Resolve the stored identity and linked user for one runtime actor. */
1049
- async function readActorIdentityFromSql(db, actor) {
1050
- const identityId = await findActorIdentityId(db, actor);
1051
- return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
1052
- }
1053
- /** Resolve the stored identity and linked user for one runtime actor. */
1054
- async function readActorIdentity(actor) {
1055
- return await readActorIdentityFromSql(getDb(), actor);
1056
- }
1057
- /** Read one stored identity and its linked user by identity id. */
1058
- async function readIdentityByIdFromSql(db, identityId) {
1059
- const row = (await db.select({
1060
- identity: juniorIdentities,
1061
- user: juniorUsers
1062
- }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
1063
- if (!row) return void 0;
1064
- return {
1065
- identity: identityFromRow(row.identity),
1066
- ...row.user ? { user: await readUserById(db, row.user) } : void 0
1067
- };
1068
- }
1069
- /** Read one stored identity and its linked user by identity id. */
1070
- async function readIdentityById(identityId) {
1071
- return await readIdentityByIdFromSql(getDb(), identityId);
1072
- }
1073
- // src/chat/inbox-items/assignees.ts
1074
- /** Text that the agent writes to assign Everyone. */
1075
- const EVERYONE_ASSIGNEE = "everyone";
1076
- /**
1077
- * Resolve one assignee: Everyone, an email, or a mention. A mention must be
1078
- * in the tenant of the item.
1079
- */
1080
- async function resolveAssignee(db, value, tenant, findMentionedUserId) {
1081
- const text = value.trim();
1082
- if (text.toLowerCase() === "everyone") return { everyone: true };
1083
- const mentionedUserId = await findMentionedUserId(text, tenant);
1084
- if (mentionedUserId) return { userId: mentionedUserId };
1085
- if (text.includes("@")) {
1086
- const user = await findUserByEmailFromSql(db, text);
1087
- if (!user) throw new ToolInputError(`No User has the email ${text}.`);
1088
- return { userId: user.id };
1089
- }
1090
- throw new ToolInputError(`Unknown assignee ${JSON.stringify(text)}. Use ${EVERYONE_ASSIGNEE}, an email, or a mention such as <@U123>.`);
1091
- }
1092
- /** Resolve the assignees of an Inbox item. One is required. */
1093
- async function resolveAssignees(db, values, tenant, findMentionedUserId) {
1094
- if (values.length === 0) throw new ToolInputError("An inbox item needs at least one assignee.");
1095
- const resolved = await mapBounded(values, (value) => resolveAssignee(db, value, tenant, findMentionedUserId));
1096
- return {
1097
- everyone: resolved.some((assignee) => "everyone" in assignee),
1098
- userIds: [...new Set(resolved.flatMap((assignee) => "userId" in assignee ? [assignee.userId] : []))]
1099
- };
1100
- }
1101
- async function participantUserIds(db, conversationIds, condition) {
1102
- return (await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorConversations, eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), condition))).map((row) => row.userId);
1103
- }
1104
- /** Return which of the Users are Participants of any of the Conversations. */
1105
- async function conversationParticipantUserIds(db, conversationIds, userIds) {
1106
- if (conversationIds.length === 0 || userIds.length === 0) return /* @__PURE__ */ new Set();
1107
- return new Set(await participantUserIds(db, conversationIds, inArray(juniorConversationParticipants.userId, [...userIds])));
1108
- }
1109
- /**
1110
- * Return the active Participants of a Conversation: the people who have not
1111
- * unsubscribed from it.
1112
- */
1113
- async function activeParticipantUserIds(db, conversationId) {
1114
- return await participantUserIds(db, [conversationId], isNull(juniorConversationParticipants.unsubscribedAt));
1115
- }
1116
- /** Return the User who created an Automation, if Junior knows them. */
1117
- async function automationCreatorUserId(db, automationId) {
1118
- const [row] = await db.select({ userId: juniorIdentities.userId }).from(juniorAutomations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorAutomations.creatorIdentityId)).where(eq(juniorAutomations.id, automationId)).limit(1);
1119
- return row?.userId ?? void 0;
1120
- }
1121
- // src/chat/inbox-items/access.ts
1122
- /** Return whether two tenants are the same. Two missing tenants match. */
1123
- function isSameTenant(a, b) {
1124
- return a?.provider === b?.provider && a?.providerTenantId === b?.providerTenantId;
1125
- }
1126
- /**
1127
- * The reader for one person: items assigned to them, and public items in the
1128
- * provider tenants of their identities.
1129
- */
1130
- function inboxItemReaderForUser(user) {
1131
- return {
1132
- tenants: user.identities.flatMap((identity) => identity.providerTenantId ? [{
1133
- provider: identity.provider,
1134
- providerTenantId: identity.providerTenantId
1135
- }] : []),
1136
- userId: user.id
1137
- };
1138
- }
1139
- /**
1140
- * SQL: a Conversation owns the Inbox item. The Conversation status and
1141
- * feeds read the items that each Conversation owns.
1142
- */
1143
- function inboxItemOwnedByConversation(conversationId) {
1144
- return and(eq(juniorInboxItems.ownerKind, "conversation"), eq(juniorInboxItems.ownerId, conversationId));
1145
- }
1146
- /** SQL: the Inbox item has this assigned User. */
1147
- function inboxItemAssignedTo(userId) {
1148
- return sql`exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id} and ${juniorInboxItemAssignees.userId} = ${userId})`;
1149
- }
1150
- /**
1151
- * SQL: the Inbox item needs this User. Only an open `action` item that is
1152
- * assigned to the User needs them. A notice, an item for Everyone, and an
1153
- * item without assignees need no one. An assigned User can always see the
1154
- * item, so this rule needs no visibility check. The nav count and the
1155
- * "Waiting on you" marker use this rule.
1156
- */
1157
- function inboxItemNeedsUser(userId) {
1158
- return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId));
1159
- }
1160
- /**
1161
- * SQL: the Inbox item waits for a person's input: an open `action` item,
1162
- * whoever it is assigned to. An item with no assignees still waits for
1163
- * anyone who can answer it. The Conversation that added it shows
1164
- * `needs_input`. `junior_inbox_items_open_action_added_by_idx` has this
1165
- * predicate.
1166
- */
1167
- function inboxItemNeedsInput() {
1168
- return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"));
1169
- }
1170
- /**
1171
- * SQL: the Inbox item is not assigned only to other people. It is assigned
1172
- * to this User, to Everyone, or to no one. This is the assignee rule of
1173
- * `canActOnInboxItem`; keep the two the same.
1174
- */
1175
- function inboxItemForUser(userId) {
1176
- return or(eq(juniorInboxItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`, inboxItemAssignedTo(userId));
1177
- }
1178
- /** SQL: the Inbox item links this Conversation. */
1179
- function inboxItemLinkedTo(conversationId) {
1180
- return sql`exists (select 1 from ${juniorInboxItemConversations} where ${juniorInboxItemConversations.itemId} = ${juniorInboxItems.id} and ${juniorInboxItemConversations.conversationId} = ${conversationId})`;
1181
- }
1182
- function publicIn(tenants) {
1183
- return tenants.map((tenant) => and(eq(juniorInboxItems.visibility, "public"), eq(juniorInboxItems.provider, tenant.provider), eq(juniorInboxItems.providerTenantId, tenant.providerTenantId)));
1184
- }
1185
- /**
1186
- * SQL form of `canReadInboxItem`, for search. Keep the two the same; the
1187
- * Inbox item access test checks that they agree.
1188
- */
1189
- function inboxItemVisibleTo(reader) {
1190
- return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [inboxItemAssignedTo(reader.userId)] : [], ...reader.conversationId ? [inboxItemLinkedTo(reader.conversationId)] : [], ...reader.automationId ? [eq(juniorInboxItems.automationId, reader.automationId)] : []) ?? sql`false`;
1191
- }
1192
- /** Return whether a reader can see one Inbox item. */
1193
- function canReadInboxItem(item, reader) {
1194
- return item.visibility === "public" && item.tenant !== void 0 && (reader.tenants ?? []).some((tenant) => isSameTenant(tenant, item.tenant)) || reader.userId !== void 0 && item.assignees.some((assignee) => assignee.userId === reader.userId) || reader.conversationId !== void 0 && item.conversationIds.includes(reader.conversationId) || reader.automationId !== void 0 && item.automationId === reader.automationId;
1195
- }
1196
- /**
1197
- * Return whether a person can read one Inbox item: by the reader rule, or
1198
- * because they take part in a Conversation that the item links. The second
1199
- * part is the person rule of `policies/conversation-access.md`; it lets the
1200
- * Conversation view show its items. Viewing a public Conversation is not
1201
- * enough: a private item stays private when its Conversation becomes public.
1202
- */
1203
- async function canUserReadInboxItem(item, user) {
1204
- if (canReadInboxItem(item, inboxItemReaderForUser(user))) return true;
1205
- const access = await readConversationAccessFromSql(getDb(), item.conversationIds, user);
1206
- return item.conversationIds.some((id) => access.get(id)?.isParticipant === true);
1207
- }
1208
- /**
1209
- * The reader for one person who looks at one Conversation: the person's
1210
- * reader, plus the items linked to the Conversation when they take part in
1211
- * it. It is the list form of `canUserReadInboxItem`.
1212
- */
1213
- async function inboxItemReaderForUserInConversation(user, conversationId) {
1214
- const reader = inboxItemReaderForUser(user);
1215
- return (await readConversationAccessFromSql(getDb(), [conversationId], user)).get(conversationId)?.isParticipant ? {
1216
- ...reader,
1217
- conversationId
1218
- } : reader;
1219
- }
1220
- /**
1221
- * Read the scope of an agent. The agent reads as its Conversation and
1222
- * Automation, not as its Actor: an assignment lets a person see the item on
1223
- * the Inbox, not let an agent read it into another Conversation.
1224
- */
1225
- async function readInboxItemAgentScope(context) {
1226
- const actor = await context.resolveActorIdentity?.();
1227
- const user = actor?.user;
1228
- const automationId = context.source.kind === "scheduled_automation" || context.source.kind === "event_automation" ? context.source.automationId : void 0;
1229
- const current = (await readConversationAccessFromSql(getDb(), [context.conversationId], user)).get(context.conversationId);
1230
- const tenant = current?.tenant;
1231
- return {
1232
- actorIsPerson: actor !== void 0,
1233
- inPrivateConversation: current?.visibility !== "public",
1234
- reader: {
1235
- conversationId: context.conversationId,
1236
- ...automationId ? { automationId } : void 0,
1237
- ...tenant ? { tenants: [tenant] } : void 0
1238
- },
1239
- ...tenant ? { tenant } : void 0,
1240
- ...user ? { user } : void 0
1241
- };
1242
- }
1243
- /**
1244
- * Dedupe keys with this prefix belong to plugins. Only the plugin that added
1245
- * the item, or a person, can change it. An agent cannot use the prefix.
1246
- */
1247
- const PLUGIN_INBOX_ITEM_KEY_PREFIX = "plugin:";
1248
- /**
1249
- * Dedupe keys with this prefix belong to Automation alerts, which core adds
1250
- * and closes. An agent cannot use the prefix.
1251
- */
1252
- const AUTOMATION_INBOX_ITEM_KEY_PREFIX = "automation:";
1253
- /** Return the plugin that owns a dedupe key, or undefined for an agent's key. */
1254
- function inboxItemPlugin(dedupeKey) {
1255
- if (!dedupeKey.startsWith("plugin:")) return void 0;
1256
- return dedupeKey.slice(7).split(":", 1)[0] || void 0;
1257
- }
1258
- /** Return whether the item is an Automation alert. Core takes its answer. */
1259
- function isAutomationAlertItem(item) {
1260
- return item.dedupeKey.startsWith(AUTOMATION_INBOX_ITEM_KEY_PREFIX);
1261
- }
1262
- /** Return whether a plugin added the item. Its answer goes to the plugin. */
1263
- function isPluginInboxItem(item) {
1264
- return inboxItemPlugin(item.dedupeKey) !== void 0;
1265
- }
1266
- /**
1267
- * Whether an agent can change an item. Only an agent in the tenant of the
1268
- * item can change it. A public item changes only from a public
1269
- * Conversation, so private content never reaches its readers. A private
1270
- * item changes only from the Conversation or Automation that added it. An
1271
- * agent never changes an item that a plugin added, or an item that another
1272
- * owner kind, such as an Automation, owns.
1273
- */
1274
- function canAgentChangeInboxItem(item, scope) {
1275
- if (item.dedupeKey.startsWith("plugin:")) return false;
1276
- if (item.owner.kind !== "conversation") return false;
1277
- if (!isSameTenant(item.tenant, scope.tenant)) return false;
1278
- if (item.visibility === "public") return !scope.inPrivateConversation;
1279
- return item.owner.id === scope.reader.conversationId || scope.reader.automationId !== void 0 && item.automationId === scope.reader.automationId;
1280
- }
1281
- /**
1282
- * Check the Conversations that an agent links. Every link must be in the
1283
- * tenant of the item. `allowedIds` (the current Conversation and the links
1284
- * that the item already has) always pass. A private item gets no other
1285
- * links. A public item can get other links only to public Conversations.
1286
- */
1287
- async function requireInboxItemLinks(args) {
1288
- const access = await readConversationAccessFromSql(getDb(), args.conversationIds, args.scope.user);
1289
- for (const conversationId of args.conversationIds) {
1290
- const conversation = access.get(conversationId);
1291
- if (!conversation || !isSameTenant(conversation.tenant, args.tenant)) throw new ToolInputError(`Conversation ${conversationId} is not found.`);
1292
- if (args.allowedIds.has(conversationId)) continue;
1293
- if (args.visibility === "private") throw new ToolInputError("A private item links only to the Conversation that added it.");
1294
- if (conversation.visibility !== "public") throw new ToolInputError(conversation.canViewPrivateContent ? `Conversation ${conversationId} is private. Only public Conversations can be linked.` : `Conversation ${conversationId} is not found.`);
1295
- }
1296
- }
1297
- /**
1298
- * Check who an agent assigns a private item to. It cannot go to Everyone.
1299
- * Each User must be the current Actor, a Participant of one of the given
1300
- * Conversations (the current one and, for an existing item, the one that
1301
- * added it), or the creator of the Automation that added the item. An
1302
- * Automation run often has no Actor and no people yet, and its creator wrote
1303
- * the work. A public item can go to anyone.
1304
- */
1305
- async function requireInboxItemAssignees(args) {
1306
- if (args.visibility === "public") return;
1307
- if (args.assignees.everyone) throw new ToolInputError("A private item cannot be assigned to Everyone. Assign Users instead.");
1308
- const creatorId = args.automationId ? await automationCreatorUserId(getDb(), args.automationId) : void 0;
1309
- const others = args.assignees.userIds.filter((id) => id !== args.scope.user?.id && id !== creatorId);
1310
- const inConversation = await conversationParticipantUserIds(getDb(), args.conversationIds, others);
1311
- if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation.");
1312
- }
1313
- /**
1314
- * Return whether a User can act on an open Inbox item: an assigned User,
1315
- * anyone for an item assigned to Everyone, and anyone for an item with no
1316
- * assignees. The caller checks that the User can see the item.
1317
- * `inboxItemForUser` is the SQL form of the assignee rule.
1318
- */
1319
- function canActOnInboxItem(item, userId) {
1320
- if (item.status !== "open") return false;
1321
- if (item.assignedToEveryone) return true;
1322
- if (item.assignees.length === 0) return true;
1323
- return item.assignees.some((assignee) => assignee.userId === userId);
1324
- }
1325
- /**
1326
- * Return whether an Inbox item needs a User: an open `action` item that is
1327
- * assigned to them. `inboxItemNeedsUser` is the SQL form; keep the two the
1328
- * same.
1329
- */
1330
- function itemNeedsUser(item, userId) {
1331
- return item.status === "open" && item.kind === "action" && item.assignees.some((assignee) => assignee.userId === userId);
1332
- }
1333
- /** Return whether a User is already the only assignee, so take does nothing. */
1334
- function isOnlyAssignee(item, userId) {
1335
- return !item.assignedToEveryone && item.assignees.length === 1 && item.assignees[0]?.userId === userId;
1336
- }
1337
- // src/chat/conversations/sql/authorization-wait.ts
1338
- /**
1339
- * How long a person can finish an authorization. The MCP auth session and the
1340
- * dashboard connect prompt expire after this time, so the parked Turn cannot
1341
- * resume after it.
1342
- */
1343
- const AUTHORIZATION_WAIT_MS = 864e5;
1344
- /**
1345
- * The request and the events that end its wait: the person connected, or a
1346
- * Turn started or ended after the request. A stop or new input ends the
1347
- * parked Turn with `turn_completed`. A child agent invocation that needs a
1348
- * connection abandons its Turn and ends it as `blocked`, so nothing resumes
1349
- * it and its parent gets the result instead.
1350
- */
1351
- const AUTHORIZATION_WAIT_EVENT_TYPES = [
1352
- "authorization_requested",
1353
- "authorization_completed",
1354
- "turn_started",
1355
- "turn_completed",
1356
- "turn_failed"
1357
- ];
1358
- /** The oldest request that still waits, on the app clock. */
1359
- function authorizationWaitStart() {
1360
- return (/* @__PURE__ */ new Date(Date.now() - AUTHORIZATION_WAIT_MS)).toISOString();
1361
- }
1362
- /**
1363
- * SQL: the Conversation waits on a person to finish an authorization. A Turn
1364
- * that needs a connection parks with execution `idle`, so only the durable
1365
- * `authorization_requested` event shows the wait: it is the newest of these
1366
- * events and has not expired. Build it for each query: it binds the app
1367
- * clock, which also dated the request.
1368
- */
1369
- function awaitsAuthorization(conversationId) {
1370
- return authorizationWait(conversationId, sql`true`);
1371
- }
1372
- /**
1373
- * SQL: the Conversation waits on this User to finish an authorization. The
1374
- * request names the person by their User id, or by the Slack user id of
1375
- * one of their Identities. Build it for each query, as `awaitsAuthorization`.
1376
- */
1377
- function awaitsAuthorizationFrom(conversationId, userId) {
1378
- const actorId = sql`${juniorConversationEvents.payload}->>'actorId'`;
1379
- return authorizationWait(conversationId, sql`(${actorId} = ${userId} or ${actorId} in (select ${juniorIdentities.providerSubjectId} from ${juniorIdentities} where ${and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, "slack"))}))`);
1380
- }
1381
- /** SQL: the newest wait event is a live request that `requester` matches. */
1382
- function authorizationWait(conversationId, requester) {
1383
- const events = juniorConversationEvents;
1384
- const start = authorizationWaitStart();
1385
- const recentRequest = sql`(select true from ${events} where ${events.conversationId} = ${conversationId} and ${events.type} = 'authorization_requested' and ${events.createdAt} > ${start}::timestamptz limit 1)`;
1386
- return sql`(coalesce(${recentRequest}, false) and coalesce((
1387
- select ${events.type} = 'authorization_requested'
1388
- and ${events.createdAt} > ${start}::timestamptz
1389
- and ${requester}
1390
- from ${events}
1391
- where ${events.conversationId} = ${conversationId}
1392
- and ${events.type} in (${sql.join(AUTHORIZATION_WAIT_EVENT_TYPES.map((type) => sql`${type}`), sql`, `)})
1393
- order by ${events.seq} desc
1394
- limit 1
1395
- ), false))`;
1396
- }
1397
- /**
1398
- * SQL: the root or a child Conversation of `rootConversationId` waits on a
1399
- * person to finish an authorization.
1400
- */
1401
- function treeAwaitsAuthorization(rootConversationId) {
1402
- const tree = alias(juniorConversations, "authorization_tree");
1403
- return sql`exists (
1404
- select 1 from ${juniorConversations} as ${tree}
1405
- where (${tree.conversationId} = ${rootConversationId}
1406
- or ${tree.rootConversationId} = ${rootConversationId})
1407
- and ${awaitsAuthorization(tree.conversationId)}
1408
- )`;
1409
- }
1410
- // src/chat/conversations/sql/conversation-row.ts
1411
- /**
1412
- * Establish the conversation metadata row on first contact for content writes
1413
- * (conversation events, visible transcript) that can land before activity has
1414
- * created the row, and whose tables FK to it.
1415
- *
1416
- * First contact creates the row; every later content write advances the
1417
- * activity clock so retention mirrors append-refresh semantics (each content
1418
- * append refreshes the retention window). Background observations may opt out
1419
- * and leave an existing row unchanged. The timestamp is content-intrinsic (the
1420
- * first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
1421
- * imported historical write — which carries an old timestamp — can never
1422
- * regress `last_activity_at`.
1423
- */
1424
- async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
1425
- const at = new Date(atMs);
1426
- const insert = executor.db().insert(juniorConversations).values({
1427
- conversationId,
1428
- createdAt: at,
1429
- lastActivityAt: at,
1430
- updatedAt: at,
1431
- executionStatus: "idle",
1432
- kind: "root"
1433
- });
1434
- if (options.activity === "preserve") {
1435
- await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
1436
- return;
1437
- }
1438
- await insert.onConflictDoUpdate({
1439
- target: juniorConversations.conversationId,
1440
- set: {
1441
- lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
1442
- updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
1443
- transcriptPurgedAt: null,
1444
- detailVersion: nextDetailVersion
1445
- }
1446
- });
1447
- }
1448
- const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
1449
- "root",
1450
- "automation",
1451
- "lead",
1452
- "thread",
1453
- "task"
1454
- ]);
1455
- /** Decode a stored kind. A null kind comes from a writer of an older deploy. */
1456
- function conversationKindFromRow(row) {
1457
- const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
1458
- if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
1459
- return kind;
1460
- }
1461
- /** SQL for the kind of a row, with the same null fallback as `conversationKindFromRow`. */
1462
- function conversationKindSql(conversation) {
1463
- return sql`coalesce(${conversation.kind}, case when ${conversation.parentConversationId} is null then 'root' else 'task' end)`;
1464
- }
1465
- // src/chat/conversations/sql/status.ts
1466
- const ACTIVE_EXECUTION_STATUSES = [
1467
- "pending",
1468
- "running",
1469
- "paused",
1470
- "awaiting_resume"
1471
- ];
1472
- /** SQL: a Turn of the Conversation is queued or running. */
1473
- function conversationIsActiveSql(conversation) {
1474
- return sql`${conversation.executionStatus} in (${sql.raw(ACTIVE_EXECUTION_STATUSES.map((status) => `'${status}'`).join(", "))})`;
1475
- }
1476
- /**
1477
- * Whether a Turn is queued or running, for a row that is already read. It
1478
- * matches `conversationIsActiveSql`. Live views poll on it; `status` can
1479
- * read `needs_input` meanwhile.
1480
- */
1481
- function executionIsActive(executionStatus) {
1482
- return ACTIVE_EXECUTION_STATUSES.includes(executionStatus);
1483
- }
1484
- /**
1485
- * SQL: the latest Turn of the Conversation failed with no newer input.
1486
- * Execution is `failed`, or the newest Turn lifecycle Event is
1487
- * `turn_failed`. Events are durable; the Redis Turn record expires. Stats
1488
- * count it; the status reads it as input that the starter needs to give.
1489
- */
1490
- function conversationTurnFailedSql(conversation) {
1491
- const newestSeq = (type) => sql`(select max(${juniorConversationEvents.seq}) from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, conversation.conversationId), eq(juniorConversationEvents.type, type))})`;
1492
- return sql`(${conversation.executionStatus} = 'failed' or ${newestSeq("turn_failed")} > coalesce(greatest(${newestSeq("turn_started")}, ${newestSeq("turn_completed")}), -1))`;
1493
- }
1494
- const DELIVERY_PAUSE_START = sql.raw(`'2026-11-10T02:48:39Z'::timestamptz`);
1495
- const starterRoot = alias(juniorConversations, "status_starter_root");
1496
- const starterIdentity = alias(juniorIdentities, "status_starter_identity");
1497
- const replyReader = alias(juniorIdentities, "status_reply_reader");
1498
- /** SQL: the User id of the Conversation's starter, the User of its root's actor. */
1499
- function conversationStarterUserIdSql(conversation) {
1500
- return sql`(select ${starterIdentity.userId} from ${juniorConversations} as ${starterRoot} join ${juniorIdentities} as ${starterIdentity} on ${eq(starterIdentity.id, starterRoot.actorIdentityId)} where ${eq(starterRoot.conversationId, sql`coalesce(${conversation.rootConversationId}, ${conversation.conversationId})`)})`;
1501
- }
1502
- /**
1503
- * SQL: the work of the Conversation waits on its starter. The starter is
1504
- * the User of the root's actor: the person whose message started the root,
1505
- * or the creator of an Automation run. A Task reports to its parent, so
1506
- * only a root, an Automation run, or a Thread waits on its starter. A stop
1507
- * ends what the Conversation waits on, and a queued or running Turn is
1508
- * `working`, not waiting. One of these applies:
1509
- *
1510
- * - The latest Turn failed.
1511
- * - The latest Brief outcome is `partial` or `blocked`, and that Brief
1512
- * covers the latest assistant Message. Turns no longer store Briefs, so a
1513
- * legacy Brief stops deciding once the Conversation moves on.
1514
- * - The latest assistant Message is an answer that the starter has not
1515
- * read. It is an answer when the latest Brief is `answered` or does not
1516
- * cover it. A `done` Brief that covers it needs no read. The starter read
1517
- * it when Slack accepted it for a root's Location, when the starter
1518
- * wrote a later Message, or when their dashboard read position reaches it.
1519
- * With no starter, nobody reads it, so an answer does not wait.
1520
- */
1521
- function conversationWaitsOnStarterSql(conversation) {
1522
- const id = conversation.conversationId;
1523
- const starter = sql.identifier("status_starter");
1524
- const brief = sql.identifier("status_brief");
1525
- const reply = sql.identifier("status_reply");
1526
- const starterUserId = sql`${starter}.user_id`;
1527
- const briefStatus = sql`${brief}.status`;
1528
- const briefThroughSeq = sql`${brief}.through_seq`;
1529
- const replySeq = sql`${reply}.seq`;
1530
- const replyInSlack = sql`${reply}.in_slack`;
1531
- const latestBrief = sql`(select ${juniorConversationBriefs.content}->'outcome'->>'status' as status, ${juniorConversationBriefs.throughSeq} as through_seq from ${juniorConversationBriefs} where ${eq(juniorConversationBriefs.conversationId, id)} order by ${desc(juniorConversationBriefs.version)} limit 1)`;
1532
- const latestReply = sql`(select ${juniorConversationEvents.seq} as seq, coalesce(${juniorConversationEvents.payload}->'meta'->>'source' = 'slack', ${juniorConversationEvents.createdAt} < ${DELIVERY_PAUSE_START}) as in_slack from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`)} order by ${desc(juniorConversationEvents.seq)} limit 1)`;
1533
- const readByStarter = or(and(sql`${conversation.parentConversationId} is null`, sql`${conversation.location} is not null`, sql`coalesce(${replyInSlack}, false)`), sql`exists (select 1 from ${juniorConversationEvents} join ${juniorIdentities} as ${replyReader} on ${eq(replyReader.id, juniorConversationEvents.actorIdentityId)} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), gt(juniorConversationEvents.seq, replySeq), eq(replyReader.userId, starterUserId))})`, sql`exists (select 1 from ${juniorConversationReadPositions} where ${and(eq(juniorConversationReadPositions.conversationId, id), eq(juniorConversationReadPositions.userId, starterUserId), gte(juniorConversationReadPositions.lastReadSeq, replySeq))})`);
1534
- const unreadAnswer = sql`${replySeq} is not null and ${starterUserId} is not null and (coalesce(${briefStatus}, 'answered') = 'answered' or ${briefThroughSeq} < ${replySeq}) and not (${readByStarter})`;
1535
- const waitsOnFacts = sql`(select (${briefStatus} in ('partial', 'blocked') and (${replySeq} is null or ${briefThroughSeq} >= ${replySeq})) or (${unreadAnswer})
1536
- from (select ${conversationStarterUserIdSql(conversation)} as user_id offset 0) as ${starter}
1537
- left join lateral ${latestBrief} as ${brief} on true
1538
- left join lateral ${latestReply} as ${reply} on true)`;
1539
- return sql`(${conversation.stoppedAt} is null
1540
- and ${conversationKindSql(conversation)} <> 'task'
1541
- and not ${conversationIsActiveSql(conversation)}
1542
- and (
1543
- ${conversationTurnFailedSql(conversation)}
1544
- or ${waitsOnFacts}
1545
- ))`;
1546
- }
1547
- /**
1548
- * SQL for the status of one Conversation's own work, shared by everyone.
1549
- * This is the only place that derives it; readers, counts, and feed tokens
1550
- * select it. When more than one applies: `needs_input` > `working` > `done`.
1551
- *
1552
- * - `needs_input`: an open action Inbox item that this Conversation added
1553
- * waits on its assignees or Everyone, a Turn waits on a person to sign in
1554
- * (`awaitsAuthorization`), or the work waits on its starter
1555
- * (`conversationWaitsOnStarterSql`).
1556
- * - `working`: a Turn is queued or running (`conversationIsActiveSql`).
1557
- * - `done`: anything else, such as a `done` Brief, a read answer, a stop,
1558
- * or an idle Conversation.
1559
- */
1560
- function conversationStatusSql(conversation) {
1561
- const needsInput = sql`exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(conversation.conversationId), inboxItemNeedsInput())})`;
1562
- return sql`case
1563
- when ${needsInput} or ${awaitsAuthorization(conversation.conversationId)} or ${conversationWaitsOnStarterSql(conversation)} then 'needs_input'
1564
- when ${conversationIsActiveSql(conversation)} then 'working'
1565
- else 'done'
1566
- end`;
1567
- }
1568
- /**
1569
- * SQL: the Conversation's work waits on this User as its starter. See
1570
- * `conversationWaitsOnStarterSql`.
1571
- */
1572
- function conversationWaitsOnUserSql(conversation, userId) {
1573
- return sql`(${conversationStarterUserIdSql(conversation)} = ${userId} and ${conversationWaitsOnStarterSql(conversation)})`;
1574
- }
1575
- // src/api/conversations/aggregate.ts
1576
- function usageTokenValue(source, field) {
1577
- return sql`CASE
1578
- WHEN ${source.usage}->>${field} IS NOT NULL
1579
- THEN (${source.usage}->>${field})::double precision
1580
- ELSE NULL
1581
- END`;
1582
- }
1583
- function tokenValue(source) {
1584
- return sql`
1585
- CASE
1586
- WHEN COALESCE(
1587
- ${source.usage}->>'inputTokens',
1588
- ${source.usage}->>'outputTokens',
1589
- ${source.usage}->>'cachedInputTokens',
1590
- ${source.usage}->>'cacheCreationTokens'
1591
- ) IS NOT NULL
1592
- THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
1593
- + COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
1594
- + COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
1595
- + COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
1596
- WHEN ${source.usage}->>'totalTokens' IS NOT NULL
1597
- THEN (${source.usage}->>'totalTokens')::double precision
1598
- ELSE NULL
1599
- END
1600
- `;
1601
- }
1602
- function costValue(source) {
1603
- return conversationUsageCostExpr(source.usage);
1604
- }
1605
- /** Read one conversation row's usage cost as a SQL expression. */
1606
- function conversationUsageCostExpr(usage) {
1607
- return sql`
1608
- CASE
1609
- WHEN ${usage}->'cost'->>'total' IS NOT NULL
1610
- THEN (${usage}->'cost'->>'total')::double precision
1611
- WHEN COALESCE(
1612
- ${usage}->'cost'->>'input',
1613
- ${usage}->'cost'->>'output',
1614
- ${usage}->'cost'->>'cacheRead',
1615
- ${usage}->'cost'->>'cacheWrite'
1616
- ) IS NOT NULL
1617
- THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
1618
- + COALESCE((${usage}->'cost'->>'output')::double precision, 0)
1619
- + COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
1620
- + COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
1621
- ELSE NULL
1622
- END
1623
- `;
1624
- }
1625
- /** Select complete conversation metrics inside the database instead of materializing source rows. */
1626
- function conversationAggregateColumns(sources) {
1627
- const metrics = sources?.metrics ?? juniorConversations;
1628
- const roots = sources?.roots ?? juniorConversations;
1629
- const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
1630
- return {
1631
- active: sql`${conversationCount} FILTER (
1632
- WHERE ${conversationIsActiveSql(roots)}
1633
- )::integer`,
1634
- conversations: sql`${conversationCount}::integer`,
1635
- cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
1636
- cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
1637
- costUsd: sql`SUM(${costValue(metrics)})::double precision`,
1638
- durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
1639
- failed: sql`${conversationCount} FILTER (
1640
- WHERE ${conversationTurnFailedSql(roots)} AND ${roots.stoppedAt} IS NULL
1641
- )::integer`,
1642
- inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
1643
- tokens: sql`SUM(${tokenValue(metrics)})::double precision`
1644
- };
1645
- }
1646
- /** Select the complete first/last activity range for a grouped conversation aggregate. */
1647
- function conversationRangeColumns() {
1648
- return {
1649
- firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
1650
- lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
1651
- };
1652
- }
1653
- // src/db/micro-usd.ts
1654
- /**
1655
- * Postgres stores every money value as whole micro-USD, in a `bigint` column
1656
- * or an integer metric value named `*_micro_usd`. Integer sums are exact and
1657
- * do not depend on row order. Round once where a USD amount is stored, and
1658
- * convert to USD once where the API returns it. `pnpm money-units:check`
1659
- * keeps money scales in this file.
1660
- */
1661
- const MICRO_USD_PER_USD = 1e6;
1662
- /** Round a USD amount to whole micro-USD for storage. */
1663
- function usdToMicroUsd(usd) {
1664
- return Math.round(usd * MICRO_USD_PER_USD);
1665
- }
1666
- /** Convert stored micro-USD to USD for an API response. */
1667
- function microUsdToUsd(microUsd) {
1668
- return microUsd / MICRO_USD_PER_USD;
1669
- }
1670
- /** SQL that rounds a USD amount to whole micro-USD. */
1671
- function usdToMicroUsdSql(usd) {
1672
- return sql`round(${usd} * 1000000)::bigint`;
1673
- }
1674
- /** SQL that converts micro-USD to USD, for usage JSON in USD. */
1675
- function microUsdToUsdSql(microUsd) {
1676
- return sql`(${microUsd}) / 1000000.0::double precision`;
1677
- }
1678
- /**
1679
- * SQL that reads a micro-USD value or sum as an exact integer. Postgres
1680
- * returns `bigint` as text, so this maps it to a number.
1681
- */
1682
- function microUsdSql(microUsd) {
1683
- return sql`(${microUsd})::bigint`.mapWith(Number);
1684
- }
1685
- // src/chat/automations/run-cost.ts
1686
- /**
1687
- * SQL for a Conversation's usage cost in whole micro-USD, the unit of a run's
1688
- * `cost_micro_usd`.
1689
- */
1690
- function costMicroUsdExpr(usage) {
1691
- return usdToMicroUsdSql(conversationUsageCostExpr(usage));
1692
- }
1693
- /**
1694
- * SQL that reads the cost of one Conversation, for the `cost_micro_usd` of its
1695
- * run. Set it in each run write that links a run to its Conversation, because
1696
- * the Conversation can record usage before its run row exists.
1697
- */
1698
- function conversationCostOf(conversationId) {
1699
- return sql`(select ${costMicroUsdExpr(juniorConversations.usage)} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
1700
- }
1701
- // src/chat/conversations/metrics.ts
1702
- function finite(value) {
1703
- return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
1704
- }
1705
- /** Convert one Run summary to metric rows. */
1706
- function conversationMetricValues(args) {
1707
- const usage = args.usage;
1708
- const costUsd = agentTurnCostUsd(usage);
1709
- return {
1710
- duration_ms: Math.max(0, args.durationMs),
1711
- total_tokens: agentTurnTotalTokens(usage),
1712
- input_tokens: finite(usage?.inputTokens),
1713
- output_tokens: finite(usage?.outputTokens),
1714
- cached_input_tokens: finite(usage?.cachedInputTokens),
1715
- cache_creation_tokens: finite(usage?.cacheCreationTokens),
1716
- reasoning_tokens: finite(usage?.reasoningTokens),
1717
- cost_micro_usd: costUsd === void 0 ? void 0 : usdToMicroUsd(costUsd)
1718
- };
1719
- }
1720
- /**
1721
- * Read one Run's stored totals from its metric rows.
1722
- *
1723
- * Returns undefined when the Run has no rows. Cost keeps only its total.
1724
- */
1725
- async function readConversationRunMetrics(executor, args) {
1726
- const rows = await executor.db().select({
1727
- metric: juniorConversationMetrics.metric,
1728
- value: juniorConversationMetrics.value
1729
- }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
1730
- const values = new Map(rows.map((row) => [row.metric, row.value]));
1731
- const durationMs = values.get("duration_ms");
1732
- if (durationMs === void 0) return void 0;
1733
- const components = {
1734
- inputTokens: values.get("input_tokens"),
1735
- outputTokens: values.get("output_tokens"),
1736
- cachedInputTokens: values.get("cached_input_tokens"),
1737
- cacheCreationTokens: values.get("cache_creation_tokens")
1738
- };
1739
- const hasComponents = Object.values(components).some((value) => value !== void 0);
1740
- const costMicroUsd = values.get("cost_micro_usd");
1741
- const usage = Object.fromEntries(Object.entries({
1742
- ...components,
1743
- reasoningTokens: values.get("reasoning_tokens"),
1744
- totalTokens: hasComponents ? void 0 : values.get("total_tokens"),
1745
- cost: costMicroUsd === void 0 ? void 0 : { total: microUsdToUsd(costMicroUsd) }
1746
- }).filter(([, value]) => value !== void 0));
1747
- return {
1748
- durationMs,
1749
- ...Object.keys(usage).length > 0 ? { usage } : void 0
1750
- };
1751
- }
1752
- /** Replace one Run's metric rows and refresh its Conversation totals. */
1753
- async function replaceConversationMetrics(executor, args) {
1754
- const [current] = await executor.db().select({ updatedAt: juniorConversationMetrics.updatedAt }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId))).limit(1);
1755
- if (current && current.updatedAt.getTime() > args.updatedAtMs) return;
1756
- await executor.db().delete(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
1757
- const metricValues = conversationMetricValues({
1758
- durationMs: args.durationMs,
1759
- usage: args.usage
1760
- });
1761
- const values = CONVERSATION_METRICS.flatMap((metric) => {
1762
- const value = metricValues[metric];
1763
- return value === void 0 ? [] : [{
1764
- actorIdentityId: args.actorIdentityId ?? null,
1765
- conversationId: args.conversationId,
1766
- runId: args.runId,
1767
- metric,
1768
- value,
1769
- occurredAt: new Date(args.occurredAtMs),
1770
- updatedAt: new Date(args.updatedAtMs)
1771
- }];
1772
- });
1773
- if (values.length > 0) await executor.db().insert(juniorConversationMetrics).values(values);
1774
- const metric = (name) => sql`(
1775
- select sum(${juniorConversationMetrics.value})
1776
- from ${juniorConversationMetrics}
1777
- where ${juniorConversationMetrics.conversationId} = ${args.conversationId}
1778
- and ${juniorConversationMetrics.metric} = ${name}
1779
- )`;
1780
- const totalTokens = metric("total_tokens");
1781
- const componentTokens = sql`
1782
- coalesce(${metric("input_tokens")}, 0)
1783
- + coalesce(${metric("output_tokens")}, 0)
1784
- + coalesce(${metric("cached_input_tokens")}, 0)
1785
- + coalesce(${metric("cache_creation_tokens")}, 0)
1786
- `;
1787
- const hasComponents = sql`
1788
- ${metric("input_tokens")} is not null
1789
- or ${metric("output_tokens")} is not null
1790
- or ${metric("cached_input_tokens")} is not null
1791
- or ${metric("cache_creation_tokens")} is not null
1792
- `;
1793
- const cost = sql`case when ${metric("cost_micro_usd")} is null then null
1794
- else jsonb_build_object('total', ${microUsdToUsdSql(metric("cost_micro_usd"))}) end`;
1795
- const db = executor.db();
1796
- const usageUpdate = db.$with("conversation_usage_update").as(db.update(juniorConversations).set({
1797
- durationMs: sql`coalesce(${metric("duration_ms")}, 0)`,
1798
- usage: sql`case
1799
- when ${totalTokens} is not null
1800
- and (${hasComponents})
1801
- and ${totalTokens} <> ${componentTokens}
1802
- then jsonb_strip_nulls(jsonb_build_object(
1803
- 'totalTokens', ${totalTokens},
1804
- 'reasoningTokens', ${metric("reasoning_tokens")},
1805
- 'cost', ${cost}
1806
- ))
1807
- else jsonb_strip_nulls(jsonb_build_object(
1808
- 'totalTokens', ${totalTokens},
1809
- 'inputTokens', ${metric("input_tokens")},
1810
- 'outputTokens', ${metric("output_tokens")},
1811
- 'cachedInputTokens', ${metric("cached_input_tokens")},
1812
- 'cacheCreationTokens', ${metric("cache_creation_tokens")},
1813
- 'reasoningTokens', ${metric("reasoning_tokens")},
1814
- 'cost', ${cost}
1815
- ))
1816
- end`,
1817
- detailVersion: nextDetailVersion
1818
- }).where(eq(juniorConversations.conversationId, args.conversationId)).returning({ costMicroUsd: costMicroUsdExpr(juniorConversations.usage).as("cost_micro_usd") }));
1819
- await db.with(usageUpdate).update(juniorAutomationRuns).set({ costMicroUsd: sql`(select ${usageUpdate.costMicroUsd} from ${usageUpdate})` }).where(eq(juniorAutomationRuns.conversationId, args.conversationId));
1820
- }
1821
- // src/chat/source.ts
1822
- /**
1823
- * Normalize a Turn Source into legacy provider fields stored on a Conversation.
1824
- * System Sources do not contain a Conversation Location.
1825
- */
1826
- function normalizeSessionSource(value) {
1827
- if (!value) return;
1828
- if (value.kind === "local") return {
1829
- kind: "local",
1830
- visibility: value.visibility,
1831
- conversationId: value.conversationId
1832
- };
1833
- if (value.kind === "web") return {
1834
- kind: "web",
1835
- visibility: value.visibility,
1836
- conversationId: value.conversationId
1837
- };
1838
- if (value.kind === "event" || value.kind === "scheduled_automation" || value.kind === "event_automation" || value.kind === "plugin_dispatch" || value.kind === "agent_invocation") return;
1839
- const threadTs = value.threadTs?.trim();
1840
- return {
1841
- kind: "slack",
1842
- visibility: value.visibility,
1843
- teamId: value.teamId,
1844
- channelId: value.channelId,
1845
- ...threadTs ? { threadTs } : void 0
1846
- };
1847
- }
1848
- /** Parse a serialized Source into legacy provider fields stored on a Conversation. */
1849
- function parseSessionSource(value) {
1850
- const parsed = sourceSchema.safeParse(value);
1851
- return parsed.success ? normalizeSessionSource(parsed.data) : void 0;
1852
- }
1853
- // src/chat/conversations/sql/bindings.ts
1854
- /** Resolve the durable conversation bound to provider-owned coordinates. */
1855
- async function getConversationIdByProviderConversation(executor, args) {
1856
- return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
1857
- }
1858
- /**
1859
- * Bind provider coordinates to a durable conversation unless another
1860
- * conversation has them. Return the conversation that has them.
1861
- */
1862
- async function claimProviderConversationOwner(executor, args) {
1863
- const ownerId = (await executor.db().insert(juniorConversationBindings).values({
1864
- ...args,
1865
- createdAt: /* @__PURE__ */ new Date()
1866
- }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args);
1867
- if (!ownerId) throw new Error("Provider conversation binding disappeared during claim");
1868
- return ownerId;
1869
- }
1870
- /**
1871
- * Bind provider coordinates to a durable conversation unless another
1872
- * conversation has them. Return whether they belong to this conversation.
1873
- */
1874
- async function claimProviderConversation(executor, args) {
1875
- return await claimProviderConversationOwner(executor, args) === args.conversationId;
1876
- }
1877
- /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
1878
- async function bindProviderConversation(executor, args) {
1879
- if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
1880
- }
1881
- // src/chat/conversations/sql/actor-identity.ts
1882
- /**
1883
- * Convert an Actor in the stored Conversation shape to a runtime Actor.
1884
- *
1885
- * TODO(dcramer): Remove after Conversations store the Identity id instead of
1886
- * StoredSlackActor.
1887
- */
1888
- function actorFromStoredActor(actor) {
1889
- if (actor?.slackUserId) return {
1890
- ...actor.email ? { email: actor.email } : void 0,
1891
- ...actor.fullName ? { fullName: actor.fullName } : void 0,
1892
- platform: "slack",
1893
- teamId: actor.teamId ?? "",
1894
- userId: actor.slackUserId,
1895
- ...actor.slackUserName ? { userName: actor.slackUserName } : void 0
1896
- };
1897
- if (!actor?.email) return;
1898
- return {
1899
- email: actor.email,
1900
- ...actor.fullName ? { fullName: actor.fullName } : void 0,
1901
- platform: "web",
1902
- userId: actor.email
1903
- };
1904
- }
1905
- /**
1906
- * Build the legacy system Identity for a Conversation that has no Actor.
1907
- *
1908
- * TODO(dcramer): Remove after every ingress supplies its Actor. These rows use
1909
- * one subject per Source (`scheduler`, `local-cli`, `event`). An Actor
1910
- * uses the one system Identity instead, so the backfill must merge them.
1911
- */
1912
- function systemIdentityFromSource(source) {
1913
- if (source === "scheduler") return {
1914
- kind: "system",
1915
- provider: "junior",
1916
- providerSubjectId: "scheduler",
1917
- displayName: "Scheduler"
1918
- };
1919
- if (source === "local") return {
1920
- kind: "system",
1921
- provider: "junior",
1922
- providerSubjectId: "local-cli",
1923
- displayName: "Local CLI"
1924
- };
1925
- if (source === "event") return {
1926
- kind: "system",
1927
- provider: "junior",
1928
- providerSubjectId: "event",
1929
- displayName: "Event"
1930
- };
1931
- }
1932
- /**
1933
- * Return the root Actor's Identity id. Save the Identity only when the
1934
- * Conversation has none yet. Use the legacy source system Identity when the
1935
- * Conversation has no actor.
1936
- */
1937
- async function resolveConversationActorIdentityId(executor, conversation) {
1938
- const [stored] = await executor.db().select({ actorIdentityId: juniorConversations.actorIdentityId }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversation.conversationId)).limit(1);
1939
- if (stored?.actorIdentityId) return stored.actorIdentityId;
1940
- const actor = actorFromStoredActor(conversation.actor);
1941
- if (actor) return await resolveActorIdentityId(executor, actor, conversation.updatedAtMs);
1942
- const fallback = systemIdentityFromSource(conversation.source);
1943
- return fallback ? (await upsertIdentity(executor, fallback, conversation.updatedAtMs)).id : void 0;
1944
- }
1945
- /**
1946
- * Reconstruct a stored actor with the linked user name and identity-scoped
1947
- * provider fields.
1948
- */
1949
- function actorFromIdentityRow(identity, userDisplayName) {
1950
- if (!identity) return;
1951
- const fullName = userDisplayName?.trim() ? userDisplayName : identity.displayName;
1952
- const email = identity.emailNormalized ?? identity.email ?? void 0;
1953
- if (identity.provider === "slack") return {
1954
- ...email ? { email } : void 0,
1955
- ...fullName ? { fullName } : void 0,
1956
- platform: "slack",
1957
- slackUserId: identity.providerSubjectId,
1958
- ...identity.handle ? { slackUserName: identity.handle } : void 0,
1959
- ...identity.providerTenantId ? { teamId: identity.providerTenantId } : void 0
1960
- };
1961
- if (identity.provider === "junior" && email) return {
1962
- email,
1963
- ...fullName ? { fullName } : void 0
1964
- };
1965
- }
1966
- /** Merge later actor observations without replacing a durable Slack subject. */
1967
- function mergeActor(current, next) {
1968
- if (!current) return next;
1969
- if (!next) return current;
1970
- if (current.slackUserId && next.slackUserId && current.slackUserId !== next.slackUserId) return current;
1971
- return {
1972
- ...current,
1973
- ...current.email ?? next.email ? { email: current.email ?? next.email } : void 0,
1974
- ...current.fullName ?? next.fullName ? { fullName: current.fullName ?? next.fullName } : void 0,
1975
- ...current.platform ?? next.platform ? { platform: current.platform ?? next.platform } : void 0,
1976
- ...current.slackUserId ?? next.slackUserId ? { slackUserId: current.slackUserId ?? next.slackUserId } : void 0,
1977
- ...current.slackUserName ?? next.slackUserName ? { slackUserName: current.slackUserName ?? next.slackUserName } : void 0,
1978
- ...current.teamId ?? next.teamId ? { teamId: current.teamId ?? next.teamId } : void 0
1979
- };
1980
- }
1981
- // src/chat/conversations/sql/location.ts
1982
- /** Build the complete Location for one Conversation SQL write. */
1983
- function locationForWrite(args) {
1984
- const location = args.location ? locationSchema.parse(args.location) : void 0;
1985
- const destination = args.destination?.platform === "slack" ? args.destination : void 0;
1986
- const source = args.sessionSource?.kind === "slack" ? args.sessionSource : void 0;
1987
- if (location) {
1988
- if (destination && (location.id !== args.destinationId || location.teamId !== destination.teamId || location.channelId !== destination.channelId) || source && (location.teamId !== source.teamId || location.channelId !== source.channelId)) throw new Error("Conversation Location changed");
1989
- const threadTs = location.threadTs ?? destination?.threadTs ?? source?.threadTs;
1990
- return threadTs === location.threadTs ? location : {
1991
- ...location,
1992
- threadTs
1993
- };
1994
- }
1995
- if (destination && source && (destination.teamId !== source.teamId || destination.channelId !== source.channelId)) throw new Error("Conversation Location does not match its session Source");
1996
- if (!destination || !args.destinationId) return;
1997
- const threadTs = destination.threadTs ?? source?.threadTs;
1998
- return locationSchema.parse({
1999
- id: args.destinationId,
2000
- provider: "slack",
2001
- teamId: destination.teamId,
2002
- channelId: destination.channelId,
2003
- ...threadTs ? { threadTs } : void 0
2004
- });
2005
- }
2006
- /** Read one complete Location from SQL. */
2007
- function locationFromRow(value, row, sessionSource) {
2008
- if (value !== void 0 && value !== null) {
2009
- const location = locationSchema.parse(value);
2010
- const slackSource = !location.threadTs && sessionSource?.kind === "slack" && sessionSource.teamId === location.teamId && sessionSource.channelId === location.channelId ? sessionSource : void 0;
2011
- return slackSource?.threadTs ? {
2012
- ...location,
2013
- threadTs: slackSource.threadTs
2014
- } : location;
2015
- }
2016
- if (!row || row.provider === "local") return;
2017
- if (row.provider !== "slack") throw new Error("Conversation Location provider is not supported");
2018
- const slackSource = sessionSource?.kind === "slack" && sessionSource.teamId === row.providerTenantId && sessionSource.channelId === row.providerDestinationId ? sessionSource : void 0;
2019
- return locationSchema.parse({
2020
- id: row.id,
2021
- provider: "slack",
2022
- teamId: row.providerTenantId,
2023
- channelId: row.providerDestinationId,
2024
- ...slackSource?.threadTs ? { threadTs: slackSource.threadTs } : void 0
2025
- });
2026
- }
2027
- /** Read confirmed visibility from one linked Location row. */
2028
- function visibilityFromLocationRow(row) {
2029
- if (!row) return;
2030
- if (row.visibility === "public" || row.visibility === "private") return row.visibility;
2031
- }
2032
- /**
2033
- * Give a root Conversation with no Location its first one, in the caller's
2034
- * SQL scope. The Location row becomes the Conversation Destination, so
2035
- * visibility then comes from that channel. Returns false when the
2036
- * Conversation already has a Location.
2037
- */
2038
- async function setFirstConversationLocation(executor, args) {
2039
- const location = locationSchema.parse(args.location);
2040
- return (await executor.db().update(juniorConversations).set({
2041
- location,
2042
- destinationId: location.id,
2043
- ...args.channelName ? { channelName: args.channelName } : void 0,
2044
- detailVersion: nextDetailVersion
2045
- }).where(and(eq(juniorConversations.conversationId, args.conversationId), isNull(juniorConversations.parentConversationId), isNull(juniorConversations.location))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
2046
- }
2047
- /** Store a channel-level Location's first bound post as its thread. */
2048
- async function startLocationThread(executor, binding) {
2049
- const location = juniorConversations.location;
2050
- await executor.db().update(juniorConversations).set({
2051
- location: sql`${location} || jsonb_build_object('threadTs', ${binding.providerConversationId}::text)`,
2052
- detailVersion: nextDetailVersion
2053
- }).where(and(eq(juniorConversations.conversationId, binding.conversationId), sql`${location}->>'provider' = ${binding.provider}`, sql`${location}->>'teamId' = ${binding.providerTenantId}`, sql`${location}->>'channelId' = ${binding.providerDestinationId}`, isNull(sql`${location}->>'threadTs'`)));
2054
- }
2055
- // src/chat/conversations/kind-behavior.ts
2056
- const ROOT = {
2057
- delivery: "location",
2058
- promptMode: "conversation",
2059
- idleNeedsPendingWork: false,
2060
- waitsForSignIn: true,
2061
- gated: false,
2062
- failureNotice: "none",
2063
- sessionTasks: true,
2064
- relatedConversations: true,
2065
- tools: {
2066
- agents: "children",
2067
- inbox: true,
2068
- subscriptions: true,
2069
- userCustomization: true,
2070
- reply: "none",
2071
- reportBlocked: "none",
2072
- noReply: true
2073
- }
2074
- };
2075
- const ROOT_RUNTIME_TURN = {
2076
- ...ROOT,
2077
- relatedConversations: false
2078
- };
2079
- const PERSON_IN_THREAD = {
2080
- ...ROOT,
2081
- promptMode: "thread",
2082
- sender: "person",
2083
- sessionTasks: false,
2084
- relatedConversations: false,
2085
- tools: {
2086
- ...ROOT.tools,
2087
- agents: "none"
2088
- }
2089
- };
2090
- const CHILD_AGENT_TURN = {
2091
- delivery: "conversation",
2092
- promptMode: "child_agent",
2093
- idleNeedsPendingWork: false,
2094
- waitsForSignIn: false,
2095
- gated: true,
2096
- failureNotice: "none",
2097
- sessionTasks: false,
2098
- relatedConversations: false,
2099
- tools: {
2100
- agents: "children_and_parent",
2101
- inbox: false,
2102
- subscriptions: false,
2103
- userCustomization: false,
2104
- reply: "parent",
2105
- reportBlocked: "parent",
2106
- noReply: true
2107
- }
2108
- };
2109
- const AGENT_IN_THREAD = {
2110
- ...CHILD_AGENT_TURN,
2111
- promptMode: "thread",
2112
- sender: "agent"
2113
- };
2114
- const THREAD_TOOLS = {
2115
- ...AGENT_IN_THREAD.tools,
2116
- inbox: PERSON_IN_THREAD.tools.inbox,
2117
- subscriptions: PERSON_IN_THREAD.tools.subscriptions,
2118
- userCustomization: PERSON_IN_THREAD.tools.userCustomization
2119
- };
2120
- const AGENT_IN_TASK = {
2121
- ...CHILD_AGENT_TURN,
2122
- missingAnswerError: "No reply was sent.",
2123
- failureNotice: "parent"
2124
- };
2125
- const AUTOMATION_RUN = {
2126
- delivery: "conversation",
2127
- promptMode: "automation",
2128
- sender: "automation",
2129
- idleNeedsPendingWork: true,
2130
- waitsForSignIn: true,
2131
- gated: true,
2132
- failureNotice: "none",
2133
- sessionTasks: true,
2134
- relatedConversations: false,
2135
- tools: {
2136
- ...ROOT.tools,
2137
- reply: "automation",
2138
- reportBlocked: "automation"
2139
- }
2140
- };
2141
- const PERSON_IN_AUTOMATION = {
2142
- ...ROOT,
2143
- promptMode: "automation",
2144
- sender: "person",
2145
- relatedConversations: false
2146
- };
2147
- const LEAD_TOOLS = [
2148
- "startConversation",
2149
- "messageAgent",
2150
- "searchConversations",
2151
- "searchConversationEvents",
2152
- "readConversationEvent",
2153
- "searchInboxItems",
2154
- "searchEventTypes",
2155
- "watchEvents",
2156
- "watchTimer",
2157
- "listWatches",
2158
- "stopWatchingResources",
2159
- "systemTime",
2160
- "updateUserCustomization",
2161
- "noReply"
2162
- ];
2163
- const LEAD = {
2164
- ...ROOT,
2165
- promptMode: "lead",
2166
- sessionTasks: false,
2167
- tools: {
2168
- ...ROOT.tools,
2169
- agents: "lead",
2170
- subscriptions: false,
2171
- only: LEAD_TOOLS
2172
- }
2173
- };
2174
- /** Return the behavior of one Turn. */
2175
- function turnBehavior(args) {
2176
- switch (args.kind) {
2177
- case "root": return args.personInput ? ROOT : ROOT_RUNTIME_TURN;
2178
- case "automation": return args.personInput ? PERSON_IN_AUTOMATION : AUTOMATION_RUN;
2179
- case "thread": return args.personInput ? PERSON_IN_THREAD : AGENT_IN_THREAD;
2180
- case "task":
2181
- if (!args.personInput) return AGENT_IN_TASK;
2182
- throw new Error("A task Conversation cannot have a person's input");
2183
- case "lead": return LEAD;
2184
- }
2185
- }
2186
- /**
2187
- * Return the tools that every Turn of one Prompt mode lists. A Turn of a mode
2188
- * with two senders can list more than its own tools. The listed tools that it
2189
- * cannot use are disabled.
2190
- */
2191
- function promptModeTurnTools(mode) {
2192
- switch (mode) {
2193
- case "automation": return AUTOMATION_RUN.tools;
2194
- case "child_agent": return AGENT_IN_TASK.tools;
2195
- case "thread": return THREAD_TOOLS;
2196
- case "conversation": return ROOT.tools;
2197
- case "lead": return LEAD.tools;
2198
- }
2199
- }
2200
- /**
2201
- * Return whether Turns update the Conversation metadata of this kind. Only
2202
- * its parent reads a Task, so a Task has no summary.
2203
- */
2204
- function hasConversationMetadata(kind) {
2205
- return kind !== "task";
2206
- }
2207
- /** Return whether a Conversation of this kind has no parent. */
2208
- function isTopLevelKind(kind) {
2209
- return kind === "root" || kind === "automation" || kind === "lead";
2210
- }
2211
- /**
2212
- * Return whether a Watch on this Conversation would repeat what already
2213
- * reaches the watcher: a child agent's results and messages go to its parent.
2214
- */
2215
- function watchRepeatsChildResults(target, watcherConversationId) {
2216
- return target.parentConversationId === watcherConversationId;
2217
- }
2218
- /** Return whether a person sent input from this Source. */
2219
- function isPersonInput(source) {
2220
- return source === "web" || source === "slack";
2221
- }
2222
- /** Narrow a Source to one that a person sent input from. */
2223
- function isPersonSource(source) {
2224
- return isPersonInput(source.kind);
2225
- }
2226
- /**
2227
- * Return the chat platform of a Source that a person writes from, or
2228
- * undefined for a runtime Source, such as an event or an Automation.
2229
- */
2230
- function personSourcePlatform(source) {
2231
- switch (source.kind) {
2232
- case "slack":
2233
- case "local":
2234
- case "web": return source.kind;
2235
- case "event":
2236
- case "scheduled_automation":
2237
- case "event_automation":
2238
- case "plugin_dispatch":
2239
- case "agent_invocation": return;
2240
- }
2241
- }
2242
- /** Return a short label that names a Source, such as `slack:T1:C1`. */
2243
- function sourceLabel(source) {
2244
- switch (source.kind) {
2245
- case "slack": return `slack:${source.teamId}:${source.channelId}`;
2246
- case "web":
2247
- case "local": return `${source.kind}:${source.conversationId}`;
2248
- case "event": return `event:${source.namespace}:${source.eventKey}`;
2249
- case "scheduled_automation":
2250
- case "event_automation":
2251
- case "plugin_dispatch":
2252
- case "agent_invocation": return source.kind;
2253
- }
2254
- }
2255
- /**
2256
- * Return whether the runtime delivers the final response of a Slack or
2257
- * dispatch run. Only root Conversations reach these paths, so only an
2258
- * Automation run keeps its final response in the Conversation. A dispatch
2259
- * with no outcomes delivers nothing.
2260
- */
2261
- function deliversFinalText(dispatch) {
2262
- return dispatch?.outcomes?.length !== 0 && !dispatch?.declaresResult;
2263
- }
2264
- /**
2265
- * Return whether the runtime may post a failure reply or a status notice,
2266
- * such as an auth prompt, for a run outside `finishedRunReply`. The rule is
2267
- * the same as for a final response. A chat Turn may post, also in a thread
2268
- * that an Automation Conversation owns. An Automation run posts only its
2269
- * `reply` text; its failed execution shows on the Automation.
2270
- */
2271
- function postsRunNotices(dispatch) {
2272
- return deliversFinalText(dispatch);
2273
- }
2274
- /**
2275
- * Return whether the task instructions of a dispatch run can invoke skills.
2276
- * Only an Automation creator writes them. Another dispatch, such as a plugin
2277
- * dispatch, has no person's text.
2278
- */
2279
- function dispatchInstructionsInvokeSkills(dispatch) {
2280
- return dispatch?.declaresResult === true;
2281
- }
2282
- // src/chat/conversations/sql/store.ts
2283
- const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
2284
- /** Serialize one conversation's durable mutations inside a SQL transaction. */
2285
- async function withConversationMutationLock(executor, conversationId, callback) {
2286
- return await executor.withLock(`${CONVERSATION_MUTATION_LOCK_PREFIX}:${conversationId}`, async () => await executor.transaction(callback));
2287
- }
2288
- function now() {
2289
- return Date.now();
2290
- }
2291
- function dateFromMs(ms) {
2292
- return new Date(ms);
2293
- }
2294
- function msFromDate(value) {
2295
- if (value === null || value === void 0) return;
2296
- return (value instanceof Date ? value : new Date(value)).getTime();
2297
- }
2298
- function requiredMsFromDate(value) {
2299
- const ms = msFromDate(value);
2300
- if (typeof ms !== "number" || Number.isNaN(ms)) throw new Error("Conversation record timestamp is invalid");
2301
- return ms;
2302
- }
2303
- function tenantId(value) {
2304
- return value ?? "";
2305
- }
2306
- function sourceFromValue(value) {
2307
- if (value === "api" || value === "internal" || value === "local" || value === "plugin" || value === "event" || value === "scheduler" || value === "slack" || value === "web") return value;
2308
- }
2309
- function localWorkspaceFromConversationId(conversationId) {
2310
- return /^local:([^:]+):/.exec(conversationId)?.[1];
2311
- }
2312
- function destinationUpsertFromDestination(args) {
2313
- const { destination } = args;
2314
- if (!destination) return;
2315
- if (destination.platform === "slack") {
2316
- const channelId = destination.channelId;
2317
- return {
2318
- kind: channelId.startsWith("D") ? "dm" : channelId.startsWith("G") ? "group" : "channel",
2319
- provider: "slack",
2320
- providerTenantId: destination.teamId,
2321
- providerDestinationId: channelId,
2322
- refreshVisibility: args.visibility !== void 0,
2323
- visibility: args.visibility ?? "unknown",
2324
- ...args.channelName ? { displayName: args.channelName } : void 0,
2325
- metadata: { platform: "slack" }
2326
- };
2327
- }
2328
- return {
2329
- kind: "local_conversation",
2330
- provider: "local",
2331
- providerTenantId: localWorkspaceFromConversationId(destination.conversationId) ?? localWorkspaceFromConversationId(args.conversationId ?? ""),
2332
- providerDestinationId: destination.conversationId,
2333
- refreshVisibility: args.visibility !== void 0,
2334
- visibility: args.visibility ?? "direct",
2335
- metadata: { platform: "local" }
2336
- };
2337
- }
2338
- function executionStatusFromValue(value) {
2339
- if (value === "failed" || value === "idle" || value === "paused" || value === "pending" || value === "running") return value;
2340
- throw new Error("Conversation record execution status is invalid");
2341
- }
2342
- function destinationFromRow(destination) {
2343
- return parseDestination(destination?.provider === "slack" ? {
2344
- platform: "slack",
2345
- teamId: destination.providerTenantId,
2346
- channelId: destination.providerDestinationId
2347
- } : destination?.provider === "local" ? {
2348
- platform: "local",
2349
- conversationId: destination.providerDestinationId
2350
- } : void 0);
2351
- }
2352
- /** Decode one SQL row and reject invalid durable conversation records. */
2353
- function conversationFromRow(readRow) {
2354
- const row = readRow.conversation;
2355
- const visibility = visibilityFromLocationRow(readRow.destination);
2356
- if (row.schemaVersion !== 1) throw new Error("Conversation record schema version is invalid");
2357
- if (row.destination !== null && readRow.destination === null) throw new Error("Conversation legacy destination is not migrated");
2358
- if (row.actor !== null && readRow.actorIdentity === null) throw new Error("Conversation legacy actor is not migrated");
2359
- const destination = destinationFromRow(readRow.destination);
2360
- const actor = actorFromIdentityRow(readRow.actorIdentity, readRow.actorUserDisplayName);
2361
- if (readRow.destination !== null && !destination) throw new Error("Conversation record destination is invalid");
2362
- const source = row.source === void 0 || row.source === null ? void 0 : sourceFromValue(row.source);
2363
- if (row.source !== void 0 && row.source !== null && !source) throw new Error("Conversation record source is invalid");
2364
- const sessionSource = row.sessionSource === void 0 || row.sessionSource === null ? void 0 : parseSessionSource(row.sessionSource);
2365
- if (row.sessionSource !== void 0 && row.sessionSource !== null && !sessionSource) throw new Error("Conversation record session source is invalid");
2366
- const execution = {
2367
- status: executionStatusFromValue(row.executionStatus),
2368
- lastCheckpointAtMs: msFromDate(row.lastCheckpointAt),
2369
- lastEnqueuedAtMs: msFromDate(row.lastEnqueuedAt),
2370
- ...row.runId ? { runId: row.runId } : void 0,
2371
- updatedAtMs: msFromDate(row.executionUpdatedAt) ?? requiredMsFromDate(row.updatedAt)
2372
- };
2373
- const location = locationFromRow(row.location, readRow.destination, sessionSource);
2374
- return {
2375
- schemaVersion: 1,
2376
- conversationId: row.conversationId,
2377
- createdAtMs: requiredMsFromDate(row.createdAt),
2378
- lastActivityAtMs: requiredMsFromDate(row.lastActivityAt),
2379
- updatedAtMs: requiredMsFromDate(row.updatedAt),
2380
- execution,
2381
- executionMetrics: {
2382
- durationMs: row.executionDurationMs,
2383
- ...row.metricRunId ? { runId: row.metricRunId } : void 0,
2384
- ...row.executionUsage ? { usage: row.executionUsage } : void 0
2385
- },
2386
- kind: conversationKindFromRow(row),
2387
- ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
2388
- ...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0,
2389
- ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
2390
- ...destination ? { destination } : void 0,
2391
- ...location ? { location } : void 0,
2392
- ...actor ? { actor } : void 0,
2393
- ...row.channelName ? { channelName: row.channelName } : void 0,
2394
- ...source ? { source } : void 0,
2395
- ...sessionSource ? { sessionSource } : void 0,
2396
- ...row.title ? { title: row.title } : void 0,
2397
- ...row.summary ? { summary: row.summary } : void 0,
2398
- ...msFromDate(row.transcriptPurgedAt) !== void 0 ? { transcriptPurgedAtMs: msFromDate(row.transcriptPurgedAt) } : void 0,
2399
- ...msFromDate(row.stoppedAt) !== void 0 ? { stoppedAtMs: msFromDate(row.stoppedAt) } : void 0,
2400
- ...msFromDate(row.deliveryPausedAt) !== void 0 ? { deliveryPausedAtMs: msFromDate(row.deliveryPausedAt) } : void 0,
2401
- ...visibility ? { visibility } : void 0
2402
- };
2403
- }
2404
- function emptyConversation(args) {
2405
- return {
2406
- schemaVersion: 1,
2407
- conversationId: args.conversationId,
2408
- createdAtMs: args.nowMs,
2409
- kind: args.kind ?? "root",
2410
- lastActivityAtMs: args.nowMs,
2411
- updatedAtMs: args.nowMs,
2412
- ...args.destination ? { destination: args.destination } : void 0,
2413
- ...args.source ? { source: args.source } : void 0,
2414
- ...args.sessionSource ? { sessionSource: args.sessionSource } : void 0,
2415
- execution: {
2416
- status: "idle",
2417
- updatedAtMs: args.nowMs
2418
- }
2419
- };
2420
- }
2421
- function assertSameConversationDestination(args) {
2422
- if (!args.current || sameDestination(args.current, args.next)) return;
2423
- throw new Error(`Conversation destination changed for ${args.conversationId}`);
2424
- }
2425
- var SqlStore = class {
2426
- executor;
2427
- constructor(executor) {
2428
- this.executor = executor;
2429
- }
2430
- async getConversationIdByProviderConversation(args) {
2431
- return await getConversationIdByProviderConversation(this.executor, args);
2432
- }
2433
- async bindProviderConversation(args) {
2434
- await bindProviderConversation(this.executor, args);
2435
- }
2436
- async claimProviderConversation(args) {
2437
- const { atMs, ...binding } = args;
2438
- return await this.executor.transaction(async () => {
2439
- await ensureConversationRow(this.executor, binding.conversationId, atMs, { activity: "preserve" });
2440
- return await claimProviderConversationOwner(this.executor, binding);
2441
- });
2442
- }
2443
- async createChild(args) {
2444
- const nowMs = args.nowMs ?? now();
2445
- await this.withConversationMutation(args.parentConversationId, async () => {
2446
- await this.withConversationMutation(args.childConversationId, async () => {
2447
- const existing = await this.get({ conversationId: args.childConversationId });
2448
- if (existing) {
2449
- if (existing.parentConversationId !== args.parentConversationId) throw new Error(`Conversation parent changed for ${args.childConversationId}`);
2450
- if (existing.kind !== args.kind) throw new Error(`Conversation kind changed for ${args.childConversationId}`);
2451
- return;
2452
- }
2453
- const parentRow = await this.readConversationRow(args.parentConversationId);
2454
- if (!parentRow) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
2455
- const { location } = conversationFromRow(parentRow);
2456
- const child = {
2457
- ...emptyConversation({
2458
- conversationId: args.childConversationId,
2459
- nowMs,
2460
- source: args.source
2461
- }),
2462
- kind: args.kind,
2463
- parentConversationId: args.parentConversationId,
2464
- ...location ? { location } : void 0,
2465
- ...args.title ? { title: args.title } : void 0
2466
- };
2467
- await this.upsertConversation({
2468
- conversation: child,
2469
- destinationId: parentRow.conversation.destinationId ?? void 0
2470
- });
2471
- });
2472
- });
2473
- }
2474
- async get(args) {
2475
- const row = await this.readConversationRow(args.conversationId);
2476
- if (!row) return;
2477
- return conversationFromRow(row);
2478
- }
2479
- async getRunMetrics(args) {
2480
- return await readConversationRunMetrics(this.executor, args);
2481
- }
2482
- async recordActivity(args) {
2483
- const nowMs = args.nowMs ?? now();
2484
- const activityAtMs = args.activityAtMs ?? nowMs;
2485
- const sessionSource = normalizeSessionSource(args.sessionSource);
2486
- await this.withConversationMutation(args.conversationId, async () => {
2487
- const existing = await this.get({ conversationId: args.conversationId });
2488
- if (existing && args.destination) assertSameConversationDestination({
2489
- conversationId: args.conversationId,
2490
- current: existing.destination,
2491
- next: args.destination
2492
- });
2493
- const current = existing ?? emptyConversation({
2494
- conversationId: args.conversationId,
2495
- destination: args.destination,
2496
- kind: args.kind,
2497
- nowMs,
2498
- source: args.source,
2499
- ...sessionSource ? { sessionSource } : void 0
2500
- });
2501
- const { sessionSource: _persistedSessionSource, visibility: _persistedVisibility, ...currentWithoutPersistedSignals } = current;
2502
- await this.upsertConversation({ conversation: {
2503
- ...currentWithoutPersistedSignals,
2504
- destination: current.destination ?? args.destination,
2505
- source: current.source ?? args.source,
2506
- ...sessionSource ? { sessionSource } : void 0,
2507
- channelName: current.channelName ?? args.channelName,
2508
- actor: mergeActor(current.actor, args.actor),
2509
- title: current.title ?? args.title,
2510
- lastActivityAtMs: Math.max(current.lastActivityAtMs, activityAtMs),
2511
- updatedAtMs: nowMs,
2512
- execution: {
2513
- ...current.execution,
2514
- updatedAtMs: current.execution.updatedAtMs ?? nowMs
2515
- },
2516
- ...args.visibility ? { visibility: args.visibility } : void 0
2517
- } });
2518
- });
2519
- }
2520
- async recordExecution(args) {
2521
- if (args.metrics && !args.execution.runId) throw new Error("Conversation Run metrics require a Run id");
2522
- await this.withConversationMutation(args.conversationId, async () => {
2523
- const existingRow = await this.readConversationRow(args.conversationId);
2524
- const existing = existingRow ? conversationFromRow(existingRow) : void 0;
2525
- if (!existing && !args.destination) return;
2526
- const incomingExecutionAt = args.execution.updatedAtMs ?? args.updatedAtMs;
2527
- const existingExecutionAt = existing?.execution.updatedAtMs ?? existing?.updatedAtMs ?? 0;
2528
- const latestMetricRunId = existing?.executionMetrics?.runId;
2529
- const incomingIsFresh = !(args.metrics !== null && args.execution.runId !== void 0 && latestMetricRunId !== void 0 && latestMetricRunId !== args.execution.runId && (args.execution.status === "idle" || args.execution.status === "failed") && await readConversationRunMetrics(this.executor, {
2530
- conversationId: args.conversationId,
2531
- runId: args.execution.runId
2532
- }) !== void 0) && incomingExecutionAt >= existingExecutionAt;
2533
- const execution = incomingIsFresh ? args.execution : existing?.execution ?? args.execution;
2534
- const actor = mergeActor(existing?.actor, args.actor);
2535
- const source = existing?.source ?? args.source;
2536
- await this.upsertConversation({ conversation: {
2537
- schemaVersion: 1,
2538
- conversationId: args.conversationId,
2539
- createdAtMs: args.createdAtMs,
2540
- kind: existing?.kind ?? "root",
2541
- lastActivityAtMs: args.lastActivityAtMs,
2542
- updatedAtMs: args.updatedAtMs,
2543
- ...existing?.parentConversationId ? { parentConversationId: existing.parentConversationId } : void 0,
2544
- ...existing?.location ? { location: existing.location } : void 0,
2545
- ...args.channelName ? { channelName: args.channelName } : void 0,
2546
- ...args.destination ? { destination: args.destination } : void 0,
2547
- ...actor ? { actor } : void 0,
2548
- ...source ? { source } : void 0,
2549
- ...args.title ? { title: args.title } : void 0,
2550
- ...args.visibility ? { visibility: args.visibility } : void 0,
2551
- execution
2552
- } });
2553
- if (args.metrics && args.execution.runId) {
2554
- await replaceConversationMetrics(this.executor, {
2555
- actorIdentityId: args.actorIdentityId,
2556
- conversationId: args.conversationId,
2557
- runId: args.execution.runId,
2558
- occurredAtMs: args.createdAtMs,
2559
- updatedAtMs: incomingExecutionAt,
2560
- ...args.metrics
2561
- });
2562
- if (incomingIsFresh) await this.executor.db().update(juniorConversations).set({
2563
- metricRunId: args.execution.runId,
2564
- executionDurationMs: args.metrics.durationMs,
2565
- executionUsage: args.metrics.usage ?? null,
2566
- detailVersion: nextDetailVersion
2567
- }).where(eq(juniorConversations.conversationId, args.conversationId));
2568
- }
2569
- });
2570
- }
2571
- async listByActivity(args = {}) {
2572
- const rows = await this.executor.db().select({
2573
- conversation: juniorConversations,
2574
- destination: juniorDestinations,
2575
- actorIdentity: juniorIdentities,
2576
- actorUserDisplayName: juniorUsers.displayName
2577
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(isNull(juniorConversations.parentConversationId)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(Math.max(0, args.limit ?? 1e4)).offset(Math.max(0, args.offset ?? 0));
2578
- const conversations = [];
2579
- for (const row of rows) conversations.push(conversationFromRow(row));
2580
- return conversations;
2581
- }
2582
- async getDestinationVisibility(args) {
2583
- const row = (await this.executor.db().select({ visibility: juniorDestinations.visibility }).from(juniorDestinations).where(and(eq(juniorDestinations.provider, args.provider), eq(juniorDestinations.providerTenantId, tenantId(args.providerTenantId)), eq(juniorDestinations.providerDestinationId, args.providerDestinationId))))[0];
2584
- if (!row) return;
2585
- if (row.visibility === "public" || row.visibility === "private") return row.visibility;
2586
- }
2587
- async recordDestinationVisibility(args) {
2588
- await this.upsertDestination(destinationUpsertFromDestination(args), args.nowMs ?? Date.now());
2589
- }
2590
- async findSlackDestinationByName(args) {
2591
- const normalized = args.channelName.trim().replace(/^#/, "").toLowerCase();
2592
- if (!normalized) return;
2593
- const rows = await this.executor.db().select({
2594
- channelId: juniorDestinations.providerDestinationId,
2595
- channelName: juniorDestinations.displayName
2596
- }).from(juniorDestinations).where(and(eq(juniorDestinations.provider, "slack"), eq(juniorDestinations.providerTenantId, tenantId(args.teamId)), eq(juniorDestinations.kind, "channel"), sql`lower(ltrim(${juniorDestinations.displayName}, '#')) = ${normalized}`)).limit(2);
2597
- if (rows.length !== 1) return;
2598
- const row = rows[0];
2599
- if (!row?.channelId) return;
2600
- return {
2601
- channelId: row.channelId,
2602
- ...row.channelName ? { channelName: row.channelName } : void 0
2603
- };
2604
- }
2605
- /** Serialize all durable mutations for one conversation inside a SQL transaction. */
2606
- async withConversationMutation(conversationId, callback) {
2607
- return await withConversationMutationLock(this.executor, conversationId, callback);
2608
- }
2609
- async readConversationRow(conversationId) {
2610
- return (await this.executor.db().select({
2611
- conversation: juniorConversations,
2612
- destination: juniorDestinations,
2613
- actorIdentity: juniorIdentities,
2614
- actorUserDisplayName: juniorUsers.displayName
2615
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(eq(juniorConversations.conversationId, conversationId)))[0];
2616
- }
2617
- /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
2618
- async upsertConversation(args) {
2619
- const { conversation } = args;
2620
- if (isTopLevelKind(conversation.kind) !== !conversation.parentConversationId) throw new Error(`Conversation ${conversation.conversationId} kind does not match its parent`);
2621
- if (!conversation.parentConversationId && !conversation.destination) {
2622
- if (!await this.get({ conversationId: conversation.conversationId })) throw new Error(`Conversation ${conversation.conversationId} requires a destination at create`);
2623
- }
2624
- const incomingExecutionVersion = sql`coalesce(excluded.execution_updated_at, excluded.updated_at)`;
2625
- const currentExecutionVersion = sql`coalesce(${juniorConversations.executionUpdatedAt}, ${juniorConversations.updatedAt})`;
2626
- const incomingExecutionIsFresh = sql`${incomingExecutionVersion} >= ${currentExecutionVersion}`;
2627
- const destinationId = await this.upsertDestination(destinationUpsertFromDestination({
2628
- channelName: conversation.channelName,
2629
- conversationId: conversation.conversationId,
2630
- destination: conversation.destination,
2631
- ...conversation.visibility ? { visibility: conversation.visibility } : void 0
2632
- }), conversation.updatedAtMs) ?? args.destinationId;
2633
- const location = locationForWrite({
2634
- destination: conversation.destination,
2635
- destinationId,
2636
- location: conversation.location,
2637
- sessionSource: conversation.sessionSource
2638
- });
2639
- const actorIdentityId = await resolveConversationActorIdentityId(this.executor, conversation);
2640
- const rootConversationId = conversation.parentConversationId ? sql`(
2641
- select parent.root_conversation_id
2642
- from junior_conversations parent
2643
- where parent.conversation_id = ${conversation.parentConversationId}
2644
- )` : conversation.conversationId;
2645
- const row = (await this.executor.db().insert(juniorConversations).values({
2646
- conversationId: conversation.conversationId,
2647
- schemaVersion: 1,
2648
- source: conversation.source ?? null,
2649
- sessionSource: conversation.sessionSource ?? null,
2650
- location: location ?? null,
2651
- destinationId: destinationId ?? null,
2652
- destination: null,
2653
- actorIdentityId: actorIdentityId ?? null,
2654
- creatorIdentityId: null,
2655
- credentialSubjectIdentityId: null,
2656
- actor: null,
2657
- channelName: conversation.channelName ?? null,
2658
- title: conversation.title ?? null,
2659
- createdAt: dateFromMs(conversation.createdAtMs),
2660
- lastActivityAt: dateFromMs(conversation.lastActivityAtMs),
2661
- updatedAt: dateFromMs(conversation.updatedAtMs),
2662
- executionUpdatedAt: conversation.execution.updatedAtMs === void 0 ? null : dateFromMs(conversation.execution.updatedAtMs),
2663
- executionStatus: conversation.execution.status,
2664
- runId: conversation.execution.runId ?? null,
2665
- lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
2666
- lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs),
2667
- parentConversationId: conversation.parentConversationId ?? null,
2668
- kind: conversation.kind,
2669
- rootConversationId
2670
- }).onConflictDoUpdate({
2671
- target: juniorConversations.conversationId,
2672
- set: {
2673
- source: sql`coalesce(${juniorConversations.source}, excluded.source)`,
2674
- sessionSource: sql`coalesce(${juniorConversations.sessionSource}, excluded.source_json)`,
2675
- location: sql`coalesce(excluded.location_json, ${juniorConversations.location})`,
2676
- destinationId: sql`coalesce(excluded.destination_id, ${juniorConversations.destinationId})`,
2677
- actorIdentityId: sql`coalesce(${juniorConversations.actorIdentityId}, excluded.actor_identity_id)`,
2678
- creatorIdentityId: sql`coalesce(excluded.creator_identity_id, ${juniorConversations.creatorIdentityId})`,
2679
- credentialSubjectIdentityId: sql`coalesce(excluded.credential_subject_identity_id, ${juniorConversations.credentialSubjectIdentityId})`,
2680
- channelName: sql`coalesce(excluded.channel_name, ${juniorConversations.channelName})`,
2681
- title: sql`coalesce(excluded.title, ${juniorConversations.title})`,
2682
- createdAt: sql`least(${juniorConversations.createdAt}, excluded.created_at)`,
2683
- lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
2684
- updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
2685
- executionUpdatedAt: sql`case when ${incomingExecutionIsFresh} then excluded.execution_updated_at else ${juniorConversations.executionUpdatedAt} end`,
2686
- executionStatus: sql`case when ${incomingExecutionIsFresh} then excluded.execution_status else ${juniorConversations.executionStatus} end`,
2687
- runId: sql`case when ${incomingExecutionIsFresh} then excluded.run_id else ${juniorConversations.runId} end`,
2688
- lastCheckpointAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_checkpoint_at, ${juniorConversations.lastCheckpointAt}) else ${juniorConversations.lastCheckpointAt} end`,
2689
- lastEnqueuedAt: sql`case when ${incomingExecutionIsFresh} then coalesce(excluded.last_enqueued_at, ${juniorConversations.lastEnqueuedAt}) else ${juniorConversations.lastEnqueuedAt} end`,
2690
- rootConversationId: sql`coalesce(${juniorConversations.rootConversationId}, excluded.root_conversation_id)`,
2691
- kind: sql`coalesce(${juniorConversations.kind}, excluded.kind)`,
2692
- detailVersion: nextDetailVersion
2693
- }
2694
- }).returning({
2695
- actorIdentityId: juniorConversations.actorIdentityId,
2696
- parentConversationId: juniorConversations.parentConversationId,
2697
- rootConversationId: juniorConversations.rootConversationId
2698
- }))[0];
2699
- if (!row?.rootConversationId) throw new Error("Conversation parent is missing its persisted root");
2700
- if (row.parentConversationId !== (conversation.parentConversationId ?? null)) throw new Error(`Conversation parent changed for ${conversation.conversationId}`);
2701
- if (row.actorIdentityId && row.parentConversationId === null) await recordConversationParticipant(this.executor, {
2702
- actorIdentityId: row.actorIdentityId,
2703
- conversationId: conversation.conversationId,
2704
- atMs: conversation.lastActivityAtMs
2705
- });
2706
- }
2707
- async upsertDestination(destination, nowMs) {
2708
- if (!destination) return;
2709
- const visibilityUpdate = destination.refreshVisibility ? sql`excluded.visibility` : juniorDestinations.visibility;
2710
- return (await this.executor.db().insert(juniorDestinations).values({
2711
- id: randomUUID(),
2712
- provider: destination.provider,
2713
- providerTenantId: tenantId(destination.providerTenantId),
2714
- providerDestinationId: destination.providerDestinationId,
2715
- kind: destination.kind,
2716
- parentDestinationId: null,
2717
- displayName: destination.displayName ?? null,
2718
- visibility: destination.visibility,
2719
- metadata: destination.metadata ?? null,
2720
- createdAt: dateFromMs(nowMs),
2721
- updatedAt: dateFromMs(nowMs)
2722
- }).onConflictDoUpdate({
2723
- target: [
2724
- juniorDestinations.provider,
2725
- juniorDestinations.providerTenantId,
2726
- juniorDestinations.providerDestinationId
2727
- ],
2728
- set: {
2729
- kind: sql`excluded.kind`,
2730
- displayName: sql`coalesce(excluded.display_name, ${juniorDestinations.displayName})`,
2731
- visibility: visibilityUpdate,
2732
- metadata: sql`coalesce(excluded.metadata_json, ${juniorDestinations.metadata})`,
2733
- updatedAt: sql`excluded.updated_at`
2734
- }
2735
- }).returning({ id: juniorDestinations.id }))[0]?.id;
2736
- }
2737
- };
2738
- /** Create a SQL-backed conversation store. */
2739
- function createSqlStore(executor) {
2740
- return new SqlStore(executor);
2741
- }
2742
- // src/chat/conversations/sql/last-message.ts
2743
- /**
2744
- * Return a query for the newest event of one type in the outer Conversation
2745
- * that matches the filter. It walks the message role or user message time
2746
- * index from the newest event. The user message index has only matching
2747
- * entries, so that read stops at the first one.
2748
- */
2749
- function latestEventAtQuery(db, type, filter) {
2750
- return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1);
2751
- }
2752
- /**
2753
- * Return queries for the latest user instruction and the latest true user
2754
- * Message of the outer Conversation.
2755
- */
2756
- function userMessageQueries(db) {
2757
- const payload = juniorConversationEvents.payload;
2758
- const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
2759
- return {
2760
- instruction: latestEventAtQuery(db, "user_message", isUserInstruction(payload)),
2761
- message: latestEventAtQuery(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`)
2762
- };
2763
- }
2764
- /**
2765
- * Return SQL for when the outer Conversation last got a Message that a
2766
- * reader would notice: a true user message or a Junior reply that the
2767
- * transcript shows. Tools, status, Events, quiet replies, and progress acks
2768
- * (`meta.progress`) do not count. It is null when there is no such Message.
2769
- */
2770
- function lastMessageAtSql(db) {
2771
- const payload = juniorConversationEvents.payload;
2772
- const { instruction, message } = userMessageQueries(db);
2773
- const reply = latestEventAtQuery(db, "message", sql`${payload}->>'role' = 'assistant' and (${payload}->'meta'->>'quiet') is distinct from 'true' and (${payload}->'meta'->>'progress') is distinct from 'true'`);
2774
- return sql`greatest((${instruction}), (${message}), (${reply}))`.mapWith(juniorConversations.lastMessageAt);
2775
- }
2776
- /**
2777
- * Store `lastMessageAtSql` on the Conversation row. Event appends call this
2778
- * in their transaction when they add a Message, so feed reads take the time
2779
- * from the row.
2780
- */
2781
- async function refreshLastMessageAt(executor, conversationId) {
2782
- const db = executor.db();
2783
- await db.update(juniorConversations).set({ lastMessageAt: lastMessageAtSql(db) }).where(eq(juniorConversations.conversationId, conversationId));
2784
- }
2785
- // src/chat/conversations/sql/event-actor.ts
2786
- const authorMetaSchema = z.object({ author: z.object({
2787
- email: z.string().optional().catch(void 0),
2788
- fullName: z.string().optional().catch(void 0),
2789
- isBot: z.boolean().optional().catch(void 0),
2790
- userId: z.string().optional().catch(void 0),
2791
- userName: z.string().optional().catch(void 0)
2792
- }) });
2793
- function readAuthor(meta) {
2794
- return authorMetaSchema.safeParse(meta).data?.author ?? {};
2795
- }
2796
- /** Read the Slack workspace that owns a conversation, when it has one. */
2797
- async function loadConversationSlackTenantId(executor, conversationId) {
2798
- return (await loadConversationSlackTenantIds(executor, [conversationId])).get(conversationId);
2799
- }
2800
- /** Read the Slack workspace that owns each conversation, with one query. */
2801
- async function loadConversationSlackTenantIds(executor, conversationIds) {
2802
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
2803
- const rows = await executor.db().select({
2804
- conversationId: juniorConversations.conversationId,
2805
- providerTenantId: juniorDestinations.providerTenantId,
2806
- sessionSource: juniorConversations.sessionSource
2807
- }).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(inArray(juniorConversations.conversationId, [...conversationIds]));
2808
- const tenants = /* @__PURE__ */ new Map();
2809
- for (const row of rows) {
2810
- const tenantId = conversationSlackTenantId(row);
2811
- if (tenantId) tenants.set(row.conversationId, tenantId);
2812
- }
2813
- return tenants;
2814
- }
2815
- /**
2816
- * Return the Slack workspace that owns a conversation, from its Destination
2817
- * tenant or its stored Slack session source.
2818
- */
2819
- function conversationSlackTenantId(row) {
2820
- const sessionSource = parseSessionSource(row.sessionSource);
2821
- return row.providerTenantId?.trim() || (sessionSource?.kind === "slack" ? sessionSource.teamId : void 0);
2822
- }
2823
- async function findIdentityIdByProviderSubject(executor, args) {
2824
- return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerSubjectId, args.providerSubjectId), args.providerTenantId === void 0 ? void 0 : eq(juniorIdentities.providerTenantId, args.providerTenantId))).limit(1))[0]?.id;
2825
- }
2826
- async function findJuniorIdentityIdByEmail(executor, email) {
2827
- const normalized = email.trim().toLowerCase();
2828
- if (!normalized) return void 0;
2829
- return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, "junior"), eq(juniorIdentities.kind, "user"), or(eq(juniorIdentities.providerSubjectId, normalized), and(eq(juniorIdentities.emailNormalized, normalized), eq(juniorIdentities.emailVerified, true))))).limit(1))[0]?.id;
2830
- }
2831
- /**
2832
- * Resolve a legacy dashboard:<hash> author against junior identities keyed by
2833
- * email. Web Actors stored dashboard:${sha256(email).slice(0,24)} before they
2834
- * used the User id. This read-only fallback serves only those old events.
2835
- *
2836
- * TODO(dcramer): Delete with the guess in resolveEventActorIdentityId, after
2837
- * every stored user Message event has its author Identity.
2838
- */
2839
- async function findJuniorIdentityIdByDashboardAuthorId(executor, dashboardAuthorId) {
2840
- if (!dashboardAuthorId.startsWith("dashboard:")) return;
2841
- return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, "junior"), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.emailVerified, true), sql`${juniorIdentities.emailNormalized} is not null`, sql`concat(
2842
- 'dashboard:',
2843
- left(encode(digest(${juniorIdentities.emailNormalized}, 'sha256'), 'hex'), 24)
2844
- ) = ${dashboardAuthorId}`)).limit(1))[0]?.id;
2845
- }
2846
- /**
2847
- * Resolve the durable actor identity for one event payload.
2848
- * Ingress sets `authorIdentityId` on new user Messages. Legacy writes without
2849
- * it still guess the author from its data, and a new Message logs the guess.
2850
- */
2851
- async function resolveEventActorIdentityId(executor, args) {
2852
- const data = args.data;
2853
- if (data.type !== "message" && data.type !== "message_updated") return;
2854
- if (typeof data.authorIdentityId === "string" && data.authorIdentityId) return data.authorIdentityId;
2855
- if (data.role !== "user") return;
2856
- if (data.type === "message") logWarn("conversation.message.author_identity.missing", { "app.message.id": data.messageId });
2857
- const author = readAuthor(data.meta);
2858
- if (author.isBot === true) return;
2859
- const userId = parseActorUserId(author.userId);
2860
- if (!userId) return;
2861
- if (isSlackUserId(userId)) {
2862
- const tenantId = await loadConversationSlackTenantId(executor, args.conversationId);
2863
- if (!tenantId) return await findIdentityIdByProviderSubject(executor, {
2864
- provider: "slack",
2865
- providerSubjectId: userId
2866
- });
2867
- return await resolveActorIdentityId(executor, {
2868
- platform: "slack",
2869
- teamId: tenantId,
2870
- userId,
2871
- ...author.email ? { email: author.email } : void 0,
2872
- ...author.fullName ? { fullName: author.fullName } : void 0,
2873
- ...author.userName ? { userName: author.userName } : void 0
2874
- }, args.nowMs);
2875
- }
2876
- const email = typeof author.email === "string" && author.email.includes("@") ? author.email : userId.includes("@") ? userId : void 0;
2877
- if (email) return await resolveActorIdentityId(executor, {
2878
- platform: "web",
2879
- userId,
2880
- email,
2881
- ...author.fullName ? { fullName: author.fullName } : void 0
2882
- }, args.nowMs);
2883
- if (userId.startsWith("dashboard:")) return findJuniorIdentityIdByDashboardAuthorId(executor, userId);
2884
- return findJuniorIdentityIdByEmail(executor, userId);
2885
- }
2886
- /** Drop payload-only authorIdentityId after lifting it onto the event column. */
2887
- function stripPayloadAuthorIdentityId(data) {
2888
- if (data.type !== "message" && data.type !== "message_updated" || data.authorIdentityId === void 0) return data;
2889
- const { authorIdentityId: _authorIdentityId, ...rest } = data;
2890
- return rest;
2891
- }
2892
- // src/db/postgres-json.ts
2893
- /**
2894
- * Replace actual NUL characters that PostgreSQL cannot store in JSONB.
2895
- * Literal `\\u0000` text is preserved because it contains no NUL character.
2896
- */
2897
- function sanitizePostgresJson(value) {
2898
- if (typeof value === "string") return value.replaceAll("\0", " ");
2899
- if (Array.isArray(value)) return value.map((item) => sanitizePostgresJson(item));
2900
- if (value === null || typeof value !== "object") return value;
2901
- const prototype = Object.getPrototypeOf(value);
2902
- if (prototype !== Object.prototype && prototype !== null) return value;
2903
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
2904
- }
2905
- // src/chat/conversations/sql/conversation-tree.ts
2906
- /**
2907
- * Read every Conversation in the trees of the given roots. Every descendant
2908
- * shares `root_conversation_id`, so one indexed read covers any depth.
2909
- */
2910
- async function readConversationTrees(db, rootConversationIds) {
2911
- if (rootConversationIds.length === 0) return /* @__PURE__ */ new Map();
2912
- const rows = await db.select({
2913
- archivedAt: juniorConversations.archivedAt,
2914
- conversationId: juniorConversations.conversationId,
2915
- kind: juniorConversations.kind,
2916
- parentConversationId: juniorConversations.parentConversationId,
2917
- rootConversationId: juniorConversations.rootConversationId
2918
- }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
2919
- return new Map(rows.map((row) => [row.conversationId, {
2920
- archivedAt: row.archivedAt,
2921
- conversationId: row.conversationId,
2922
- kind: conversationKindFromRow(row),
2923
- ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
2924
- ...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0
2925
- }]));
2926
- }
2927
- /** List the ancestors of one Conversation, nearest first, root last. */
2928
- function conversationAncestors(tree, conversationId) {
2929
- const ancestors = [];
2930
- const seen = /* @__PURE__ */ new Set([conversationId]);
2931
- let parentId = tree.get(conversationId)?.parentConversationId;
2932
- while (parentId && !seen.has(parentId)) {
2933
- const parent = tree.get(parentId);
2934
- if (!parent) break;
2935
- ancestors.push(parent);
2936
- seen.add(parentId);
2937
- parentId = parent.parentConversationId;
2938
- }
2939
- return ancestors;
2940
- }
2941
- /** List every descendant of one Conversation, at any depth. */
2942
- function conversationDescendants(tree, conversationId) {
2943
- const childrenByParent = /* @__PURE__ */ new Map();
2944
- for (const node of tree.values()) {
2945
- if (!node.parentConversationId) continue;
2946
- const siblings = childrenByParent.get(node.parentConversationId) ?? [];
2947
- siblings.push(node);
2948
- childrenByParent.set(node.parentConversationId, siblings);
2949
- }
2950
- const descendants = [];
2951
- const seen = /* @__PURE__ */ new Set([conversationId]);
2952
- const pending = [conversationId];
2953
- for (let id = pending.pop(); id !== void 0; id = pending.pop()) for (const child of childrenByParent.get(id) ?? []) {
2954
- if (seen.has(child.conversationId)) continue;
2955
- seen.add(child.conversationId);
2956
- descendants.push(child);
2957
- pending.push(child.conversationId);
2958
- }
2959
- return descendants;
2960
- }
2961
- /**
2962
- * Set or clear the shared archive and count the rows written. This is the
2963
- * only write of `archived_at`. `conversations` names the rows by id or by a
2964
- * condition. `guard` is a condition that each row must still meet when it is
2965
- * written, so a stale read loses to a newer change.
2966
- */
2967
- async function setArchivedAt(db, conversations, archivedAt, guard) {
2968
- if (!(conversations instanceof SQL) && conversations.length === 0) return 0;
2969
- return (await db.update(juniorConversations).set({
2970
- archivedAt,
2971
- detailVersion: nextDetailVersion
2972
- }).where(and(conversations instanceof SQL ? conversations : inArray(juniorConversations.conversationId, [...conversations]), guard)).returning({ conversationId: juniorConversations.conversationId })).length;
2973
- }
2974
- /**
2975
- * Restore one archived Conversation and its archived ancestors, so it shows
2976
- * again. Its descendants keep their archive.
2977
- */
2978
- async function restoreArchivedPath(db, conversationId) {
2979
- const [row] = await db.select({
2980
- archivedAt: juniorConversations.archivedAt,
2981
- parentConversationId: juniorConversations.parentConversationId,
2982
- rootConversationId: juniorConversations.rootConversationId
2983
- }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
2984
- if (!row) return;
2985
- if (!row.parentConversationId || !row.rootConversationId) {
2986
- if (row.archivedAt) await setArchivedAt(db, [conversationId], null);
2987
- return;
2988
- }
2989
- const tree = await readConversationTrees(db, [row.rootConversationId]);
2990
- const node = tree.get(conversationId);
2991
- if (!node) return;
2992
- await setArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.archivedAt).map((entry) => entry.conversationId), null);
2993
- }
2994
- // src/chat/conversations/sql/event-lock.ts
2995
- /** Serialize event sequence allocation with other conversation writes. */
2996
- async function withConversationEventLock(executor, conversationId, callback) {
2997
- return executor.withLock(`junior_conversation:${conversationId}`, callback);
2998
- }
2999
- // src/chat/conversations/message-links.ts
3000
- /**
3001
- * Web link matches in message text. Slack wraps links as <url|label>, and
3002
- * Markdown as (url), so a match stops at those delimiters. Trailing
3003
- * punctuation is dropped. Readers parse a link before they show it.
3004
- *
3005
- * Migration `0112_attachment_url_fill` runs these patterns in Postgres to
3006
- * fill links for older messages, so they use only syntax that JavaScript and
3007
- * Postgres read the same way. The whitespace set is the one that JavaScript
3008
- * `\s` matches, spelled out, because Postgres `\s` depends on the locale.
3009
- */
3010
- const MESSAGE_URL_PATTERN = String.raw`https?://[^\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff<>|"'\u0060]+`;
3011
- const TRAILING_PUNCTUATION_PATTERN = String.raw`[.,;:!?)\]}*_~]+$`;
3012
- /**
3013
- * Longest link, in UTF-8 bytes, that a message stores. The unique index on
3014
- * `(conversation_id, url)` holds the whole link, and a Postgres btree entry
3015
- * cannot pass about 2.7 kB. Migration `0112_attachment_url_fill` uses the
3016
- * same limit.
3017
- */
3018
- const MAX_LINK_BYTES = 2048;
3019
- const messageUrlPattern = new RegExp(MESSAGE_URL_PATTERN, "g");
3020
- const trailingPunctuation = new RegExp(TRAILING_PUNCTUATION_PATTERN);
3021
- /**
3022
- * Id of a Conversation's `url` Attachment. A repeat of the link in the
3023
- * Conversation gets the same id. A link never holds a space, so the space
3024
- * keeps the two parts apart. Migration `0112_attachment_url_fill` computes
3025
- * the same id in SQL.
3026
- */
3027
- function urlAttachmentId(conversationId, url) {
3028
- return createHash("sha256").update(`${conversationId} ${url}`).digest("hex");
3029
- }
3030
- /**
3031
- * The links of one stored event payload, first match of each link only. Only
3032
- * messages count, and a channel message that did not mention Junior stays
3033
- * out, as in the transcript.
3034
- */
3035
- function messageLinks(event) {
3036
- const { meta, text } = event.payload;
3037
- if (event.type !== "message" || typeof text !== "string") return [];
3038
- const mention = meta !== null && typeof meta === "object" && !Array.isArray(meta) && "explicitMention" in meta ? meta.explicitMention : void 0;
3039
- if (mention === false || mention === "false") return [];
3040
- const links = /* @__PURE__ */ new Map();
3041
- let position = 0;
3042
- for (const match of text.matchAll(messageUrlPattern)) {
3043
- position += 1;
3044
- const url = match[0].replace(trailingPunctuation, "");
3045
- if (links.has(url) || Buffer.byteLength(url) > MAX_LINK_BYTES) continue;
3046
- links.set(url, {
3047
- conversationId: event.conversationId,
3048
- createdAt: event.createdAt,
3049
- position,
3050
- seq: event.seq,
3051
- url
3052
- });
3053
- }
3054
- return [...links.values()];
3055
- }
3056
- /**
3057
- * The links that a batch of new event rows writes. Links keep the seq of the
3058
- * first save of their message, like the transcript, and an edit replaces
3059
- * them. `storedMessageSeqs` maps the Message ids that the batch edits to
3060
- * their stored seqs; `replacedSeqs` names the stored seqs whose links go.
3061
- */
3062
- function batchMessageLinks(rows, storedMessageSeqs) {
3063
- const seqById = new Map(storedMessageSeqs);
3064
- const linksBySeq = /* @__PURE__ */ new Map();
3065
- const replacedSeqs = /* @__PURE__ */ new Set();
3066
- for (const row of rows) {
3067
- const { messageId } = row.payload;
3068
- if (row.type === "message") {
3069
- if (typeof messageId === "string" && !seqById.has(messageId)) seqById.set(messageId, row.seq);
3070
- linksBySeq.set(row.seq, messageLinks(row));
3071
- continue;
3072
- }
3073
- if (row.type !== "message_updated" || typeof messageId !== "string") continue;
3074
- const seq = seqById.get(messageId);
3075
- if (seq === void 0) continue;
3076
- if (storedMessageSeqs.get(messageId) === seq) replacedSeqs.add(seq);
3077
- linksBySeq.set(seq, messageLinks({
3078
- ...row,
3079
- seq,
3080
- type: "message"
3081
- }));
3082
- }
3083
- return {
3084
- links: [...linksBySeq.values()].flat(),
3085
- replacedSeqs: [...replacedSeqs]
3086
- };
3087
- }
3088
- // src/chat/conversations/sql/message-links.ts
3089
- /**
3090
- * The stored seqs of the Messages that new `message_updated` rows edit, so
3091
- * their links can be replaced. An edit of a Message that is not stored yet
3092
- * finds no seq here.
3093
- */
3094
- async function readEditedMessageSeqs(executor, conversationId, rows) {
3095
- const messageIds = rows.flatMap(({ payload, type }) => type === "message_updated" && typeof payload["messageId"] === "string" ? [payload["messageId"]] : []);
3096
- if (messageIds.length === 0) return /* @__PURE__ */ new Map();
3097
- const e = juniorConversationEvents;
3098
- const messageId = sql`${e.payload}->>'messageId'`;
3099
- const stored = await executor.db().select({
3100
- messageId,
3101
- seq: e.seq
3102
- }).from(e).where(and(eq(e.conversationId, conversationId), eq(e.type, "message"), inArray(messageId, messageIds))).orderBy(desc(e.seq));
3103
- return new Map(stored.map((row) => [row.messageId, row.seq]));
3104
- }
3105
- /**
3106
- * Store the web links of new message events as `url` Attachments of their
3107
- * Conversation, and where each message uses them. Call it in the transaction
3108
- * that inserts the events, so a message is never stored without its links.
3109
- */
3110
- async function writeMessageLinks(executor, conversationId, rows) {
3111
- const { links, replacedSeqs } = batchMessageLinks(rows, await readEditedMessageSeqs(executor, conversationId, rows));
3112
- const db = executor.db();
3113
- if (replacedSeqs.length > 0) await db.delete(juniorMessageAttachments).where(and(eq(juniorMessageAttachments.conversationId, conversationId), inArray(juniorMessageAttachments.seq, replacedSeqs)));
3114
- await insertLinks(executor, conversationId, links);
3115
- }
3116
- async function insertLinks(executor, conversationId, links) {
3117
- if (links.length === 0) return;
3118
- const db = executor.db();
3119
- const withIds = links.map((link) => ({
3120
- ...link,
3121
- attachmentId: urlAttachmentId(conversationId, link.url)
3122
- }));
3123
- const attachments = new Map(withIds.map((link) => [link.attachmentId, {
3124
- conversationId,
3125
- createdAt: link.createdAt,
3126
- id: link.attachmentId,
3127
- kind: "url",
3128
- url: link.url
3129
- }]));
3130
- await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorAttachments).values([...attachments.values()]).onConflictDoNothing({ target: juniorAttachments.id });
3131
- await db.insert(juniorMessageAttachments).values(withIds.map(({ attachmentId, position, seq }) => ({
3132
- attachmentId,
3133
- conversationId,
3134
- position,
3135
- seq
3136
- }))).onConflictDoNothing();
3137
- }
3138
- /**
3139
- * Copy the links of the copied messages into a fork. Copies keep their seq,
3140
- * and the fork gets its own `url` Attachments.
3141
- */
3142
- async function copyMessageLinks(executor, args) {
3143
- if (args.seqs.length === 0) return;
3144
- const m = juniorMessageAttachments;
3145
- const a = juniorAttachments;
3146
- const links = await executor.db().select({
3147
- createdAt: a.createdAt,
3148
- position: m.position,
3149
- seq: m.seq,
3150
- url: a.url
3151
- }).from(m).innerJoin(a, eq(a.id, m.attachmentId)).where(and(eq(m.conversationId, args.sourceConversationId), inArray(m.seq, [...args.seqs]), isNull(a.deleteRequestedAt)));
3152
- await insertLinks(executor, args.conversationId, links.flatMap(({ url, ...link }) => url === null ? [] : [{
3153
- ...link,
3154
- url
3155
- }]));
3156
- }
3157
- /** Delete where purged messages use Attachments, with the messages. */
3158
- async function deleteMessageLinks(executor, conversationIds) {
3159
- await executor.db().delete(juniorMessageAttachments).where(inArray(juniorMessageAttachments.conversationId, [...conversationIds]));
3160
- }
3161
- // src/chat/conversations/sql/history.ts
3162
- const messageHistoryEventTypes = [
3163
- "message",
3164
- "message_updated",
3165
- "message_handled"
3166
- ];
3167
- const HUMAN_INSTRUCTION_PLATFORMS = /* @__PURE__ */ new Set([
3168
- "slack",
3169
- "local",
3170
- "web"
3171
- ]);
3172
- /**
3173
- * True when a Turn input message is addressed to Junior, which subscribes its
3174
- * author again (contract: `api/conversations/subscription.ts`). A Slack
3175
- * message in a subscribed thread that does not mention Junior is marked
3176
- * `explicitMention: false`. Other Sources, such as the dashboard and Slack
3177
- * mentions and DMs, always address Junior.
3178
- */
3179
- function eventAddressesJunior(data) {
3180
- return data.type === "message" && data.meta?.["explicitMention"] !== false;
3181
- }
3182
- /**
3183
- * Whether one event should restore an archived conversation to the feed.
3184
- *
3185
- * Archive hides finished noise until a human comes back. Events,
3186
- * turn lifecycle, compaction, and other system writes may still refresh
3187
- * activity clocks, but they must not unarchive on their own.
3188
- */
3189
- function eventUnarchivesConversation(data) {
3190
- if (data.type === "user_message") {
3191
- const provenance = data.provenance;
3192
- if (provenance.authority !== "instruction") return false;
3193
- const platform = provenance.actor?.platform;
3194
- return platform === void 0 || HUMAN_INSTRUCTION_PLATFORMS.has(platform);
3195
- }
3196
- if (data.type !== "message") return false;
3197
- if (data.role !== "user") return false;
3198
- const meta = data.meta;
3199
- if (!meta) return true;
3200
- if (typeof meta["eventType"] === "string" && meta["eventType"].length > 0) return false;
3201
- const author = meta["author"];
3202
- if (author && typeof author === "object" && !Array.isArray(author) && author.isBot === true) return false;
3203
- return true;
3204
- }
3205
- /** Split validated event data into column-lifted and JSON payload fields. */
3206
- function insertFromEvent(conversationId, seq, historyVersion, event, actorIdentityId) {
3207
- const stripped = stripPayloadAuthorIdentityId(event.data);
3208
- const data = conversationEventDataSchema.parse(stripped);
3209
- const encoded = encodeHistoryPayload(data);
3210
- return {
3211
- conversationId,
3212
- seq,
3213
- historyVersion,
3214
- schemaVersion: encoded.schemaVersion,
3215
- idempotencyKey: event.idempotencyKey ?? null,
3216
- type: data.type,
3217
- payload: sanitizePostgresJson(encoded.payload),
3218
- actorIdentityId: actorIdentityId ?? null,
3219
- createdAt: new Date(event.createdAtMs)
3220
- };
3221
- }
3222
- /** Parse one physical event row into the storage-compatible domain envelope. */
3223
- function eventFromRow(row) {
3224
- const payload = row.actorIdentityId && typeof row.payload === "object" && row.payload !== null && !Array.isArray(row.payload) && (row.type === "message" || row.type === "message_updated") && !("authorIdentityId" in row.payload) ? {
3225
- ...row.payload,
3226
- authorIdentityId: row.actorIdentityId
3227
- } : row.payload;
3228
- return decodeStoredConversationEvent({
3229
- schemaVersion: row.schemaVersion,
3230
- seq: row.seq,
3231
- historyVersion: row.historyVersion,
3232
- ...row.idempotencyKey ? { idempotencyKey: row.idempotencyKey } : void 0,
3233
- createdAtMs: row.createdAt.getTime(),
3234
- type: row.type,
3235
- payload
3236
- });
3237
- }
3238
- /** Decode the summary row that defines a readable message-history suffix. */
3239
- function messagesSummarizedEventFromRow(row) {
3240
- const event = eventFromRow(row);
3241
- if (event.schemaVersion !== 1 || event.data.type !== "messages_summarized") throw new Error("Message compaction row did not decode as messages_summarized");
3242
- return {
3243
- ...event,
3244
- schemaVersion: 1,
3245
- data: event.data
3246
- };
3247
- }
3248
- var SqlConversationEventStore = class {
3249
- executor;
3250
- constructor(executor) {
3251
- this.executor = executor;
3252
- }
3253
- async append(conversationId, events, options = {}) {
3254
- const parsed = events.map((event) => newConversationEventSchema.parse(event));
3255
- if (parsed.length === 0) return [];
3256
- return withConversationEventLock(this.executor, conversationId, async () => {
3257
- const existingKeys = parsed.map((event) => event.idempotencyKey).filter((key) => key !== void 0);
3258
- const persistedKeys = existingKeys.length === 0 ? /* @__PURE__ */ new Set() : new Set((await this.executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, existingKeys)))).flatMap((row) => row.key ? [row.key] : []));
3259
- const acceptedKeys = new Set(persistedKeys);
3260
- const pending = parsed.filter((event) => {
3261
- if (event.idempotencyKey === void 0) return true;
3262
- if (acceptedKeys.has(event.idempotencyKey)) return false;
3263
- acceptedKeys.add(event.idempotencyKey);
3264
- return true;
3265
- });
3266
- if (pending.length === 0) return [];
3267
- const newestCreatedAtMs = Math.max(...pending.map((event) => event.createdAtMs));
3268
- await ensureConversationRow(this.executor, conversationId, newestCreatedAtMs, options);
3269
- const cursor = await this.readCursor(conversationId);
3270
- const historyVersion = cursor.maxHistoryVersion ?? 0;
3271
- let seq = cursor.nextSeq;
3272
- const rows = [];
3273
- for (const event of pending) {
3274
- const actorIdentityId = await resolveEventActorIdentityId(this.executor, {
3275
- conversationId,
3276
- data: event.data,
3277
- nowMs: event.createdAtMs
3278
- });
3279
- rows.push(insertFromEvent(conversationId, seq++, historyVersion, event, actorIdentityId));
3280
- }
3281
- const db = this.executor.db();
3282
- await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(rows);
3283
- await writeMessageLinks(this.executor, conversationId, rows);
3284
- if (pending.some((event) => event.data.type === "message" || event.data.type === "user_message")) await refreshLastMessageAt(this.executor, conversationId);
3285
- for (const event of pending) if (event.data.type === "turn_started") await this.recordTurnInputParticipants(conversationId, event.data.inputMessageIds);
3286
- return rows.map((row) => ({
3287
- seq: row.seq,
3288
- historyVersion: row.historyVersion
3289
- }));
3290
- });
3291
- }
3292
- /**
3293
- * Add the authors of Turn input messages to the conversation.
3294
- * Only people who start a Turn join it. Thread context, such as backfilled
3295
- * or skipped messages, and Event Messages keep their author without
3296
- * membership.
3297
- */
3298
- async recordTurnInputParticipants(conversationId, inputMessageIds) {
3299
- const rows = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), inArray(sql`${juniorConversationEvents.payload}->>'messageId'`, [...inputMessageIds])));
3300
- const rootArchived = await rootConversationIsArchived(this.executor, conversationId);
3301
- let restores = false;
3302
- for (const row of rows) {
3303
- const { data } = eventFromRow(row);
3304
- if (!row.actorIdentityId || data.type !== "message") continue;
3305
- if (data.meta?.["eventType"]) continue;
3306
- const unarchives = eventUnarchivesConversation(data);
3307
- const isPerson = await recordConversationParticipant(this.executor, {
3308
- actorIdentityId: row.actorIdentityId,
3309
- conversationId,
3310
- atMs: row.createdAt.getTime(),
3311
- resubscribe: eventAddressesJunior(data) || rootArchived && unarchives
3312
- });
3313
- restores ||= isPerson && unarchives;
3314
- }
3315
- if (restores) await restoreArchivedPath(this.executor.db(), conversationId);
3316
- }
3317
- async replaceHistory(conversationId, replacement, options = {}) {
3318
- const parsed = historyReplacementSchema.parse(replacement);
3319
- return withConversationEventLock(this.executor, conversationId, async () => {
3320
- const cursor = await this.readCursor(conversationId);
3321
- const currentHistoryVersion = cursor.maxHistoryVersion ?? 0;
3322
- if (options.expectedHistoryVersion !== void 0 && options.expectedHistoryVersion !== currentHistoryVersion) return {
3323
- status: "conflict",
3324
- historyVersion: currentHistoryVersion
3325
- };
3326
- await ensureConversationRow(this.executor, conversationId, Date.now());
3327
- const historyVersion = currentHistoryVersion + 1;
3328
- const db = this.executor.db();
3329
- await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(insertFromEvent(conversationId, cursor.nextSeq, historyVersion, parsed));
3330
- return {
3331
- status: "replaced",
3332
- historyVersion,
3333
- seq: cursor.nextSeq
3334
- };
3335
- });
3336
- }
3337
- async loadCurrentHistoryVersion(conversationId) {
3338
- return (await this.readCursor(conversationId)).maxHistoryVersion ?? 0;
3339
- }
3340
- async loadCurrentHistory(conversationId) {
3341
- const db = this.executor.db();
3342
- const currentHistoryVersion = db.select({ historyVersion: sql`max(${juniorConversationEvents.historyVersion})` }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
3343
- return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersion))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
3344
- }
3345
- async loadByIdempotencyKey(conversationId, idempotencyKey) {
3346
- const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.idempotencyKey, idempotencyKey))).limit(1);
3347
- return row ? eventFromRow(row) : void 0;
3348
- }
3349
- async loadEventsAfter(conversationId, afterSeq) {
3350
- return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), gt(juniorConversationEvents.seq, afterSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
3351
- }
3352
- async loadHistoryContaining(conversationId, seq, throughSeq) {
3353
- const db = this.executor.db();
3354
- const boundaryHistoryVersion = db.select({ historyVersion: juniorConversationEvents.historyVersion }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, seq)));
3355
- const rows = await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, boundaryHistoryVersion), throughSeq === void 0 ? void 0 : lte(juniorConversationEvents.seq, Math.max(seq, throughSeq)))).orderBy(asc(juniorConversationEvents.seq));
3356
- if (rows.length === 0) return void 0;
3357
- return rows.filter((row) => throughSeq === void 0 || row.seq <= throughSeq).map(eventFromRow);
3358
- }
3359
- async loadLatestStructuredEvent(conversationId, namespace, name) {
3360
- const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${namespace}`, sql`${juniorConversationEvents.payload}->>'name' = ${name}`)).orderBy(desc(juniorConversationEvents.seq)).limit(1);
3361
- return row ? eventFromRow(row) : void 0;
3362
- }
3363
- async loadLatestInstruction(conversationId) {
3364
- const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "user_message"), sql`${juniorConversationEvents.payload}->'provenance'->>'authority' = 'instruction'`)).orderBy(desc(juniorConversationEvents.seq)).limit(1);
3365
- return row ? eventFromRow(row) : void 0;
3366
- }
3367
- async loadMessageHistory(conversationId) {
3368
- const [compactionRow] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "messages_summarized"))).orderBy(desc(juniorConversationEvents.seq)).limit(1);
3369
- const historyFromSeq = compactionRow ? messagesSummarizedEventFromRow(compactionRow).data.historyFromSeq : 0;
3370
- return {
3371
- events: (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.type, messageHistoryEventTypes), gte(juniorConversationEvents.seq, historyFromSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow),
3372
- historyFromSeq
3373
- };
3374
- }
3375
- async loadHistory(conversationId) {
3376
- return (await this.executor.db().select().from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId)).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
3377
- }
3378
- async loadEventsOfType(conversationId, type) {
3379
- return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
3380
- }
3381
- async loadCurrentEventsOfType(conversationId, type) {
3382
- const db = this.executor.db();
3383
- const currentHistoryVersion = db.select({ historyVersion: sql`max(${juniorConversationEvents.historyVersion})` }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
3384
- return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersion), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
3385
- }
3386
- async query(conversationId, query) {
3387
- if (query.limit < 1) throw new Error("Conversation event query limit must be at least 1");
3388
- if (query.afterSeq !== void 0 && query.beforeSeq !== void 0 && query.afterSeq >= query.beforeSeq) return {
3389
- events: [],
3390
- hasOlder: false,
3391
- hasNewer: false
3392
- };
3393
- const typeFilter = query.types && query.types.length > 0 ? inArray(juniorConversationEvents.type, [...query.types]) : void 0;
3394
- const bounds = and(eq(juniorConversationEvents.conversationId, conversationId), query.afterSeq === void 0 ? void 0 : gt(juniorConversationEvents.seq, query.afterSeq), query.beforeSeq === void 0 ? void 0 : lt(juniorConversationEvents.seq, query.beforeSeq), typeFilter);
3395
- const newestFirst = query.afterSeq === void 0;
3396
- const rows = await this.executor.db().select().from(juniorConversationEvents).where(bounds).orderBy(newestFirst ? desc(juniorConversationEvents.seq) : asc(juniorConversationEvents.seq)).limit(query.limit + 1);
3397
- const overflow = rows.length > query.limit;
3398
- const pageRows = overflow ? rows.slice(0, query.limit) : rows;
3399
- const events = (newestFirst ? [...pageRows].reverse() : pageRows).map(eventFromRow);
3400
- if (events.length === 0) return {
3401
- events,
3402
- hasOlder: false,
3403
- hasNewer: false
3404
- };
3405
- const firstSeq = events[0].seq;
3406
- const lastSeq = events[events.length - 1].seq;
3407
- return {
3408
- events,
3409
- hasOlder: newestFirst && overflow ? true : await this.hasMatchingEvent({
3410
- conversationId,
3411
- beforeSeq: firstSeq,
3412
- typeFilter
3413
- }),
3414
- hasNewer: !newestFirst && overflow ? true : await this.hasMatchingEvent({
3415
- conversationId,
3416
- afterSeq: lastSeq,
3417
- typeFilter
3418
- })
3419
- };
3420
- }
3421
- /** Return whether any matching event exists inside the exclusive seq window. */
3422
- async hasMatchingEvent(args) {
3423
- if (args.afterSeq !== void 0 && args.beforeSeq !== void 0 && args.afterSeq >= args.beforeSeq) return false;
3424
- const [row] = await this.executor.db().select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, args.conversationId), args.afterSeq === void 0 ? void 0 : gt(juniorConversationEvents.seq, args.afterSeq), args.beforeSeq === void 0 ? void 0 : lt(juniorConversationEvents.seq, args.beforeSeq), args.typeFilter)).limit(1);
3425
- return row !== void 0;
3426
- }
3427
- /** Read the next sequence and active model-history version. */
3428
- async readCursor(conversationId) {
3429
- const rows = await this.executor.db().select({
3430
- maxSeq: sql`max(${juniorConversationEvents.seq})`,
3431
- maxHistoryVersion: sql`max(${juniorConversationEvents.historyVersion})`
3432
- }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
3433
- const maxSeq = rows[0]?.maxSeq;
3434
- const maxHistoryVersion = rows[0]?.maxHistoryVersion;
3435
- return {
3436
- maxHistoryVersion: maxHistoryVersion === null || maxHistoryVersion === void 0 ? null : Number(maxHistoryVersion),
3437
- nextSeq: maxSeq === null || maxSeq === void 0 ? 0 : Number(maxSeq) + 1
3438
- };
3439
- }
3440
- };
3441
- /** Create a SQL-backed canonical conversation event store. */
3442
- function createSqlConversationEventStore(executor) {
3443
- return new SqlConversationEventStore(executor);
3444
- }
3445
- // src/chat/conversations/sql/annotation-filter.ts
3446
- function annotationKeyMatches(key) {
3447
- const annotation = key.toLowerCase();
3448
- return sql`(
3449
- lower(${juniorConversationAnnotations.key}) = ${annotation}
3450
- or starts_with(
3451
- lower(${juniorConversationAnnotations.key}),
3452
- ${`${annotation}#`}
3453
- )
3454
- )`;
3455
- }
3456
- /**
3457
- * Match Conversations that have an Annotation with `key`, or a nested child
3458
- * key that continues with `#`. Matching ignores case.
3459
- */
3460
- function hasAnnotationKey(conversationId, key) {
3461
- return sql`exists (
3462
- select 1
3463
- from ${juniorConversationAnnotations}
3464
- where ${and(eq(juniorConversationAnnotations.conversationId, conversationId), annotationKeyMatches(key))}
3465
- )`;
3466
- }
3467
- const ANNOTATED_ALIAS = "annotated_conversations";
3468
- /**
3469
- * Match root Conversations where any Conversation in the tree has an
3470
- * Annotation with `key`. Tools write the Annotation on the Conversation that
3471
- * ran them, which can be a child agent.
3472
- */
3473
- function treeHasAnnotationKey(rootConversationId, key) {
3474
- const annotated = alias(juniorConversations, ANNOTATED_ALIAS);
3475
- return sql`exists (
3476
- select 1
3477
- from ${juniorConversationAnnotations}
3478
- inner join ${juniorConversations} as ${sql.identifier(ANNOTATED_ALIAS)}
3479
- on ${annotated.conversationId} = ${juniorConversationAnnotations.conversationId}
3480
- where ${and(eq(annotated.rootConversationId, rootConversationId), annotationKeyMatches(key))}
3481
- )`;
3482
- }
3483
- // src/chat/conversations/sql/message-search.ts
3484
- const EXCERPT_WITHOUT_QUERY_CHARS = 240;
3485
- var SqlConversationMessageSearchStore = class {
3486
- executor;
3487
- constructor(executor) {
3488
- this.executor = executor;
3489
- }
3490
- async search(args) {
3491
- const db = this.executor.db();
3492
- const query = args.filters.query?.trim() || void 0;
3493
- const text = sql`${juniorConversationEvents.payload}->>'text'`;
3494
- const role = sql`${juniorConversationEvents.payload}->>'role'`;
3495
- const messageId = sql`${juniorConversationEvents.payload}->>'messageId'`;
3496
- const tsquery = query ? sql`websearch_to_tsquery('english', ${query})` : void 0;
3497
- const rank = tsquery ? sql`ts_rank_cd(to_tsvector('english', ${text}), ${tsquery})` : sql`1`;
3498
- const excerpt = tsquery ? sql`ts_headline('english', ${text}, ${tsquery}, 'MaxFragments=2, MinWords=8, MaxWords=40, FragmentDelimiter=" … ", StartSel=**, StopSel=**')` : sql`left(${text}, ${EXCERPT_WITHOUT_QUERY_CHARS})`;
3499
- const conditions = [
3500
- eq(juniorConversations.source, "slack"),
3501
- isNull(juniorConversations.parentConversationId),
3502
- isNull(juniorConversations.transcriptPurgedAt),
3503
- ne(juniorConversations.conversationId, args.currentConversationId),
3504
- eq(juniorDestinations.visibility, "public"),
3505
- eq(juniorConversationEvents.type, "message"),
3506
- sql`${role} in ('user', 'assistant')`
3507
- ];
3508
- if (tsquery) conditions.push(sql`to_tsvector('english', ${text}) @@ ${tsquery}`);
3509
- if (args.filters.channelId) conditions.push(eq(juniorDestinations.providerDestinationId, args.filters.channelId));
3510
- if (args.filters.afterMs !== void 0 && Number.isFinite(args.filters.afterMs)) conditions.push(gte(juniorConversations.lastActivityAt, new Date(args.filters.afterMs)));
3511
- if (args.filters.beforeMs !== void 0 && Number.isFinite(args.filters.beforeMs)) conditions.push(lt(juniorConversations.lastActivityAt, new Date(args.filters.beforeMs)));
3512
- if (args.filters.annotation) conditions.push(hasAnnotationKey(juniorConversations.conversationId, args.filters.annotation));
3513
- const bestPerConversation = db.selectDistinctOn([juniorConversations.conversationId], {
3514
- channelName: juniorDestinations.displayName,
3515
- conversationId: juniorConversations.conversationId,
3516
- excerpt: excerpt.as("excerpt"),
3517
- lastActivityAt: juniorConversations.lastActivityAt,
3518
- messageCreatedAt: juniorConversationEvents.createdAt,
3519
- messageId: messageId.as("message_id"),
3520
- providerDestinationId: juniorDestinations.providerDestinationId,
3521
- rank: rank.as("rank"),
3522
- role: role.as("role")
3523
- }).from(juniorConversationEvents).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorConversationEvents.conversationId)).innerJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(and(...conditions)).orderBy(juniorConversations.conversationId, desc(rank), desc(juniorConversationEvents.createdAt)).as("best_conversation_matches");
3524
- return (await db.select().from(bestPerConversation).orderBy(desc(bestPerConversation.rank), desc(bestPerConversation.lastActivityAt), desc(bestPerConversation.messageCreatedAt)).limit(args.limit)).map((row) => ({
3525
- conversationId: row.conversationId,
3526
- excerpt: row.excerpt,
3527
- messageCreatedAtMs: row.messageCreatedAt.getTime(),
3528
- messageId: row.messageId,
3529
- providerDestinationId: row.providerDestinationId,
3530
- role: row.role,
3531
- ...row.channelName ? { channelName: row.channelName } : void 0
3532
- }));
3533
- }
3534
- };
3535
- /** Create a SQL-backed public workspace message search store. */
3536
- function createSqlConversationMessageSearchStore(executor) {
3537
- return new SqlConversationMessageSearchStore(executor);
3538
- }
3539
- // src/chat/db.ts
3540
- var db_exports = /* @__PURE__ */ __exportAll({
3541
- closeDb: () => closeDb,
3542
- getConversationEventStore: () => getConversationEventStore,
3543
- getConversationMessageSearchStore: () => getConversationMessageSearchStore,
3544
- getConversationStore: () => getConversationStore,
3545
- getDb: () => getDb,
3546
- getSqlExecutor: () => getSqlExecutor
3547
- });
3548
- let current;
3549
- function createDb(args) {
3550
- return createJuniorSqlExecutor({
3551
- connectionString: args.databaseUrl,
3552
- driver: args.driver,
3553
- statementTimeoutMs: args.statementTimeoutMs
3554
- });
3555
- }
3556
- /** Return the process SQL executor for SQL-specific queries and transactions. */
3557
- function getSqlExecutor() {
3558
- const { sql } = getChatConfig();
3559
- if (current?.databaseUrl !== sql.databaseUrl || current.driver !== sql.driver || current.statementTimeoutMs !== sql.statementTimeoutMs) {
3560
- if (current) {
3561
- const previous = current;
3562
- current = void 0;
3563
- previous.db.close().catch(() => void 0);
3564
- }
3565
- const db = createDb({
3566
- databaseUrl: sql.databaseUrl,
3567
- driver: sql.driver,
3568
- statementTimeoutMs: sql.statementTimeoutMs
3569
- });
3570
- current = {
3571
- databaseUrl: sql.databaseUrl,
3572
- driver: sql.driver,
3573
- statementTimeoutMs: sql.statementTimeoutMs,
3574
- db,
3575
- store: createSqlStore(db),
3576
- eventStore: createSqlConversationEventStore(db),
3577
- searchStore: createSqlConversationMessageSearchStore(db)
3578
- };
3579
- }
3580
- return current.db;
3581
- }
3582
- /** Return the process Drizzle database. */
3583
- function getDb() {
3584
- return getSqlExecutor().db();
3585
- }
3586
- /** Return the SQL-backed conversation store. */
3587
- function getConversationStore() {
3588
- getSqlExecutor();
3589
- return current.store;
3590
- }
3591
- /** Return the canonical SQL-backed conversation event store. */
3592
- function getConversationEventStore() {
3593
- getSqlExecutor();
3594
- return current.eventStore;
3595
- }
3596
- /** Return the SQL-backed public provider-tenant conversation search store. */
3597
- function getConversationMessageSearchStore() {
3598
- getSqlExecutor();
3599
- return current.searchStore;
3600
- }
3601
- /** Close the process SQL database when it has been opened. */
3602
- async function closeDb() {
3603
- const previous = current;
3604
- current = void 0;
3605
- await previous?.db.close();
3606
- }
3607
- export { conversationWaitsOnUserSql as $, saveActorAvatar as $t, isTopLevelKind as A, agentTurnUsageSchema as An, automationCreatorUserId as At, claimProviderConversation as B, sameDestination as Bn, readViewerAvatarUrl as Bt, createSqlStore as C, conversationPinnedForUser as Cn, isPluginInboxItem as Ct, hasConversationMetadata as D, addAgentTurnUsage as Dn, requireInboxItemLinks as Dt, dispatchInstructionsInvokeSkills as E, viewerMarksFromParticipant as En, requireInboxItemAssignees as Et, turnBehavior as F, nextDetailVersion as Fn, listAdminUsersFromSql as Ft, microUsdToUsd as G, identityAvatarUrl as Gt, parseSessionSource as H, setUserAdminFromSql as Ht, watchRepeatsChildResults as I, touchConversationDetail as In, readActorIdentity as It, conversationRangeColumns as J, readUserAvatarUrls as Jt, usdToMicroUsd as K, parseAvatarUrl as Kt, locationFromRow as L, createSlackDestination as Ln, readActorIdentityFromSql as Lt, postsRunNotices as M, resolveRootConversationId as Mn, resolveAssignees as Mt, promptModeTurnTools as N, rootConversationIsArchived as Nn, findUserByEmail as Nt, isPersonInput as O, agentTurnCostUsd as On, EVERYONE_ASSIGNEE as Ot, sourceLabel as P, conversationDetailTouch as Pn, findUserByEmailFromSql as Pt, conversationTurnFailedSql as Q, resolveActorIdentityId as Qt, setFirstConversationLocation as R, parseDestination as Rn, readIdentityById as Rt, userMessageQueries as S, conversationIsNotUnsubscribedRoot as Sn, isOnlyAssignee as St, deliversFinalText as T, rootVisibleToViewer as Tn, readInboxItemAgentScope as Tt, conversationCostOf as U, updateViewerDisplayName as Ut, getConversationIdByProviderConversation as V, resolveViewerUser as Vt, microUsdSql as W, hasUserPhoto as Wt, conversationIsActiveSql as X, userAvatarUrlsFromJoinedPhotos as Xt, conversationUsageCostExpr as Y, userAvatarUrlsFromIdentities as Yt, conversationStatusSql as Z, SYSTEM_IDENTITY_ID as Zt, readConversationTrees as _, createConversationAccessReader as _n, inboxItemPlugin as _t, getConversationStore as a, linkedSlackUser as an, AUTOMATION_INBOX_ITEM_KEY_PREFIX as at, loadConversationSlackTenantIds as b, readableSlackTeamId as bn, inboxItemVisibleTo as bt, hasAnnotationKey as c, saveUserTimezone as cn, canAgentChangeInboxItem as ct, eventFromRow as d, ToolInputError as dn, inboxItemAssignedTo as dt, deleteProviderIdentityForSlackUser as en, executionIsActive as et, copyMessageLinks as f, isToolInputError as fn, inboxItemForUser as ft, conversationDescendants as g, conversationAccessFromRows as gn, inboxItemOwnedByConversation as gt, conversationAncestors as h, canReadConversation as hn, inboxItemNeedsUser as ht, getConversationMessageSearchStore as i, findUserByVerifiedEmails as in, treeAwaitsAuthorization as it, personSourcePlatform as j, hasAgentTurnUsage as jn, resolveAssignee as jt, isPersonSource as k, agentTurnTotalTokens as kn, activeParticipantUserIds as kt, treeHasAnnotationKey as l, upsertLinkedIdentity as ln, canReadInboxItem as lt, withConversationEventLock as m, canAddConversationMessages as mn, inboxItemNeedsInput as mt, db_exports as n, findLinkedSlackUser as nn, conversationKindSql as nt, getDb as o, readUserTimezone as on, PLUGIN_INBOX_ITEM_KEY_PREFIX as ot, deleteMessageLinks as p, canAccessConversation as pn, inboxItemLinkedTo as pt, conversationAggregateColumns as q, readAvatarFetch as qt, getConversationEventStore as r, findSlackUserByPrimaryEmail as rn, awaitsAuthorizationFrom as rt, getSqlExecutor as s, recordGoogleSignIn as sn, canActOnInboxItem as st, closeDb as t, deleteProviderIdentityForUser as tn, conversationKindFromRow as tt, createSqlConversationEventStore as u, readCachedUserByEmail as un, canUserReadInboxItem as ut, setArchivedAt as v, readConversationAccessFromSql as vn, inboxItemReaderForUser as vt, withConversationMutationLock as w, readMemberParticipants as wn, itemNeedsUser as wt, lastMessageAtSql as x, conversationIsMemberRoot as xn, isAutomationAlertItem as xt, conversationSlackTenantId as y, readConversationAccessRows as yn, inboxItemReaderForUserInConversation as yt, startLocationThread as z, requireSlackDestination as zn, readIdentityByIdFromSql as zt };