@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,1858 +0,0 @@
1
- import { h as logWarn, p as logException } from "./logging-DNt-qOIO.js";
2
- import { _ as withScope } from "./sentry-CPbZjomA.js";
3
- import "./config-CWbwKj0j.js";
4
- import * as z from "zod";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
- import { actorSchema, sourceSchema } from "@sentry/junior-plugin-api";
7
- import { sql } from "drizzle-orm";
8
- import { bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
9
- import { Pool as Pool$1, neon } from "@neondatabase/serverless";
10
- import { drizzle } from "drizzle-orm/neon-serverless";
11
- import { Agent } from "undici";
12
- import { readMigrationFiles } from "drizzle-orm/migrator";
13
- import pg from "pg";
14
- import { drizzle as drizzle$1 } from "drizzle-orm/node-postgres";
15
- // src/db/schema/timestamps.ts
16
- const timestamptz = (name) => timestamp(name, { withTimezone: true });
17
- // src/db/schema/artifacts.ts
18
- /** Durable metadata for conversation-owned artifacts. */
19
- const juniorArtifacts = pgTable("junior_artifacts", {
20
- /** Row identity. A public row serves at `/public/artifacts/<id>.<ext>`. */
21
- id: text("id").primaryKey(),
22
- conversationId: text("conversation_id").notNull(),
23
- sha256: text("sha256").notNull(),
24
- ext: text("ext").notNull(),
25
- storageKey: text("storage_key").notNull(),
26
- contentType: text("content_type").notNull(),
27
- bytes: integer("bytes").notNull(),
28
- /**
29
- * Path under the Sandbox `artifacts/` directory for a live file. Null for
30
- * a public frozen copy, such as a published image.
31
- */
32
- path: text("path"),
33
- visibility: text("visibility").$type().notNull().default("conversation"),
34
- createdAt: timestamptz("created_at").notNull(),
35
- /** Set when the artifact is unpublished or its live file is deleted. */
36
- deleteRequestedAt: timestamptz("delete_requested_at"),
37
- /** When a public artifact stops serving. Null serves until unpublished. */
38
- expiresAt: timestamptz("expires_at")
39
- }, (table) => [
40
- check("junior_artifacts_visibility_check", sql`${table.visibility} in ('conversation', 'internal', 'public')`),
41
- check("junior_artifacts_path_visibility_check", sql`(${table.path} is null) = (${table.visibility} = 'public')`),
42
- uniqueIndex("junior_artifacts_conversation_path_uidx").on(table.conversationId, table.path),
43
- uniqueIndex("junior_artifacts_permanent_sha_uidx").on(table.conversationId, table.sha256).where(sql`${table.visibility} = 'public' and ${table.expiresAt} is null`),
44
- index("junior_artifacts_gc_idx").on(table.deleteRequestedAt, table.createdAt),
45
- index("junior_artifacts_conversation_idx").on(table.conversationId)
46
- ]);
47
- // src/db/embeddings.ts
48
- /**
49
- * Shared parts of the derived embedding indexes. Each owner keeps its own
50
- * table, so a foreign key still deletes a vector with its source row. These
51
- * helpers keep the column types, the distance SQL, the batch checks, and the
52
- * backfill loop the same in every table.
53
- */
54
- function pgvectorColumn(dataType) {
55
- return customType({
56
- dataType() {
57
- return dataType;
58
- },
59
- toDriver(value) {
60
- return JSON.stringify(value);
61
- },
62
- fromDriver(value) {
63
- return value.slice(1, -1).split(",").map(Number);
64
- }
65
- });
66
- }
67
- /**
68
- * pgvector `vector` column without a fixed size, so a new embedding model
69
- * needs no migration. Each table records the size of each row in its own
70
- * column.
71
- */
72
- const embeddingVector = pgvectorColumn("vector");
73
- /**
74
- * Half-precision `embeddingVector`: 2 bytes per value instead of 4, for
75
- * tables that hold many vectors.
76
- */
77
- const embeddingHalfvec = pgvectorColumn("halfvec");
78
- const embeddingResultSchema = z.object({
79
- costUsd: z.number().finite().nonnegative().optional(),
80
- dimensions: z.number().int().positive(),
81
- model: z.string().min(1),
82
- provider: z.string().min(1),
83
- vectors: z.array(z.array(z.number().finite()))
84
- }).strict();
85
- /**
86
- * Validate an embedder result: one vector per text, all of the reported
87
- * size. With `dimensions`, the size must be one that the table accepts. With
88
- * `expected`, the result must come from that provider and model, because a
89
- * backfill that finds rows by model would see a row of another model as
90
- * missing on every run.
91
- */
92
- function parseEmbeddingBatch(raw, args) {
93
- const result = embeddingResultSchema.parse(raw);
94
- if (args.dimensions && !args.dimensions.includes(result.dimensions)) throw new Error("Unsupported embedding vector size.");
95
- if (result.vectors.length !== args.textCount) throw new Error("Embedding provider returned an unexpected vector count.");
96
- if (result.vectors.some((vector) => vector.length !== result.dimensions)) throw new Error("Embedding provider returned an unexpected vector size.");
97
- if (args.expected && (result.provider !== args.expected.provider || result.model !== args.expected.model)) throw new Error(`Embedding provider used model ${result.provider}/${result.model}, not ${args.expected.provider}/${args.expected.model}.`);
98
- return {
99
- dimensions: result.dimensions,
100
- model: result.model,
101
- provider: result.provider,
102
- vectors: result.vectors
103
- };
104
- }
105
- /** Embed one text with the embedder's model and return its vector. */
106
- async function embedText(embedder, input) {
107
- const batch = parseEmbeddingBatch(await embedder.embedTexts({
108
- inputType: input.inputType,
109
- texts: [input.text]
110
- }), {
111
- expected: embedder,
112
- textCount: 1
113
- });
114
- return {
115
- model: batch.model,
116
- provider: batch.provider,
117
- vector: batch.vectors[0]
118
- };
119
- }
120
- function vectorSize(query) {
121
- if (query.length === 0) throw new Error("Embedding vector is empty.");
122
- return sql.raw(String(query.length));
123
- }
124
- /**
125
- * Cosine distance from a stored vector to a query vector. Both sides are cast
126
- * to the query size, the form that an HNSW expression index on that size
127
- * matches. The cast fails on a stored vector of another size, so filter on the
128
- * size first, as the index predicate does, or use `guardedCosineDistance`.
129
- * A caller with another copy of drizzle-orm embeds the result in its own
130
- * `sql` template to get its own `SQL` type.
131
- */
132
- function cosineDistance(args) {
133
- const size = vectorSize(args.query);
134
- const type = sql.raw(args.type);
135
- return sql`(${args.column}::${type}(${size})) <=> ${JSON.stringify(args.query)}::${type}(${size})`;
136
- }
137
- /**
138
- * `cosineDistance`, or null for a stored vector of another size. Postgres
139
- * does not promise to check a WHERE term before it computes an ORDER BY or
140
- * SELECT expression, and pgvector fails on vectors of two sizes. CASE fixes
141
- * the order.
142
- */
143
- function guardedCosineDistance(args) {
144
- return sql`CASE WHEN ${args.dimensions} = ${vectorSize(args.query)} THEN ${cosineDistance(args)} END`;
145
- }
146
- /**
147
- * Embed items that have no current vector, one batch at a time, and store
148
- * each batch before the next starts. `listMissing` returns the next items in
149
- * the caller's order, after the last item of the previous page, so each run
150
- * ends even when a write leaves an item missing. Text that trims to nothing
151
- * is skipped, because the embedder rejects it. A provider failure stops the
152
- * run and keeps the batches stored before it, so a later run continues.
153
- */
154
- async function refreshEmbeddings(args) {
155
- const now = args.now ?? Date.now;
156
- let after;
157
- let embedded = 0;
158
- for (;;) {
159
- const remaining = (args.maxItems ?? 1e400) - embedded;
160
- if (remaining <= 0 || args.deadlineMs !== void 0 && now() >= args.deadlineMs) return {
161
- done: false,
162
- embedded
163
- };
164
- const page = await args.listMissing({
165
- after,
166
- limit: Math.min(args.batchSize, remaining)
167
- });
168
- after = page.at(-1);
169
- if (!after) return {
170
- done: true,
171
- embedded
172
- };
173
- const items = page.filter((item) => item.text.trim() !== "");
174
- if (items.length === 0) continue;
175
- const batch = parseEmbeddingBatch(await args.embedder.embedTexts({
176
- inputType: "document",
177
- texts: items.map((item) => item.text)
178
- }), {
179
- ...args.dimensions ? { dimensions: args.dimensions } : void 0,
180
- expected: args.embedder,
181
- textCount: items.length
182
- });
183
- await args.write(items.map((item, index) => ({
184
- item,
185
- vector: batch.vectors[index]
186
- })), batch);
187
- embedded += items.length;
188
- }
189
- }
190
- // src/db/schema/tsvector.ts
191
- /** Postgres full-text lexemes. Queries read them only through SQL. */
192
- const tsvector = customType({ dataType() {
193
- return "tsvector";
194
- } });
195
- // src/chat/memory/types.ts
196
- const MEMORY_KINDS = [
197
- "preference",
198
- "procedure",
199
- "knowledge"
200
- ];
201
- const MEMORY_SCOPES = ["private", "public"];
202
- const MEMORY_SUBJECT_TYPES = [
203
- "user",
204
- "conversation",
205
- "general"
206
- ];
207
- const MEMORY_SOURCE_PLATFORMS = [
208
- "slack",
209
- "local",
210
- "web"
211
- ];
212
- const MEMORY_EMBEDDING_METRICS = ["cosine"];
213
- /** Things that can happen to a stored memory and feed future recall weights. */
214
- /** `contradicted` and `superseded` record why a memory was retired. */
215
- const MEMORY_SIGNALS = [
216
- "duplicate",
217
- "contradicted",
218
- "superseded"
219
- ];
220
- /**
221
- * Vector sizes the embeddings table can store, so one table can hold vectors
222
- * from an old and a new model while a model change is in progress. Only 1024
223
- * has an HNSW index.
224
- */
225
- const MEMORY_EMBEDDING_DIMENSIONS = [1024, 1536];
226
- const nonEmptyStringSchema = z.string().min(1);
227
- /** Host data used to set memory access, subject, and source. */
228
- const memoryRuntimeContextSchema = z.object({
229
- conversationId: nonEmptyStringSchema.optional(),
230
- locationId: nonEmptyStringSchema.optional(),
231
- actor: actorSchema.optional(),
232
- source: sourceSchema,
233
- /** User linked to the active Actor. */
234
- userId: nonEmptyStringSchema.optional()
235
- }).strict();
236
- // src/db/schema/memory.ts
237
- const juniorMemoryMemories = pgTable("junior_memory_memories", {
238
- id: text("id").primaryKey(),
239
- scope: text("scope", { enum: MEMORY_SCOPES }).notNull(),
240
- scopeKey: text("scope_key").notNull(),
241
- kind: text("type", { enum: MEMORY_KINDS }).notNull(),
242
- subjectType: text("subject_type", { enum: MEMORY_SUBJECT_TYPES }).notNull(),
243
- subjectKey: text("subject_key"),
244
- content: text("content").notNull(),
245
- searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', "content")`),
246
- sourcePlatform: text("source_platform", { enum: MEMORY_SOURCE_PLATFORMS }).notNull(),
247
- sourceKey: text("source_key").notNull(),
248
- /** Location where Junior learned the memory, when known. */
249
- locationId: text("location_id"),
250
- /** Conversation where Junior learned the memory, when known. */
251
- conversationId: text("conversation_id"),
252
- idempotencyKey: text("idempotency_key"),
253
- observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull(),
254
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
255
- expiresAtMs: bigint("expires_at_ms", { mode: "number" }),
256
- supersededAtMs: bigint("superseded_at_ms", { mode: "number" }),
257
- supersededById: text("superseded_by_id"),
258
- archivedAtMs: bigint("archived_at_ms", { mode: "number" }),
259
- archiveReason: text("archive_reason")
260
- }, (table) => [
261
- index("junior_memory_memories_visible_idx").on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
262
- index("junior_memory_memories_expiration_idx").on(table.expiresAtMs).where(sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`),
263
- index("junior_memory_memories_search_idx").using("gin", table.scope, table.scopeKey, table.searchVector).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
264
- uniqueIndex("junior_memory_memories_idempotency_idx").on(table.scope, table.scopeKey, table.idempotencyKey).where(sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
265
- index("junior_memory_memories_archived_idempotency_idx").on(table.scope, table.scopeKey, table.idempotencyKey).where(sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NOT NULL AND ${table.archiveReason} <> 'expired'`),
266
- check("junior_memory_memories_scope_check", sql`${table.scope} IN ('private', 'public')`),
267
- check("junior_memory_memories_kind_check", sql`${table.kind} IN (
268
- 'preference',
269
- 'procedure',
270
- 'knowledge'
271
- )`),
272
- check("junior_memory_memories_subject_type_check", sql`${table.subjectType} IN ('user', 'conversation', 'general')`),
273
- check("junior_memory_memories_subject_key_check", sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`),
274
- check("junior_memory_memories_source_platform_check", sql`${table.sourcePlatform} IN ('slack', 'local', 'web')`)
275
- ]);
276
- const juniorMemoryEmbeddings = pgTable("junior_memory_embeddings", {
277
- memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
278
- provider: text("provider").notNull(),
279
- model: text("model").notNull(),
280
- dimensions: integer("dimensions").notNull(),
281
- metric: text("metric", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),
282
- contentHash: text("content_hash").notNull(),
283
- embedding: embeddingVector("embedding").notNull(),
284
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull()
285
- }, (table) => [
286
- primaryKey({ columns: [
287
- table.memoryId,
288
- table.provider,
289
- table.model
290
- ] }),
291
- index("junior_memory_embeddings_model_idx").on(table.provider, table.model, table.dimensions, table.metric),
292
- index("junior_memory_embeddings_embedding_1024_hnsw_idx").using("hnsw", sql`(${table.embedding}::vector(1024)) vector_cosine_ops`).with({
293
- m: 16,
294
- ef_construction: 64
295
- }).where(sql`${table.dimensions} = 1024`),
296
- check("junior_memory_embeddings_metric_check", sql`${table.metric} IN ('cosine')`),
297
- check("junior_memory_embeddings_dimensions_check", sql`${table.dimensions} IN (${sql.raw(MEMORY_EMBEDDING_DIMENSIONS.join(", "))}) AND vector_dims(${table.embedding}) = ${table.dimensions}`)
298
- ]);
299
- /**
300
- * Thin log of signals about stored memories, such as a capture that resolved
301
- * to an existing memory. Callers count recent rows to weigh memories.
302
- */
303
- const juniorMemorySignals = pgTable("junior_memory_signals", {
304
- memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
305
- signal: text("signal", { enum: MEMORY_SIGNALS }).notNull(),
306
- idempotencyKey: text("idempotency_key").notNull(),
307
- /** Conversation where Junior saw the signal, when known. */
308
- conversationId: text("conversation_id"),
309
- observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull()
310
- }, (table) => [
311
- primaryKey({ columns: [
312
- table.memoryId,
313
- table.signal,
314
- table.idempotencyKey
315
- ] }),
316
- index("junior_memory_signals_observed_idx").on(table.memoryId, table.signal, table.observedAtMs),
317
- check("junior_memory_signals_signal_check", sql`${table.signal} IN ('duplicate', 'contradicted', 'superseded')`)
318
- ]);
319
- // src/db/schema/destinations.ts
320
- const juniorDestinations = pgTable("junior_destinations", {
321
- id: text("id").primaryKey(),
322
- provider: text("provider").notNull(),
323
- providerTenantId: text("provider_tenant_id").notNull().default(""),
324
- providerDestinationId: text("provider_destination_id").notNull(),
325
- kind: text("kind").$type().notNull(),
326
- parentDestinationId: text("parent_destination_id"),
327
- displayName: text("display_name"),
328
- visibility: text("visibility").$type().notNull().default("unknown"),
329
- metadata: jsonb("metadata_json"),
330
- createdAt: timestamptz("created_at").notNull(),
331
- updatedAt: timestamptz("updated_at").notNull()
332
- }, (table) => [uniqueIndex("junior_destinations_provider_destination_uidx").on(table.provider, table.providerTenantId, table.providerDestinationId), index("junior_destinations_provider_kind_idx").on(table.provider, table.kind)]);
333
- const juniorUsers = pgTable("junior_users", {
334
- id: text("id").primaryKey(),
335
- primaryEmail: text("primary_email").notNull(),
336
- primaryEmailNormalized: text("primary_email_normalized").notNull(),
337
- displayName: text("display_name"),
338
- timezone: text("timezone"),
339
- /** Text the user saved to change how Junior replies to them. */
340
- customization: text("customization"),
341
- /** Push notification hours. Null means the default schedule. */
342
- notificationSchedule: jsonb("notification_schedule").$type(),
343
- /** Junior-wide admin role. Only the `junior admin` CLI changes it. */
344
- isAdmin: boolean("is_admin").notNull().default(false),
345
- /** Auto-archive this user's conversations when their work is done. */
346
- autoArchiveDefault: boolean("auto_archive_default").notNull().default(false),
347
- /** Hours done work and the conversation stay quiet before auto-archive. */
348
- autoArchiveGraceHours: integer("auto_archive_grace_hours").notNull().default(24),
349
- /**
350
- * Small per-user choices, such as an experiment opt-in, that can come
351
- * and go without a migration. `api/user-settings.ts` owns the keys.
352
- */
353
- preferences: jsonb("preferences").$type().notNull().default({}),
354
- createdAt: timestamptz("created_at").notNull(),
355
- updatedAt: timestamptz("updated_at").notNull()
356
- }, (table) => [uniqueIndex("junior_users_primary_email_normalized_uidx").on(table.primaryEmailNormalized)]);
357
- // src/db/schema/identities.ts
358
- /** Words of a Slack person's name and handle, for prefix search. */
359
- function slackPersonSearchDocument(table) {
360
- return sql`to_tsvector('simple', coalesce(${table.displayName}, '') || ' ' || coalesce(${table.handle}, ''))`;
361
- }
362
- /**
363
- * Slack people. Literal values, so a prepared query with this predicate
364
- * can use the partial index.
365
- */
366
- function slackPersonPredicate(table) {
367
- return sql`${table.provider} = 'slack' AND ${table.kind} = 'user'`;
368
- }
369
- const juniorIdentities = pgTable("junior_identities", {
370
- id: text("id").primaryKey(),
371
- kind: text("kind").$type().notNull(),
372
- provider: text("provider").notNull(),
373
- providerTenantId: text("provider_tenant_id").notNull().default(""),
374
- providerSubjectId: text("provider_subject_id").notNull(),
375
- displayName: text("display_name"),
376
- handle: text("handle"),
377
- email: text("email"),
378
- avatarUrl: text("avatar_url"),
379
- metadata: jsonb("metadata_json"),
380
- createdAt: timestamptz("created_at").notNull(),
381
- updatedAt: timestamptz("updated_at").notNull(),
382
- userId: text("user_id").references(() => juniorUsers.id),
383
- emailNormalized: text("email_normalized"),
384
- emailVerified: boolean("email_verified").notNull().default(false),
385
- signedInAt: timestamptz("signed_in_at")
386
- }, (table) => [
387
- uniqueIndex("junior_identities_provider_subject_uidx").on(table.provider, table.providerTenantId, table.providerSubjectId),
388
- index("junior_identities_user_idx").on(table.userId),
389
- index("junior_identities_verified_email_idx").on(table.emailNormalized).where(sql`${table.emailVerified} = true AND ${table.emailNormalized} IS NOT NULL`),
390
- index("junior_identities_kind_provider_idx").on(table.kind, table.provider),
391
- index("junior_identities_slack_person_search_idx").using("gin", slackPersonSearchDocument(table)).where(slackPersonPredicate(table))
392
- ]);
393
- // src/db/schema/conversations.ts
394
- const juniorConversations = pgTable("junior_conversations", {
395
- conversationId: text("conversation_id").primaryKey(),
396
- schemaVersion: integer("schema_version").notNull().default(1),
397
- source: text("source").$type(),
398
- /** Structured session Source locator; set-once on the conversation root. */
399
- sessionSource: jsonb("source_json").$type(),
400
- /** Complete Location associated with this Conversation. */
401
- location: jsonb("location_json").$type(),
402
- destinationId: text("destination_id").references(() => juniorDestinations.id),
403
- destination: jsonb("destination_json").$type(),
404
- actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
405
- creatorIdentityId: text("creator_identity_id").references(() => juniorIdentities.id),
406
- credentialSubjectIdentityId: text("credential_subject_identity_id").references(() => juniorIdentities.id),
407
- actor: jsonb("actor_json").$type(),
408
- channelName: text("channel_name"),
409
- title: text("title"),
410
- summary: text("summary"),
411
- metadataThroughSeq: integer("metadata_through_seq"),
412
- createdAt: timestamptz("created_at").notNull(),
413
- lastActivityAt: timestamptz("last_activity_at").notNull(),
414
- /**
415
- * The newest Message that a reader would notice (`refreshLastMessageAt`).
416
- * Null until the Conversation has one.
417
- */
418
- lastMessageAt: timestamptz("last_message_at"),
419
- updatedAt: timestamptz("updated_at").notNull(),
420
- executionUpdatedAt: timestamptz("execution_updated_at"),
421
- executionStatus: text("execution_status").$type().notNull(),
422
- runId: text("run_id"),
423
- lastCheckpointAt: timestamptz("last_checkpoint_at"),
424
- lastEnqueuedAt: timestamptz("last_enqueued_at"),
425
- parentConversationId: text("parent_conversation_id").references(() => juniorConversations.conversationId),
426
- kind: text("kind").$type(),
427
- agentConfig: jsonb("agent_config_json").$type(),
428
- archivedAt: timestamptz("archived_at"),
429
- forkedFromConversationId: text("forked_from_conversation_id").references(() => juniorConversations.conversationId, { onDelete: "set null" }),
430
- quickQuestionAt: timestamptz("quick_question_at"),
431
- rootConversationId: text("root_conversation_id").references(() => juniorConversations.conversationId),
432
- transcriptPurgedAt: timestamptz("transcript_purged_at"),
433
- /**
434
- * Set while the Conversation is stopped. Its Watch Events are then saved
435
- * as Messages that start no Turn. A person's later input, or new work
436
- * from its parent, clears it.
437
- */
438
- stoppedAt: timestamptz("stopped_at"),
439
- /**
440
- * Set while a root's Event Turn replies stay out of its Location. Junior
441
- * still stores them. A person's next mention in the Location clears it.
442
- */
443
- deliveryPausedAt: timestamptz("delivery_paused_at"),
444
- durationMs: integer("duration_ms").notNull().default(0),
445
- usage: jsonb("usage_json").$type(),
446
- executionDurationMs: integer("execution_duration_ms").notNull().default(0),
447
- executionUsage: jsonb("execution_usage_json").$type(),
448
- metricRunId: text("metric_run_id"),
449
- detailVersion: integer("detail_version").notNull().default(0)
450
- }, (table) => [
451
- check("junior_conversations_kind_check", sql`${table.kind} in ('root', 'automation', 'lead', 'thread', 'task')`),
452
- check("junior_conversations_kind_parent_check", sql`${table.kind} is null or ((${table.kind} in ('root', 'automation', 'lead')) = (${table.parentConversationId} is null))`),
453
- index("junior_conversations_last_activity_idx").on(table.lastActivityAt.desc(), table.conversationId),
454
- index("junior_conversations_active_idx").using("btree", sql`coalesce(${table.executionUpdatedAt}, ${table.updatedAt})`, table.conversationId).where(sql`${table.executionStatus} <> 'idle'`),
455
- index("junior_conversations_destination_activity_idx").on(table.destinationId, table.lastActivityAt.desc()),
456
- index("junior_conversations_actor_activity_idx").on(table.actorIdentityId, table.lastActivityAt.desc()),
457
- index("junior_conversations_parent_idx").on(table.parentConversationId),
458
- index("junior_conversations_forked_from_idx").on(table.forkedFromConversationId),
459
- index("junior_conversations_root_idx").on(table.rootConversationId),
460
- uniqueIndex("junior_conversations_lead_actor_idx").on(table.actorIdentityId).where(sql`${table.kind} = 'lead'`),
461
- index("junior_conversations_search_idx").using("gin", sql`to_tsvector('english', coalesce(${table.title}, '') || ' ' || coalesce(${table.summary}, ''))`)
462
- ]);
463
- // src/db/schema/attachments.ts
464
- /**
465
- * What a Message carries: a stored file (`file`) or a web link that its text
466
- * names (`url`). Rows are owned by one Conversation, and a repeat of the same
467
- * thing in that Conversation reuses its row.
468
- */
469
- const juniorAttachments = pgTable("junior_attachments", {
470
- id: text("id").primaryKey(),
471
- /** `file` or `url`. Only `file` rows have storage and file fields. */
472
- kind: text("kind").notNull().default("file"),
473
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
474
- /** Service that stores the file bytes. */
475
- storageProvider: text("storage_provider"),
476
- /**
477
- * Object key of the stored bytes. Null for a file that Junior records
478
- * without storing, such as a large Slack file.
479
- */
480
- storageKey: text("storage_key"),
481
- /** Provider that supplied the file. */
482
- provider: text("provider"),
483
- /** File id assigned by the source provider. */
484
- providerId: text("provider_id"),
485
- /**
486
- * File name of a file. The column keeps its old name until no worker
487
- * that reads `filename` runs.
488
- */
489
- title: text("filename"),
490
- contentType: text("content_type"),
491
- bytes: integer("bytes"),
492
- /** Web link of a `url` row, as its message text wrote it. */
493
- url: text("url"),
494
- /** Digest of the stored bytes. Null when `storage_key` is null. */
495
- sha256: text("sha256"),
496
- visionSummary: text("vision_summary"),
497
- createdAt: timestamptz("created_at").notNull(),
498
- /** Set when conversation purge marks the attachment unavailable. */
499
- deleteRequestedAt: timestamptz("delete_requested_at")
500
- }, (table) => [
501
- index("junior_attachments_conversation_idx").on(table.conversationId),
502
- index("junior_attachments_provider_idx").on(table.conversationId, table.provider, table.providerId),
503
- index("junior_attachments_gc_idx").on(table.storageProvider, table.deleteRequestedAt, table.createdAt),
504
- uniqueIndex("junior_attachments_conversation_url_idx").on(table.conversationId, table.url).where(sql`${table.url} IS NOT NULL`)
505
- ]);
506
- /**
507
- * Where each stored message event uses an Attachment. `seq` is the seq of the
508
- * first save of its message, as in the transcript. `position` is the 1-based
509
- * order of a link in the message text, and null for an Attachment that is not
510
- * in the text. No foreign keys, so creating the table locks no existing
511
- * table.
512
- */
513
- const juniorMessageAttachments = pgTable("junior_message_attachments", {
514
- conversationId: text("conversation_id").notNull(),
515
- seq: integer("seq").notNull(),
516
- attachmentId: text("attachment_id").notNull(),
517
- position: integer("position")
518
- }, (table) => [primaryKey({
519
- name: "junior_message_attachments_pk",
520
- columns: [
521
- table.conversationId,
522
- table.seq,
523
- table.attachmentId
524
- ]
525
- })]);
526
- /**
527
- * Browser uploads that wait for a web Message.
528
- *
529
- * A row binds one object key to the viewer, Conversation, and Message
530
- * idempotency key that asked for it. A Message turns the upload into a
531
- * `junior_attachments` row with the same id. Cleanup deletes the object of an
532
- * upload that no Message used.
533
- */
534
- const juniorAttachmentUploads = pgTable("junior_attachment_uploads", {
535
- id: text("id").primaryKey(),
536
- /** No foreign key: a new Conversation has no row until its first send. */
537
- conversationId: text("conversation_id").notNull(),
538
- userId: text("user_id").notNull(),
539
- idempotencyKey: text("idempotency_key").notNull(),
540
- storageProvider: text("storage_provider").notNull(),
541
- storageKey: text("storage_key").notNull(),
542
- filename: text("filename").notNull(),
543
- contentType: text("content_type").notNull(),
544
- /** Size that the browser declared and the upload target allows. */
545
- bytes: integer("bytes").notNull(),
546
- createdAt: timestamptz("created_at").notNull()
547
- }, (table) => [index("junior_attachment_uploads_gc_idx").on(table.storageProvider, table.createdAt)]);
548
- // src/db/schema/code.ts
549
- /**
550
- * Words of a repository name, for prefix search. `owner/repo` is one token
551
- * to the text parser, so the slash becomes a space.
552
- */
553
- function codeRepositorySearchDocument(table) {
554
- return sql`to_tsvector('simple', translate(${table.name}, '/', ' '))`;
555
- }
556
- /** The number and the title words of a code change, for prefix search. */
557
- function codeChangeSearchDocument(table) {
558
- return sql`to_tsvector('simple', ${table.number}::text || ' ' || coalesce(${table.title}, ''))`;
559
- }
560
- /** Repository known to Junior through an installed code plugin. */
561
- const juniorCodeRepositories = pgTable("junior_code_repositories", {
562
- id: uuid("id").primaryKey(),
563
- name: text("name").notNull(),
564
- provider: text("provider").notNull(),
565
- providerId: text("provider_id").notNull(),
566
- url: text("url"),
567
- updatedAt: timestamptz("updated_at").notNull()
568
- }, (table) => [uniqueIndex("junior_code_repositories_provider_id_idx").on(table.provider, table.providerId), index("junior_code_repositories_search_idx").using("gin", codeRepositorySearchDocument(table))]);
569
- /** Latest known state for one code change created by Junior. */
570
- const juniorCodeChanges = pgTable("junior_code_changes", {
571
- id: uuid("id").primaryKey(),
572
- additions: integer("additions"),
573
- changedFiles: integer("changed_files"),
574
- closedAt: timestamptz("closed_at"),
575
- conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
576
- deletions: integer("deletions"),
577
- draft: boolean("draft").notNull().default(false),
578
- /** Latest push, review, or comment by a person, from the code plugin. */
579
- lastActivityAt: timestamptz("last_activity_at"),
580
- mergedAt: timestamptz("merged_at"),
581
- number: integer("number").notNull(),
582
- openedAt: timestamptz("opened_at").notNull(),
583
- provider: text("provider").notNull(),
584
- providerId: text("provider_id").notNull(),
585
- repositoryId: uuid("repository_id").notNull().references(() => juniorCodeRepositories.id, { onDelete: "cascade" }),
586
- state: text("state").$type().notNull(),
587
- title: text("title"),
588
- updatedAt: timestamptz("updated_at").notNull(),
589
- url: text("url")
590
- }, (table) => [
591
- uniqueIndex("junior_code_changes_provider_id_idx").on(table.provider, table.providerId),
592
- index("junior_code_changes_opened_at_idx").on(table.openedAt),
593
- index("junior_code_changes_merged_at_idx").on(table.mergedAt),
594
- index("junior_code_changes_closed_at_idx").on(table.closedAt),
595
- index("junior_code_changes_repository_state_idx").on(table.repositoryId, table.state, table.updatedAt.desc()),
596
- index("junior_code_changes_search_idx").using("gin", codeChangeSearchDocument(table)),
597
- index("junior_code_changes_open_idx").on(table.id).where(sql`${table.state} = 'open'`)
598
- ]);
599
- // src/db/schema/conversation-annotations.ts
600
- const juniorConversationAnnotations = pgTable("junior_conversation_annotations", {
601
- conversationId: text("conversation_id").notNull(),
602
- plugin: text("plugin").notNull(),
603
- kind: text("kind").notNull(),
604
- key: text("key").notNull(),
605
- annotation: jsonb("annotation_json").$type().notNull(),
606
- createdAt: timestamptz("created_at").notNull(),
607
- updatedAt: timestamptz("updated_at").notNull()
608
- }, (table) => [primaryKey({
609
- name: "junior_conversation_annotations_pk",
610
- columns: [
611
- table.conversationId,
612
- table.plugin,
613
- table.kind,
614
- table.key
615
- ]
616
- }), foreignKey({
617
- name: "junior_conversation_annotations_conversation_id_fk",
618
- columns: [table.conversationId],
619
- foreignColumns: [juniorConversations.conversationId]
620
- }).onDelete("cascade")]);
621
- // src/db/schema/api-tokens.ts
622
- const juniorApiTokens = pgTable("junior_api_tokens", {
623
- id: text("id").primaryKey(),
624
- ownerEmailNormalized: text("owner_email_normalized").notNull(),
625
- name: text("name").notNull(),
626
- tokenHash: text("token_hash").notNull(),
627
- tokenSuffix: text("token_suffix").notNull(),
628
- createdAt: timestamptz("created_at").notNull(),
629
- expiresAt: timestamptz("expires_at").notNull(),
630
- lastUsedAt: timestamptz("last_used_at"),
631
- revokedAt: timestamptz("revoked_at")
632
- }, (table) => [uniqueIndex("junior_api_tokens_token_hash_uidx").on(table.tokenHash), index("junior_api_tokens_owner_email_idx").on(table.ownerEmailNormalized)]);
633
- // src/db/schema/conversation-events.ts
634
- /**
635
- * Match a user_message payload that a person sent as an instruction from a
636
- * chat surface. `junior_conversation_events_user_message_time_idx` has this
637
- * predicate, so a query with it can use the index and skip other events.
638
- */
639
- function isUserInstruction(payload) {
640
- return sql`(${payload}->'provenance'->>'authority') = 'instruction' and (${payload}->'provenance'->'actor'->>'platform') in ('slack', 'local', 'web')`;
641
- }
642
- /**
643
- * Append-only canonical conversation history. `history_version` partitions
644
- * model-history replacements, while `(conversation_id, seq)` is the stable
645
- * event identity and lease-fencing tripwire.
646
- *
647
- * `actor_identity_id` is the first-class author identity for human-authored
648
- * events. Message payloads may still carry display author fields in `meta`.
649
- */
650
- const juniorConversationEvents = pgTable("junior_conversation_events", {
651
- conversationId: text("conversation_id").notNull(),
652
- seq: integer("seq").notNull(),
653
- historyVersion: integer("history_version").notNull(),
654
- schemaVersion: integer("schema_version").default(1).notNull(),
655
- idempotencyKey: text("idempotency_key"),
656
- type: text("type").notNull(),
657
- payload: jsonb("payload").$type().notNull(),
658
- actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
659
- createdAt: timestamptz("created_at").notNull()
660
- }, (table) => [
661
- primaryKey({
662
- name: "junior_conversation_events_conversation_id_seq_pk",
663
- columns: [table.conversationId, table.seq]
664
- }),
665
- foreignKey({
666
- name: "junior_conversation_events_conversation_id_junior_conversations_conversation_id_fk",
667
- columns: [table.conversationId],
668
- foreignColumns: [juniorConversations.conversationId]
669
- }),
670
- index("junior_conversation_events_history_version_idx").on(table.conversationId, table.historyVersion, table.seq),
671
- index("junior_conversation_events_type_idx").on(table.conversationId, table.type, table.seq),
672
- index("junior_conversation_events_plugin_report_idx").on(sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.createdAt).where(sql`${table.type} = 'structured_event'`),
673
- index("junior_conversation_events_guardian_review_time_idx").on(table.createdAt).where(sql`${table.type} = 'guardian_action_reviewed'`),
674
- index("junior_conversation_events_authorization_request_idx").on(table.conversationId, table.createdAt).where(sql`${table.type} = 'authorization_requested'`),
675
- index("junior_conversation_events_plugin_conversation_idx").on(table.conversationId, sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.seq).where(sql`${table.type} = 'structured_event'`),
676
- index("junior_conversation_events_actor_identity_idx").on(table.actorIdentityId, table.conversationId, table.seq),
677
- index("junior_conversation_events_author_idx").on(table.conversationId, table.actorIdentityId, table.seq).where(sql`${table.actorIdentityId} is not null`),
678
- index("junior_conversation_events_message_role_idx").on(table.conversationId, sql`(${table.payload}->>'role')`, table.createdAt, table.seq).where(sql`${table.type} = 'message'`),
679
- index("junior_conversation_events_user_message_time_idx").on(table.conversationId, table.createdAt, table.seq).where(sql`${table.type} = 'user_message' and ${isUserInstruction(table.payload)}`),
680
- index("junior_conversation_events_message_search_idx").using("gin", sql`to_tsvector('english', ${table.payload}->>'text')`).where(sql`${table.type} = 'message'`),
681
- uniqueIndex("junior_conversation_events_idempotency_idx").on(table.conversationId, table.idempotencyKey)
682
- ]);
683
- // src/db/schema/conversation-metrics.ts
684
- const CONVERSATION_METRICS = [
685
- "duration_ms",
686
- "total_tokens",
687
- "input_tokens",
688
- "output_tokens",
689
- "cached_input_tokens",
690
- "cache_creation_tokens",
691
- "reasoning_tokens",
692
- "cost_micro_usd"
693
- ];
694
- /**
695
- * One metric value for one Conversation Run. A Run is one Turn, so People
696
- * spend reads the Identity of the Turn Actor from these rows.
697
- */
698
- const juniorConversationMetrics = pgTable("junior_conversation_metrics", {
699
- conversationId: text("conversation_id").notNull(),
700
- runId: text("run_id").notNull(),
701
- metric: text("metric").$type().notNull(),
702
- actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
703
- value: doublePrecision("value").notNull(),
704
- occurredAt: timestamptz("occurred_at").notNull(),
705
- updatedAt: timestamptz("updated_at").notNull()
706
- }, (table) => [
707
- primaryKey({
708
- name: "junior_conversation_metrics_conversation_id_run_id_metric_pk",
709
- columns: [
710
- table.conversationId,
711
- table.runId,
712
- table.metric
713
- ]
714
- }),
715
- foreignKey({
716
- name: "junior_conversation_metrics_conversation_id_junior_conversations_conversation_id_fk",
717
- columns: [table.conversationId],
718
- foreignColumns: [juniorConversations.conversationId]
719
- }),
720
- index("junior_conversation_metrics_actor_identity_occurred_at_idx").on(table.actorIdentityId, table.occurredAt),
721
- index("junior_conversation_metrics_occurred_at_metric_idx").on(table.occurredAt, table.metric),
722
- index("junior_conversation_metrics_turn_metric_occurred_at_idx").on(table.metric, table.occurredAt, table.actorIdentityId, table.conversationId, table.value).where(sql`${table.metric} IN ('duration_ms', 'total_tokens', 'cost_micro_usd')`)
723
- ]);
724
- // src/db/schema/conversation-embeddings.ts
725
- /**
726
- * One embedding per Conversation, for semantic search. Its text is the
727
- * Conversation metadata. A derived index: the next metadata update replaces
728
- * the row.
729
- */
730
- const juniorConversationEmbeddings = pgTable("junior_conversation_embeddings", {
731
- conversationId: text("conversation_id").primaryKey(),
732
- legacyBriefVersion: integer("brief_version"),
733
- /** The `metadata_through_seq` of the embedded Conversation metadata. */
734
- throughSeq: integer("through_seq"),
735
- provider: text("provider").notNull(),
736
- model: text("model").notNull(),
737
- dimensions: integer("dimensions").notNull(),
738
- embedding: embeddingVector("embedding").notNull(),
739
- createdAt: timestamptz("created_at").defaultNow().notNull()
740
- }, (table) => [foreignKey({
741
- name: "junior_conversation_embeddings_conversation_fk",
742
- columns: [table.conversationId],
743
- foreignColumns: [juniorConversations.conversationId]
744
- }).onDelete("cascade"), check("junior_conversation_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)]);
745
- // src/db/schema/conversation-event-embeddings.ts
746
- /**
747
- * One embedding per searchable Conversation event, for semantic search of the
748
- * history of one Conversation. A derived index: a purge that deletes the
749
- * event deletes its row, and a new embedding model replaces the row.
750
- */
751
- const juniorConversationEventEmbeddings = pgTable("junior_conversation_event_embeddings", {
752
- conversationId: text("conversation_id").notNull(),
753
- seq: integer("seq").notNull(),
754
- provider: text("provider").notNull(),
755
- model: text("model").notNull(),
756
- dimensions: integer("dimensions").notNull(),
757
- embedding: embeddingHalfvec("embedding").notNull(),
758
- createdAt: timestamptz("created_at").defaultNow().notNull()
759
- }, (table) => [
760
- primaryKey({
761
- name: "junior_conversation_event_embeddings_pk",
762
- columns: [table.conversationId, table.seq]
763
- }),
764
- foreignKey({
765
- name: "junior_conversation_event_embeddings_event_fk",
766
- columns: [table.conversationId, table.seq],
767
- foreignColumns: [juniorConversationEvents.conversationId, juniorConversationEvents.seq]
768
- }).onDelete("cascade"),
769
- check("junior_conversation_event_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)
770
- ]);
771
- // src/db/schema/conversation-event-lexemes.ts
772
- /**
773
- * Stored full-text lexemes of one searchable Conversation event, for keyword
774
- * search of the history of one Conversation. A derived index: a purge that
775
- * deletes the event deletes its row. Events are immutable, so a row never
776
- * changes.
777
- */
778
- const juniorConversationEventLexemes = pgTable("junior_conversation_event_lexemes", {
779
- conversationId: text("conversation_id").notNull(),
780
- seq: integer("seq").notNull(),
781
- lexemes: tsvector("lexemes").notNull(),
782
- createdAt: timestamptz("created_at").defaultNow().notNull()
783
- }, (table) => [
784
- primaryKey({
785
- name: "junior_conversation_event_lexemes_pk",
786
- columns: [table.conversationId, table.seq]
787
- }),
788
- foreignKey({
789
- name: "junior_conversation_event_lexemes_event_fk",
790
- columns: [table.conversationId, table.seq],
791
- foreignColumns: [juniorConversationEvents.conversationId, juniorConversationEvents.seq]
792
- }).onDelete("cascade"),
793
- index("junior_conversation_event_lexemes_lexemes_idx").using("gin", table.lexemes)
794
- ]);
795
- // src/db/schema/conversation-briefs.ts
796
- /**
797
- * Legacy Brief versions. Conversation metadata replaced Briefs; only purge
798
- * still deletes rows here.
799
- * TODO(dcramer): Drop this table after the metadata backfill ships.
800
- */
801
- const juniorConversationBriefs = pgTable("junior_conversation_briefs", {
802
- conversationId: text("conversation_id").notNull(),
803
- version: integer("version").notNull(),
804
- turnId: text("turn_id").notNull(),
805
- throughSeq: integer("through_seq").notNull(),
806
- content: jsonb("content").notNull(),
807
- outcomeStatus: text("outcome_status"),
808
- searchText: text("search_text").notNull(),
809
- modelId: text("model_id").notNull(),
810
- costMicroUsd: bigint("cost_micro_usd", { mode: "number" }),
811
- legacyCostUsd: doublePrecision("cost_usd"),
812
- createdAt: timestamptz("created_at").defaultNow().notNull()
813
- }, (table) => [
814
- primaryKey({
815
- name: "junior_conversation_briefs_conversation_id_version_pk",
816
- columns: [table.conversationId, table.version]
817
- }),
818
- foreignKey({
819
- name: "junior_conversation_briefs_conversation_id_junior_conversations_conversation_id_fk",
820
- columns: [table.conversationId],
821
- foreignColumns: [juniorConversations.conversationId]
822
- }).onDelete("cascade"),
823
- uniqueIndex("junior_conversation_briefs_conversation_turn_idx").on(table.conversationId, table.turnId),
824
- index("junior_conversation_briefs_conversation_version_idx").on(table.conversationId, table.version.desc()),
825
- index("junior_conversation_briefs_created_at_idx").on(table.createdAt, table.conversationId),
826
- index("junior_conversation_briefs_search_idx").using("gin", sql`to_tsvector('english', ${table.searchText})`)
827
- ]);
828
- // src/db/schema/conversation-bindings.ts
829
- /** Provider conversation coordinates bound to Junior's opaque durable conversation id. */
830
- const juniorConversationBindings = pgTable("junior_conversation_bindings", {
831
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId),
832
- provider: text("provider").notNull(),
833
- providerTenantId: text("provider_tenant_id").notNull().default(""),
834
- providerDestinationId: text("provider_destination_id").notNull(),
835
- providerConversationId: text("provider_conversation_id").notNull(),
836
- createdAt: timestamptz("created_at").notNull()
837
- }, (table) => [primaryKey({
838
- name: "junior_conversation_bindings_provider_conversation_pk",
839
- columns: [
840
- table.provider,
841
- table.providerTenantId,
842
- table.providerDestinationId,
843
- table.providerConversationId
844
- ]
845
- }), index("junior_conversation_bindings_conversation_idx").on(table.conversationId)]);
846
- // src/db/schema/conversation-participants.ts
847
- /**
848
- * One Participant: a linked user on one root conversation. Rows come from
849
- * Turn Actors: the root Actor and the authors of Turn input messages, and
850
- * the root Actor again when their Identity gets its User later. Thread
851
- * context authors do not get a row. Access and feeds read only these rows.
852
- * An unsubscribed row keeps access but leaves the active feed.
853
- */
854
- const juniorConversationParticipants = pgTable("junior_conversation_participants", {
855
- userId: text("user_id").notNull().references(() => juniorUsers.id),
856
- rootConversationId: text("root_conversation_id").notNull().references(() => juniorConversations.conversationId),
857
- lastMessageAt: timestamptz("last_message_at").notNull(),
858
- pinnedAt: timestamptz("pinned_at"),
859
- /**
860
- * The viewer's place for this pin in the Pinned section, from a drag
861
- * reorder. Null until the first reorder, and cleared on unpin and
862
- * re-pin. Null pins sort first, by activity.
863
- */
864
- pinPosition: integer("pin_position"),
865
- /**
866
- * Per-conversation auto-archive choice for this user. Null uses the
867
- * user's `autoArchiveDefault`.
868
- */
869
- autoArchive: boolean("auto_archive"),
870
- /**
871
- * Set when this user left the conversation. It stays out of their
872
- * active feed until they mention Junior in it again, subscribe, or pin
873
- * it. The row keeps its access, so it is not deleted.
874
- */
875
- unsubscribedAt: timestamptz("unsubscribed_at")
876
- }, (table) => [
877
- primaryKey({
878
- name: "junior_conversation_participants_user_root_pk",
879
- columns: [table.userId, table.rootConversationId]
880
- }),
881
- index("junior_conversation_participants_user_activity_idx").on(table.userId, table.lastMessageAt.desc()),
882
- index("junior_conversation_participants_root_idx").on(table.rootConversationId),
883
- index("junior_conversation_participants_auto_archive_idx").on(table.userId).where(sql`${table.autoArchive}`),
884
- index("junior_conversation_participants_unsubscribed_idx").on(table.userId, table.rootConversationId).where(sql`${table.unsubscribedAt} is not null`)
885
- ]);
886
- // src/db/schema/conversation-read-positions.ts
887
- /**
888
- * How far one signed-in user has read one Conversation transcript.
889
- *
890
- * `last_read_seq` is the event sequence of the last transcript row the user
891
- * saw. It only moves forward, so clients on several devices can write in any
892
- * order.
893
- */
894
- const juniorConversationReadPositions = pgTable("junior_conversation_read_positions", {
895
- userId: text("user_id").notNull().references(() => juniorUsers.id),
896
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId),
897
- lastReadSeq: integer("last_read_seq").notNull(),
898
- updatedAt: timestamptz("updated_at").notNull()
899
- }, (table) => [primaryKey({
900
- name: "junior_conversation_read_positions_user_conversation_pk",
901
- columns: [table.userId, table.conversationId]
902
- })]);
903
- // src/db/schema/agent-invocations.ts
904
- const juniorAgentBindings = pgTable("junior_agent_bindings", {
905
- parentConversationId: text("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
906
- name: text("name").notNull(),
907
- childConversationId: text("child_conversation_id").notNull().references(() => juniorConversations.conversationId)
908
- }, (table) => [primaryKey({ columns: [table.parentConversationId, table.name] }), uniqueIndex("junior_agent_bindings_child_idx").on(table.childConversationId)]);
909
- const juniorAgentInvocations = pgTable("junior_agent_invocations", {
910
- invocationId: text("invocation_id").primaryKey(),
911
- parentConversationId: text("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
912
- childConversationId: text("child_conversation_id").notNull().references(() => juniorConversations.conversationId),
913
- agentName: text("agent_name"),
914
- input: text("input").notNull(),
915
- title: text("title"),
916
- actor: jsonb("actor_json").$type().notNull(),
917
- credentialContext: jsonb("credential_context_json").$type(),
918
- source: jsonb("source_json").$type().notNull(),
919
- destination: jsonb("destination_json").$type().notNull(),
920
- destinationVisibility: text("destination_visibility").$type(),
921
- agentType: text("agent_type").$type(),
922
- fork: boolean("fork").notNull().default(false),
923
- reasoningLevel: text("reasoning_level").$type(),
924
- parentToolCallId: text("parent_tool_call_id"),
925
- status: text("status").$type().notNull(),
926
- mailboxStatus: text("mailbox_status").$type().notNull(),
927
- parentMailboxStatus: text("parent_mailbox_status").$type(),
928
- result: text("result"),
929
- errorMessage: text("error_message"),
930
- createdAt: timestamptz("created_at").notNull(),
931
- updatedAt: timestamptz("updated_at").notNull(),
932
- terminalAt: timestamptz("terminal_at")
933
- }, (table) => [
934
- index("junior_agent_invocations_child_idx").on(table.childConversationId),
935
- index("junior_agent_invocations_mailbox_idx").on(table.mailboxStatus, table.createdAt),
936
- index("junior_agent_invocations_parent_mailbox_idx").on(table.parentMailboxStatus, table.terminalAt)
937
- ]);
938
- // src/db/schema/location-configurations.ts
939
- /** Durable user configuration entries scoped to provider Locations. */
940
- const juniorLocationConfigurations = pgTable("junior_location_configurations", {
941
- locationId: text("location_id").notNull().references(() => juniorDestinations.id, { onDelete: "cascade" }),
942
- key: text("key").notNull(),
943
- value: text("value").notNull(),
944
- updatedAt: timestamptz("updated_at").notNull(),
945
- updatedBy: text("updated_by"),
946
- source: text("source"),
947
- expiresAt: text("expires_at")
948
- }, (table) => [primaryKey({ columns: [table.locationId, table.key] })]);
949
- // src/db/schema/automation-versions.ts
950
- /** One saved Automation definition. Lifecycle and scheduler state are not versioned. */
951
- const juniorAutomationVersions = pgTable("junior_automation_versions", {
952
- automationId: text("automation_id").notNull(),
953
- /** Starts at 1 and increases by 1 for each saved definition change. */
954
- version: integer("version").notNull(),
955
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
956
- /** Slack principal that saved this definition. Null when unknown. */
957
- editedBy: jsonb("edited_by"),
958
- definition: jsonb("definition").notNull()
959
- }, (table) => [primaryKey({
960
- name: "junior_automation_versions_pk",
961
- columns: [table.automationId, table.version]
962
- }), foreignKey({
963
- name: "junior_automation_versions_automation_id_fk",
964
- columns: [table.automationId],
965
- foreignColumns: [juniorAutomations.id]
966
- }).onDelete("cascade")]);
967
- // src/db/schema/automation-runs.ts
968
- /**
969
- * One dispatch of an Automation, from claim or dispatch to its outcome. A
970
- * Scheduled automation run id is `<automation id>:<scheduled time>`. An event
971
- * automation run id is its dispatch id. Automation code sets
972
- * `conversation_id` when it dispatches the run. A run that was skipped, or
973
- * that failed before dispatch, has no Conversation.
974
- *
975
- * `automation_version` is the Automation version that the run dispatched. It
976
- * shows which instruction ran and who saved it after the definition changes.
977
- * It is null before dispatch, and when no saved version matched.
978
- */
979
- const juniorAutomationRuns = pgTable("junior_automation_runs", {
980
- id: text("id").primaryKey(),
981
- automationId: text("automation_id").notNull().references(() => juniorAutomations.id, { onDelete: "cascade" }),
982
- conversationId: text("conversation_id").unique().references(() => juniorConversations.conversationId),
983
- status: text("status").$type().notNull(),
984
- automationVersion: integer("automation_version"),
985
- scheduledForMs: bigint("scheduled_for_ms", { mode: "number" }),
986
- attempt: integer("attempt"),
987
- claimedAtMs: bigint("claimed_at_ms", { mode: "number" }),
988
- dispatchId: text("dispatch_id"),
989
- startedAtMs: bigint("started_at_ms", { mode: "number" }),
990
- completedAtMs: bigint("completed_at_ms", { mode: "number" }),
991
- errorMessage: text("error_message"),
992
- resultMessageTs: text("result_message_ts"),
993
- costMicroUsd: bigint("cost_micro_usd", { mode: "number" })
994
- }, (table) => [
995
- foreignKey({
996
- name: "junior_automation_runs_automation_version_fk",
997
- columns: [table.automationId, table.automationVersion],
998
- foreignColumns: [juniorAutomationVersions.automationId, juniorAutomationVersions.version]
999
- }),
1000
- check("junior_automation_runs_status_check", sql`${table.status} in ('pending', 'running', 'completed', 'failed', 'blocked', 'skipped')`),
1001
- index("junior_automation_runs_automation_idx").on(table.automationId, table.completedAtMs),
1002
- index("junior_automation_runs_completed_idx").on(table.completedAtMs),
1003
- index("junior_automation_runs_incomplete_idx").on(table.automationId, table.scheduledForMs).where(sql`${table.status} in ('pending', 'running')`)
1004
- ]);
1005
- // src/db/schema/automations.ts
1006
- /**
1007
- * One row per Automation of either kind. `record` holds the fields that have
1008
- * no column. Each write also copies the nested fields that queries filter or
1009
- * search on into columns: `team_id`, `channel_id`, `creator_slack_user_id`,
1010
- * the task `instruction` or `skill`, and the event trigger `namespace` and
1011
- * `identifier`. Exactly one of `instruction` and `skill` is set, by the task
1012
- * kind. A skill's context is only in `record`. An event trigger with no
1013
- * identifier runs for every resource of its namespace, so its `identifier` is
1014
- * null. The match index finds those rows with `identifier is null`.
1015
- */
1016
- const juniorAutomations = pgTable("junior_automations", {
1017
- id: text("id").primaryKey(),
1018
- kind: text("kind").$type().notNull(),
1019
- teamId: text("team_id").notNull(),
1020
- channelId: text("channel_id").notNull(),
1021
- creatorSlackUserId: text("creator_slack_user_id").notNull(),
1022
- /** Junior identity that created the Automation. It decides ownership. */
1023
- creatorIdentityId: text("creator_identity_id").notNull().references(() => juniorIdentities.id),
1024
- status: text("status").$type().notNull(),
1025
- /** Why a run blocked this Automation, until its creator resumes it. */
1026
- statusReason: text("status_reason"),
1027
- title: text("title"),
1028
- /** The instruction of an instruction task. Null for a skill task. */
1029
- instruction: text("instruction"),
1030
- /** The skill of a skill task. Null for an instruction task. */
1031
- skill: text("skill"),
1032
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
1033
- nextRunAtMs: bigint("next_run_at_ms", { mode: "number" }),
1034
- runNowAtMs: bigint("run_now_at_ms", { mode: "number" }),
1035
- /**
1036
- * The latest run with an outcome. The list reads its end time and status
1037
- * to order by activity and to find failed last runs.
1038
- * `refreshAutomationLastRun` sets it after each run write. A purged run
1039
- * clears it.
1040
- */
1041
- lastRunId: text("last_run_id").references(() => juniorAutomationRuns.id, { onDelete: "set null" }),
1042
- /**
1043
- * When core last saw this Automation recover after a person dismissed
1044
- * its alert. A dismissed alert hides the Automation's alerts until then.
1045
- */
1046
- alertRecoveredAtMs: bigint("alert_recovered_at_ms", { mode: "number" }),
1047
- namespace: text("namespace"),
1048
- identifier: text("identifier"),
1049
- record: jsonb("record").$type().notNull()
1050
- }, (table) => [
1051
- check("junior_automations_kind_check", sql`${table.kind} in ('scheduled', 'event')`),
1052
- check("junior_automations_status_check", sql`${table.status} in ('active', 'blocked', 'paused', 'completed', 'deleted')`),
1053
- check("junior_automations_task_check", sql`(${table.instruction} is null) <> (${table.skill} is null)`),
1054
- check("junior_automations_record_check", sql`jsonb_typeof(${table.record}) = 'object'`),
1055
- check("junior_automations_trigger_check", sql`(${table.kind} = 'scheduled' and ${table.namespace} is null and ${table.identifier} is null) or (${table.kind} = 'event' and ${table.namespace} is not null and ${table.nextRunAtMs} is null and ${table.runNowAtMs} is null and ${table.status} <> 'completed')`),
1056
- index("junior_automations_team_idx").on(table.teamId, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`),
1057
- index("junior_automations_creator_identity_idx").on(table.creatorIdentityId, table.createdAtMs, table.id),
1058
- index("junior_automations_creator_slack_idx").on(table.teamId, table.creatorSlackUserId).where(sql`${table.status} <> 'deleted'`),
1059
- index("junior_automations_last_run_idx").on(table.lastRunId),
1060
- index("junior_automations_run_now_due_idx").on(table.runNowAtMs, table.createdAtMs, table.id).where(sql`${table.status} = 'active' AND ${table.runNowAtMs} IS NOT NULL`),
1061
- index("junior_automations_next_run_due_idx").on(table.nextRunAtMs, table.createdAtMs, table.id).where(sql`${table.status} = 'active' AND ${table.nextRunAtMs} IS NOT NULL`),
1062
- index("junior_automations_skill_idx").on(table.skill, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted' AND ${table.skill} IS NOT NULL`),
1063
- index("junior_automations_match_idx").on(table.namespace, table.identifier, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`)
1064
- ]);
1065
- // src/db/schema/inbox-items.ts
1066
- /**
1067
- * One Inbox item: something that needs a person. An action item stores its
1068
- * `request`, and
1069
- * its `answer` after an assignee submits it. `closed_at` is set for `done`
1070
- * and `dismissed`. `closed_by_user_id` is null when an agent closed it.
1071
- * `owner_kind` and `owner_id` name its owner. The owner kind decides how the
1072
- * item gets its visibility and tenant, and where the Inbox stacks it. The id
1073
- * has no foreign key, because it can name a row of more than one table.
1074
- */
1075
- const juniorInboxItems = pgTable("junior_inbox_items", {
1076
- id: text("id").primaryKey(),
1077
- kind: text("kind").$type().notNull(),
1078
- status: text("status").$type().notNull(),
1079
- /**
1080
- * `private` when the Conversation that added it is not public. A private
1081
- * item stays private and links only to that Conversation.
1082
- */
1083
- visibility: text("visibility").$type().notNull(),
1084
- title: text("title").notNull(),
1085
- body: text("body").notNull(),
1086
- request: jsonb("request").$type(),
1087
- answer: jsonb("answer").$type(),
1088
- assignedToEveryone: boolean("assigned_to_everyone").notNull().default(false),
1089
- dedupeKey: text("dedupe_key").notNull(),
1090
- subjectId: text("subject_id"),
1091
- subjectTitle: text("subject_title"),
1092
- subjectUrl: text("subject_url"),
1093
- /** The parsed subject title of a code change (`InboxItemSubjectTitleParts`). */
1094
- subjectTitleParts: jsonb("subject_title_parts").$type(),
1095
- ownerKind: text("owner_kind").$type().notNull().default("conversation"),
1096
- ownerId: text("owner_id").notNull(),
1097
- /**
1098
- * Turn of the agent that added the item, or that last added it again with
1099
- * its dedupe key. Null for a plugin item, which has no Turn.
1100
- */
1101
- addedByTurnId: text("added_by_turn_id"),
1102
- /**
1103
- * Provider tenant, such as a Slack workspace, of the Conversation that
1104
- * added the item. A public item is visible only inside it.
1105
- */
1106
- provider: text("provider"),
1107
- providerTenantId: text("provider_tenant_id"),
1108
- automationId: text("automation_id").references(() => juniorAutomations.id, { onDelete: "set null" }),
1109
- closedAt: timestamptz("closed_at"),
1110
- closedByUserId: text("closed_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
1111
- closeReason: text("close_reason"),
1112
- createdAt: timestamptz("created_at").notNull(),
1113
- updatedAt: timestamptz("updated_at").notNull()
1114
- }, (table) => [
1115
- check("junior_inbox_items_kind_check", sql`(${table.kind} = 'notice' and ${table.request} is null and ${table.answer} is null) or (${table.kind} = 'action' and (${table.request} is not null or ((${table.dedupeKey} like 'plugin:%' or ${table.dedupeKey} like 'automation:%') and ${table.answer} is null)))`),
1116
- check("junior_inbox_items_owner_check", sql`(${table.ownerKind} = 'conversation' and ${table.dedupeKey} not like 'automation:%') or (${table.ownerKind} = 'automation' and ${table.dedupeKey} like 'automation:%')`),
1117
- check("junior_inbox_items_status_check", sql`(${table.status} = 'open' and ${table.closedAt} is null) or (${table.status} in ('done', 'dismissed') and ${table.closedAt} is not null)`),
1118
- check("junior_inbox_items_tenant_check", sql`(${table.provider} is null) = (${table.providerTenantId} is null)`),
1119
- check("junior_inbox_items_visibility_check", sql`${table.visibility} = 'public' or not ${table.assignedToEveryone}`),
1120
- uniqueIndex("junior_inbox_items_open_dedupe_uidx").on(sql`coalesce(${table.provider}, '')`, sql`coalesce(${table.providerTenantId}, '')`, table.dedupeKey).where(sql`${table.status} = 'open'`),
1121
- index("junior_inbox_items_status_idx").on(table.status, table.updatedAt, table.id),
1122
- index("junior_inbox_items_subject_idx").on(table.subjectId, table.status),
1123
- index("junior_inbox_items_owner_idx").on(table.ownerKind, table.ownerId),
1124
- index("junior_inbox_items_open_action_owner_idx").on(table.ownerId).where(sql`${table.status} = 'open' and ${table.kind} = 'action'`),
1125
- index("junior_inbox_items_automation_idx").on(table.automationId, table.status),
1126
- index("junior_inbox_items_answered_idx").on(table.ownerId, table.closedByUserId, table.closedAt).where(sql`${table.answer} is not null`)
1127
- ]);
1128
- /** The assigned Users of an Inbox item. Everyone is a flag on the item. */
1129
- const juniorInboxItemAssignees = pgTable("junior_inbox_item_assignees", {
1130
- itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1131
- userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" })
1132
- }, (table) => [primaryKey({ columns: [table.itemId, table.userId] }), index("junior_inbox_item_assignees_user_idx").on(table.userId)]);
1133
- /** The Conversations linked to an Inbox item. */
1134
- const juniorInboxItemConversations = pgTable("junior_inbox_item_conversations", {
1135
- itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1136
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" })
1137
- }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] }), index("junior_inbox_item_conversations_conversation_idx").on(table.conversationId)]);
1138
- /**
1139
- * The Slack message that shows an Inbox item in one linked Slack thread.
1140
- * Junior updates it in place after each change.
1141
- */
1142
- const juniorInboxItemSlackCards = pgTable("junior_inbox_item_slack_cards", {
1143
- itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1144
- conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
1145
- teamId: text("team_id").notNull(),
1146
- channelId: text("channel_id").notNull(),
1147
- messageTs: text("message_ts").notNull()
1148
- }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] })]);
1149
- // src/db/schema/inbox-snoozes.ts
1150
- /**
1151
- * One person's snooze of one Inbox item. A `snoozed` row hides the item
1152
- * from that person's Inbox until one of its triggers fires. `woken` and
1153
- * `cancelled` are final. The item's own status says whether it resolved.
1154
- * A trigger that wakes it records why in `wake_reason`, which only that
1155
- * person sees, until they open or act on the item.
1156
- */
1157
- const juniorInboxSnoozes = pgTable("junior_inbox_snoozes", {
1158
- id: text("id").primaryKey(),
1159
- userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1160
- inboxItemId: text("inbox_item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1161
- state: text("state").$type().notNull(),
1162
- wakeReason: jsonb("wake_reason").$type(),
1163
- createdAt: timestamptz("created_at").notNull()
1164
- }, (table) => [
1165
- check("junior_inbox_snoozes_state_check", sql`${table.state} in ('snoozed', 'woken', 'cancelled')`),
1166
- uniqueIndex("junior_inbox_snoozes_snoozed_uidx").on(table.userId, table.inboxItemId).where(sql`${table.state} = 'snoozed'`),
1167
- index("junior_inbox_snoozes_settled_idx").on(table.createdAt).where(sql`${table.state} <> 'snoozed'`),
1168
- index("junior_inbox_snoozes_inbox_item_idx").on(table.inboxItemId)
1169
- ]);
1170
- /**
1171
- * An Event that ends a snooze. `wake` brings the item back; `resolve`
1172
- * dismisses the item and cancels the snooze. A snooze's triggers join with
1173
- * OR: the first to fire wins, and the snooze ignores the rest. Time is a
1174
- * `timer.fired` Event like any other.
1175
- */
1176
- const juniorInboxSnoozeTriggers = pgTable("junior_inbox_snooze_triggers", {
1177
- snoozeId: text("snooze_id").notNull().references(() => juniorInboxSnoozes.id, { onDelete: "cascade" }),
1178
- outcome: text("outcome").$type().notNull(),
1179
- namespace: text("namespace").notNull(),
1180
- identifier: text("identifier").notNull(),
1181
- eventType: text("event_type").notNull(),
1182
- match: jsonb("match").$type()
1183
- }, (table) => [
1184
- check("junior_inbox_snooze_triggers_outcome_check", sql`${table.outcome} in ('wake', 'resolve')`),
1185
- index("junior_inbox_snooze_triggers_event_idx").on(table.namespace, table.identifier, table.eventType),
1186
- index("junior_inbox_snooze_triggers_snooze_idx").on(table.snoozeId)
1187
- ]);
1188
- // src/db/schema/stats.ts
1189
- /**
1190
- * Daily named counters used by Junior and loaded plugins.
1191
- * TODO: store hour keys when dashboard 24h workspace usage needs hourly bars.
1192
- * `date` is a Postgres date column, so counters stay day-bucketed today.
1193
- */
1194
- const juniorStats = pgTable("junior_stats", {
1195
- date: date("date", { mode: "string" }).notNull(),
1196
- namespace: text("namespace").notNull(),
1197
- metric: text("metric").notNull(),
1198
- name: text("name").notNull(),
1199
- count: bigint("value", { mode: "number" }).notNull().default(0),
1200
- legacyCount: integer("count").notNull().default(0)
1201
- }, (table) => [primaryKey({
1202
- name: "junior_stats_date_namespace_metric_name_pk",
1203
- columns: [
1204
- table.date,
1205
- table.namespace,
1206
- table.metric,
1207
- table.name
1208
- ]
1209
- })]);
1210
- // src/db/schema/todos.ts
1211
- /**
1212
- * Gives each To-do its id and each change its version. One sequence serves
1213
- * every Conversation, so history that a fork copies from its parent never
1214
- * shows a version that the fork's own To-dos reuse.
1215
- */
1216
- const juniorTodoVersionSeq = pgSequence("junior_todo_version_seq");
1217
- /**
1218
- * One To-do: work that a Conversation has not finished. At most one
1219
- * assignee: a Conversation (the list's own agent or one of its child agents)
1220
- * or a User. A To-do without one belongs to the list's own agent.
1221
- * `changed_by_user_id` is set when a person made the latest change.
1222
- * `changed_by_conversation_id` is set when the assignee child agent closed
1223
- * it, or core closed it on that child's result. Both are null when the
1224
- * list's own agent made the latest change. Both User keys block deleting the User, as
1225
- * Conversation participants do: setting them null would turn a person's
1226
- * To-do into the agent's and hide an unseen change from `<todo-delta>`.
1227
- */
1228
- const juniorTodos = pgTable("junior_todos", {
1229
- conversationId: text("conversation_id").notNull(),
1230
- id: bigint("id", { mode: "number" }).notNull(),
1231
- title: text("title").notNull(),
1232
- notes: text("notes"),
1233
- status: text("status").$type().notNull(),
1234
- assigneeConversationId: text("assignee_conversation_id"),
1235
- assigneeUserId: text("assignee_user_id").references(() => juniorUsers.id),
1236
- version: bigint("version", { mode: "number" }).notNull(),
1237
- changedByUserId: text("changed_by_user_id").references(() => juniorUsers.id),
1238
- changedByConversationId: text("changed_by_conversation_id"),
1239
- createdAt: timestamptz("created_at").notNull(),
1240
- updatedAt: timestamptz("updated_at").notNull()
1241
- }, (table) => [
1242
- primaryKey({
1243
- name: "junior_todos_pk",
1244
- columns: [table.conversationId, table.id]
1245
- }),
1246
- foreignKey({
1247
- name: "junior_todos_conversation_id_fk",
1248
- columns: [table.conversationId],
1249
- foreignColumns: [juniorConversations.conversationId]
1250
- }).onDelete("cascade"),
1251
- check("junior_todos_status_check", sql`${table.status} in ('open', 'in_progress', 'done', 'dropped')`),
1252
- check("junior_todos_assignee_check", sql`${table.assigneeConversationId} is null or ${table.assigneeUserId} is null`)
1253
- ]);
1254
- // src/db/schema/push-subscriptions.ts
1255
- /**
1256
- * One browser Web Push subscription for one user. A user can have one row for
1257
- * each browser or installed dashboard app. The push service owns the endpoint.
1258
- */
1259
- const juniorPushSubscriptions = pgTable("junior_push_subscriptions", {
1260
- id: text("id").primaryKey(),
1261
- userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1262
- endpoint: text("endpoint").notNull(),
1263
- p256dh: text("p256dh").notNull(),
1264
- auth: text("auth").notNull(),
1265
- createdAt: timestamptz("created_at").notNull(),
1266
- updatedAt: timestamptz("updated_at").notNull()
1267
- }, (table) => [uniqueIndex("junior_push_subscriptions_endpoint_uidx").on(table.endpoint), index("junior_push_subscriptions_user_idx").on(table.userId)]);
1268
- // src/db/schema/workspaces.ts
1269
- /** Named recipe used to prepare a reusable Sandbox. */
1270
- const juniorWorkspaces = pgTable("junior_workspaces", {
1271
- id: text("id").primaryKey(),
1272
- name: text("name").notNull(),
1273
- setupScript: text("setup_script").notNull().default(""),
1274
- vcpus: integer("vcpus"),
1275
- createdAt: timestamptz("created_at").notNull(),
1276
- updatedAt: timestamptz("updated_at").notNull()
1277
- }, (table) => [uniqueIndex("junior_workspaces_name_idx").on(table.name)]);
1278
- /** Repository included in one Workspace recipe. */
1279
- const juniorWorkspaceRepos = pgTable("junior_workspace_repos", {
1280
- workspaceId: text("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
1281
- provider: text("provider").notNull(),
1282
- repo: text("repo").notNull()
1283
- }, (table) => [primaryKey({ columns: [
1284
- table.workspaceId,
1285
- table.provider,
1286
- table.repo
1287
- ] })]);
1288
- // src/db/schema/snapshots.ts
1289
- /**
1290
- * Sandbox snapshot build and ready artifact for one Workspace recipe.
1291
- * A ready row keeps its builder owner until the snapshot is discarded.
1292
- */
1293
- const juniorSnapshots = pgTable("junior_snapshots", {
1294
- id: text("id").primaryKey(),
1295
- workspaceId: text("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
1296
- profileHash: text("profile_hash").notNull(),
1297
- status: text("status").$type().notNull(),
1298
- snapshotId: text("snapshot_id"),
1299
- buildDurationMs: integer("build_duration_ms"),
1300
- sizeBytes: bigint("size_bytes", { mode: "number" }),
1301
- generatedAt: timestamptz("generated_at"),
1302
- buildStartedAt: timestamptz("build_started_at"),
1303
- buildPhase: text("build_phase").$type(),
1304
- buildSandboxName: text("build_sandbox_name"),
1305
- buildCommandId: text("build_command_id"),
1306
- buildError: text("build_error"),
1307
- createdAt: timestamptz("created_at").notNull(),
1308
- updatedAt: timestamptz("updated_at").notNull()
1309
- }, (table) => [
1310
- check("junior_snapshots_status_check", sql`${table.status} in ('building', 'failed', 'ready')`),
1311
- check("junior_snapshots_build_phase_check", sql`${table.buildPhase} is null or ${table.buildPhase} in ('created', 'dependencies_installed', 'repositories_prepared')`),
1312
- check("junior_snapshots_ready_fields_check", sql`${table.status} <> 'ready' or (${table.snapshotId} is not null and ${table.buildDurationMs} is not null and ${table.generatedAt} is not null)`),
1313
- check("junior_snapshots_build_fields_check", sql`${table.status} = 'ready' or (${table.buildStartedAt} is not null and ${table.buildPhase} is not null)`),
1314
- check("junior_snapshots_build_duration_check", sql`${table.buildDurationMs} is null or ${table.buildDurationMs} >= 0`),
1315
- check("junior_snapshots_size_bytes_check", sql`${table.sizeBytes} is null or ${table.sizeBytes} >= 0`),
1316
- uniqueIndex("junior_snapshots_snapshot_id_uidx").on(table.snapshotId),
1317
- index("junior_snapshots_workspace_idx").on(table.workspaceId),
1318
- index("junior_snapshots_workspace_profile_status_idx").on(table.workspaceId, table.profileHash, table.status),
1319
- uniqueIndex("junior_snapshots_active_build_uidx").on(table.workspaceId, table.profileHash).where(sql`${table.status} = 'building'`),
1320
- index("junior_snapshots_workspace_status_idx").on(table.workspaceId, table.status)
1321
- ]);
1322
- // src/db/schema.ts
1323
- const juniorSqlSchema = {
1324
- juniorArtifacts,
1325
- juniorAttachmentUploads,
1326
- juniorAttachments,
1327
- juniorMessageAttachments,
1328
- juniorCodeChanges,
1329
- juniorCodeRepositories,
1330
- juniorConversationAnnotations,
1331
- juniorApiTokens,
1332
- juniorAgentBindings,
1333
- juniorAgentInvocations,
1334
- juniorConversationEvents,
1335
- juniorConversationMetrics,
1336
- juniorConversationEmbeddings,
1337
- juniorConversationEventEmbeddings,
1338
- juniorConversationEventLexemes,
1339
- juniorConversationBriefs,
1340
- juniorConversationBindings,
1341
- juniorConversationParticipants,
1342
- juniorConversationReadPositions,
1343
- juniorConversations,
1344
- juniorLocationConfigurations,
1345
- juniorMemoryEmbeddings,
1346
- juniorMemoryMemories,
1347
- juniorMemorySignals,
1348
- juniorDestinations,
1349
- juniorIdentities,
1350
- juniorInboxSnoozes,
1351
- juniorInboxSnoozeTriggers,
1352
- juniorInboxItemAssignees,
1353
- juniorInboxItemConversations,
1354
- juniorInboxItemSlackCards,
1355
- juniorInboxItems,
1356
- juniorTodos,
1357
- juniorPushSubscriptions,
1358
- juniorSnapshots,
1359
- juniorStats,
1360
- juniorAutomationRuns,
1361
- juniorAutomationVersions,
1362
- juniorAutomations,
1363
- juniorUsers,
1364
- juniorWorkspaceRepos,
1365
- juniorWorkspaces
1366
- };
1367
- // src/db/info-messages.ts
1368
- /**
1369
- * Send Postgres `INFO` messages from every pool connection to `onInfo`.
1370
- * A migration uses `RAISE INFO` to report its result to the operator.
1371
- * Postgres always sends `INFO` to the client. Its own messages, such as
1372
- * "already exists, skipping", are `NOTICE`, so they stay out.
1373
- */
1374
- function forwardInfoMessages(pool, onInfo) {
1375
- pool.on("connect", (client) => {
1376
- client.on("notice", (notice) => {
1377
- if (notice.severity === "INFO" && notice.message) onInfo(notice.message);
1378
- });
1379
- });
1380
- }
1381
- // src/db/postgres-error.ts
1382
- const MAX_CAUSE_DEPTH = 5;
1383
- /**
1384
- * Return whether a PostgreSQL failure, or an error that it wraps as `cause`,
1385
- * has the requested SQLSTATE.
1386
- */
1387
- function isPostgresErrorCode(error, code) {
1388
- let current = error;
1389
- for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === "object" && current !== null; depth += 1) {
1390
- if ("code" in current && current.code === code) return true;
1391
- current = "cause" in current ? current.cause : void 0;
1392
- }
1393
- return false;
1394
- }
1395
- // src/db/migrate.ts
1396
- const LOCK_TIMEOUT_MS = 5e3;
1397
- const LOCK_ATTEMPTS = 5;
1398
- const LOCK_RETRY_DELAY_MS = 5e3;
1399
- const LOCK_NOT_AVAILABLE = "55P03";
1400
- const MIGRATION_LOCK_POLL_MS = 1e3;
1401
- const CONCURRENT_STATEMENT = /^(?:CREATE (?:UNIQUE )?INDEX|DROP INDEX|REINDEX)\b[^;]*\bCONCURRENTLY\b/i;
1402
- const CONCURRENT_INDEX = /^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS "([a-z0-9_]+)" /i;
1403
- /** Statement text without its leading comment lines. */
1404
- function sqlOf(statement) {
1405
- return statement.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").trim();
1406
- }
1407
- /**
1408
- * Index builds of a migration that only builds indexes concurrently, or
1409
- * undefined for a migration that runs in a transaction.
1410
- */
1411
- function concurrentIndexes(tag, statements) {
1412
- const sql = statements.map(sqlOf).filter(Boolean);
1413
- if (!sql.some((statement) => CONCURRENT_STATEMENT.test(statement))) return;
1414
- return sql.map((statement) => {
1415
- const name = CONCURRENT_INDEX.exec(statement)?.[1];
1416
- if (!name) throw new Error(`Migration ${tag}: a migration that uses CONCURRENTLY must contain only CREATE [UNIQUE] INDEX CONCURRENTLY IF NOT EXISTS "name" statements.`);
1417
- return {
1418
- name,
1419
- statement
1420
- };
1421
- });
1422
- }
1423
- /**
1424
- * Wait for the migration lock by polling `pg_try_advisory_lock`. A session
1425
- * blocked in `pg_advisory_lock` holds a snapshot, and `CREATE INDEX
1426
- * CONCURRENTLY` waits for every older snapshot, so a second migrator that
1427
- * blocked there would deadlock with the build of the first.
1428
- */
1429
- async function waitForMigrationLock(tryLock) {
1430
- while (!await tryLock()) await new Promise((resolve) => setTimeout(resolve, MIGRATION_LOCK_POLL_MS));
1431
- }
1432
- async function retryOnLockTimeout(tag, apply) {
1433
- for (let attempt = 1;; attempt += 1) try {
1434
- await apply();
1435
- return;
1436
- } catch (error) {
1437
- if (attempt >= LOCK_ATTEMPTS || !isPostgresErrorCode(error, LOCK_NOT_AVAILABLE)) throw error;
1438
- logWarn("db.migration.lock_timeout", {
1439
- "app.db.migration.tag": tag,
1440
- "app.db.migration.attempt": attempt
1441
- });
1442
- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_DELAY_MS));
1443
- }
1444
- }
1445
- /**
1446
- * Apply pending Drizzle migrations, each in its own transaction.
1447
- *
1448
- * Drizzle's `migrate()` runs every pending migration in one transaction
1449
- * (drizzle-orm#3249), so locks from earlier migrations stay held while later
1450
- * migrations wait for theirs. That can deadlock with live traffic. This keeps
1451
- * Drizzle's journal table and skip rule, so existing databases are unaffected.
1452
- * A migration that waits too long for a lock rolls back and runs again. A
1453
- * migration that only builds indexes concurrently runs outside a transaction.
1454
- */
1455
- async function applyMigrations(executor, config) {
1456
- const schema = config.migrationsSchema ?? "drizzle";
1457
- const table = `"${schema}"."${config.migrationsTable ?? "__drizzle_migrations"}"`;
1458
- await executor.execute(`CREATE SCHEMA IF NOT EXISTS "${schema}"`);
1459
- await executor.execute(`CREATE TABLE IF NOT EXISTS ${table} (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint)`);
1460
- const [last] = await executor.query(`SELECT created_at::text AS "createdAt" FROM ${table} ORDER BY created_at DESC LIMIT 1`);
1461
- const appliedAt = Number(last?.createdAt ?? 0);
1462
- for (const migration of readMigrationFiles(config)) {
1463
- if (migration.folderMillis <= appliedAt) continue;
1464
- const tag = String(migration.folderMillis);
1465
- const recordApplied = () => executor.execute(`INSERT INTO ${table} (hash, created_at) VALUES ($1, $2)`, [migration.hash, migration.folderMillis]);
1466
- const indexes = concurrentIndexes(tag, migration.sql);
1467
- if (indexes) {
1468
- for (const { name, statement } of indexes) {
1469
- const [state] = await executor.query(`SELECT indisvalid AND indisready AS usable FROM pg_index WHERE indexrelid = to_regclass($1)`, [name]);
1470
- if (state && !state.usable) await executor.execute(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
1471
- await executor.execute(statement);
1472
- }
1473
- await recordApplied();
1474
- continue;
1475
- }
1476
- await retryOnLockTimeout(tag, async () => {
1477
- await executor.transaction(async () => {
1478
- await executor.execute(`SET LOCAL lock_timeout = ${LOCK_TIMEOUT_MS}`);
1479
- for (const statement of migration.sql) await executor.execute(statement);
1480
- await recordApplied();
1481
- });
1482
- });
1483
- }
1484
- }
1485
- // src/db/neon.ts
1486
- const POOL_MAX = 10;
1487
- function toWebSocketError(error, failure) {
1488
- if (error instanceof Error) return error;
1489
- const event = error ?? {};
1490
- const cause = event.error instanceof Error ? event.error : void 0;
1491
- const reason = typeof event.message === "string" && event.message || cause?.message || cause && `${cause.name} (no message)` || typeof event.type === "string" && event.type || String(error);
1492
- return new Error(`WebSocket ${failure}: ${reason}`, event.error === void 0 ? void 0 : { cause: event.error });
1493
- }
1494
- function warnWebSocketFailure(name, error, failure) {
1495
- const reported = toWebSocketError(error, failure);
1496
- logWarn(name, {
1497
- "app.db.driver": "neon",
1498
- "error.type": reported.name,
1499
- "exception.message": reported.message
1500
- });
1501
- }
1502
- /**
1503
- * Sends a pool query over Neon's SQL-over-HTTP endpoint when no idle
1504
- * WebSocket client is free.
1505
- *
1506
- * pg-pool reuses the newest idle client, so light polling keeps one or two
1507
- * clients warm and the rest idle out. A parallel read batch then opens about
1508
- * eight WebSockets, each with a new Postgres session. An HTTP query reuses the
1509
- * proxy's cached backend connection, so the batch skips that handshake. The
1510
- * warm path stays on WebSocket. `connect()` and transactions are unchanged.
1511
- */
1512
- var OverflowPool = class extends Pool$1 {
1513
- pendingAcquires = 0;
1514
- webSocketOnly = new AsyncLocalStorage();
1515
- sql;
1516
- dispatcher;
1517
- statementTimeoutMs;
1518
- constructor(args) {
1519
- super({
1520
- connectionString: args.connectionString,
1521
- max: POOL_MAX,
1522
- idleTimeoutMillis: 3e5,
1523
- min: 1,
1524
- statement_timeout: args.statementTimeoutMs
1525
- });
1526
- this.sql = neon(args.connectionString, { fullResults: true });
1527
- this.dispatcher = args.dispatcher;
1528
- this.statementTimeoutMs = args.statementTimeoutMs;
1529
- this.on("remove", () => this.reconnectWhenEmpty());
1530
- }
1531
- query(input, values, callback) {
1532
- const query = typeof input === "string" ? { text: input } : input;
1533
- if (callback !== void 0 || typeof values === "function" || typeof query?.text !== "string" || "submit" in query) return super.query(input, values, callback);
1534
- const params = values ?? query.values ?? [];
1535
- if (this.webSocketOnly.getStore() || this.idleCount > this.pendingAcquires || this.totalCount === 0) return this.queryWebSocket(query, params);
1536
- this.growInBackground();
1537
- return this.queryHttp(query, params);
1538
- }
1539
- growInBackground() {
1540
- setImmediate(() => {
1541
- if (this.ending || this.idleCount > 0 || this.totalCount >= POOL_MAX) return;
1542
- this.openClient();
1543
- });
1544
- }
1545
- reconnectWhenEmpty() {
1546
- setImmediate(() => {
1547
- if (this.ending || this.totalCount > 0) return;
1548
- this.openClient();
1549
- });
1550
- }
1551
- openClient() {
1552
- this.connect((error, client) => {
1553
- if (client) {
1554
- client.release();
1555
- return;
1556
- }
1557
- warnWebSocketFailure("db.pool.client.connect_failed", error, "connect failed");
1558
- });
1559
- }
1560
- /** Keep every pool query in `callback` on WebSocket. */
1561
- async onWebSocket(callback) {
1562
- return await this.webSocketOnly.run(true, callback);
1563
- }
1564
- async queryWebSocket(query, params) {
1565
- const client = await this.acquire();
1566
- try {
1567
- const result = await client.query({
1568
- ...query,
1569
- values: params
1570
- });
1571
- client.release();
1572
- return result;
1573
- } catch (error) {
1574
- client.release(error);
1575
- throw error;
1576
- }
1577
- }
1578
- acquire() {
1579
- this.pendingAcquires++;
1580
- return new Promise((resolve, reject) => {
1581
- this.connect((error, client) => {
1582
- this.pendingAcquires--;
1583
- if (client) resolve(client);
1584
- else reject(error ?? /* @__PURE__ */ new Error("pg pool returned no client"));
1585
- });
1586
- });
1587
- }
1588
- async queryHttp(query, params) {
1589
- const fetchOptions = { dispatcher: this.dispatcher };
1590
- if (this.statementTimeoutMs) fetchOptions.signal = AbortSignal.timeout(this.statementTimeoutMs);
1591
- return await withScope(async (scope) => {
1592
- scope.setAttributes({ "app.db.transport": "http" });
1593
- return await this.sql.query(query.text, params, {
1594
- arrayMode: query.rowMode === "array",
1595
- fullResults: true,
1596
- types: query.types ?? this.options.types,
1597
- fetchOptions
1598
- });
1599
- });
1600
- }
1601
- };
1602
- var NeonExecutor = class {
1603
- transactionClient = new AsyncLocalStorage();
1604
- savepointId = 0;
1605
- isolatedQueryId = 0;
1606
- pool;
1607
- dispatcher;
1608
- constructor(pool, dispatcher) {
1609
- this.pool = pool;
1610
- this.dispatcher = dispatcher;
1611
- }
1612
- db() {
1613
- return drizzle(this.queryClient(), { schema: juniorSqlSchema });
1614
- }
1615
- async execute(statement, params = []) {
1616
- await this.queryClient().query(statement, [...params]);
1617
- }
1618
- async query(statement, params = []) {
1619
- return (await this.queryClient().query(statement, [...params])).rows;
1620
- }
1621
- async queryIsolated(statement, params = []) {
1622
- const client = await this.pool.connect();
1623
- try {
1624
- return (await client.query({
1625
- name: `junior_isolated_${++this.isolatedQueryId}`,
1626
- text: statement,
1627
- values: [...params]
1628
- })).rows;
1629
- } finally {
1630
- client.release(true);
1631
- }
1632
- }
1633
- async migrate(config) {
1634
- await applyMigrations(this, config);
1635
- }
1636
- async transaction(callback) {
1637
- const existingClient = this.transactionClient.getStore();
1638
- if (existingClient) {
1639
- const savepoint = `junior_savepoint_${++this.savepointId}`;
1640
- await existingClient.query(`SAVEPOINT ${savepoint}`);
1641
- try {
1642
- const result = await callback();
1643
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1644
- return result;
1645
- } catch (error) {
1646
- await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
1647
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1648
- throw error;
1649
- }
1650
- }
1651
- const client = await this.pool.connect();
1652
- try {
1653
- await client.query("BEGIN");
1654
- const result = await this.transactionClient.run(client, callback);
1655
- await client.query("COMMIT");
1656
- return result;
1657
- } catch (error) {
1658
- await client.query("ROLLBACK");
1659
- throw error;
1660
- } finally {
1661
- client.release();
1662
- }
1663
- }
1664
- async withLock(lockName, callback) {
1665
- if (!lockName) throw new Error("SQL lock name is required");
1666
- const existingClient = this.transactionClient.getStore();
1667
- if (existingClient) {
1668
- await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1669
- return await callback();
1670
- }
1671
- const client = await this.pool.connect();
1672
- try {
1673
- await client.query("BEGIN");
1674
- return await this.transactionClient.run(client, async () => {
1675
- try {
1676
- await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1677
- const result = await callback();
1678
- await client.query("COMMIT");
1679
- return result;
1680
- } catch (error) {
1681
- await client.query("ROLLBACK");
1682
- throw error;
1683
- }
1684
- });
1685
- } finally {
1686
- client.release();
1687
- }
1688
- }
1689
- async withMigrationLock(migrationTable, callback) {
1690
- const client = await this.pool.connect();
1691
- const lockName = `junior:migrate:${migrationTable}`;
1692
- try {
1693
- await waitForMigrationLock(async () => {
1694
- return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
1695
- });
1696
- return await this.pool.onWebSocket(callback);
1697
- } finally {
1698
- client.release(true);
1699
- }
1700
- }
1701
- async close() {
1702
- await this.pool.end();
1703
- await this.dispatcher.close();
1704
- }
1705
- queryClient() {
1706
- return this.transactionClient.getStore() ?? this.pool;
1707
- }
1708
- };
1709
- /** Create the shared Neon-backed Junior SQL executor. */
1710
- function createNeonJuniorSqlExecutor(args) {
1711
- const { onInfo, ...poolArgs } = args;
1712
- const dispatcher = new Agent({ allowH2: true });
1713
- const pool = new OverflowPool({
1714
- ...poolArgs,
1715
- dispatcher
1716
- });
1717
- pool.on("error", (error) => {
1718
- warnWebSocketFailure("db.pool.client.failed", error, "idle client failed");
1719
- });
1720
- if (onInfo) forwardInfoMessages(pool, onInfo);
1721
- return new NeonExecutor(pool, dispatcher);
1722
- }
1723
- // src/db/postgres.ts
1724
- const { Pool } = pg;
1725
- var PostgresExecutor = class {
1726
- transactionClient = new AsyncLocalStorage();
1727
- savepointId = 0;
1728
- isolatedQueryId = 0;
1729
- pool;
1730
- constructor(pool) {
1731
- this.pool = pool;
1732
- }
1733
- db() {
1734
- return drizzle$1(this.queryClient(), { schema: juniorSqlSchema });
1735
- }
1736
- async execute(statement, params = []) {
1737
- await this.queryClient().query(statement, [...params]);
1738
- }
1739
- async query(statement, params = []) {
1740
- return (await this.queryClient().query(statement, [...params])).rows;
1741
- }
1742
- async queryIsolated(statement, params = []) {
1743
- const client = await this.pool.connect();
1744
- try {
1745
- return (await client.query({
1746
- name: `junior_isolated_${++this.isolatedQueryId}`,
1747
- text: statement,
1748
- values: [...params]
1749
- })).rows;
1750
- } finally {
1751
- client.release(true);
1752
- }
1753
- }
1754
- async migrate(config) {
1755
- await applyMigrations(this, config);
1756
- }
1757
- async transaction(callback) {
1758
- const existingClient = this.transactionClient.getStore();
1759
- if (existingClient) {
1760
- const savepoint = `junior_savepoint_${++this.savepointId}`;
1761
- await existingClient.query(`SAVEPOINT ${savepoint}`);
1762
- try {
1763
- const result = await callback();
1764
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1765
- return result;
1766
- } catch (error) {
1767
- await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
1768
- await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
1769
- throw error;
1770
- }
1771
- }
1772
- const client = await this.pool.connect();
1773
- try {
1774
- await client.query("BEGIN");
1775
- const result = await this.transactionClient.run(client, callback);
1776
- await client.query("COMMIT");
1777
- return result;
1778
- } catch (error) {
1779
- await client.query("ROLLBACK");
1780
- throw error;
1781
- } finally {
1782
- client.release();
1783
- }
1784
- }
1785
- async withLock(lockName, callback) {
1786
- if (!lockName) throw new Error("SQL lock name is required");
1787
- const existingClient = this.transactionClient.getStore();
1788
- if (existingClient) {
1789
- await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1790
- return await callback();
1791
- }
1792
- const client = await this.pool.connect();
1793
- try {
1794
- await client.query("BEGIN");
1795
- return await this.transactionClient.run(client, async () => {
1796
- try {
1797
- await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
1798
- const result = await callback();
1799
- await client.query("COMMIT");
1800
- return result;
1801
- } catch (error) {
1802
- await client.query("ROLLBACK");
1803
- throw error;
1804
- }
1805
- });
1806
- } finally {
1807
- client.release();
1808
- }
1809
- }
1810
- async withMigrationLock(migrationTable, callback) {
1811
- const client = await this.pool.connect();
1812
- const lockName = `junior:migrate:${migrationTable}`;
1813
- try {
1814
- await waitForMigrationLock(async () => {
1815
- return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
1816
- });
1817
- return await callback();
1818
- } finally {
1819
- client.release(true);
1820
- }
1821
- }
1822
- async close() {
1823
- await this.pool.end();
1824
- }
1825
- queryClient() {
1826
- return this.transactionClient.getStore() ?? this.pool;
1827
- }
1828
- };
1829
- /** Create the shared Node Postgres-backed Junior SQL executor. */
1830
- function createPostgresJuniorSqlExecutor(args) {
1831
- const pool = new Pool({
1832
- application_name: args.applicationName,
1833
- connectionString: args.connectionString,
1834
- max: 3,
1835
- statement_timeout: args.statementTimeoutMs
1836
- });
1837
- pool.on("error", (error) => {
1838
- logException(error, "db.pool.client.failed", { "app.db.driver": "postgres" });
1839
- });
1840
- if (args.onInfo) forwardInfoMessages(pool, args.onInfo);
1841
- return new PostgresExecutor(pool);
1842
- }
1843
- // src/db/executor.ts
1844
- /** Create the SQL executor appropriate for the configured database URL. */
1845
- function createJuniorSqlExecutor(args) {
1846
- const statementTimeoutMs = args.statementTimeoutMs ?? 3e4;
1847
- if (args.driver === "postgres") return createPostgresJuniorSqlExecutor({
1848
- connectionString: args.connectionString,
1849
- onInfo: args.onInfo,
1850
- statementTimeoutMs
1851
- });
1852
- return createNeonJuniorSqlExecutor({
1853
- connectionString: args.connectionString,
1854
- onInfo: args.onInfo,
1855
- statementTimeoutMs
1856
- });
1857
- }
1858
- export { MEMORY_SCOPES as $, juniorConversationMetrics as A, juniorAttachments as B, juniorConversationParticipants as C, juniorConversationEventEmbeddings as D, juniorConversationEventLexemes as E, codeChangeSearchDocument as F, slackPersonSearchDocument as G, juniorConversations as H, codeRepositorySearchDocument as I, juniorMemoryEmbeddings as J, juniorUsers as K, juniorCodeChanges as L, juniorConversationEvents as M, juniorApiTokens as N, juniorConversationEmbeddings as O, juniorConversationAnnotations as P, MEMORY_KINDS as Q, juniorCodeRepositories as R, juniorConversationReadPositions as S, juniorConversationBriefs as T, juniorIdentities as U, juniorMessageAttachments as V, slackPersonPredicate as W, juniorMemorySignals as X, juniorMemoryMemories as Y, MEMORY_EMBEDDING_DIMENSIONS as Z, juniorAutomationRuns as _, juniorWorkspaces as a, guardedCosineDistance as at, juniorAgentBindings as b, juniorTodos as c, juniorArtifacts as ct, juniorInboxSnoozes as d, MEMORY_SOURCE_PLATFORMS as et, juniorInboxItemAssignees as f, juniorAutomations as g, juniorInboxItems as h, juniorWorkspaceRepos as i, embedText as it, isUserInstruction as j, CONVERSATION_METRICS as k, juniorStats as l, juniorInboxItemSlackCards as m, isPostgresErrorCode as n, memoryRuntimeContextSchema as nt, juniorPushSubscriptions as o, parseEmbeddingBatch as ot, juniorInboxItemConversations as p, juniorDestinations as q, juniorSnapshots as r, cosineDistance as rt, juniorTodoVersionSeq as s, refreshEmbeddings as st, createJuniorSqlExecutor as t, MEMORY_SUBJECT_TYPES as tt, juniorInboxSnoozeTriggers as u, juniorAutomationVersions as v, juniorConversationBindings as w, juniorAgentInvocations as x, juniorLocationConfigurations as y, juniorAttachmentUploads as z };